Merge remote-tracking branch 'upstream/main' into patches
Signed-off-by: MOVZX <movzx@yahoo.com>
This commit is contained in:
@@ -185,7 +185,7 @@ class AsyncOutput(AsyncModelRunnerOutput):
|
||||
|
||||
if self.sampling_mask_tensors is not None:
|
||||
self.model_runner_output.sampling_masks = (
|
||||
self.sampling_mask_tensors.tolists()
|
||||
self.sampling_mask_tensors.tolists(self.num_sampled_tokens_np)
|
||||
)
|
||||
|
||||
if self.num_nans is not None:
|
||||
|
||||
@@ -23,7 +23,7 @@ from vllm.v1.attention.backend import (
|
||||
from vllm.v1.attention.backends.utils import create_fast_prefill_custom_backend
|
||||
from vllm.v1.hisparse.binding import (
|
||||
init_hisparse_kv_cache,
|
||||
resolve_hisparse_block_size,
|
||||
resolve_hisparse_specs,
|
||||
)
|
||||
from vllm.v1.kv_cache_interface import (
|
||||
AttentionSpec,
|
||||
@@ -142,7 +142,8 @@ def get_kv_cache_spec(vllm_config: VllmConfig) -> dict[str, KVCacheSpec]:
|
||||
if isinstance(spec, AttentionSpec):
|
||||
spec = attn_module.get_attn_backend().customize_spec(spec)
|
||||
kv_cache_spec[layer_name] = spec
|
||||
resolve_hisparse_block_size(vllm_config, kv_cache_spec, attn_layers)
|
||||
if vllm_config.attention_config.hisparse_config is not None:
|
||||
kv_cache_spec = resolve_hisparse_specs(vllm_config, kv_cache_spec, attn_layers)
|
||||
return kv_cache_spec
|
||||
|
||||
|
||||
|
||||
@@ -103,6 +103,9 @@ class InputBatch:
|
||||
# [num_reqs] per-request prompt length, only populated for R-SWA.
|
||||
prompt_lens: torch.Tensor | None
|
||||
|
||||
# [num_reqs] only populated for non-dummy pipeline-parallel batches.
|
||||
max_seq_len_np: np.ndarray | None = None
|
||||
|
||||
# Longest query the batch may contain. Set when a cudagraph descriptor promises
|
||||
# a query length this batch's own split does not reach, so attention metadata
|
||||
# stays valid for every replay the graph serves.
|
||||
@@ -203,6 +206,7 @@ class InputBatch:
|
||||
num_computed_prefill_tokens_np=np.zeros(num_reqs, dtype=np.int32),
|
||||
is_prefilling_np=np.zeros(num_reqs, dtype=np.bool_),
|
||||
has_prefill=False,
|
||||
max_seq_len_np=None,
|
||||
decode_graph_eligible=True,
|
||||
input_ids=input_ids,
|
||||
positions=positions,
|
||||
|
||||
@@ -164,7 +164,10 @@ from vllm.v1.worker.gpu.spec_decode.rejection_sampler import (
|
||||
from vllm.v1.worker.gpu.spec_decode.speculator import DraftModelSpeculator
|
||||
from vllm.v1.worker.gpu.spec_decode.utils import DraftTokensHandler
|
||||
from vllm.v1.worker.gpu.states import RequestState
|
||||
from vllm.v1.worker.gpu.structured_outputs import StructuredOutputsWorker
|
||||
from vllm.v1.worker.gpu.structured_outputs import (
|
||||
StructuredOutputsWorker,
|
||||
grammar_invalid_drafts,
|
||||
)
|
||||
from vllm.v1.worker.gpu.ubatch_utils import (
|
||||
UBatchRunner,
|
||||
UBatchState,
|
||||
@@ -802,6 +805,7 @@ class GPUModelRunner(LoRAModelRunnerMixin):
|
||||
skip_eplb: bool = False,
|
||||
is_profile: bool = False,
|
||||
valid_dummy_state_slots: bool = False,
|
||||
randomize_inputs: bool = False,
|
||||
**kwargs,
|
||||
) -> tuple[torch.Tensor | None, torch.Tensor | None]:
|
||||
if skip_attn and not is_profile:
|
||||
@@ -875,6 +879,7 @@ class GPUModelRunner(LoRAModelRunnerMixin):
|
||||
is_profile=is_profile,
|
||||
context_len=context_len,
|
||||
valid_dummy_state_slots=valid_dummy_state_slots,
|
||||
randomize_inputs=randomize_inputs,
|
||||
)
|
||||
self.kv_connector.set_disabled(False)
|
||||
|
||||
@@ -914,8 +919,7 @@ class GPUModelRunner(LoRAModelRunnerMixin):
|
||||
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],
|
||||
self.sampler, input_batch.idx_mapping
|
||||
)
|
||||
with use_workspace_lane(self._draft_workspace_lane):
|
||||
self.speculator.propose(
|
||||
@@ -966,7 +970,7 @@ class GPUModelRunner(LoRAModelRunnerMixin):
|
||||
self.pooling_runner.dummy_pooler_run(hidden_states)
|
||||
|
||||
@torch.inference_mode()
|
||||
def profile_run(self) -> None:
|
||||
def profile_run(self, randomize_inputs: bool = False) -> None:
|
||||
if self.supports_mm_inputs and self.is_first_pp_rank:
|
||||
mm_config = self.model_config.multimodal_config
|
||||
if mm_config is not None and not mm_config.skip_mm_profiling:
|
||||
@@ -979,7 +983,10 @@ class GPUModelRunner(LoRAModelRunnerMixin):
|
||||
)
|
||||
|
||||
hidden_states, sample_hidden_states = self._dummy_run(
|
||||
self.max_num_tokens, skip_attn=True, is_profile=True
|
||||
self.max_num_tokens,
|
||||
skip_attn=True,
|
||||
is_profile=True,
|
||||
randomize_inputs=randomize_inputs,
|
||||
)
|
||||
|
||||
# Only run sampler/pooler on last PP rank (non-last ranks return None).
|
||||
@@ -1272,6 +1279,10 @@ class GPUModelRunner(LoRAModelRunnerMixin):
|
||||
]
|
||||
is_prefilling_np = num_computed_prefill_tokens_np < prefill_len_np
|
||||
has_prefill = bool(is_prefilling_np.any())
|
||||
max_seq_len_np = None
|
||||
if self.use_pp and has_prefill:
|
||||
# consumed by the PP `compute_need_sampled_mask` for batches with prefill.
|
||||
max_seq_len_np = self.req_states.max_seq_len[idx_mapping_np]
|
||||
|
||||
num_draft_tokens_np = None
|
||||
if draft_tokens:
|
||||
@@ -1310,6 +1321,7 @@ class GPUModelRunner(LoRAModelRunnerMixin):
|
||||
has_prefill=has_prefill,
|
||||
prefill_runs_as_decode_np=prefill_runs_as_decode_np,
|
||||
decode_graph_eligible=decode_graph_eligible,
|
||||
max_seq_len_np=max_seq_len_np,
|
||||
)
|
||||
return batch_state, get_uniform_decode_token_count(
|
||||
num_reqs, num_toks, max_query_len, decode_graph_eligible
|
||||
@@ -1497,6 +1509,7 @@ class GPUModelRunner(LoRAModelRunnerMixin):
|
||||
has_prefill=batch_req_state.has_prefill,
|
||||
prefill_runs_as_decode_np=batch_req_state.prefill_runs_as_decode_np,
|
||||
decode_graph_eligible=batch_req_state.decode_graph_eligible,
|
||||
max_seq_len_np=batch_req_state.max_seq_len_np,
|
||||
input_ids=self.input_buffers.input_ids[:num_tokens_after_padding],
|
||||
positions=self.input_buffers.positions[:num_tokens_after_padding],
|
||||
is_padding=is_padding,
|
||||
@@ -1577,6 +1590,7 @@ class GPUModelRunner(LoRAModelRunnerMixin):
|
||||
sample_hidden_states = hidden_states[input_batch.logits_indices]
|
||||
logits = self.model.compute_logits(sample_hidden_states)
|
||||
|
||||
invalid_drafts = None
|
||||
# A diffusion prefill has no logit rows even when a bitmask row
|
||||
# arrived for it.
|
||||
if grammar_output is not None and logits.shape[0] > 0:
|
||||
@@ -1588,6 +1602,11 @@ class GPUModelRunner(LoRAModelRunnerMixin):
|
||||
grammar_output.structured_output_request_ids,
|
||||
grammar_output.grammar_bitmask,
|
||||
)
|
||||
invalid_drafts = grammar_invalid_drafts(
|
||||
input_batch,
|
||||
grammar_output.structured_output_request_ids,
|
||||
grammar_output.num_acceptable_drafts,
|
||||
)
|
||||
|
||||
sampler_output: SamplerOutput | None
|
||||
if input_batch.num_reqs == 0:
|
||||
@@ -1606,6 +1625,7 @@ class GPUModelRunner(LoRAModelRunnerMixin):
|
||||
input_batch,
|
||||
# Draft logits are needed for probabilistic rejection sampling.
|
||||
self.speculator.draft_logits,
|
||||
invalid_drafts,
|
||||
)
|
||||
|
||||
if shard_metadata is not None:
|
||||
@@ -1681,6 +1701,7 @@ class GPUModelRunner(LoRAModelRunnerMixin):
|
||||
is_profile: bool = False,
|
||||
context_len: int = 0,
|
||||
valid_dummy_state_slots: bool = False,
|
||||
randomize_inputs: bool = False,
|
||||
) -> ModelRunnerOutput | IntermediateTensors | None:
|
||||
if not dummy_run:
|
||||
# Update the request states.
|
||||
@@ -1799,6 +1820,9 @@ class GPUModelRunner(LoRAModelRunnerMixin):
|
||||
# so MoE memory is measured and MoE kernels are exercised.
|
||||
is_padding=not is_profile,
|
||||
)
|
||||
if randomize_inputs:
|
||||
# All-zero input_ids route every token to the same experts.
|
||||
input_batch.input_ids.random_(0, self.vocab_size)
|
||||
if self.pcp_manager is not None:
|
||||
input_batch = self.pcp_manager.prepare_inputs_to_capture(input_batch)
|
||||
if skip_attn_for_dummy_run:
|
||||
@@ -2064,6 +2088,8 @@ class GPUModelRunner(LoRAModelRunnerMixin):
|
||||
# Non-last PP rank: hidden_states is None because this rank produced
|
||||
# IntermediateTensors instead of final hidden states. Receive the
|
||||
# sampled tokens broadcast from the last rank and update local state.
|
||||
if self.pcp_manager is not None:
|
||||
input_batch = self.pcp_manager.global_batch
|
||||
assert self.pp_handler is not None
|
||||
all_decode_next = self.pp_handler.receive(input_batch)
|
||||
# Optimistically update num_computed_tokens for entire batch here.
|
||||
@@ -2192,8 +2218,7 @@ class GPUModelRunner(LoRAModelRunnerMixin):
|
||||
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],
|
||||
self.sampler, input_batch.idx_mapping
|
||||
)
|
||||
with use_workspace_lane(self._draft_workspace_lane):
|
||||
draft_tokens = self.speculator.propose(
|
||||
@@ -2382,6 +2407,7 @@ class BatchReqState(NamedTuple):
|
||||
prefill_len_np: np.ndarray # [num_reqs]
|
||||
num_computed_prefill_tokens_np: np.ndarray # [num_reqs]
|
||||
is_prefilling_np: np.ndarray # [num_reqs]
|
||||
max_seq_len_np: np.ndarray | None # [num_reqs], None in non-pp case
|
||||
has_prefill: bool
|
||||
prefill_runs_as_decode_np: np.ndarray | None # [num_reqs]
|
||||
decode_graph_eligible: bool
|
||||
|
||||
@@ -49,6 +49,7 @@ class PCPManager:
|
||||
pcp_world_size: int,
|
||||
pcp_rank: int,
|
||||
device: torch.device,
|
||||
shard_decode_requests: bool,
|
||||
max_num_reqs: int | None = None,
|
||||
max_num_tokens: int | None = None,
|
||||
block_tables: BlockTables | None = None,
|
||||
@@ -62,6 +63,7 @@ class PCPManager:
|
||||
self.dcp_world_size = dcp_world_size
|
||||
self.dcp_rank = dcp_rank
|
||||
self.cp_interleave = cp_interleave
|
||||
self.shard_decode_requests = shard_decode_requests
|
||||
|
||||
self._global_batch: InputBatch | None = None
|
||||
self._local_batch: InputBatch | None = None
|
||||
@@ -131,8 +133,6 @@ class PCPManager:
|
||||
|
||||
if not model_config.use_mla:
|
||||
raise NotImplementedError("MRV2 PCP currently supports MLA models only.")
|
||||
if parallel_config.pipeline_parallel_size > 1:
|
||||
raise NotImplementedError("MRV2 PCP does not support PP yet.")
|
||||
if model_config.is_encoder_decoder:
|
||||
raise NotImplementedError(
|
||||
"MRV2 PCP does not support encoder-decoder models yet."
|
||||
@@ -250,6 +250,7 @@ class PCPManager:
|
||||
|
||||
Decodes, and prefills too short to fill all eight, are replicated instead.
|
||||
"""
|
||||
decode_ordinal = 0
|
||||
num_chunks = 2 * self.pcp_world_size
|
||||
replicated = self.replicated_requests(num_scheduled_tokens, is_prefilling)
|
||||
for global_batch_req_idx, num_tokens in enumerate(num_scheduled_tokens):
|
||||
@@ -260,7 +261,16 @@ class PCPManager:
|
||||
if not replicated[global_batch_req_idx]:
|
||||
chunk_size = (query_len + num_chunks - 1) // num_chunks
|
||||
chunk_indices = (rank, num_chunks - 1 - rank)
|
||||
else: # decodes, and short prefills under DCP, are replicated
|
||||
elif self.shard_decode_requests:
|
||||
chunk_size = query_len
|
||||
# KV and hidden states are gathered back to every PCP rank, so
|
||||
# decode ownership does not need to persist across steps. Use a
|
||||
# compact decode-only ordinal to keep each step exactly
|
||||
# balanced even when prefills and zero-token rows are present.
|
||||
owner_rank = decode_ordinal % self.pcp_world_size
|
||||
decode_ordinal += 1
|
||||
chunk_indices = (0,) if rank == owner_rank else ()
|
||||
else: # DCP requires decode queries on every participating rank.
|
||||
chunk_size = query_len
|
||||
chunk_indices = (0,)
|
||||
|
||||
@@ -348,8 +358,18 @@ class PCPManager:
|
||||
segment.global_batch_slice.stop,
|
||||
dtype=np.int64,
|
||||
)
|
||||
# Cache insertion pairs one slot entry with each rank's local decode.
|
||||
if replicated[segment.global_batch_req_idx] and rank != 0:
|
||||
# Replicated rows contain identical KV, so rank 0 is the
|
||||
# canonical writer. A sharded decode has exactly one owner and
|
||||
# therefore needs no de-duplication here.
|
||||
is_sharded_decode = (
|
||||
not bool(is_prefilling[segment.global_batch_req_idx])
|
||||
and self.shard_decode_requests
|
||||
)
|
||||
if (
|
||||
replicated[segment.global_batch_req_idx]
|
||||
and not is_sharded_decode
|
||||
and rank != 0
|
||||
):
|
||||
continue
|
||||
gathered_kv_write_mask[padded_gathered_slice] = True
|
||||
hidden_restore_idx[segment.global_batch_slice] = np.arange(
|
||||
@@ -406,6 +426,11 @@ class PCPManager:
|
||||
assert self._input_buffers is not None
|
||||
return self._input_buffers
|
||||
|
||||
@property
|
||||
def global_batch(self) -> InputBatch:
|
||||
assert self._global_batch is not None
|
||||
return self._global_batch
|
||||
|
||||
def partition_batch(
|
||||
self, input_batch: InputBatch, batch_desc: "BatchExecutionDescriptor"
|
||||
) -> InputBatch:
|
||||
@@ -646,6 +671,7 @@ class PCPManager:
|
||||
prefill_len_np=local_prefill_len_np,
|
||||
num_computed_prefill_tokens_np=local_num_computed_prefill_tokens_np,
|
||||
is_prefilling_np=local_is_prefilling_np,
|
||||
max_seq_len_np=None,
|
||||
has_prefill=local_has_prefill,
|
||||
decode_graph_eligible=not local_has_prefill,
|
||||
prefill_runs_as_decode_np=None,
|
||||
@@ -825,6 +851,7 @@ def maybe_build_pcp_manager(
|
||||
pcp_world_size=pcp_size,
|
||||
pcp_rank=pcp_rank,
|
||||
device=device,
|
||||
shard_decode_requests=parallel_config.pcp_shard_decode_requests,
|
||||
max_num_reqs=vllm_config.scheduler_config.max_num_seqs,
|
||||
max_num_tokens=vllm_config.scheduler_config.max_num_batched_tokens,
|
||||
block_tables=block_tables,
|
||||
|
||||
@@ -51,7 +51,11 @@ class PoolingRunner:
|
||||
self.pooling_params: dict[int, PoolingParams] = {}
|
||||
self.pooling_states: dict[int, PoolingStates] = {}
|
||||
self.prompt_token_ids: dict[int, torch.Tensor] = {}
|
||||
self.late_interaction_runner = LateInteractionRunner()
|
||||
pooler_config = self.model_config.pooler_config
|
||||
self.late_interaction_runner = LateInteractionRunner(
|
||||
enable_flash=pooler_config is None
|
||||
or getattr(pooler_config, "enable_flash_late_interaction", True)
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def get_supported_tasks(model: nn.Module) -> list[PoolingTask]:
|
||||
|
||||
@@ -37,14 +37,19 @@ class PendingRecv:
|
||||
|
||||
def compute_need_sampled_mask(input_batch: InputBatch) -> np.ndarray | None:
|
||||
"""Return a bool array of shape `[input_batch.num_reqs]` marking requests
|
||||
that produce a sampled token this step, and therefore must have that token
|
||||
(and the draft block proposed from it) propagated to the earlier PP stages.
|
||||
Returns None if no request in the batch produces a sample."""
|
||||
with outputs that might be needed in a subsequent (decode) step.
|
||||
Returns None if no sampled outputs are needed in the requests' next step."""
|
||||
old_computed = input_batch.num_computed_tokens_np
|
||||
prefill_len = input_batch.prefill_len_np
|
||||
# Exclude non-final prefill chunks (they don't produce a sample).
|
||||
produces_sample = old_computed + input_batch.num_scheduled_tokens >= prefill_len
|
||||
return produces_sample if produces_sample.any() else None
|
||||
need_sampled_mask = old_computed + input_batch.num_scheduled_tokens >= prefill_len
|
||||
if input_batch.max_seq_len_np is not None:
|
||||
# Also exclude final prefill chunks whose single sampled token reaches
|
||||
# the request's length cap.
|
||||
finished_prefill = prefill_len + 1 >= input_batch.max_seq_len_np
|
||||
finished_prefill &= input_batch.is_prefilling_np
|
||||
need_sampled_mask &= ~finished_prefill
|
||||
return need_sampled_mask if need_sampled_mask.any() else None
|
||||
|
||||
|
||||
class PPHandler:
|
||||
|
||||
@@ -339,9 +339,16 @@ def _shard_grammar_output(
|
||||
cursor += num_req_logits
|
||||
if not local_ids:
|
||||
return None
|
||||
# num_acceptable_drafts is ordered with structured_output_request_ids.
|
||||
num_acceptable = grammar_output.num_acceptable_drafts
|
||||
if num_acceptable is not None:
|
||||
owned = set(local_ids)
|
||||
ids = grammar_output.structured_output_request_ids
|
||||
num_acceptable = [n for i, n in zip(ids, num_acceptable) if i in owned]
|
||||
return GrammarOutput(
|
||||
structured_output_request_ids=local_ids,
|
||||
grammar_bitmask=grammar_output.grammar_bitmask[keep_indices],
|
||||
num_acceptable_drafts=num_acceptable,
|
||||
)
|
||||
|
||||
|
||||
|
||||
@@ -220,6 +220,8 @@ def gumbel_block_argmax(
|
||||
logits_cache_stride_0,
|
||||
logits_cache_stride_1,
|
||||
logits_cache_col_ptr,
|
||||
logits_cache_source_ptr,
|
||||
logits_cache_source_stride,
|
||||
vocab_size,
|
||||
IS_DRAFTING: tl.constexpr,
|
||||
APPLY_TEMPERATURE: tl.constexpr,
|
||||
@@ -240,12 +242,16 @@ def gumbel_block_argmax(
|
||||
col = tl.load(logits_cache_col_ptr + token_idx)
|
||||
else:
|
||||
col = tl.load(logits_cache_col_ptr)
|
||||
cached_logits = tl.load(
|
||||
logits_cache_source_ptr + token_idx * logits_cache_source_stride + block,
|
||||
mask=mask,
|
||||
)
|
||||
tl.store(
|
||||
logits_cache_ptr
|
||||
+ req_state_idx * logits_cache_stride_0
|
||||
+ col * logits_cache_stride_1
|
||||
+ block,
|
||||
logits,
|
||||
cached_logits,
|
||||
mask=mask & is_valid_req,
|
||||
)
|
||||
|
||||
@@ -275,6 +281,8 @@ def _gumbel_sample_kernel(
|
||||
logits_cache_stride_0,
|
||||
logits_cache_stride_1,
|
||||
logits_cache_col_ptr,
|
||||
logits_cache_source_ptr,
|
||||
logits_cache_source_stride,
|
||||
logits_ptr,
|
||||
logits_stride,
|
||||
expanded_idx_mapping_ptr,
|
||||
@@ -312,6 +320,8 @@ def _gumbel_sample_kernel(
|
||||
logits_cache_stride_0,
|
||||
logits_cache_stride_1,
|
||||
logits_cache_col_ptr,
|
||||
logits_cache_source_ptr,
|
||||
logits_cache_source_stride,
|
||||
vocab_size,
|
||||
IS_DRAFTING=IS_DRAFTING,
|
||||
APPLY_TEMPERATURE=APPLY_TEMPERATURE,
|
||||
@@ -334,6 +344,7 @@ def gumbel_sample(
|
||||
logits_cache: torch.Tensor | None = None, # [max_num_reqs, num_cols, vocab_size]
|
||||
logits_cache_col: torch.Tensor | None = None, # scalar or [num_tokens]
|
||||
use_fp64: bool = False,
|
||||
logits_cache_source: torch.Tensor | None = None,
|
||||
) -> torch.Tensor:
|
||||
# Enforce contiguity on non-strided input tensors
|
||||
expanded_idx_mapping = expanded_idx_mapping.contiguous()
|
||||
@@ -342,11 +353,26 @@ def gumbel_sample(
|
||||
logits_cache_col = logits_cache_col.contiguous()
|
||||
num_tokens, vocab_size = logits.shape
|
||||
if logits_cache is not None:
|
||||
if logits_cache_source is None:
|
||||
logits_cache_source = logits
|
||||
assert logits_cache_source.shape == logits.shape, (
|
||||
"logits cache source must match sampled logits shape"
|
||||
)
|
||||
assert logits_cache_source.device == logits.device, (
|
||||
"logits cache source must be on the sampled logits device"
|
||||
)
|
||||
assert logits_cache_source.dtype == logits_cache.dtype, (
|
||||
"logits cache source and destination must have the same dtype"
|
||||
)
|
||||
assert logits_cache.size(-1) >= vocab_size, (
|
||||
f"draft logits cache vocab dim ({logits_cache.size(-1)}) is narrower "
|
||||
f"than the sampled logits ({vocab_size}). Cached logits would be "
|
||||
"truncated."
|
||||
)
|
||||
elif logits_cache_source is not None:
|
||||
raise ValueError("logits_cache_source requires logits_cache")
|
||||
if logits_cache_source is not None and logits_cache_source.stride(-1) != 1:
|
||||
logits_cache_source = logits_cache_source.contiguous()
|
||||
BLOCK_SIZE = 1024
|
||||
num_blocks = triton.cdiv(vocab_size, BLOCK_SIZE)
|
||||
local_argmax = logits.new_empty(num_tokens, num_blocks, dtype=torch.int64)
|
||||
@@ -362,6 +388,8 @@ def gumbel_sample(
|
||||
logits_cache.stride(0) if logits_cache is not None else 0,
|
||||
logits_cache.stride(1) if logits_cache is not None else 0,
|
||||
logits_cache_col,
|
||||
logits_cache_source,
|
||||
logits_cache_source.stride(0) if logits_cache_source is not None else 0,
|
||||
logits,
|
||||
logits.stride(0),
|
||||
expanded_idx_mapping,
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Sequence
|
||||
from dataclasses import dataclass
|
||||
from typing import NamedTuple
|
||||
|
||||
@@ -27,6 +28,7 @@ def _compact_sampling_mask_kernel(
|
||||
logits_ptr,
|
||||
logits_row_stride,
|
||||
logits_col_stride,
|
||||
cu_num_logits_ptr,
|
||||
num_sampled_tokens_ptr,
|
||||
token_ids_ptr,
|
||||
token_ids_row_stride,
|
||||
@@ -35,25 +37,32 @@ def _compact_sampling_mask_kernel(
|
||||
counts_ptr,
|
||||
vocab_size,
|
||||
max_num_kept,
|
||||
ROWS_PER_REQUEST: tl.constexpr,
|
||||
BLOCK_SIZE: tl.constexpr,
|
||||
):
|
||||
"""Per row: first ``max_num_kept`` finite-logit ids, the full count, the bitmask."""
|
||||
req_idx = tl.program_id(0)
|
||||
is_active = tl.load(num_sampled_tokens_ptr + req_idx) > 0
|
||||
output_row = tl.program_id(0)
|
||||
req_idx = output_row // ROWS_PER_REQUEST
|
||||
slot_idx = output_row % ROWS_PER_REQUEST
|
||||
if slot_idx >= tl.load(num_sampled_tokens_ptr + req_idx):
|
||||
tl.store(counts_ptr + output_row, 0)
|
||||
return
|
||||
source_row = tl.load(cu_num_logits_ptr + req_idx) + slot_idx
|
||||
|
||||
count = tl.zeros((), dtype=tl.int32)
|
||||
|
||||
for start_idx in range(0, vocab_size, BLOCK_SIZE):
|
||||
offsets = start_idx + tl.arange(0, BLOCK_SIZE)
|
||||
logits = tl.load(
|
||||
logits_ptr + req_idx * logits_row_stride + offsets * logits_col_stride,
|
||||
logits_ptr + source_row * logits_row_stride + offsets * logits_col_stride,
|
||||
mask=offsets < vocab_size,
|
||||
other=-float("inf"),
|
||||
)
|
||||
keep = (logits > -float("inf")) & (logits < float("inf")) & is_active
|
||||
keep = (logits > -float("inf")) & (logits < float("inf"))
|
||||
keep_i32 = keep.to(tl.int32)
|
||||
pos = count + tl.cumsum(keep_i32, axis=0) - keep_i32
|
||||
tl.store(
|
||||
token_ids_ptr + req_idx * token_ids_row_stride + pos,
|
||||
token_ids_ptr + output_row * token_ids_row_stride + pos,
|
||||
offsets.to(tl.int32),
|
||||
mask=keep & (pos < max_num_kept),
|
||||
)
|
||||
@@ -62,12 +71,12 @@ def _compact_sampling_mask_kernel(
|
||||
bits = tl.reshape(keep_i32, (BLOCK_SIZE // 8, 8)) << tl.arange(0, 8)[None, :]
|
||||
byte_offsets = start_idx // 8 + tl.arange(0, BLOCK_SIZE // 8)
|
||||
tl.store(
|
||||
packed_mask_ptr + req_idx * packed_mask_row_stride + byte_offsets,
|
||||
packed_mask_ptr + output_row * packed_mask_row_stride + byte_offsets,
|
||||
tl.sum(bits, axis=1).to(tl.uint8),
|
||||
mask=byte_offsets < tl.cdiv(vocab_size, 8),
|
||||
)
|
||||
|
||||
tl.store(counts_ptr + req_idx, count)
|
||||
tl.store(counts_ptr + output_row, count)
|
||||
|
||||
|
||||
# Bounds the [num_reqs, width] int32 buffer; wider rows use the bitmask instead.
|
||||
@@ -78,37 +87,46 @@ class SamplingMaskTensors(NamedTuple):
|
||||
"""Device-side masks pending async D2H: compact ids, plus the bitmask as
|
||||
the exact fallback for rows wider than ``max_num_kept``."""
|
||||
|
||||
# [num_requests, max_num_kept]
|
||||
# [num_requests * rows_per_request, max_num_kept]
|
||||
token_ids: torch.Tensor
|
||||
# [num_requests, ceil(vocab_size / 8)]
|
||||
# [num_requests * rows_per_request, ceil(vocab_size / 8)]
|
||||
packed_mask: torch.Tensor
|
||||
# [num_requests]
|
||||
# [num_requests * rows_per_request]
|
||||
counts: torch.Tensor
|
||||
vocab_size: int
|
||||
# Fixed request-major output slots. Ordinary sampling has one slot.
|
||||
rows_per_request: int = 1
|
||||
|
||||
@classmethod
|
||||
def from_logits(
|
||||
cls,
|
||||
logits: torch.Tensor,
|
||||
cu_num_logits: torch.Tensor,
|
||||
num_sampled_tokens: torch.Tensor,
|
||||
max_num_kept: int,
|
||||
rows_per_request: int = 1,
|
||||
) -> SamplingMaskTensors:
|
||||
"""Capture the finite-logit support of every row with a sampled token."""
|
||||
num_reqs, vocab_size = logits.shape
|
||||
"""Capture committed target supports in fixed request-major slots."""
|
||||
num_reqs = num_sampled_tokens.shape[0]
|
||||
vocab_size = logits.shape[1]
|
||||
max_num_kept = min(max_num_kept, vocab_size, MAX_COMPACT_SUPPORT)
|
||||
num_output_rows = num_reqs * rows_per_request
|
||||
device = logits.device
|
||||
|
||||
token_ids = torch.empty(
|
||||
(num_reqs, max_num_kept), dtype=torch.int32, device=device
|
||||
(num_output_rows, max_num_kept), dtype=torch.int32, device=device
|
||||
)
|
||||
packed_mask = torch.empty(
|
||||
(num_reqs, (vocab_size + 7) // 8), dtype=torch.uint8, device=device
|
||||
(num_output_rows, (vocab_size + 7) // 8),
|
||||
dtype=torch.uint8,
|
||||
device=device,
|
||||
)
|
||||
counts = torch.empty(num_reqs, dtype=torch.int32, device=device)
|
||||
_compact_sampling_mask_kernel[(num_reqs,)](
|
||||
counts = torch.empty(num_output_rows, dtype=torch.int32, device=device)
|
||||
_compact_sampling_mask_kernel[(num_output_rows,)](
|
||||
logits,
|
||||
logits.stride(0),
|
||||
logits.stride(1),
|
||||
cu_num_logits,
|
||||
num_sampled_tokens,
|
||||
token_ids,
|
||||
token_ids.stride(0),
|
||||
@@ -117,9 +135,23 @@ class SamplingMaskTensors(NamedTuple):
|
||||
counts,
|
||||
vocab_size,
|
||||
max_num_kept,
|
||||
ROWS_PER_REQUEST=rows_per_request,
|
||||
BLOCK_SIZE=8192,
|
||||
)
|
||||
return cls(token_ids, packed_mask, counts, vocab_size)
|
||||
return cls(token_ids, packed_mask, counts, vocab_size, rows_per_request)
|
||||
|
||||
@classmethod
|
||||
def cat(cls, chunks: Sequence[SamplingMaskTensors]) -> SamplingMaskTensors:
|
||||
"""Join request-contiguous chunks that share one output layout."""
|
||||
first = chunks[0]
|
||||
assert len({(c.vocab_size, c.rows_per_request) for c in chunks}) == 1
|
||||
return cls(
|
||||
torch.cat([chunk.token_ids for chunk in chunks]),
|
||||
torch.cat([chunk.packed_mask for chunk in chunks]),
|
||||
torch.cat([chunk.counts for chunk in chunks]),
|
||||
first.vocab_size,
|
||||
first.rows_per_request,
|
||||
)
|
||||
|
||||
def to_cpu_nonblocking(self) -> SamplingMaskTensors:
|
||||
if self.token_ids.device.type == "cpu":
|
||||
@@ -129,15 +161,31 @@ class SamplingMaskTensors(NamedTuple):
|
||||
self.packed_mask.to("cpu", non_blocking=True),
|
||||
self.counts.to("cpu", non_blocking=True),
|
||||
self.vocab_size,
|
||||
self.rows_per_request,
|
||||
)
|
||||
|
||||
def tolists(self) -> SamplingMaskLists:
|
||||
"""CSR over all requests; rows without a sampled token are empty."""
|
||||
def tolists(
|
||||
self, num_sampled_tokens: np.ndarray | None = None
|
||||
) -> SamplingMaskLists:
|
||||
"""Convert fixed output rows to the scheduler's CSR representation."""
|
||||
counts = self.counts.cpu().numpy()
|
||||
token_ids = self.token_ids.cpu().numpy()
|
||||
packed_mask = self.packed_mask.cpu().numpy()
|
||||
width = token_ids.shape[1]
|
||||
|
||||
cu_num_generated_tokens = None
|
||||
if self.rows_per_request == 1:
|
||||
sampled_rows = np.arange(len(counts))
|
||||
else:
|
||||
assert num_sampled_tokens is not None
|
||||
active_slots = (
|
||||
np.arange(self.rows_per_request)[None, :] < num_sampled_tokens[:, None]
|
||||
)
|
||||
sampled_rows = np.flatnonzero(active_slots)
|
||||
cu_num_generated_tokens = np.cumsum(
|
||||
np.concatenate(([0], num_sampled_tokens))
|
||||
).tolist()
|
||||
|
||||
def support(row: int) -> np.ndarray:
|
||||
if counts[row] <= width:
|
||||
return token_ids[row, : counts[row]]
|
||||
@@ -147,7 +195,8 @@ class SamplingMaskTensors(NamedTuple):
|
||||
)
|
||||
return np.flatnonzero(bits).astype(np.int32, copy=False)
|
||||
|
||||
supports = [support(row) for row in range(len(counts))]
|
||||
supports = [support(row) for row in sampled_rows]
|
||||
offsets = np.zeros(len(supports) + 1, dtype=np.int64)
|
||||
np.cumsum([len(s) for s in supports], out=offsets[1:])
|
||||
return SamplingMaskLists(np.concatenate(supports), offsets)
|
||||
flat = np.concatenate([np.empty(0, dtype=np.int32), *supports])
|
||||
return SamplingMaskLists(flat, offsets, cu_num_generated_tokens)
|
||||
|
||||
@@ -203,7 +203,10 @@ class Sampler:
|
||||
# Size by the validated top_k batch max; wider supports use the bitmask.
|
||||
max_num_kept = int(np.max(self.sampling_states.top_k.np[idx_mapping_np]))
|
||||
sampling_mask_tensors = SamplingMaskTensors.from_logits(
|
||||
processed_logits, num_sampled, max_num_kept
|
||||
processed_logits,
|
||||
input_batch.cu_num_logits,
|
||||
num_sampled,
|
||||
max_num_kept,
|
||||
)
|
||||
|
||||
# These are GPU tensors.
|
||||
|
||||
@@ -51,12 +51,25 @@ def _repeated_context_mask_kernel(
|
||||
req_indices_ptr,
|
||||
prompt_lens_ptr,
|
||||
total_lens_ptr,
|
||||
history_offsets_ptr,
|
||||
history_offsets_stride,
|
||||
contexts_ptr,
|
||||
context_stride,
|
||||
local_positions_ptr,
|
||||
prior_contexts_ptr,
|
||||
prior_contexts_stride_0,
|
||||
prior_contexts_stride_1,
|
||||
steps_ptr,
|
||||
steps_stride,
|
||||
enabled_ptr,
|
||||
CONTEXT_WIDTH: tl.constexpr,
|
||||
NUM_SPECULATIVE_STEPS: tl.constexpr,
|
||||
MAX_HISTORY: tl.constexpr,
|
||||
INCLUDE_PROMPT: tl.constexpr,
|
||||
SKIP_PARTIAL_CONTEXT: tl.constexpr,
|
||||
HAS_HISTORY_OFFSETS: tl.constexpr,
|
||||
SPECULATIVE_CONTEXTS: tl.constexpr,
|
||||
DRAFT_CONTEXTS: tl.constexpr,
|
||||
BLOCK: tl.constexpr,
|
||||
):
|
||||
row = tl.program_id(0).to(tl.int64)
|
||||
@@ -71,12 +84,16 @@ def _repeated_context_mask_kernel(
|
||||
return
|
||||
sequence_start = 0 if INCLUDE_PROMPT else prompt_len
|
||||
history_len = total_len - sequence_start
|
||||
history_offset = 0
|
||||
if HAS_HISTORY_OFFSETS:
|
||||
history_offset = tl.load(history_offsets_ptr + row * history_offsets_stride)
|
||||
|
||||
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)
|
||||
remaining_history = tl.maximum(MAX_HISTORY - history_offset, 0)
|
||||
scan_start = tl.maximum(history_len - remaining_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):
|
||||
@@ -96,6 +113,93 @@ def _repeated_context_mask_kernel(
|
||||
)
|
||||
matches &= historical_token == context_token
|
||||
repeated |= tl.max(matches.to(tl.int32), axis=0)
|
||||
|
||||
if SPECULATIVE_CONTEXTS:
|
||||
local_pos = tl.load(local_positions_ptr + row)
|
||||
if INCLUDE_PROMPT:
|
||||
partial_context = tl.full((), 0, tl.int32)
|
||||
for context_offset in range(CONTEXT_WIDTH):
|
||||
context_token = tl.load(
|
||||
contexts_ptr + row * context_stride + context_offset
|
||||
)
|
||||
partial_context |= context_token < 0
|
||||
repeated |= partial_context
|
||||
for offset in range(1, NUM_SPECULATIVE_STEPS + 1):
|
||||
prior_row = row - offset
|
||||
in_history = (prior_row >= 0) & (local_pos >= offset)
|
||||
if MAX_HISTORY > 0:
|
||||
in_history &= offset <= MAX_HISTORY
|
||||
prior_req_idx = tl.load(
|
||||
req_indices_ptr + tl.maximum(prior_row, 0),
|
||||
mask=in_history,
|
||||
other=-1,
|
||||
)
|
||||
prior_local_pos = tl.load(
|
||||
local_positions_ptr + tl.maximum(prior_row, 0),
|
||||
mask=in_history,
|
||||
other=-1,
|
||||
)
|
||||
matches = (
|
||||
in_history
|
||||
& (req_idx == prior_req_idx)
|
||||
& (local_pos == prior_local_pos + offset)
|
||||
)
|
||||
for context_offset in range(CONTEXT_WIDTH):
|
||||
context_token = tl.load(
|
||||
contexts_ptr + row * context_stride + context_offset
|
||||
)
|
||||
prior_token = tl.load(
|
||||
contexts_ptr
|
||||
+ tl.maximum(prior_row, 0) * context_stride
|
||||
+ context_offset,
|
||||
mask=in_history,
|
||||
other=-2,
|
||||
)
|
||||
matches &= context_token == prior_token
|
||||
repeated |= matches
|
||||
|
||||
if DRAFT_CONTEXTS:
|
||||
step = tl.load(steps_ptr + row * steps_stride).to(tl.int64)
|
||||
partial_context = tl.full((), 0, tl.int32)
|
||||
for context_offset in range(CONTEXT_WIDTH):
|
||||
context_token = tl.load(
|
||||
contexts_ptr + row * context_stride + context_offset
|
||||
)
|
||||
partial_context |= context_token < 0
|
||||
if INCLUDE_PROMPT:
|
||||
repeated |= partial_context
|
||||
|
||||
for prior_step in range(NUM_SPECULATIVE_STEPS):
|
||||
in_history = prior_step < step
|
||||
if MAX_HISTORY > 0:
|
||||
in_history &= prior_step >= step - MAX_HISTORY
|
||||
matches = in_history
|
||||
for context_offset in range(CONTEXT_WIDTH):
|
||||
context_token = tl.load(
|
||||
contexts_ptr + row * context_stride + context_offset
|
||||
)
|
||||
prior_token = tl.load(
|
||||
prior_contexts_ptr
|
||||
+ row * prior_contexts_stride_0
|
||||
+ prior_step * prior_contexts_stride_1
|
||||
+ context_offset
|
||||
)
|
||||
matches &= context_token == prior_token
|
||||
repeated |= matches
|
||||
|
||||
for context_offset in range(CONTEXT_WIDTH):
|
||||
context_token = tl.load(
|
||||
contexts_ptr + row * context_stride + context_offset
|
||||
)
|
||||
tl.store(
|
||||
prior_contexts_ptr
|
||||
+ row * prior_contexts_stride_0
|
||||
+ step * prior_contexts_stride_1
|
||||
+ context_offset,
|
||||
context_token,
|
||||
)
|
||||
enabled = tl.load(enabled_ptr + row)
|
||||
repeated = enabled & (repeated == 0)
|
||||
tl.store(output_ptr + row, repeated)
|
||||
|
||||
|
||||
@@ -108,6 +212,7 @@ def _repeated_context_mask_cpu(
|
||||
max_history: int | None = None,
|
||||
include_prompt: bool = False,
|
||||
skip_partial_context: bool = False,
|
||||
history_offsets: torch.Tensor | None = None,
|
||||
) -> torch.Tensor:
|
||||
"""Reference implementation; the parity tests check the Triton kernel against it."""
|
||||
repeated = torch.zeros(len(req_indices), dtype=torch.bool)
|
||||
@@ -124,8 +229,11 @@ def _repeated_context_mask_cpu(
|
||||
history_tokens = all_token_ids[req_idx, sequence_start:total_len].tolist()
|
||||
prefix = [-1] * contexts.shape[-1]
|
||||
current_context = tuple(contexts[row].tolist())
|
||||
history_offset = 0 if history_offsets is None else int(history_offsets[row])
|
||||
history_start = (
|
||||
max(0, len(history_tokens) - max_history) if max_history is not None else 0
|
||||
max(0, len(history_tokens) - max(0, max_history - history_offset))
|
||||
if max_history is not None
|
||||
else 0
|
||||
)
|
||||
for history_pos, token_id in enumerate(history_tokens):
|
||||
if history_pos >= history_start and (
|
||||
@@ -146,6 +254,9 @@ def repeated_context_mask(
|
||||
max_history: int | None = None,
|
||||
include_prompt: bool = False,
|
||||
skip_partial_context: bool = False,
|
||||
history_offsets: torch.Tensor | None = None,
|
||||
local_positions: torch.Tensor | None = None,
|
||||
num_speculative_steps: int = 0,
|
||||
) -> torch.Tensor:
|
||||
"""Return, per row, whether the row's context already occurred in its history.
|
||||
|
||||
@@ -163,12 +274,23 @@ def repeated_context_mask(
|
||||
include_prompt: Search the prompt as well as the generated tokens.
|
||||
skip_partial_context: Mark contexts containing start padding so they use
|
||||
ordinary sampling.
|
||||
history_offsets: Number of newer, non-committed positions preceding each
|
||||
context. These positions count toward `max_history`. Must be 1-D
|
||||
over rows; a stride-0 broadcast row is fine.
|
||||
local_positions: Position within each request's speculative block. When
|
||||
provided, compare each context with earlier contexts in that block.
|
||||
num_speculative_steps: Maximum number of draft tokens in the block.
|
||||
|
||||
"""
|
||||
if max_history is not None and max_history < 1:
|
||||
raise ValueError("max_history must be positive or None")
|
||||
if (local_positions is None) != (num_speculative_steps == 0):
|
||||
raise ValueError(
|
||||
"local_positions and positive num_speculative_steps must be "
|
||||
"provided together"
|
||||
)
|
||||
if all_token_ids.device.type == "cpu":
|
||||
return _repeated_context_mask_cpu(
|
||||
repeated = _repeated_context_mask_cpu(
|
||||
all_token_ids,
|
||||
req_indices,
|
||||
prompt_lens,
|
||||
@@ -177,10 +299,42 @@ def repeated_context_mask(
|
||||
max_history,
|
||||
include_prompt,
|
||||
skip_partial_context,
|
||||
history_offsets,
|
||||
)
|
||||
if local_positions is not None:
|
||||
max_offset = num_speculative_steps + 1
|
||||
if max_history is not None:
|
||||
max_offset = min(max_offset, max_history + 1)
|
||||
for offset in range(1, max_offset):
|
||||
prior_contexts = torch.cat(
|
||||
(contexts[:offset], contexts[:-offset]), dim=0
|
||||
)
|
||||
prior_requests = torch.cat(
|
||||
(req_indices[:offset], req_indices[:-offset]), dim=0
|
||||
)
|
||||
prior_local_pos = torch.cat(
|
||||
(local_positions[:offset], local_positions[:-offset]), dim=0
|
||||
)
|
||||
repeated |= (
|
||||
(req_indices >= 0)
|
||||
& (local_positions >= offset)
|
||||
& (req_indices == prior_requests)
|
||||
& (local_positions == prior_local_pos + offset)
|
||||
& (contexts == prior_contexts).all(dim=-1)
|
||||
)
|
||||
if include_prompt:
|
||||
repeated |= (contexts < 0).any(dim=-1)
|
||||
return repeated
|
||||
|
||||
if contexts.stride(-1) != 1:
|
||||
contexts = contexts.contiguous()
|
||||
# Only history_offsets passes its row stride to the kernel.
|
||||
req_indices = req_indices.contiguous()
|
||||
if local_positions is not None:
|
||||
local_positions = local_positions.contiguous()
|
||||
# `prompt_lens` and `total_lens` are indexed flat by request slot, and
|
||||
# `all_token_ids` takes a row stride but is read flat within the row. Those
|
||||
# three are contiguous by contract; every caller owns them outright.
|
||||
repeated = torch.empty(len(req_indices), dtype=torch.bool, device=contexts.device)
|
||||
_repeated_context_mask_kernel[(len(req_indices),)](
|
||||
repeated,
|
||||
@@ -189,17 +343,104 @@ def repeated_context_mask(
|
||||
req_indices,
|
||||
prompt_lens,
|
||||
total_lens,
|
||||
history_offsets,
|
||||
0 if history_offsets is None else history_offsets.stride(0),
|
||||
contexts,
|
||||
contexts.stride(0),
|
||||
local_positions,
|
||||
None,
|
||||
0,
|
||||
0,
|
||||
None,
|
||||
0,
|
||||
None,
|
||||
CONTEXT_WIDTH=contexts.shape[-1],
|
||||
NUM_SPECULATIVE_STEPS=num_speculative_steps,
|
||||
MAX_HISTORY=0 if max_history is None else max_history,
|
||||
INCLUDE_PROMPT=include_prompt,
|
||||
SKIP_PARTIAL_CONTEXT=skip_partial_context,
|
||||
HAS_HISTORY_OFFSETS=history_offsets is not None,
|
||||
SPECULATIVE_CONTEXTS=local_positions is not None,
|
||||
DRAFT_CONTEXTS=False,
|
||||
BLOCK=512,
|
||||
)
|
||||
return repeated
|
||||
|
||||
|
||||
def draft_watermarking_mask(
|
||||
all_token_ids: torch.Tensor,
|
||||
req_indices: torch.Tensor,
|
||||
prompt_lens: torch.Tensor,
|
||||
total_lens: torch.Tensor,
|
||||
prior_contexts: torch.Tensor,
|
||||
contexts: torch.Tensor,
|
||||
steps: torch.Tensor,
|
||||
enabled: torch.Tensor,
|
||||
max_history: int | None,
|
||||
include_prompt: bool,
|
||||
) -> torch.Tensor:
|
||||
if contexts.device.type == "cpu":
|
||||
repeated = repeated_context_mask(
|
||||
all_token_ids,
|
||||
req_indices,
|
||||
prompt_lens,
|
||||
total_lens,
|
||||
contexts,
|
||||
max_history,
|
||||
include_prompt=include_prompt,
|
||||
history_offsets=steps,
|
||||
)
|
||||
prior_steps = torch.arange(prior_contexts.shape[1]).unsqueeze(0)
|
||||
in_history = prior_steps < steps.unsqueeze(1)
|
||||
if max_history is not None:
|
||||
in_history &= prior_steps >= steps.unsqueeze(1) - max_history
|
||||
repeated |= (
|
||||
(prior_contexts[: len(contexts)] == contexts.unsqueeze(1)).all(dim=-1)
|
||||
& in_history
|
||||
).any(dim=-1)
|
||||
if include_prompt:
|
||||
repeated |= (contexts < 0).any(dim=-1)
|
||||
row_indices = torch.arange(len(contexts))
|
||||
prior_contexts.index_put_((row_indices, steps), contexts)
|
||||
return enabled & ~repeated
|
||||
|
||||
if contexts.stride(-1) != 1:
|
||||
contexts = contexts.contiguous()
|
||||
# Only `steps` passes its row stride to the kernel.
|
||||
req_indices = req_indices.contiguous()
|
||||
enabled = enabled.contiguous()
|
||||
active = torch.empty(len(contexts), dtype=torch.bool, device=contexts.device)
|
||||
_repeated_context_mask_kernel[(len(contexts),)](
|
||||
active,
|
||||
all_token_ids,
|
||||
all_token_ids.stride(0),
|
||||
req_indices,
|
||||
prompt_lens,
|
||||
total_lens,
|
||||
steps,
|
||||
steps.stride(0),
|
||||
contexts,
|
||||
contexts.stride(0),
|
||||
None,
|
||||
prior_contexts,
|
||||
prior_contexts.stride(0),
|
||||
prior_contexts.stride(1),
|
||||
steps,
|
||||
steps.stride(0),
|
||||
enabled,
|
||||
NUM_SPECULATIVE_STEPS=prior_contexts.shape[1],
|
||||
CONTEXT_WIDTH=contexts.shape[1],
|
||||
MAX_HISTORY=0 if max_history is None else max_history,
|
||||
INCLUDE_PROMPT=include_prompt,
|
||||
SKIP_PARTIAL_CONTEXT=False,
|
||||
HAS_HISTORY_OFFSETS=True,
|
||||
SPECULATIVE_CONTEXTS=False,
|
||||
DRAFT_CONTEXTS=True,
|
||||
BLOCK=512,
|
||||
)
|
||||
return active
|
||||
|
||||
|
||||
@triton.jit
|
||||
def _mulhilo32(multiplier: tl.constexpr, value):
|
||||
high = tl_math.umulhi(multiplier, value)
|
||||
@@ -351,28 +592,58 @@ def _philox_gumbel_kernel(
|
||||
seeds_ptr,
|
||||
pos_ptr,
|
||||
temp_ptr,
|
||||
logits_cache_ptr,
|
||||
logits_cache_stride_0,
|
||||
logits_cache_stride_1,
|
||||
logits_cache_col_ptr,
|
||||
logits_cache_source_ptr,
|
||||
logits_cache_source_stride,
|
||||
key_0_value,
|
||||
key_1_value,
|
||||
vocab_size,
|
||||
CONTEXT_WIDTH: tl.constexpr,
|
||||
BLOCK_SIZE: tl.constexpr,
|
||||
USE_FP64: tl.constexpr,
|
||||
IS_DRAFTING: tl.constexpr,
|
||||
PER_TOKEN_COL: 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)
|
||||
candidate = block_index * BLOCK_SIZE + tl.arange(0, BLOCK_SIZE)
|
||||
mask = candidate < vocab_size
|
||||
|
||||
if skip_mask_ptr is not None:
|
||||
req_state_idx = row
|
||||
valid_req = True
|
||||
if expanded_idx_mapping_ptr is not None:
|
||||
req_state_idx = tl.load(expanded_idx_mapping_ptr + row).to(tl.int64)
|
||||
valid_req = req_state_idx >= 0
|
||||
|
||||
if logits_cache_ptr is not None:
|
||||
if PER_TOKEN_COL:
|
||||
col = tl.load(logits_cache_col_ptr + row)
|
||||
else:
|
||||
col = tl.load(logits_cache_col_ptr)
|
||||
cached_logits = tl.load(
|
||||
logits_cache_source_ptr + row * logits_cache_source_stride + candidate,
|
||||
mask=mask,
|
||||
)
|
||||
tl.store(
|
||||
logits_cache_ptr
|
||||
+ req_state_idx * logits_cache_stride_0
|
||||
+ col * logits_cache_stride_1
|
||||
+ candidate,
|
||||
cached_logits,
|
||||
mask=mask & valid_req,
|
||||
)
|
||||
|
||||
if skip_mask_ptr is not None: # noqa: SIM102
|
||||
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
|
||||
@@ -384,7 +655,7 @@ def _philox_gumbel_kernel(
|
||||
seed,
|
||||
pos,
|
||||
temp,
|
||||
IS_DRAFTING=False,
|
||||
IS_DRAFTING=IS_DRAFTING,
|
||||
USE_FP64=USE_FP64,
|
||||
APPLY_TEMPERATURE=False,
|
||||
)
|
||||
@@ -443,12 +714,37 @@ def philox_gumbel_sample(
|
||||
seeds: torch.Tensor | None = None,
|
||||
positions: torch.Tensor | None = None,
|
||||
use_fp64: bool = False,
|
||||
is_drafting: bool = False,
|
||||
logits_cache: torch.Tensor | None = None,
|
||||
logits_cache_col: torch.Tensor | None = None,
|
||||
logits_cache_source: torch.Tensor | None = None,
|
||||
) -> 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_cache is not None:
|
||||
if logits_cache_col is None or logits_cache_source is None:
|
||||
raise ValueError("logits cache requires its column and source logits")
|
||||
if expanded_idx_mapping is None:
|
||||
raise ValueError("logits cache requires expanded_idx_mapping")
|
||||
assert logits_cache_source.shape == logits.shape, (
|
||||
"logits cache source must match sampled logits shape"
|
||||
)
|
||||
assert logits_cache_source.device == logits.device, (
|
||||
"logits cache source must be on the sampled logits device"
|
||||
)
|
||||
assert logits_cache_source.dtype == logits_cache.dtype, (
|
||||
"logits cache source and destination must have the same dtype"
|
||||
)
|
||||
assert logits_cache.size(-1) >= logits.shape[-1], (
|
||||
f"draft logits cache vocab dim ({logits_cache.size(-1)}) is narrower "
|
||||
f"than the sampled logits ({logits.shape[-1]}). Cached logits would be "
|
||||
"truncated."
|
||||
)
|
||||
elif logits_cache_col is not None or logits_cache_source is not None:
|
||||
raise ValueError("logits cache column and source require logits_cache")
|
||||
|
||||
if logits.stride(-1) != 1:
|
||||
logits = logits.contiguous()
|
||||
@@ -460,6 +756,10 @@ def philox_gumbel_sample(
|
||||
expanded_idx_mapping = expanded_idx_mapping.contiguous()
|
||||
if positions is not None:
|
||||
positions = positions.contiguous()
|
||||
if logits_cache_col is not None:
|
||||
logits_cache_col = logits_cache_col.contiguous()
|
||||
if logits_cache_source is not None and logits_cache_source.stride(-1) != 1:
|
||||
logits_cache_source = logits_cache_source.contiguous()
|
||||
num_tokens, vocab_size = logits.shape
|
||||
block_size = 1024
|
||||
num_blocks = triton.cdiv(vocab_size, block_size)
|
||||
@@ -483,12 +783,20 @@ def philox_gumbel_sample(
|
||||
seeds,
|
||||
positions,
|
||||
temperatures,
|
||||
logits_cache,
|
||||
logits_cache.stride(0) if logits_cache is not None else 0,
|
||||
logits_cache.stride(1) if logits_cache is not None else 0,
|
||||
logits_cache_col,
|
||||
logits_cache_source,
|
||||
logits_cache_source.stride(0) if logits_cache_source is not None else 0,
|
||||
key & _UINT32_MASK_VALUE,
|
||||
key >> 32,
|
||||
vocab_size,
|
||||
CONTEXT_WIDTH=contexts.shape[-1],
|
||||
BLOCK_SIZE=block_size,
|
||||
USE_FP64=use_fp64,
|
||||
IS_DRAFTING=is_drafting,
|
||||
PER_TOKEN_COL=logits_cache_col is not None and logits_cache_col.dim() > 0,
|
||||
)
|
||||
max_block_index = local_max.argmax(dim=-1, keepdim=True)
|
||||
return local_argmax.gather(dim=-1, index=max_block_index).view(-1)
|
||||
|
||||
@@ -135,7 +135,12 @@ 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.
|
||||
sampled = gumbel_sample(
|
||||
sampler = (
|
||||
gumbel_sample
|
||||
if self.draft_watermarker is None
|
||||
else self.draft_watermarker.sample
|
||||
)
|
||||
return sampler(
|
||||
logits,
|
||||
idx_map,
|
||||
self.temperature,
|
||||
@@ -147,11 +152,6 @@ 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:
|
||||
|
||||
@@ -13,10 +13,14 @@ from vllm.v1.worker.gpu.spec_decode.utils import get_pp_safe_draft_load_config
|
||||
|
||||
|
||||
def _should_share(eagle: nn.Module, flag: str, draft, target) -> bool:
|
||||
"""Share when the draft has no own copy, or its copy matches the target."""
|
||||
if not getattr(eagle, flag, False) or draft is None:
|
||||
"""Share unless the draft declares its own copy that differs from the target.
|
||||
|
||||
A draft that declares its own copy but has no top-level one (e.g. MTP
|
||||
heads stored per layer) keeps it.
|
||||
"""
|
||||
if not getattr(eagle, flag, False):
|
||||
return True
|
||||
if target is None:
|
||||
if draft is None or target is None:
|
||||
return False
|
||||
# torch.equal on GPU allocates a bool mask the size of the input.
|
||||
# Use the faster GPU path when there is plenty of headroom;
|
||||
|
||||
@@ -253,6 +253,17 @@ class MultiModuleMTPSpeculator(DraftModelSpeculator):
|
||||
)
|
||||
return self.draft_tokens[:num_reqs]
|
||||
|
||||
# Each MTP module may carry its own LM head, selected by spec_step_idx.
|
||||
def compute_draft_logits(
|
||||
self, hidden_states: torch.Tensor, spec_step_idx: int
|
||||
) -> torch.Tensor:
|
||||
return self.model.compute_logits(hidden_states, spec_step_idx=spec_step_idx)
|
||||
|
||||
def get_draft_top_tokens(
|
||||
self, hidden_states: torch.Tensor, spec_step_idx: int
|
||||
) -> torch.Tensor:
|
||||
return self.model.get_top_tokens(hidden_states, spec_step_idx=spec_step_idx)
|
||||
|
||||
@torch.inference_mode()
|
||||
def _run_model(
|
||||
self,
|
||||
@@ -427,6 +438,7 @@ class MultiModuleMTPSpeculator(DraftModelSpeculator):
|
||||
self.seeds,
|
||||
self.current_draft_step,
|
||||
self.draft_logits,
|
||||
spec_step_idx=step,
|
||||
)
|
||||
|
||||
self.draft_tokens[:num_reqs, step] = draft_tokens
|
||||
|
||||
@@ -18,7 +18,7 @@ from vllm.v1.worker.gpu.input_batch import (
|
||||
)
|
||||
from vllm.v1.worker.gpu.metrics.logits import get_num_nans
|
||||
from vllm.v1.worker.gpu.sample.logprob import compute_topk_scores
|
||||
from vllm.v1.worker.gpu.sample.output import SamplerOutput
|
||||
from vllm.v1.worker.gpu.sample.output import SamplerOutput, SamplingMaskTensors
|
||||
from vllm.v1.worker.gpu.sample.sampler import Sampler
|
||||
from vllm.v1.worker.gpu.sample.states import NO_LOGPROBS
|
||||
from vllm.v1.worker.gpu.spec_decode.rejection_sampler_utils import (
|
||||
@@ -226,11 +226,18 @@ class RejectionSampler:
|
||||
if self.watermark_key is None:
|
||||
return {}
|
||||
assert isinstance(self.sampler, GPUWatermarkSampler)
|
||||
contexts = self.sampler._get_contexts(
|
||||
expanded_idx_mapping, expanded_local_pos, draft_sampled
|
||||
)
|
||||
watermarking_skip_mask = None
|
||||
if self.sampler.deduplicate_contexts != "none":
|
||||
watermarking_skip_mask = self.sampler._get_repeated_contexts(
|
||||
expanded_idx_mapping, contexts, expanded_local_pos
|
||||
)
|
||||
return {
|
||||
"contexts": self.sampler._get_contexts(
|
||||
expanded_idx_mapping, expanded_local_pos, draft_sampled
|
||||
),
|
||||
"contexts": contexts,
|
||||
"watermarking": self.sampler.watermarking.gpu,
|
||||
"watermarking_skip_mask": watermarking_skip_mask,
|
||||
"watermark_key": self.watermark_key,
|
||||
}
|
||||
|
||||
@@ -246,6 +253,7 @@ class RejectionSampler:
|
||||
expanded_idx_mapping: torch.Tensor,
|
||||
expanded_local_pos: torch.Tensor,
|
||||
seq_lens_upper_bound_np: np.ndarray,
|
||||
verify_draft_sampled: torch.Tensor,
|
||||
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
|
||||
processed_logits = self.sampler.apply_sampling_params(
|
||||
logits,
|
||||
@@ -260,7 +268,7 @@ class RejectionSampler:
|
||||
sampled, num_sampled = rejection_sample(
|
||||
processed_logits,
|
||||
draft_logits,
|
||||
draft_sampled,
|
||||
verify_draft_sampled,
|
||||
cu_num_logits,
|
||||
pos,
|
||||
idx_mapping,
|
||||
@@ -287,7 +295,15 @@ class RejectionSampler:
|
||||
pos: torch.Tensor,
|
||||
max_chunk_logits: int,
|
||||
max_num_logprobs: int,
|
||||
) -> tuple[torch.Tensor, torch.Tensor, LogprobsTensors | None]:
|
||||
verify_draft_sampled: torch.Tensor | None = None,
|
||||
) -> tuple[
|
||||
torch.Tensor,
|
||||
torch.Tensor,
|
||||
LogprobsTensors | None,
|
||||
SamplingMaskTensors | None,
|
||||
]:
|
||||
if verify_draft_sampled is None:
|
||||
verify_draft_sampled = draft_sampled
|
||||
cu_num_logits_np = input_batch.cu_num_logits_np
|
||||
use_processed_logits = self.sampler.logprobs_mode in PROCESSED_LOGPROBS_MODES
|
||||
num_reqs = input_batch.num_reqs
|
||||
@@ -305,6 +321,14 @@ class RejectionSampler:
|
||||
sampled_chunks: list[torch.Tensor] = []
|
||||
num_sampled_chunks: list[torch.Tensor] = []
|
||||
logprobs_chunks: list[LogprobsTensors] = []
|
||||
sampling_mask_chunks: list[SamplingMaskTensors] = []
|
||||
max_num_kept = None
|
||||
if self.sampler.return_sampling_mask:
|
||||
max_num_kept = int(
|
||||
np.max(
|
||||
self.sampler.sampling_states.top_k.np[input_batch.idx_mapping_np]
|
||||
)
|
||||
)
|
||||
|
||||
for start, end in request_chunks:
|
||||
lo = int(cu_num_logits_np[start])
|
||||
@@ -323,6 +347,7 @@ class RejectionSampler:
|
||||
input_batch.expanded_idx_mapping[lo:hi],
|
||||
input_batch.expanded_local_pos[lo:hi],
|
||||
input_batch.seq_lens_cpu_upper_bound.numpy()[start:end],
|
||||
verify_draft_sampled[lo:hi],
|
||||
)
|
||||
chunk_logprobs = self._get_logprobs_tensors(
|
||||
sampled,
|
||||
@@ -334,13 +359,31 @@ class RejectionSampler:
|
||||
)
|
||||
if chunk_logprobs is not None:
|
||||
logprobs_chunks.append(chunk_logprobs)
|
||||
if max_num_kept is not None:
|
||||
sampling_mask_chunks.append(
|
||||
SamplingMaskTensors.from_logits(
|
||||
processed_logits,
|
||||
chunk_cu_num_logits,
|
||||
num_sampled,
|
||||
max_num_kept,
|
||||
self.num_speculative_steps + 1,
|
||||
)
|
||||
)
|
||||
del processed_logits
|
||||
sampled_chunks.append(sampled)
|
||||
num_sampled_chunks.append(num_sampled)
|
||||
|
||||
if len(sampled_chunks) == 1:
|
||||
logprobs_tensors = logprobs_chunks[0] if logprobs_chunks else None
|
||||
return sampled_chunks[0], num_sampled_chunks[0], logprobs_tensors
|
||||
sampling_mask_tensors = (
|
||||
sampling_mask_chunks[0] if sampling_mask_chunks else None
|
||||
)
|
||||
return (
|
||||
sampled_chunks[0],
|
||||
num_sampled_chunks[0],
|
||||
logprobs_tensors,
|
||||
sampling_mask_tensors,
|
||||
)
|
||||
|
||||
logprobs_tensors = None
|
||||
if logprobs_chunks:
|
||||
@@ -354,13 +397,19 @@ class RejectionSampler:
|
||||
|
||||
sampled = torch.cat(sampled_chunks)
|
||||
num_sampled = torch.cat(num_sampled_chunks)
|
||||
return sampled, num_sampled, logprobs_tensors
|
||||
sampling_mask_tensors = (
|
||||
SamplingMaskTensors.cat(sampling_mask_chunks)
|
||||
if sampling_mask_chunks
|
||||
else None
|
||||
)
|
||||
return sampled, num_sampled, logprobs_tensors, sampling_mask_tensors
|
||||
|
||||
def __call__(
|
||||
self,
|
||||
logits: torch.Tensor,
|
||||
input_batch: InputBatch,
|
||||
draft_logits: torch.Tensor | None = None,
|
||||
invalid_drafts: torch.Tensor | None = None,
|
||||
) -> SamplerOutput:
|
||||
# NOTE(woosuk): We intentionally compute num_nans before sampling to make clear
|
||||
# that num_nans is computed before applying penalties and temperature.
|
||||
@@ -375,11 +424,24 @@ class RejectionSampler:
|
||||
self.sampler.req_states.prefill_len.gpu,
|
||||
)
|
||||
|
||||
# Marking a draft invalid (`is_valid_draft = draft_sampled >= 0`) pins the
|
||||
# accepted length before it reaches a permissive bitmask row. Only
|
||||
# verification sees the copy: `apply_sampling_params` and watermarking
|
||||
# keep the real draft ids.
|
||||
verify_draft_sampled = draft_sampled
|
||||
if invalid_drafts is not None:
|
||||
verify_draft_sampled = draft_sampled.masked_fill(invalid_drafts, -1)
|
||||
|
||||
max_num_logprobs = self.sampler.sampling_states.max_num_logprobs(
|
||||
input_batch.idx_mapping_np
|
||||
)
|
||||
chunk_logit_limit = get_max_chunk_logits(logits.shape[1])
|
||||
sampled, num_sampled, logprobs_tensors = self._verify_in_chunks(
|
||||
(
|
||||
sampled,
|
||||
num_sampled,
|
||||
logprobs_tensors,
|
||||
sampling_mask_tensors,
|
||||
) = self._verify_in_chunks(
|
||||
logits,
|
||||
input_batch,
|
||||
draft_logits,
|
||||
@@ -387,6 +449,7 @@ class RejectionSampler:
|
||||
pos,
|
||||
chunk_logit_limit,
|
||||
max_num_logprobs,
|
||||
verify_draft_sampled,
|
||||
)
|
||||
|
||||
num_sampled, num_rejected = get_num_sampled_and_rejected(
|
||||
@@ -403,4 +466,5 @@ class RejectionSampler:
|
||||
num_nans=num_nans,
|
||||
num_sampled=num_sampled,
|
||||
num_rejected=num_rejected,
|
||||
sampling_mask_tensors=sampling_mask_tensors,
|
||||
)
|
||||
|
||||
@@ -564,7 +564,6 @@ def _rejection_kernel(
|
||||
# stores the target argmax upon first rejection, so it rejects the
|
||||
# placeholder via `accepted` instead.
|
||||
verifying &= is_valid_draft
|
||||
|
||||
if verifying:
|
||||
pos = tl.load(pos_ptr + logit_idx)
|
||||
u = tl_rand32(seed, pos, includes_zero=False)
|
||||
@@ -719,6 +718,8 @@ def _seeded_resample_argmax(
|
||||
0, # logits_cache_stride_0
|
||||
0, # logits_cache_stride_1
|
||||
None, # logits_cache_col_ptr
|
||||
None, # logits_cache_source_ptr
|
||||
0, # logits_cache_source_stride
|
||||
vocab_size,
|
||||
IS_DRAFTING=False,
|
||||
APPLY_TEMPERATURE=False,
|
||||
@@ -766,6 +767,7 @@ def _resample_kernel(
|
||||
contexts_stride,
|
||||
# [max_num_reqs], uint8 view of a bool tensor
|
||||
watermarking_ptr,
|
||||
watermarking_skip_mask_ptr,
|
||||
watermark_key_0,
|
||||
watermark_key_1,
|
||||
vocab_size,
|
||||
@@ -775,6 +777,7 @@ def _resample_kernel(
|
||||
USE_BLOCK_VERIFICATION: tl.constexpr,
|
||||
CONTEXT_WIDTH: tl.constexpr,
|
||||
WATERMARK: tl.constexpr,
|
||||
DEDUPLICATE_CONTEXTS: tl.constexpr,
|
||||
):
|
||||
req_idx = tl.program_id(0)
|
||||
resample_idx = tl.load(rejected_step_ptr + req_idx)
|
||||
@@ -807,6 +810,25 @@ def _resample_kernel(
|
||||
).to(tl.float32)
|
||||
|
||||
# Compute the residual logits to resample the rejected token from.
|
||||
is_watermarked = False
|
||||
if WATERMARK:
|
||||
is_watermarked = (
|
||||
tl.load(
|
||||
watermarking_ptr + req_state_idx,
|
||||
mask=req_state_idx >= 0,
|
||||
other=0,
|
||||
)
|
||||
!= 0
|
||||
)
|
||||
|
||||
skip_watermarking = False
|
||||
if DEDUPLICATE_CONTEXTS:
|
||||
skip_watermarking = (
|
||||
(tl.load(watermarking_skip_mask_ptr + resample_token_idx) != 0)
|
||||
& is_watermarked
|
||||
& (temp != 0.0)
|
||||
)
|
||||
|
||||
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.
|
||||
@@ -868,15 +890,7 @@ def _resample_kernel(
|
||||
# Resample the rejected/bonus token.
|
||||
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):
|
||||
if is_watermarked & (temp != 0.0) & ~skip_watermarking:
|
||||
watermark_value, idx = philox_gumbel_block_argmax(
|
||||
residual_logits,
|
||||
mask,
|
||||
@@ -1023,6 +1037,7 @@ def rejection_sample(
|
||||
use_block_verification: bool = False,
|
||||
contexts: torch.Tensor | None = None,
|
||||
watermarking: torch.Tensor | None = None,
|
||||
watermarking_skip_mask: 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
|
||||
@@ -1036,9 +1051,13 @@ def rejection_sample(
|
||||
assert watermark == (watermarking is not None) == (watermark_key is not None), (
|
||||
"contexts, watermarking and watermark_key must be set together."
|
||||
)
|
||||
assert watermarking_skip_mask is None or watermark, (
|
||||
"watermarking_skip_mask requires watermarking."
|
||||
)
|
||||
contexts_stride = 0
|
||||
context_width = 1
|
||||
watermarking_bytes: torch.Tensor | None = None
|
||||
watermarking_skip_mask_bytes: torch.Tensor | None = None
|
||||
watermark_key_0 = 0
|
||||
watermark_key_1 = 0
|
||||
if contexts is not None:
|
||||
@@ -1053,6 +1072,12 @@ def rejection_sample(
|
||||
contexts_stride = contexts.stride(0)
|
||||
context_width = contexts.shape[-1]
|
||||
watermarking_bytes = watermarking.view(torch.uint8)
|
||||
if watermarking_skip_mask is not None:
|
||||
assert watermarking_skip_mask.shape == (num_logits,)
|
||||
assert watermarking_skip_mask.dtype == torch.bool
|
||||
if not watermarking_skip_mask.is_contiguous():
|
||||
watermarking_skip_mask = watermarking_skip_mask.contiguous()
|
||||
watermarking_skip_mask_bytes = watermarking_skip_mask.view(torch.uint8)
|
||||
watermark_key_0 = watermark_key & 0xFFFFFFFF
|
||||
watermark_key_1 = watermark_key >> 32
|
||||
draft_logits_stride_0 = 0
|
||||
@@ -1269,6 +1294,7 @@ def rejection_sample(
|
||||
contexts,
|
||||
contexts_stride,
|
||||
watermarking_bytes,
|
||||
watermarking_skip_mask_bytes,
|
||||
watermark_key_0,
|
||||
watermark_key_1,
|
||||
vocab_size,
|
||||
@@ -1278,6 +1304,7 @@ def rejection_sample(
|
||||
USE_BLOCK_VERIFICATION=use_block_verification,
|
||||
CONTEXT_WIDTH=context_width,
|
||||
WATERMARK=watermark,
|
||||
DEDUPLICATE_CONTEXTS=watermarking_skip_mask is not None,
|
||||
)
|
||||
|
||||
# Insert the resampled tokens into the output sampled.
|
||||
|
||||
@@ -38,6 +38,7 @@ from vllm.v1.worker.gpu.spec_decode.acceptance_estimator import (
|
||||
from vllm.v1.worker.utils import AttentionGroup
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from vllm.v1.watermarking.gpu_sampler import GPUWatermarkSampler
|
||||
from vllm.v1.worker.gpu.pcp_manager import PCPManager
|
||||
|
||||
logger = init_logger(__name__)
|
||||
@@ -198,6 +199,9 @@ class DraftModelSpeculator(BaseSpeculator):
|
||||
self.max_num_reqs,
|
||||
device,
|
||||
watermark_config.allow_target_only_watermarking,
|
||||
self.num_speculative_steps,
|
||||
watermark_config.deduplicate_contexts,
|
||||
watermark_config.deduplicate_contexts_max_history,
|
||||
)
|
||||
|
||||
self.supports_mm_inputs = False
|
||||
@@ -220,13 +224,13 @@ class DraftModelSpeculator(BaseSpeculator):
|
||||
self.model = self.load_draft_model(target_model, target_attn_layer_names)
|
||||
self._validate_local_argmax_reduction()
|
||||
|
||||
all_attn_layers = set[str](
|
||||
get_layers_from_vllm_config(
|
||||
self.vllm_config,
|
||||
AttentionLayerBase, # type: ignore[type-abstract]
|
||||
).keys()
|
||||
all_attn_layers = get_layers_from_vllm_config(
|
||||
self.vllm_config,
|
||||
AttentionLayerBase, # type: ignore[type-abstract]
|
||||
)
|
||||
self.draft_attn_layer_names = all_attn_layers - target_attn_layer_names
|
||||
self.draft_attn_layer_names = set(all_attn_layers) - target_attn_layer_names
|
||||
for layer_name in self.draft_attn_layer_names:
|
||||
all_attn_layers[layer_name].is_draft_layer = True
|
||||
|
||||
target_supports_mm = self.vllm_config.model_config.supports_multimodal_inputs
|
||||
draft_supports_mm = supports_multimodal_embeddings(self.model)
|
||||
@@ -399,6 +403,16 @@ class DraftModelSpeculator(BaseSpeculator):
|
||||
"(communication: O(2*tp_size) vs O(vocab_size))."
|
||||
)
|
||||
|
||||
def compute_draft_logits(
|
||||
self, hidden_states: torch.Tensor, spec_step_idx: int
|
||||
) -> torch.Tensor:
|
||||
return self.model.compute_logits(hidden_states)
|
||||
|
||||
def get_draft_top_tokens(
|
||||
self, hidden_states: torch.Tensor, spec_step_idx: int
|
||||
) -> torch.Tensor:
|
||||
return self.model.get_top_tokens(hidden_states)
|
||||
|
||||
def sample_draft(
|
||||
self,
|
||||
hidden_states: torch.Tensor,
|
||||
@@ -408,10 +422,19 @@ class DraftModelSpeculator(BaseSpeculator):
|
||||
seeds: torch.Tensor,
|
||||
draft_step: torch.Tensor,
|
||||
draft_logits: torch.Tensor | None,
|
||||
spec_step_idx: int = 0,
|
||||
) -> torch.Tensor:
|
||||
if draft_logits is None and self.use_local_argmax_reduction:
|
||||
return self.get_draft_top_tokens(hidden_states, spec_step_idx)
|
||||
|
||||
logits = self.compute_draft_logits(hidden_states, spec_step_idx)
|
||||
if draft_logits is not None:
|
||||
logits = self.model.compute_logits(hidden_states)
|
||||
sampled = gumbel_sample(
|
||||
sampler = (
|
||||
gumbel_sample
|
||||
if self.draft_watermarker is None
|
||||
else self.draft_watermarker.sample
|
||||
)
|
||||
sampled = sampler(
|
||||
logits,
|
||||
idx_mapping,
|
||||
temperature,
|
||||
@@ -423,14 +446,7 @@ 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
|
||||
)
|
||||
elif self.use_local_argmax_reduction:
|
||||
return self.model.get_top_tokens(hidden_states)
|
||||
else:
|
||||
logits = self.model.compute_logits(hidden_states)
|
||||
sampled = logits.argmax(dim=-1)
|
||||
self._maybe_predict_acceptance(logits, idx_mapping, draft_step)
|
||||
return sampled
|
||||
@@ -462,11 +478,19 @@ class DraftModelSpeculator(BaseSpeculator):
|
||||
self.acceptance_estimator.step(idx_mapping, num_sampled, num_rejected)
|
||||
|
||||
def prepare_watermarking(
|
||||
self, contexts: torch.Tensor, watermarking: torch.Tensor
|
||||
self,
|
||||
sampler: "GPUWatermarkSampler",
|
||||
idx_mapping: torch.Tensor,
|
||||
) -> None:
|
||||
if self.draft_watermarker is None:
|
||||
return
|
||||
self.draft_watermarker.prepare(contexts, watermarking)
|
||||
self.draft_watermarker.prepare(
|
||||
sampler._get_contexts(idx_mapping),
|
||||
sampler.watermarking.gpu[idx_mapping],
|
||||
sampler.req_states.all_token_ids.gpu,
|
||||
sampler.req_states.prompt_len.gpu,
|
||||
sampler.req_states.total_len.gpu,
|
||||
)
|
||||
|
||||
def _copy_request_inputs(
|
||||
self,
|
||||
|
||||
@@ -35,6 +35,43 @@ def _build_grammar_mapping(
|
||||
return mapping
|
||||
|
||||
|
||||
def grammar_invalid_drafts(
|
||||
input_batch: InputBatch,
|
||||
grammar_req_ids: list[str],
|
||||
num_acceptable_drafts: list[int] | None,
|
||||
) -> torch.Tensor | None:
|
||||
"""Mask over logit rows whose draft was verified against a permissive row.
|
||||
|
||||
Draft i sits at local position i + 1, and drafts from `num_acceptable_drafts`
|
||||
on met `_full_mask`. Local positions come from the device `cu_num_logits`, so
|
||||
this stays right when adaptive verification trims drafts on device.
|
||||
Returns None when there is nothing to invalidate.
|
||||
"""
|
||||
if not grammar_req_ids or input_batch.num_draft_tokens == 0:
|
||||
return None
|
||||
req_id_to_idx = {req_id: i for i, req_id in enumerate(input_batch.req_ids)}
|
||||
limit = np.full(input_batch.num_reqs, np.iinfo(np.int32).max, dtype=np.int32)
|
||||
for i, req_id in enumerate(grammar_req_ids):
|
||||
req_idx = req_id_to_idx.get(req_id)
|
||||
if req_idx is not None:
|
||||
# None (an older scheduler, or warmup): invalidate the whole window.
|
||||
limit[req_idx] = (
|
||||
num_acceptable_drafts[i] if num_acceptable_drafts is not None else 0
|
||||
)
|
||||
# Adaptive verification only trims drafts, so this bound holds either way.
|
||||
num_drafts = input_batch.num_draft_tokens_per_req
|
||||
if num_drafts is not None and (limit >= num_drafts).all():
|
||||
return None
|
||||
local_pos = input_batch.expanded_local_pos
|
||||
cu_num_logits = input_batch.cu_num_logits
|
||||
row_limit = torch.repeat_interleave(
|
||||
async_tensor_h2d(limit, device=local_pos.device),
|
||||
cu_num_logits[1:] - cu_num_logits[:-1],
|
||||
output_size=local_pos.shape[0],
|
||||
)
|
||||
return local_pos > row_limit
|
||||
|
||||
|
||||
class StructuredOutputsWorker:
|
||||
def __init__(
|
||||
self,
|
||||
|
||||
@@ -194,6 +194,7 @@ def _slice_input_batch(
|
||||
if input_batch.prompt_lens is None
|
||||
else input_batch.prompt_lens[req_start:req_stop]
|
||||
),
|
||||
max_seq_len_np=None,
|
||||
fast_prefill=None,
|
||||
)
|
||||
|
||||
|
||||
Reference in New Issue
Block a user