[watermarking] Dual-key gumbel-max watermarking for speculative decoding support (#56122)
Signed-off-by: Raphael Rialland <raphael.rialland@mistral.ai> Signed-off-by: Simon Veitner <sveitner@redhat.com> Signed-off-by: Tomas Ruiz <tomas.ruiz.te@gmail.com> Co-authored-by: OpenAI Codex <codex@openai.com> Co-authored-by: Simon Veitner <sveitner@redhat.com> Co-authored-by: Tomas Ruiz <tomas.ruiz.te@gmail.com>
This commit is contained in:
co-authored by
OpenAI Codex
Simon Veitner
Tomas Ruiz
parent
1ee4be4dbc
commit
7ee8a6dd01
@@ -79,6 +79,10 @@ from vllm.v1.outputs import (
|
||||
)
|
||||
from vllm.v1.watermarking import create_watermarker
|
||||
from vllm.v1.watermarking.gpu_sampler import GPUWatermarkSampler
|
||||
from vllm.v1.watermarking.spec_decode import (
|
||||
create_speculative_target_watermarker,
|
||||
speculative_target_watermark_key,
|
||||
)
|
||||
from vllm.v1.worker.block_table import get_block_table_width
|
||||
from vllm.v1.worker.cp_utils import check_attention_cp_compatibility
|
||||
from vllm.v1.worker.gpu import pcp_manager as pcp
|
||||
@@ -472,8 +476,18 @@ class GPUModelRunner(LoRAModelRunnerMixin):
|
||||
if self.vllm_config.watermark_config is None:
|
||||
self.sampler = Sampler(**sampler_kwargs)
|
||||
else:
|
||||
watermarker = create_watermarker(self.vllm_config.watermark_config)
|
||||
self.sampler = GPUWatermarkSampler(watermarker, **sampler_kwargs)
|
||||
wm_config = self.vllm_config.watermark_config
|
||||
watermarker = create_watermarker(wm_config)
|
||||
if self.speculative_config is not None:
|
||||
watermarker = create_speculative_target_watermarker(watermarker)
|
||||
self.sampler = GPUWatermarkSampler(
|
||||
watermarker,
|
||||
deduplicate_contexts=wm_config.deduplicate_contexts,
|
||||
deduplicate_contexts_max_history=(
|
||||
wm_config.deduplicate_contexts_max_history
|
||||
),
|
||||
**sampler_kwargs,
|
||||
)
|
||||
custom = self.model_state.custom_sampler(self.sampler)
|
||||
|
||||
if custom:
|
||||
@@ -484,6 +498,9 @@ class GPUModelRunner(LoRAModelRunnerMixin):
|
||||
self.sampler,
|
||||
self.speculative_config,
|
||||
self.device,
|
||||
watermark_key=speculative_target_watermark_key(
|
||||
self.vllm_config.watermark_config
|
||||
),
|
||||
)
|
||||
self.prompt_logprobs_worker = PromptLogprobsWorker(
|
||||
self.max_num_reqs,
|
||||
@@ -860,6 +877,11 @@ class GPUModelRunner(LoRAModelRunnerMixin):
|
||||
if hasattr(self.model, "get_mtp_target_hidden_states"):
|
||||
pre_hc_hidden_states = self.model.get_mtp_target_hidden_states()
|
||||
spec_hidden_states = pre_hc_hidden_states[: hidden_states.shape[0]] # type: ignore[union-attr]
|
||||
if isinstance(self.sampler, GPUWatermarkSampler):
|
||||
self.speculator.prepare_watermarking(
|
||||
self.sampler._get_contexts(input_batch.idx_mapping),
|
||||
self.sampler.watermarking.gpu[input_batch.idx_mapping],
|
||||
)
|
||||
with use_workspace_lane(self._draft_workspace_lane):
|
||||
self.speculator.propose(
|
||||
input_batch=input_batch,
|
||||
@@ -2086,6 +2108,11 @@ class GPUModelRunner(LoRAModelRunnerMixin):
|
||||
if hasattr(self.model, "get_mtp_target_hidden_states"):
|
||||
pre_hc_hidden_states = self.model.get_mtp_target_hidden_states()
|
||||
spec_hidden_states = pre_hc_hidden_states[: draft_hidden_states.size(0)]
|
||||
if isinstance(self.sampler, GPUWatermarkSampler):
|
||||
self.speculator.prepare_watermarking(
|
||||
self.sampler._get_contexts(input_batch.idx_mapping),
|
||||
self.sampler.watermarking.gpu[input_batch.idx_mapping],
|
||||
)
|
||||
with use_workspace_lane(self._draft_workspace_lane):
|
||||
draft_tokens = self.speculator.propose(
|
||||
input_batch,
|
||||
|
||||
@@ -25,6 +25,7 @@ from vllm.v1.watermarking.prfs.philox import (
|
||||
from vllm.v1.watermarking.prfs.philox import (
|
||||
_UINT32_MASK as _UINT32_MASK_VALUE,
|
||||
)
|
||||
from vllm.v1.worker.gpu.sample.gumbel import gumbel_noised_argmax
|
||||
|
||||
if HAS_TRITON:
|
||||
from triton.language import math as tl_math
|
||||
@@ -42,6 +43,162 @@ _CONTEXT_DOMAIN = (
|
||||
_TOKEN_DOMAIN = tl.constexpr(_TOKEN_DOMAIN_VALUE) if HAS_TRITON else _TOKEN_DOMAIN_VALUE
|
||||
|
||||
|
||||
@triton.jit
|
||||
def _repeated_context_mask_kernel(
|
||||
output_ptr,
|
||||
all_token_ids_ptr,
|
||||
all_token_ids_stride,
|
||||
req_indices_ptr,
|
||||
prompt_lens_ptr,
|
||||
total_lens_ptr,
|
||||
contexts_ptr,
|
||||
context_stride,
|
||||
CONTEXT_WIDTH: tl.constexpr,
|
||||
MAX_HISTORY: tl.constexpr,
|
||||
INCLUDE_PROMPT: tl.constexpr,
|
||||
SKIP_PARTIAL_CONTEXT: tl.constexpr,
|
||||
BLOCK: tl.constexpr,
|
||||
):
|
||||
row = tl.program_id(0).to(tl.int64)
|
||||
req_idx = tl.load(req_indices_ptr + row).to(tl.int64)
|
||||
if req_idx < 0:
|
||||
tl.store(output_ptr + row, 0)
|
||||
return
|
||||
prompt_len = tl.load(prompt_lens_ptr + req_idx)
|
||||
total_len = tl.load(total_lens_ptr + req_idx)
|
||||
if SKIP_PARTIAL_CONTEXT and total_len - prompt_len < CONTEXT_WIDTH:
|
||||
tl.store(output_ptr + row, 1)
|
||||
return
|
||||
sequence_start = 0 if INCLUDE_PROMPT else prompt_len
|
||||
history_len = total_len - sequence_start
|
||||
|
||||
offsets = tl.arange(0, BLOCK)
|
||||
repeated = tl.full((), 0, tl.int32)
|
||||
scan_start = 0
|
||||
if MAX_HISTORY > 0:
|
||||
scan_start = tl.maximum(history_len - MAX_HISTORY, 0)
|
||||
# Aligned loop bounds let the per-lane offsets fold into immediates.
|
||||
aligned_start = (scan_start // BLOCK) * BLOCK
|
||||
for block_start in tl.range(aligned_start, history_len, BLOCK):
|
||||
previous_pos = block_start + offsets
|
||||
in_window = (previous_pos >= scan_start) & (previous_pos < history_len)
|
||||
matches = in_window
|
||||
for offset in range(CONTEXT_WIDTH):
|
||||
context_token = tl.load(contexts_ptr + row * context_stride + offset)
|
||||
historical_pos = previous_pos + offset - CONTEXT_WIDTH
|
||||
historical_token = tl.load(
|
||||
all_token_ids_ptr
|
||||
+ req_idx * all_token_ids_stride
|
||||
+ sequence_start
|
||||
+ tl.maximum(historical_pos, 0),
|
||||
mask=in_window & (historical_pos >= 0),
|
||||
other=-1,
|
||||
)
|
||||
matches &= historical_token == context_token
|
||||
repeated |= tl.max(matches.to(tl.int32), axis=0)
|
||||
tl.store(output_ptr + row, repeated)
|
||||
|
||||
|
||||
def _repeated_context_mask_cpu(
|
||||
all_token_ids: torch.Tensor,
|
||||
req_indices: torch.Tensor,
|
||||
prompt_lens: torch.Tensor,
|
||||
total_lens: torch.Tensor,
|
||||
contexts: torch.Tensor,
|
||||
max_history: int | None = None,
|
||||
include_prompt: bool = False,
|
||||
skip_partial_context: bool = False,
|
||||
) -> torch.Tensor:
|
||||
"""Reference implementation; the parity tests check the Triton kernel against it."""
|
||||
repeated = torch.zeros(len(req_indices), dtype=torch.bool)
|
||||
for row, req_idx_tensor in enumerate(req_indices):
|
||||
req_idx = int(req_idx_tensor)
|
||||
if req_idx < 0:
|
||||
continue
|
||||
prompt_len = int(prompt_lens[req_idx])
|
||||
total_len = int(total_lens[req_idx])
|
||||
if skip_partial_context and total_len - prompt_len < contexts.shape[-1]:
|
||||
repeated[row] = True
|
||||
continue
|
||||
sequence_start = 0 if include_prompt else prompt_len
|
||||
history_tokens = all_token_ids[req_idx, sequence_start:total_len].tolist()
|
||||
prefix = [-1] * contexts.shape[-1]
|
||||
current_context = tuple(contexts[row].tolist())
|
||||
history_start = (
|
||||
max(0, len(history_tokens) - max_history) if max_history is not None else 0
|
||||
)
|
||||
for history_pos, token_id in enumerate(history_tokens):
|
||||
if history_pos >= history_start and (
|
||||
tuple(prefix[-contexts.shape[-1] :]) == current_context
|
||||
):
|
||||
repeated[row] = True
|
||||
break
|
||||
prefix.append(token_id)
|
||||
return repeated
|
||||
|
||||
|
||||
def repeated_context_mask(
|
||||
all_token_ids: torch.Tensor,
|
||||
req_indices: torch.Tensor,
|
||||
prompt_lens: torch.Tensor,
|
||||
total_lens: torch.Tensor,
|
||||
contexts: torch.Tensor,
|
||||
max_history: int | None = None,
|
||||
include_prompt: bool = False,
|
||||
skip_partial_context: bool = False,
|
||||
) -> torch.Tensor:
|
||||
"""Return, per row, whether the row's context already occurred in its history.
|
||||
|
||||
Args:
|
||||
all_token_ids: `[max_num_reqs, max_model_len]` token ids of every request.
|
||||
req_indices: Request slot per sampled row; -1 marks a padding row, which
|
||||
is reported as not repeated.
|
||||
prompt_lens: Prompt length per request slot.
|
||||
total_lens: Prompt plus generated length per request slot.
|
||||
contexts: `[num_rows, context_width]` context per row, padded with -1
|
||||
before the start of the scanned history.
|
||||
max_history: Number of most recent history positions searched, or
|
||||
``None`` for all of them. The window compared at each position
|
||||
reaches `context_width` tokens further back.
|
||||
include_prompt: Search the prompt as well as the generated tokens.
|
||||
skip_partial_context: Mark contexts containing start padding so they use
|
||||
ordinary sampling.
|
||||
"""
|
||||
if max_history is not None and max_history < 1:
|
||||
raise ValueError("max_history must be positive or None")
|
||||
if all_token_ids.device.type == "cpu":
|
||||
return _repeated_context_mask_cpu(
|
||||
all_token_ids,
|
||||
req_indices,
|
||||
prompt_lens,
|
||||
total_lens,
|
||||
contexts,
|
||||
max_history,
|
||||
include_prompt,
|
||||
skip_partial_context,
|
||||
)
|
||||
|
||||
if contexts.stride(-1) != 1:
|
||||
contexts = contexts.contiguous()
|
||||
repeated = torch.empty(len(req_indices), dtype=torch.bool, device=contexts.device)
|
||||
_repeated_context_mask_kernel[(len(req_indices),)](
|
||||
repeated,
|
||||
all_token_ids,
|
||||
all_token_ids.stride(0),
|
||||
req_indices,
|
||||
prompt_lens,
|
||||
total_lens,
|
||||
contexts,
|
||||
contexts.stride(0),
|
||||
CONTEXT_WIDTH=contexts.shape[-1],
|
||||
MAX_HISTORY=0 if max_history is None else max_history,
|
||||
INCLUDE_PROMPT=include_prompt,
|
||||
SKIP_PARTIAL_CONTEXT=skip_partial_context,
|
||||
BLOCK=512,
|
||||
)
|
||||
return repeated
|
||||
|
||||
|
||||
@triton.jit
|
||||
def _mulhilo32(multiplier: tl.constexpr, value):
|
||||
high = tl_math.umulhi(multiplier, value)
|
||||
@@ -73,12 +230,100 @@ def _uint32_to_uniform(value):
|
||||
return (scaled.to(tl.uint32, bitcast=True) - 1).to(tl.float32, bitcast=True)
|
||||
|
||||
|
||||
@triton.jit
|
||||
def _philox_context_state(
|
||||
contexts_row_ptr,
|
||||
key_0,
|
||||
key_1,
|
||||
CONTEXT_WIDTH: tl.constexpr,
|
||||
):
|
||||
state_0 = tl.full((), _CONTEXT_DOMAIN, tl.uint32)
|
||||
state_1 = tl.full((), CONTEXT_WIDTH, tl.uint32)
|
||||
state_2 = tl.full((), 0, tl.uint32)
|
||||
state_3 = tl.full((), 0, tl.uint32)
|
||||
for offset in range(0, CONTEXT_WIDTH, 4):
|
||||
context_0 = tl.load(contexts_row_ptr + offset).to(tl.uint32)
|
||||
if offset + 1 < CONTEXT_WIDTH:
|
||||
context_1 = tl.load(contexts_row_ptr + offset + 1).to(tl.uint32)
|
||||
else:
|
||||
context_1 = tl.full((), _UINT32_MASK - 1, tl.uint32)
|
||||
if offset + 2 < CONTEXT_WIDTH:
|
||||
context_2 = tl.load(contexts_row_ptr + offset + 2).to(tl.uint32)
|
||||
else:
|
||||
context_2 = tl.full((), _UINT32_MASK - 2, tl.uint32)
|
||||
if offset + 3 < CONTEXT_WIDTH:
|
||||
context_3 = tl.load(contexts_row_ptr + offset + 3).to(tl.uint32)
|
||||
else:
|
||||
context_3 = tl.full((), _UINT32_MASK - 3, tl.uint32)
|
||||
state_0, state_1, state_2, state_3 = _philox4x32_10(
|
||||
(state_0 ^ context_0) & _UINT32_MASK,
|
||||
(state_1 ^ context_1) & _UINT32_MASK,
|
||||
(state_2 ^ context_2) & _UINT32_MASK,
|
||||
(state_3 ^ context_3) & _UINT32_MASK,
|
||||
(key_0 ^ offset) & _UINT32_MASK,
|
||||
key_1,
|
||||
)
|
||||
return state_0, state_1, state_2, state_3
|
||||
|
||||
|
||||
@triton.jit
|
||||
def _philox_candidate_words(groups, state_0, state_1, state_2, state_3, key_0, key_1):
|
||||
candidate_words = groups.to(tl.uint32)
|
||||
vector_zero = candidate_words * 0
|
||||
return _philox4x32_10(
|
||||
candidate_words & _UINT32_MASK,
|
||||
state_0 + vector_zero,
|
||||
state_1 + vector_zero,
|
||||
state_2 + vector_zero,
|
||||
((key_0 ^ state_3) & _UINT32_MASK) + vector_zero,
|
||||
((key_1 ^ _TOKEN_DOMAIN) & _UINT32_MASK) + vector_zero,
|
||||
)
|
||||
|
||||
|
||||
@triton.jit
|
||||
def _philox_gumbel_from_logits(logits, word):
|
||||
logits = tl.where(logits != logits, float("-inf"), logits)
|
||||
uniform = _uint32_to_uniform(word)
|
||||
return logits - tl.log(-tl.log(uniform))
|
||||
|
||||
|
||||
@triton.jit
|
||||
def _gumbel_value(logits_ptr, output, mask):
|
||||
logits = tl.load(logits_ptr, mask=mask, other=float("-inf")).to(tl.float32)
|
||||
logits = tl.where(logits != logits, float("-inf"), logits)
|
||||
uniform = _uint32_to_uniform(output)
|
||||
return logits - tl.log(-tl.log(uniform))
|
||||
return _philox_gumbel_from_logits(logits, output)
|
||||
|
||||
|
||||
@triton.jit
|
||||
def philox_gumbel_block_argmax(
|
||||
logits,
|
||||
mask,
|
||||
block_idx,
|
||||
contexts_row_ptr,
|
||||
key_0,
|
||||
key_1,
|
||||
CONTEXT_WIDTH: tl.constexpr,
|
||||
BLOCK_SIZE: tl.constexpr,
|
||||
):
|
||||
"""Apply the detector-compatible PRF to one vocabulary block."""
|
||||
tl.static_assert(BLOCK_SIZE % 4 == 0)
|
||||
state_0, state_1, state_2, state_3 = _philox_context_state(
|
||||
contexts_row_ptr, key_0, key_1, CONTEXT_WIDTH
|
||||
)
|
||||
groups = block_idx * (BLOCK_SIZE // 4) + tl.arange(0, BLOCK_SIZE // 4)
|
||||
output_0, output_1, output_2, output_3 = _philox_candidate_words(
|
||||
groups, state_0, state_1, state_2, state_3, key_0, key_1
|
||||
)
|
||||
# Lay the per-group words out in token order: 4g+0, 4g+1, 4g+2, 4g+3.
|
||||
words = tl.interleave(
|
||||
tl.interleave(output_0, output_2),
|
||||
tl.interleave(output_1, output_3),
|
||||
)
|
||||
values = tl.where(
|
||||
mask,
|
||||
_philox_gumbel_from_logits(logits.to(tl.float32), words),
|
||||
float("-inf"),
|
||||
)
|
||||
return tl.max(values, axis=0, return_indices=True)
|
||||
|
||||
|
||||
@triton.jit
|
||||
@@ -100,60 +345,63 @@ def _philox_gumbel_kernel(
|
||||
logits_stride,
|
||||
contexts_ptr,
|
||||
context_stride,
|
||||
skip_mask_ptr,
|
||||
expanded_idx_mapping_ptr,
|
||||
seeds_ptr,
|
||||
pos_ptr,
|
||||
temp_ptr,
|
||||
key_0_value,
|
||||
key_1_value,
|
||||
vocab_size,
|
||||
CONTEXT_WIDTH: tl.constexpr,
|
||||
BLOCK_SIZE: tl.constexpr,
|
||||
USE_FP64: tl.constexpr,
|
||||
):
|
||||
row = tl.program_id(0).to(tl.int64)
|
||||
block_index = tl.program_id(1)
|
||||
groups = block_index * (BLOCK_SIZE // 4) + tl.arange(0, BLOCK_SIZE // 4)
|
||||
|
||||
if skip_mask_ptr is not None:
|
||||
req_state_idx = tl.load(expanded_idx_mapping_ptr + row).to(tl.int64)
|
||||
valid_req = req_state_idx >= 0
|
||||
if tl.load(skip_mask_ptr + row):
|
||||
temp = tl.load(temp_ptr + req_state_idx, mask=valid_req, other=0.0).to(
|
||||
tl.float32
|
||||
)
|
||||
seed = tl.load(seeds_ptr + req_state_idx, mask=valid_req, other=0)
|
||||
pos = tl.load(pos_ptr + row)
|
||||
candidate = block_index * BLOCK_SIZE + tl.arange(0, BLOCK_SIZE)
|
||||
mask = candidate < vocab_size
|
||||
logits_row = logits_ptr + row * logits_stride
|
||||
logits = tl.load(logits_row + candidate, mask=mask, other=float("-inf")).to(
|
||||
tl.float32
|
||||
)
|
||||
value, index = gumbel_noised_argmax(
|
||||
logits,
|
||||
candidate,
|
||||
mask,
|
||||
seed,
|
||||
pos,
|
||||
temp,
|
||||
IS_DRAFTING=False,
|
||||
USE_FP64=USE_FP64,
|
||||
APPLY_TEMPERATURE=False,
|
||||
)
|
||||
token_id = block_index * BLOCK_SIZE + index
|
||||
tl.store(
|
||||
local_argmax_ptr + row * local_argmax_stride + block_index,
|
||||
token_id,
|
||||
)
|
||||
tl.store(local_max_ptr + row * local_max_stride + block_index, value)
|
||||
return
|
||||
|
||||
key_0 = key_0_value.to(tl.uint32)
|
||||
key_1 = key_1_value.to(tl.uint32)
|
||||
state_0 = tl.full((), _CONTEXT_DOMAIN, tl.uint32)
|
||||
state_1 = tl.full((), CONTEXT_WIDTH, tl.uint32)
|
||||
state_2 = tl.full((), 0, tl.uint32)
|
||||
state_3 = tl.full((), 0, tl.uint32)
|
||||
for offset in range(0, CONTEXT_WIDTH, 4):
|
||||
context_0 = tl.load(contexts_ptr + row * context_stride + offset).to(tl.uint32)
|
||||
if offset + 1 < CONTEXT_WIDTH:
|
||||
context_1 = tl.load(contexts_ptr + row * context_stride + offset + 1).to(
|
||||
tl.uint32
|
||||
)
|
||||
else:
|
||||
context_1 = tl.full((), _UINT32_MASK - 1, tl.uint32)
|
||||
if offset + 2 < CONTEXT_WIDTH:
|
||||
context_2 = tl.load(contexts_ptr + row * context_stride + offset + 2).to(
|
||||
tl.uint32
|
||||
)
|
||||
else:
|
||||
context_2 = tl.full((), _UINT32_MASK - 2, tl.uint32)
|
||||
if offset + 3 < CONTEXT_WIDTH:
|
||||
context_3 = tl.load(contexts_ptr + row * context_stride + offset + 3).to(
|
||||
tl.uint32
|
||||
)
|
||||
else:
|
||||
context_3 = tl.full((), _UINT32_MASK - 3, tl.uint32)
|
||||
state_0, state_1, state_2, state_3 = _philox4x32_10(
|
||||
(state_0 ^ context_0) & _UINT32_MASK,
|
||||
(state_1 ^ context_1) & _UINT32_MASK,
|
||||
(state_2 ^ context_2) & _UINT32_MASK,
|
||||
(state_3 ^ context_3) & _UINT32_MASK,
|
||||
(key_0 ^ offset) & _UINT32_MASK,
|
||||
key_1,
|
||||
)
|
||||
|
||||
candidate_words = groups.to(tl.uint32)
|
||||
vector_zero = candidate_words * 0
|
||||
output_0, output_1, output_2, output_3 = _philox4x32_10(
|
||||
candidate_words & _UINT32_MASK,
|
||||
state_0 + vector_zero,
|
||||
state_1 + vector_zero,
|
||||
state_2 + vector_zero,
|
||||
((key_0 ^ state_3) & _UINT32_MASK) + vector_zero,
|
||||
((key_1 ^ _TOKEN_DOMAIN) & _UINT32_MASK) + vector_zero,
|
||||
state_0, state_1, state_2, state_3 = _philox_context_state(
|
||||
contexts_ptr + row * context_stride, key_0, key_1, CONTEXT_WIDTH
|
||||
)
|
||||
output_0, output_1, output_2, output_3 = _philox_candidate_words(
|
||||
groups, state_0, state_1, state_2, state_3, key_0, key_1
|
||||
)
|
||||
candidate_0 = groups * 4
|
||||
candidate_1 = candidate_0 + 1
|
||||
@@ -184,17 +432,42 @@ def _philox_gumbel_kernel(
|
||||
|
||||
|
||||
def philox_gumbel_sample(
|
||||
logits: torch.Tensor, contexts: torch.Tensor, key: int
|
||||
logits: torch.Tensor,
|
||||
contexts: torch.Tensor,
|
||||
key: int,
|
||||
*,
|
||||
skip_mask: torch.Tensor | None = None,
|
||||
expanded_idx_mapping: torch.Tensor | None = None,
|
||||
temperatures: torch.Tensor | None = None,
|
||||
seeds: torch.Tensor | None = None,
|
||||
positions: torch.Tensor | None = None,
|
||||
use_fp64: bool = False,
|
||||
) -> torch.Tensor:
|
||||
sampling_state = (expanded_idx_mapping, temperatures, seeds, positions)
|
||||
if skip_mask is None and any(value is not None for value in sampling_state):
|
||||
raise ValueError("sampling state requires skip_mask")
|
||||
if skip_mask is not None and any(value is None for value in sampling_state):
|
||||
raise ValueError("skip_mask requires complete sampling state")
|
||||
|
||||
if logits.stride(-1) != 1:
|
||||
logits = logits.contiguous()
|
||||
if contexts.stride(-1) != 1:
|
||||
contexts = contexts.contiguous()
|
||||
if skip_mask is not None:
|
||||
skip_mask = skip_mask.contiguous()
|
||||
if expanded_idx_mapping is not None:
|
||||
expanded_idx_mapping = expanded_idx_mapping.contiguous()
|
||||
if positions is not None:
|
||||
positions = positions.contiguous()
|
||||
num_tokens, vocab_size = logits.shape
|
||||
block_size = 1024
|
||||
num_blocks = triton.cdiv(vocab_size, block_size)
|
||||
local_argmax = logits.new_empty(num_tokens, num_blocks, dtype=torch.int64)
|
||||
local_max = logits.new_empty(num_tokens, num_blocks, dtype=torch.float32)
|
||||
local_max = logits.new_empty(
|
||||
num_tokens,
|
||||
num_blocks,
|
||||
dtype=torch.float64 if use_fp64 else torch.float32,
|
||||
)
|
||||
_philox_gumbel_kernel[(num_tokens, num_blocks)](
|
||||
local_argmax,
|
||||
local_argmax.stride(0),
|
||||
@@ -204,11 +477,17 @@ def philox_gumbel_sample(
|
||||
logits.stride(0),
|
||||
contexts,
|
||||
contexts.stride(0),
|
||||
skip_mask,
|
||||
expanded_idx_mapping,
|
||||
seeds,
|
||||
positions,
|
||||
temperatures,
|
||||
key & _UINT32_MASK_VALUE,
|
||||
key >> 32,
|
||||
vocab_size,
|
||||
CONTEXT_WIDTH=contexts.shape[-1],
|
||||
BLOCK_SIZE=block_size,
|
||||
USE_FP64=use_fp64,
|
||||
)
|
||||
max_block_index = local_max.argmax(dim=-1, keepdim=True)
|
||||
return local_argmax.gather(dim=-1, index=max_block_index).view(-1)
|
||||
|
||||
@@ -137,7 +137,7 @@ class DSparkSpeculator(DFlashSpeculator):
|
||||
|
||||
# sample_pos is the predicted token's position P. Sampling keys a draw
|
||||
# by the position before the sampled token, P-1.
|
||||
return gumbel_sample(
|
||||
sampled = gumbel_sample(
|
||||
logits,
|
||||
idx_map,
|
||||
self.temperature,
|
||||
@@ -149,6 +149,14 @@ class DSparkSpeculator(DFlashSpeculator):
|
||||
logits_cache_col=self._step_cols[step],
|
||||
use_fp64=self.use_fp64_gumbel,
|
||||
)
|
||||
if self.draft_watermarker is not None:
|
||||
sampled = self.draft_watermarker.sample(
|
||||
logits,
|
||||
sampled,
|
||||
idx_map,
|
||||
self.temperature,
|
||||
)
|
||||
return sampled
|
||||
|
||||
def _sample_sequential(self, num_reqs: int, head_hidden: torch.Tensor) -> None:
|
||||
if self._draft_topk is not None:
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
from collections.abc import Iterable, Iterator
|
||||
from typing import Any
|
||||
|
||||
import numpy as np
|
||||
import torch
|
||||
@@ -10,6 +11,7 @@ from vllm.config.model import PROCESSED_LOGPROBS_MODES
|
||||
from vllm.triton_utils import tl, triton
|
||||
from vllm.v1.outputs import LogprobsTensors
|
||||
from vllm.v1.spec_decode.utils import unconditional_to_conditional_rates
|
||||
from vllm.v1.watermarking.gpu_sampler import GPUWatermarkSampler
|
||||
from vllm.v1.worker.gpu.input_batch import (
|
||||
InputBatch,
|
||||
get_num_sampled_and_rejected,
|
||||
@@ -78,8 +80,13 @@ class RejectionSampler:
|
||||
sampler: Sampler,
|
||||
spec_config: SpeculativeConfig,
|
||||
device: torch.device,
|
||||
*,
|
||||
watermark_key: int | None = None,
|
||||
):
|
||||
self.sampler = sampler
|
||||
self.watermark_key = watermark_key
|
||||
if watermark_key is not None:
|
||||
assert isinstance(sampler, GPUWatermarkSampler)
|
||||
self.num_speculative_steps = spec_config.num_speculative_tokens
|
||||
self.enable_adaptive_verification = spec_config.enable_adaptive_verification
|
||||
rejection_sample_method = spec_config.rejection_sample_method
|
||||
@@ -141,6 +148,23 @@ class RejectionSampler:
|
||||
in ("raw_logits", "processed_logits"),
|
||||
)
|
||||
|
||||
def _watermarking_kwargs(
|
||||
self,
|
||||
draft_sampled: torch.Tensor,
|
||||
expanded_idx_mapping: torch.Tensor,
|
||||
expanded_local_pos: torch.Tensor,
|
||||
) -> dict[str, Any]:
|
||||
if self.watermark_key is None:
|
||||
return {}
|
||||
assert isinstance(self.sampler, GPUWatermarkSampler)
|
||||
return {
|
||||
"contexts": self.sampler._get_contexts(
|
||||
expanded_idx_mapping, expanded_local_pos, draft_sampled
|
||||
),
|
||||
"watermarking": self.sampler.watermarking.gpu,
|
||||
"watermark_key": self.watermark_key,
|
||||
}
|
||||
|
||||
def _verify(
|
||||
self,
|
||||
logits: torch.Tensor,
|
||||
@@ -177,6 +201,9 @@ class RejectionSampler:
|
||||
self.synthetic_conditional_rates,
|
||||
use_fp64=self.sampler.use_fp64_gumbel,
|
||||
use_block_verification=self.use_block_verification,
|
||||
**self._watermarking_kwargs(
|
||||
draft_sampled, expanded_idx_mapping, expanded_local_pos
|
||||
),
|
||||
)
|
||||
return processed_logits, sampled, num_sampled
|
||||
|
||||
|
||||
@@ -4,6 +4,7 @@ import torch
|
||||
|
||||
from vllm.triton_utils import tl, tldevice, triton
|
||||
from vllm.v1.worker.gpu.sample.gumbel import gumbel_block_argmax, tl_rand32
|
||||
from vllm.v1.worker.gpu.sample.watermark import philox_gumbel_block_argmax
|
||||
|
||||
|
||||
@triton.jit
|
||||
@@ -693,6 +694,39 @@ def _rejection_kernel(
|
||||
|
||||
|
||||
@triton.jit
|
||||
def _seeded_resample_argmax(
|
||||
residual_logits,
|
||||
block,
|
||||
mask,
|
||||
resample_token_idx,
|
||||
expanded_idx_mapping_ptr,
|
||||
temp_ptr,
|
||||
seed_ptr,
|
||||
pos_ptr,
|
||||
vocab_size,
|
||||
USE_FP64: tl.constexpr,
|
||||
):
|
||||
return gumbel_block_argmax(
|
||||
residual_logits,
|
||||
block,
|
||||
mask,
|
||||
resample_token_idx,
|
||||
expanded_idx_mapping_ptr,
|
||||
temp_ptr,
|
||||
seed_ptr,
|
||||
pos_ptr,
|
||||
None, # logits_cache_ptr
|
||||
0, # logits_cache_stride_0
|
||||
0, # logits_cache_stride_1
|
||||
None, # logits_cache_col_ptr
|
||||
vocab_size,
|
||||
IS_DRAFTING=False,
|
||||
APPLY_TEMPERATURE=False,
|
||||
USE_FP64=USE_FP64,
|
||||
)
|
||||
|
||||
|
||||
@triton.jit(do_not_specialize=["watermark_key_0", "watermark_key_1"])
|
||||
def _resample_kernel(
|
||||
# [num_reqs, num_blocks]
|
||||
resampled_local_argmax_ptr,
|
||||
@@ -727,11 +761,20 @@ def _resample_kernel(
|
||||
pos_ptr,
|
||||
# [num_logits]
|
||||
cumulative_log_p_ptr,
|
||||
# [num_logits, CONTEXT_WIDTH]
|
||||
contexts_ptr,
|
||||
contexts_stride,
|
||||
# [max_num_reqs], uint8 view of a bool tensor
|
||||
watermarking_ptr,
|
||||
watermark_key_0,
|
||||
watermark_key_1,
|
||||
vocab_size,
|
||||
BLOCK_SIZE: tl.constexpr,
|
||||
HAS_DRAFT_LOGITS: tl.constexpr,
|
||||
USE_FP64: tl.constexpr,
|
||||
USE_BLOCK_VERIFICATION: tl.constexpr,
|
||||
CONTEXT_WIDTH: tl.constexpr,
|
||||
WATERMARK: tl.constexpr,
|
||||
):
|
||||
req_idx = tl.program_id(0)
|
||||
resample_idx = tl.load(rejected_step_ptr + req_idx)
|
||||
@@ -763,10 +806,7 @@ def _resample_kernel(
|
||||
other=float("-inf"),
|
||||
).to(tl.float32)
|
||||
|
||||
# Compute the residual logits to resample the rejected token from.
|
||||
if is_bonus or not is_valid_rejected_draft:
|
||||
# Bonus token (no rejections) or -1 placeholder token. In either case,
|
||||
# directly use the target logits.
|
||||
residual_logits = target_logits
|
||||
elif HAS_DRAFT_LOGITS:
|
||||
# draft_logits is stored pre-temperature, so apply scale first.
|
||||
@@ -796,12 +836,7 @@ def _resample_kernel(
|
||||
)
|
||||
target_log_probs += log_p_tau
|
||||
draft_log_probs = draft_logits - draft_lse
|
||||
# Compute the residual:
|
||||
# r(x) = max(p(x) - q(x), 0)
|
||||
# Gumbel sampling needs logits, so we compute it in log space:
|
||||
# log(r(x)) = log(max(exp(log_p(x)) - exp(log_q(x)), 0))
|
||||
# The more numerically stable form is:
|
||||
# log(max(exp(a) - exp(b), 0)) = a + log(max(1 - exp(b - a), 0))
|
||||
# Compute log(max(p - q, 0)) without subtracting probabilities.
|
||||
ratio = tl.exp(draft_log_probs - target_log_probs)
|
||||
residual_logits = tl.where(
|
||||
ratio < 1.0,
|
||||
@@ -809,38 +844,62 @@ def _resample_kernel(
|
||||
float("-inf"),
|
||||
).to(tl.float32)
|
||||
else:
|
||||
# One-hot draft. The residual is just the target distribution with
|
||||
# the rejected draft token probability zeroed out.
|
||||
# NOTE: During block verification, the residual becomes:
|
||||
# 0 if x == rejected_draft_token
|
||||
# p_tau * M_b(x) / Z otherwise
|
||||
# Therefore p_tau is a constant that cancels under normalization,
|
||||
# and does not need to be applied.
|
||||
# The block-verification factor is constant and cancels on normalization.
|
||||
residual_logits = tl.where(
|
||||
block != rejected_draft_token,
|
||||
target_logits,
|
||||
float("-inf"),
|
||||
).to(tl.float32)
|
||||
|
||||
# Resample the rejected/bonus token.
|
||||
value, idx = gumbel_block_argmax(
|
||||
residual_logits,
|
||||
block,
|
||||
mask,
|
||||
resample_token_idx,
|
||||
expanded_idx_mapping_ptr,
|
||||
temp_ptr,
|
||||
seed_ptr,
|
||||
pos_ptr,
|
||||
None, # logits_cache_ptr
|
||||
0, # logits_cache_stride_0
|
||||
0, # logits_cache_stride_1
|
||||
None, # logits_cache_col_ptr
|
||||
vocab_size,
|
||||
IS_DRAFTING=False,
|
||||
APPLY_TEMPERATURE=False,
|
||||
USE_FP64=USE_FP64,
|
||||
)
|
||||
if WATERMARK:
|
||||
# Padded and greedy rows retain the stock draw.
|
||||
is_watermarked = (
|
||||
tl.load(
|
||||
watermarking_ptr + req_state_idx,
|
||||
mask=req_state_idx >= 0,
|
||||
other=0,
|
||||
)
|
||||
!= 0
|
||||
)
|
||||
if is_watermarked & (temp != 0.0):
|
||||
watermark_value, idx = philox_gumbel_block_argmax(
|
||||
residual_logits,
|
||||
mask,
|
||||
block_idx,
|
||||
contexts_ptr + resample_token_idx * contexts_stride,
|
||||
watermark_key_0.to(tl.uint32),
|
||||
watermark_key_1.to(tl.uint32),
|
||||
CONTEXT_WIDTH,
|
||||
BLOCK_SIZE,
|
||||
)
|
||||
# Detector compatibility fixes the keyed draw at fp32.
|
||||
value = watermark_value.to(tl.float64) if USE_FP64 else watermark_value
|
||||
else:
|
||||
value, idx = _seeded_resample_argmax(
|
||||
residual_logits,
|
||||
block,
|
||||
mask,
|
||||
resample_token_idx,
|
||||
expanded_idx_mapping_ptr,
|
||||
temp_ptr,
|
||||
seed_ptr,
|
||||
pos_ptr,
|
||||
vocab_size,
|
||||
USE_FP64=USE_FP64,
|
||||
)
|
||||
else:
|
||||
value, idx = _seeded_resample_argmax(
|
||||
residual_logits,
|
||||
block,
|
||||
mask,
|
||||
resample_token_idx,
|
||||
expanded_idx_mapping_ptr,
|
||||
temp_ptr,
|
||||
seed_ptr,
|
||||
pos_ptr,
|
||||
vocab_size,
|
||||
USE_FP64=USE_FP64,
|
||||
)
|
||||
token_id = block_idx * BLOCK_SIZE + idx
|
||||
tl.store(
|
||||
resampled_local_argmax_ptr
|
||||
@@ -947,6 +1006,9 @@ def rejection_sample(
|
||||
synthetic_conditional_rates: torch.Tensor | None = None,
|
||||
use_fp64: bool = False,
|
||||
use_block_verification: bool = False,
|
||||
contexts: torch.Tensor | None = None,
|
||||
watermarking: torch.Tensor | None = None,
|
||||
watermark_key: int | None = None,
|
||||
) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
assert target_logits.ndim == 2 and target_logits.stride(-1) == 1
|
||||
assert draft_logits is None or (
|
||||
@@ -954,6 +1016,30 @@ def rejection_sample(
|
||||
)
|
||||
num_reqs = cu_num_logits.shape[0] - 1
|
||||
num_logits, vocab_size = target_logits.shape
|
||||
|
||||
watermark = contexts is not None
|
||||
assert watermark == (watermarking is not None) == (watermark_key is not None), (
|
||||
"contexts, watermarking and watermark_key must be set together."
|
||||
)
|
||||
contexts_stride = 0
|
||||
context_width = 1
|
||||
watermarking_bytes: torch.Tensor | None = None
|
||||
watermark_key_0 = 0
|
||||
watermark_key_1 = 0
|
||||
if contexts is not None:
|
||||
assert watermarking is not None and watermark_key is not None
|
||||
assert contexts.ndim == 2 and contexts.shape[0] == num_logits
|
||||
# Context words are hashed as uint32, so int32 (the request-state token
|
||||
# dtype) and int64 both land on the same PRF stream, -1 included.
|
||||
assert contexts.dtype in (torch.int32, torch.int64)
|
||||
if contexts.stride(-1) != 1:
|
||||
contexts = contexts.contiguous()
|
||||
assert watermarking.ndim == 1 and watermarking.dtype == torch.bool
|
||||
contexts_stride = contexts.stride(0)
|
||||
context_width = contexts.shape[-1]
|
||||
watermarking_bytes = watermarking.view(torch.uint8)
|
||||
watermark_key_0 = watermark_key & 0xFFFFFFFF
|
||||
watermark_key_1 = watermark_key >> 32
|
||||
draft_logits_stride_0 = 0
|
||||
draft_logits_stride_1 = 0
|
||||
if has_draft_logits := draft_logits is not None:
|
||||
@@ -1165,11 +1251,18 @@ def rejection_sample(
|
||||
seed,
|
||||
pos,
|
||||
cumulative_log_p,
|
||||
contexts,
|
||||
contexts_stride,
|
||||
watermarking_bytes,
|
||||
watermark_key_0,
|
||||
watermark_key_1,
|
||||
vocab_size,
|
||||
BLOCK_SIZE=RESAMPLE_BLOCK_SIZE,
|
||||
HAS_DRAFT_LOGITS=has_draft_logits,
|
||||
USE_FP64=use_fp64,
|
||||
USE_BLOCK_VERIFICATION=use_block_verification,
|
||||
CONTEXT_WIDTH=context_width,
|
||||
WATERMARK=watermark,
|
||||
)
|
||||
|
||||
# Insert the resampled tokens into the output sampled.
|
||||
|
||||
@@ -17,6 +17,11 @@ from vllm.model_executor.layers.attention_layer_base import AttentionLayerBase
|
||||
from vllm.model_executor.models import supports_multimodal_embeddings
|
||||
from vllm.multimodal import MULTIMODAL_REGISTRY
|
||||
from vllm.v1.kv_cache_interface import KVCacheConfig
|
||||
from vllm.v1.watermarking import create_watermarker
|
||||
from vllm.v1.watermarking.spec_decode import (
|
||||
DraftWatermarker,
|
||||
create_speculative_draft_watermarker,
|
||||
)
|
||||
from vllm.v1.worker.gpu.attn_utils import (
|
||||
build_attn_metadata,
|
||||
init_attn_backend,
|
||||
@@ -168,6 +173,17 @@ class DraftModelSpeculator(BaseSpeculator):
|
||||
device=device,
|
||||
)
|
||||
|
||||
self.draft_watermarker: DraftWatermarker | None = None
|
||||
watermark_config = getattr(vllm_config, "watermark_config", None)
|
||||
if watermark_config is not None:
|
||||
watermarker = create_watermarker(watermark_config)
|
||||
self.draft_watermarker = create_speculative_draft_watermarker(
|
||||
watermarker,
|
||||
self.max_num_reqs,
|
||||
device,
|
||||
watermark_config.allow_target_only_watermarking,
|
||||
)
|
||||
|
||||
self.supports_mm_inputs = False
|
||||
self.pcp_manager: PCPManager | None = None
|
||||
|
||||
@@ -373,7 +389,7 @@ class DraftModelSpeculator(BaseSpeculator):
|
||||
) -> torch.Tensor:
|
||||
if draft_logits is not None:
|
||||
logits = self.model.compute_logits(hidden_states)
|
||||
return gumbel_sample(
|
||||
sampled = gumbel_sample(
|
||||
logits,
|
||||
idx_mapping,
|
||||
temperature,
|
||||
@@ -385,8 +401,23 @@ class DraftModelSpeculator(BaseSpeculator):
|
||||
logits_cache_col=draft_step,
|
||||
use_fp64=self.use_fp64_gumbel,
|
||||
)
|
||||
if self.draft_watermarker is not None:
|
||||
sampled = self.draft_watermarker.sample(
|
||||
logits,
|
||||
sampled,
|
||||
idx_mapping,
|
||||
temperature,
|
||||
)
|
||||
return sampled
|
||||
return self._greedy_sample_draft(hidden_states)
|
||||
|
||||
def prepare_watermarking(
|
||||
self, contexts: torch.Tensor, watermarking: torch.Tensor
|
||||
) -> None:
|
||||
if self.draft_watermarker is None:
|
||||
return
|
||||
self.draft_watermarker.prepare(contexts, watermarking)
|
||||
|
||||
def _copy_request_inputs(
|
||||
self,
|
||||
num_reqs: int,
|
||||
|
||||
Reference in New Issue
Block a user