diff --git a/python/sglang/srt/arg_groups/kv_cache_hook.py b/python/sglang/srt/arg_groups/kv_cache_hook.py index bc39b3fa36..2041e1e3d5 100644 --- a/python/sglang/srt/arg_groups/kv_cache_hook.py +++ b/python/sglang/srt/arg_groups/kv_cache_hook.py @@ -4,7 +4,7 @@ from __future__ import annotations import logging -from typing import Any +from typing import Any, Optional from sglang.srt.arg_groups.overrides import ( attention_backends_of, @@ -488,24 +488,35 @@ _SPEC_VERIFY_AUDITED_BACKENDS = frozenset( } ) +# The MHA backends that read through the KV-index translator on every path a +# draft forward takes. A fused draft region holds dense K/V rows, so a fused +# draft runs only on these. +TRANSLATED_MHA_RAILS = frozenset({"triton", "flashinfer", "fa3"}) -def _assert_spec_verify_backends(server_args: Any, *, algorithm: str) -> None: + +def _assert_spec_verify_backends( + server_args: Any, *, algorithm: str, allowed: Optional[frozenset] = None +) -> None: """Refuse target backends whose verify id rails are not translation-audited. - Only the target's prefill/decode pair is checked. A draft with a KV pool - of its own indexes that pool directly by virtual id, so its translator is - a passthrough and its backend has nothing to translate.""" - allowed = _SPEC_VERIFY_AUDITED_BACKENDS + Only the target's prefill/decode pair is checked here. A draft that fuses + into the target's pages must run on the translated rails; the fused-draft + decision enforces that by declining fusion otherwise, and a private-pool + draft indexes its own pool by virtual id.""" + if allowed is None: + allowed = _SPEC_VERIFY_AUDITED_BACKENDS + dcp_note = "" if resolving_view(server_args).dcp_size > 1: # flashinfer's spec verify gathers its CSR args with no DCP read # translation (`translate_dcp_read_ids`); the MLA verify family builds # its DCP block table itself. allowed = allowed - {"flashinfer"} + dcp_note = " (flashinfer is excluded under --dcp-size > 1)" backends = set(attention_backends_of(resolved_view(server_args))) backends.discard(None) assert backends <= allowed, ( f"--enable-unified-memory + {algorithm} requires spec-verify-audited " - f"attention backends {sorted(allowed)} for both prefill " + f"attention backends {sorted(allowed)}{dcp_note} for both prefill " f"and decode; got {sorted(backends)}. Other backends do " "not translate speculative verify indices to the unified " "pool's physical ids yet." @@ -572,11 +583,18 @@ def handle_unified_memory_pool(server_args: Any) -> None: "--enable-unified-memory host-pool decode retraction does not " "support hybrid-Mamba models." ) - assert cfg.speculative_algorithm in (None, "DSPARK", "EAGLE", "EAGLE3"), ( + assert cfg.speculative_algorithm in ( + None, + "DSPARK", + "EAGLE", + "EAGLE3", + "DFLASH", + ), ( "--enable-unified-memory only supports --speculative-algorithm " - "DSPARK (chain draft) and EAGLE/EAGLE3 (fused draft KV); other " - "speculative algorithms are not yet audited for the unified pool's " - "virtual-to-physical loc translation. Got " + "DSPARK (chain draft), DFLASH (fused block draft), and " + "EAGLE/EAGLE3 (fused draft KV); other speculative algorithms are " + "not yet audited for the unified pool's virtual-to-physical loc " + "translation. Got " f"--speculative-algorithm={cfg.speculative_algorithm!r}." ) assert cfg.speculative_eagle_topk in (None, 1), ( @@ -593,13 +611,11 @@ def handle_unified_memory_pool(server_args: Any) -> None: "target (hybrid-SWA or a mamba hybrid): the draft's KV lives " "fused inside the full-attention page envelope." ) - # The translated MHA rails. A fused draft is MHA-shaped on every host - # (its region holds dense K/V rows), and these three also serve a - # draft that keeps an MLA pool of its own. - mha_rails = {"triton", "flashinfer", "fa3"} # The target verifies on its own pages: the MLA family on an MLA host. eagle_allowed = ( - _SPEC_VERIFY_AUDITED_BACKENDS if use_mla_backend(server_args) else mha_rails + _SPEC_VERIFY_AUDITED_BACKENDS + if use_mla_backend(server_args) + else TRANSLATED_MHA_RAILS ) eagle_backends = set(attention_backends_of(resolved_view(server_args))) assert ( @@ -611,17 +627,26 @@ def handle_unified_memory_pool(server_args: Any) -> None: f"spec-verify-audited attention backends {sorted(eagle_allowed)} " f"(got {sorted(eagle_backends, key=str)})." ) - # An unset draft backend inherits the target's pair. + # An unset draft backend inherits the target's pair. A fused draft is + # MHA-shaped on every host, and these rails also serve a draft that + # keeps an MLA pool of its own. draft_backend = cfg.speculative_draft_attention_backend draft_backends = {draft_backend} if draft_backend else eagle_backends - assert draft_backends <= mha_rails, ( + assert draft_backends <= TRANSLATED_MHA_RAILS, ( "--enable-unified-memory + EAGLE/EAGLE3 runs the draft on " f"{sorted(draft_backends)}, but a fused draft is MHA-shaped and " - f"reads its KV through the translated MHA rails {sorted(mha_rails)}. " + "reads its KV through the translated MHA rails " + f"{sorted(TRANSLATED_MHA_RAILS)}. " "Set --speculative-draft-attention-backend to one of them." ) if cfg.speculative_algorithm == "DSPARK": _assert_spec_verify_backends(server_args, algorithm="DSPARK") + if cfg.speculative_algorithm == "DFLASH": + _assert_spec_verify_backends( + server_args, + algorithm="DFLASH", + allowed=TRANSLATED_MHA_RAILS, + ) assert not cfg.enable_two_batch_overlap, ( "--enable-unified-memory does not support --enable-two-batch-overlap: " "TBO's replay split hands each child a view without the pre-translate " @@ -650,17 +675,21 @@ def handle_unified_memory_pool(server_args: Any) -> None: ) assert not ( cfg.speculative_algorithm in ("EAGLE", "EAGLE3") - and ( - cfg.enable_hierarchical_cache - or cfg.disaggregation_decode_retraction_backup == "host_pool" - ) + and cfg.disaggregation_decode_retraction_backup == "host_pool" ), ( "--enable-unified-memory + EAGLE/EAGLE3 does not support " - "--enable-hierarchical-cache or " - "--disaggregation-decode-retraction-backup=host_pool: both build host " - "pools off the draft's device pool, and a draft fused into the " - "target's entries has no transfer surface of its own (the page " - "envelope host pool refuses per-layer draft loads)." + "--disaggregation-decode-retraction-backup=host_pool: the backup builds " + "the draft's host pool off a device pool of its own, and an EAGLE draft " + "on the unified pool lives fused in the target's pages, without one." + ) + assert not ( + cfg.speculative_algorithm in ("EAGLE", "EAGLE3") + and cfg.enable_hierarchical_cache + ), ( + "--enable-unified-memory + EAGLE/EAGLE3 does not support " + "--enable-hierarchical-cache: HiCache keeps the draft on a private " + "pool, and would pack an MTP head's KV into the target's " + "page-envelope host pool, which refuses per-layer draft loads." ) if cfg.dcp_size > 1: _validate_unified_memory_dcp(server_args) diff --git a/python/sglang/srt/mem_cache/kv_cache_configurator.py b/python/sglang/srt/mem_cache/kv_cache_configurator.py index c3fa09f08c..6622a61c85 100644 --- a/python/sglang/srt/mem_cache/kv_cache_configurator.py +++ b/python/sglang/srt/mem_cache/kv_cache_configurator.py @@ -9,6 +9,7 @@ from typing import TYPE_CHECKING, Any, Optional import msgspec import torch +from sglang.srt.arg_groups.kv_cache_hook import TRANSLATED_MHA_RAILS from sglang.srt.arg_groups.overrides import resolving_view from sglang.srt.configs.hybrid_arch import ( hybrid_gdn_config, @@ -590,9 +591,10 @@ class KVCacheConfigurator: draft_state_layer_classes, ) - assert req_to_token_pool is not None, ( - "a draft worker shares the target's req_to_token_pool" - ) + if req_to_token_pool is None: + req_to_token_pool = self._build_req_to_token_pool( + max_num_reqs=sizes.max_running_requests + ) # The target placed this draft from its config; the built # model is the ground truth for whether it carries state. state_layers = draft_state_layer_classes(self.model) @@ -733,9 +735,12 @@ class KVCacheConfigurator: def _fused_draft_from_target_buffer(self, alloc): """The placement this draft binds to, or None for the private-pool fallback (the draft then owns a raw-virtual-indexed pool of its own). - Target boot declines a placement for legitimate geometry, so the - private arm is the rollback lever, not a boot-order bug.""" - if not self.spec_algorithm.is_eagle(): + Target boot declines a placement whenever the fused region cannot + serve the draft (`_fused_draft_decision`), so the private arm is the + rollback lever, not a boot-order bug.""" + if not ( + self.spec_algorithm.is_eagle() or self.spec_algorithm.is_dflash_family() + ): return None placement = alloc.unified_buffer.fused_draft if placement is None: @@ -955,11 +960,15 @@ class KVCacheConfigurator: ) def _fused_draft_decision(self): - """Whether, and where, the EAGLE draft's layers fuse into the target's + """Whether, and where, the draft's layers fuse into the target's sub-pools. Fusion applies only for: unified memory ON, a unified target (hybrid-SWA or mamba hybrid, either full-pool kind), an EAGLE-family - algorithm whose draft config was loaded at target boot; - `place_fused_draft` then admits or declines the draft's layer kinds.""" + or DFLASH/DSPARK algorithm whose draft config was loaded at target + boot. It declines, keeping the draft's private pool, for a non-MHA + draft, a draft backend off the translated MHA rails, DCP, HiCache, + host-pool decode retraction, or an explicit draft KV dtype unlike the + host's; `place_fused_draft` then admits or declines the draft's layer + kinds.""" from sglang.srt.mem_cache.layout.fused_draft import ( FusedDraftDecision, draft_kv_profile, @@ -975,7 +984,9 @@ class KVCacheConfigurator: get_memory().enable_unified_memory and host_has_fusable_full_pool and not self.is_draft_worker - and self.spec_algorithm.is_eagle() + and ( + self.spec_algorithm.is_eagle() or self.spec_algorithm.is_dflash_family() + ) and aux.draft_kv_num_layers and aux.draft_model_config is not None ): @@ -987,10 +998,67 @@ class KVCacheConfigurator: "the fused region holds dense MHA K/V rows" ) ) + # The backend(s) the draft runner will run. A DFLASH-family draft + # worker resolves one as `build_draft_tp_worker` does; an EAGLE draft + # runs the published draft backend, else the target's prefill/decode + # pair. A published draft backend carries model-hook declarations. + if self.spec_algorithm.is_dflash_family(): + from sglang.srt.speculative.draft_worker_common import ( + resolve_draft_worker_attention_backend, + ) + + draft_backend = resolve_draft_worker_attention_backend() + else: + draft_backend = get_spec().speculative_draft_attention_backend + draft_backends = ( + {draft_backend} if draft_backend else set(attention_backends()) - {None} + ) + # A fused draft reads its rows through the KV-index translator, which + # other backends miss on some draft path: trtllm_mha's graph replay + # refills its page table from stale lengths, and its eager build does + # not widen the table by the draft block. + if not draft_backends <= TRANSLATED_MHA_RAILS: + return FusedDraftDecision( + declined=( + f"the draft runs on {', '.join(sorted(draft_backends))}, " + "off the translated MHA rails " + f"({', '.join(sorted(TRANSLATED_MHA_RAILS))})" + ) + ) + # Under DCP each rank's host rows hold only its share of the widened + # id space, while the draft never joins the DCP group and needs every + # token; its translator also leaves the read ids widened for a DCP + # index kernel that a draft's backend never runs. + if get_parallel().attn_dcp_size > 1: + return FusedDraftDecision( + declined=( + f"--dcp-size {get_parallel().attn_dcp_size} shards the host's " + "rows, but the replicated draft reads every token" + ) + ) + # HiCache and host-pool retraction build the draft's host pool off its + # own device pool, which a fused draft does not have. The external + # linker would too; the gate refuses it on the unified pool. + if get_memory().enable_hierarchical_cache: + host_pool_flag = "--enable-hierarchical-cache" + elif get_disagg().disaggregation_decode_retraction_backup == "host_pool": + host_pool_flag = "--disaggregation-decode-retraction-backup=host_pool" + else: + host_pool_flag = None + if host_pool_flag is not None: + return FusedDraftDecision( + declined=( + f"{host_pool_flag} builds the draft's host pool off a device " + "pool of its own" + ) + ) profile = draft_kv_profile( aux.draft_model_config, num_layers=int(aux.draft_kv_num_layers), attn_tp_size=get_parallel().attn_tp_size, + # A DFLASH-family draft config inherits the target's NEXTN depth + # count; its draft is one block, replicated per runner. + num_depths=None if self.spec_algorithm.is_eagle() else 1, ) num_runners = ( int(get_spec().speculative_num_steps) @@ -998,20 +1066,21 @@ class KVCacheConfigurator: else 1 ) # A fused draft stores its rows in the host's KV dtype. An explicit - # draft dtype resolves without the draft model, so a mismatch is - # declined here; `auto` follows the draft's quant config, which only - # the draft runner knows, and is checked when it binds. + # draft dtype resolves without the draft model, as the draft runner + # resolves it, so a mismatch is declined here; `auto` follows the + # draft's quant config, which only the draft runner knows, and is + # checked when it binds. draft_kv_cache_dtype = get_spec().speculative_draft_kv_cache_dtype if draft_kv_cache_dtype not in (None, "auto"): from sglang.srt.mem_cache.kv_cache_dtype import configure_kv_cache_dtype _, draft_kv_dtype = configure_kv_cache_dtype( - server_args_kv_cache_dtype=draft_kv_cache_dtype, + server_args_kv_cache_dtype=get_model().kv_cache_dtype, model=None, model_dtype=aux.draft_model_config.dtype, is_draft_worker=True, - is_dflash=False, - speculative_draft_attention_backend=None, + is_dflash=self.spec_algorithm.is_dflash_family(), + speculative_draft_attention_backend=draft_backend, speculative_draft_kv_cache_dtype=draft_kv_cache_dtype, ) if draft_kv_dtype != self.kv_cache_dtype: @@ -1082,23 +1151,25 @@ class KVCacheConfigurator: def _fused_draft_for_mamba_factory(self): """`_fused_draft_for_pool_factory` for a mamba-hybrid host. Its unified buffer takes the WHOLE profiled KV budget (`unified_total_bytes`), so a - private EAGLE draft pool -- sized to the full virtual id span -- would - be allocated on top of it, unbudgeted. Until the mamba solve prices that - pool, an EAGLE draft that does not fuse is refused here instead of - overcommitting GPU memory.""" - placement = self._fused_draft_for_pool_factory() + private draft pool -- sized to the full virtual id span -- would be + allocated on top of it, unbudgeted. Until the mamba solve prices that + pool, an EAGLE-family or DFLASH draft that does not fuse is refused here + instead of overcommitting GPU memory. A DSPARK draft that does not fuse + keeps its private pool, unpriced: refusing it would refuse DSPARK on + these hosts whenever its draft declines fusion, as the Kimi-Linear + default (a trtllm_mha draft) does.""" + decision = self._fused_draft_decision() + placement = self._fused_draft_for_pool_factory(decision) if ( placement is None - and self.spec_algorithm.is_eagle() + and (self.spec_algorithm.is_eagle() or self.spec_algorithm.is_dflash()) and not self.is_draft_worker ): - reason = ( - self._fused_draft_decision().declined or "fusion does not apply to it" - ) + reason = decision.declined or "fusion does not apply to it" raise ValueError( - "--enable-unified-memory + EAGLE/EAGLE3 on a mamba-hybrid target " - "needs the draft's KV fused into the target's pages, but this " - f"draft would keep a private pool ({reason}). A mamba host's " + "--enable-unified-memory + EAGLE/EAGLE3/DFLASH on a mamba-hybrid " + "target needs the draft's KV fused into the target's pages, but " + f"this draft would keep a private pool ({reason}). A mamba host's " "unified buffer takes the whole KV budget, so a private draft " "pool would overcommit GPU memory." ) @@ -1110,15 +1181,14 @@ class KVCacheConfigurator: at the draft's own heads, head_dim and KV dtype, so a draft that does not fuse is refused here, as on a mamba host, instead of overcommitting GPU memory.""" - placement = self._fused_draft_for_pool_factory() + decision = self._fused_draft_decision() + placement = self._fused_draft_for_pool_factory(decision) if ( placement is None and self.spec_algorithm.is_eagle() and not self.is_draft_worker ): - reason = ( - self._fused_draft_decision().declined or "fusion does not apply to it" - ) + reason = decision.declined or "fusion does not apply to it" raise ValueError( "--enable-unified-memory + EAGLE/EAGLE3 on a hybrid-SWA target " "needs the draft's KV fused into the target's pages, but this " @@ -1127,11 +1197,10 @@ class KVCacheConfigurator: ) return placement - def _fused_draft_for_pool_factory(self): - """Resolve ONCE per factory call (not inline) so the boot log reports - exactly the placement the factory is handed: a declined fusion and an - engaged one otherwise look identical from outside.""" - decision = self._fused_draft_decision() + def _fused_draft_for_pool_factory(self, decision): + """The placement a pool factory is handed, from ONE resolved decision, + so the boot log reports exactly that placement: a declined fusion and + an engaged one otherwise look identical from outside.""" if decision.placement is None: if decision.declined is not None: logger.warning("fused draft KV disabled: %s", decision.declined) diff --git a/python/sglang/srt/mem_cache/layout/fused_draft.py b/python/sglang/srt/mem_cache/layout/fused_draft.py index 8c67632192..dbe1748af3 100644 --- a/python/sglang/srt/mem_cache/layout/fused_draft.py +++ b/python/sglang/srt/mem_cache/layout/fused_draft.py @@ -191,12 +191,18 @@ def draft_swa_layer_ids(draft_model_config) -> Tuple[int, ...]: def draft_kv_profile( - draft_model_config, *, num_layers: int, attn_tp_size: int + draft_model_config, + *, + num_layers: int, + attn_tp_size: int, + num_depths: Optional[int] = None, ) -> DraftKVProfile: """The profile of a draft `ModelConfig`, heads divided by attn_tp the way - the target divides its own (drafts never join the DCP group).""" + the target divides its own (drafts never join the DCP group). + ``num_depths`` overrides the config's `num_nextn_predict_layers`.""" mc = draft_model_config - num_depths = mc.num_nextn_predict_layers + if num_depths is None: + num_depths = mc.num_nextn_predict_layers return DraftKVProfile( num_layers=int(num_layers), full=DraftKVGeometry( diff --git a/python/sglang/srt/model_executor/model_runner_components/spec_aux_hidden_state.py b/python/sglang/srt/model_executor/model_runner_components/spec_aux_hidden_state.py index 1ad8fda9df..eba7d123f0 100644 --- a/python/sglang/srt/model_executor/model_runner_components/spec_aux_hidden_state.py +++ b/python/sglang/srt/model_executor/model_runner_components/spec_aux_hidden_state.py @@ -44,9 +44,9 @@ class SpecAuxHiddenStateConfig(msgspec.Struct, kw_only=True): dflash_target_layer_ids: Any = None # DFLASH draft KV bytes/token; None when unresolved. dflash_draft_cell_size_per_token: int | None = None - # The draft checkpoint read in draft mode, and its KV layer count: the - # fused-draft placement's input. `eagle_draft_num_layers` above keeps - # sizing a private draft pool exactly as before. + # The draft checkpoint read in draft mode, and its KV layer count, for + # every drafting algorithm: the fused-draft placement's input. A private + # EAGLE draft pool is sized by `eagle_draft_num_layers` instead. draft_model_config: Optional[ModelConfig] = None draft_kv_num_layers: Optional[int] = None @@ -94,29 +94,28 @@ def _resolve_eagle_aux_hidden_state( # The draft read in draft mode. A path-less NEXTN/MTP head is the TARGET # checkpoint rewritten to its MTP form, which is where its # `num_nextn_predict_layers` gets filled in. - draft_model_config = ModelConfig.from_server_args( + draft_mode_config = ModelConfig.from_server_args( server_args, model_path=draft_path, model_revision=get_spec().speculative_draft_model_revision, is_draft_model=True, ) - if draft_model_config.num_nextn_predict_layers is not None: - config.draft_kv_num_layers = int(draft_model_config.num_nextn_predict_layers) - elif draft_path is not None: + if draft_mode_config.num_nextn_predict_layers is not None: + config.draft_kv_num_layers = int(draft_mode_config.num_nextn_predict_layers) + elif draft_path: config.draft_kv_num_layers = int( max( - draft_model_config.num_hidden_layers, - draft_model_config.num_attention_layers, + draft_mode_config.num_hidden_layers, + draft_mode_config.num_attention_layers, ) ) if config.draft_kv_num_layers is not None: - config.draft_model_config = draft_model_config + config.draft_model_config = draft_mode_config - # The private draft pool's budget keeps its reading: a path-less run sizes - # the draft off the TARGET config. Reading the draft-mode config here would - # change the token budget of every path-less MTP deployment. - if not draft_path: - draft_model_config = model_config + # A private draft pool is sized off the TARGET config when path-less, so + # a path-less MTP deployment's token budget does not depend on the + # draft-mode rewrite. + draft_model_config = draft_mode_config if draft_path else model_config num_nextn_predict_layers = draft_model_config.num_nextn_predict_layers if num_nextn_predict_layers is not None: config.eagle_draft_num_layers = int(num_nextn_predict_layers) @@ -223,6 +222,8 @@ def _resolve_dflash_aux_hidden_state( config.dflash_use_aux_hidden_state = True config.dflash_draft_num_layers = int(draft_num_layers) + config.draft_model_config = draft_model_config + config.draft_kv_num_layers = int(draft_num_layers) config.dflash_target_layer_ids = target_layer_ids config.dflash_draft_cell_size_per_token = _resolve_dflash_draft_cell_size( draft_model_config=draft_model_config, diff --git a/python/sglang/srt/model_executor/pool_configurator.py b/python/sglang/srt/model_executor/pool_configurator.py index ac0e5cc550..a68cf10fe4 100644 --- a/python/sglang/srt/model_executor/pool_configurator.py +++ b/python/sglang/srt/model_executor/pool_configurator.py @@ -299,7 +299,10 @@ class DefaultPoolConfigurator(MemoryPoolConfigurator): ) draft_num_layers = kvc.spec_aux_config.dflash_draft_num_layers - if ( + fused_full_entry = kvc.fused_entry_bytes("full") + if fused_full_entry is not None: + self._cell_size = int(fused_full_entry) + elif ( draft_num_layers is not None and int(draft_num_layers) > 0 and int(num_layers) > 0 diff --git a/python/sglang/srt/models/dspark.py b/python/sglang/srt/models/dspark.py index c39d13200d..3a2e173a18 100644 --- a/python/sglang/srt/models/dspark.py +++ b/python/sglang/srt/models/dspark.py @@ -803,7 +803,8 @@ class DSparkDraftMixin: attn.attn.v_scale, ) else: - # The draft pool is static, so its slot ids are physical. + # Translated by the injector (physical by allocation on a plain + # pool). pool.set_kv_buffer( attn.attn, KVWriteLoc(cache_loc, physical=True), diff --git a/python/sglang/srt/speculative/dflash_worker_v2.py b/python/sglang/srt/speculative/dflash_worker_v2.py index 8ce832ef66..773a6cf7af 100644 --- a/python/sglang/srt/speculative/dflash_worker_v2.py +++ b/python/sglang/srt/speculative/dflash_worker_v2.py @@ -1759,6 +1759,7 @@ class DFlashWorkerV2(BaseSpecWorker): For the spec-v2 overlap path, callers can pass dense `[bs, block_size]` `cache_loc_2d` plus `commit_lens`; the prefix-valid writer then commits only the live prefix rows without constructing masked/packed index tensors. + `cache_loc_2d` holds the same ids as `cache_loc`, row-major. """ if target_hidden is None: raise RuntimeError("DFLASH missing target hidden context features.") @@ -1844,6 +1845,17 @@ class DFlashWorkerV2(BaseSpecWorker): if commit_lens.dtype != torch.int32: commit_lens = commit_lens.to(torch.int32) + # On a translating pool the translate writes a new tensor, so the + # callers' locs stay virtual: the post-verify 2-D buffer is re-read as + # virtual ids by the compact req_to_token rebuild. On a plain pool it + # returns `cache_loc` itself. + translator = self.draft_model_runner.kv_index_translator + cache_loc = translator.translate_full_attn_ids(cache_loc) + if cache_loc_2d is not None: + # Same ids, so reshape the translated copy rather than translate + # them a second time. + cache_loc_2d = cache_loc.reshape(cache_loc_2d.shape) + with ( torch.inference_mode(), draft_tp_context(self.draft_owns_attention), @@ -1950,7 +1962,6 @@ class DFlashWorkerV2(BaseSpecWorker): k = attn.apply_k_rope(ctx_positions, k) k = k.view(-1, attn.num_kv_heads, attn.head_dim) v = v.view(-1, attn.num_kv_heads, attn.head_dim) - # The draft pool is static, so its slot ids are physical. self.draft_model_runner.token_to_kv_pool.set_kv_buffer( attn.attn, KVWriteLoc(ctx_cache_loc, physical=True), @@ -2525,7 +2536,6 @@ class DFlashWorkerV2(BaseSpecWorker): forward_batch = ForwardBatch( forward_mode=ForwardMode.TARGET_VERIFY, - out_cache_loc_is_physical=True, batch_size=bs, input_ids=block_ids.flatten(), req_pool_indices=batch.req_pool_indices, @@ -2545,6 +2555,10 @@ class DFlashWorkerV2(BaseSpecWorker): ), global_num_token_non_padded_cpu=bs * block_size, ) + # Hand-built draft batch bypasses ForwardBatch.init_new: under the + # unified pool the write loc must be rebound to the draft's + # kernel-facing ids here (no-op on plain pools). + self.draft_model_runner.kv_index_translator.rebind_write_loc(forward_batch) if self.selector is not None or self.lilicorr is not None: self._selector_sample = None diff --git a/python/sglang/srt/speculative/draft_worker_common.py b/python/sglang/srt/speculative/draft_worker_common.py index 9387550f48..c207df8f7b 100644 --- a/python/sglang/srt/speculative/draft_worker_common.py +++ b/python/sglang/srt/speculative/draft_worker_common.py @@ -28,12 +28,15 @@ class DraftWorkerBundle(msgspec.Struct, frozen=True): resolved_attention_backend: str -def _resolve_draft_attention_backend_fallback(*, algo_label: str) -> str: - """The draft's attention backend, from the published leaves. +def resolve_draft_worker_attention_backend(*, algo_label: Optional[str] = None) -> str: + """The attention backend `build_draft_tp_worker` gives a draft worker when + the caller names none, from the published leaves. `spec.speculative_draft_attention_backend` when the operator named one, otherwise the process's prefill backend. Both are resolution's answers, so - they come from the bags. + they come from the bags. A backend the draft worker does not support falls + back to the platform default, with a warning when ``algo_label`` names the + caller. """ # FlashInfer is CUDA-only; fall back to triton on XPU and ROCm. platform_fallback = ( @@ -46,14 +49,15 @@ def _resolve_draft_attention_backend_fallback(*, algo_label: str) -> str: return platform_fallback if draft_backend not in DRAFT_ATTENTION_BACKEND_CHOICES: fallback = platform_fallback - logger.warning( - "%s draft worker only supports attention_backend in %s for now, " - "but got %r. Falling back to '%s'.", - algo_label, - DRAFT_ATTENTION_BACKEND_CHOICES, - draft_backend, - fallback, - ) + if algo_label is not None: + logger.warning( + "%s draft worker only supports attention_backend in %s for now, " + "but got %r. Falling back to '%s'.", + algo_label, + DRAFT_ATTENTION_BACKEND_CHOICES, + draft_backend, + fallback, + ) return fallback return draft_backend @@ -73,7 +77,7 @@ def build_draft_tp_worker( # validated (e.g. a self-drafting architecture); it skips the generic # supported-backend fallback below. draft_backend = attention_backend_override or ( - _resolve_draft_attention_backend_fallback(algo_label=algo_label) + resolve_draft_worker_attention_backend(algo_label=algo_label) ) from sglang.srt.layers.moe.utils import draft_model_build_scope diff --git a/python/sglang/srt/speculative/dspark_components/dspark_draft.py b/python/sglang/srt/speculative/dspark_components/dspark_draft.py index 888c172e18..e71aadf4ab 100644 --- a/python/sglang/srt/speculative/dspark_components/dspark_draft.py +++ b/python/sglang/srt/speculative/dspark_components/dspark_draft.py @@ -346,7 +346,6 @@ class DraftBlockProposer: empty_long = torch.empty((0,), dtype=torch.int64, device=device) idle_batch = ForwardBatch( forward_mode=ForwardMode.IDLE, - out_cache_loc_is_physical=True, batch_size=0, input_ids=empty_long, req_pool_indices=empty_long, @@ -359,6 +358,9 @@ class DraftBlockProposer: spec_info=self._draft_block_spec_info, capture_hidden_mode=CaptureHiddenMode.NULL, ) + # Hand-built batch bypasses ForwardBatch.init_new: rebind the write + # loc to the draft's kernel-facing ids (no-op on plain pools). + self.draft_model_runner.kv_index_translator.rebind_write_loc(idle_batch) self._fill_dp_moe_sync_metadata(idle_batch, batch) with torch.inference_mode(): self.draft_model_runner.forward(idle_batch) @@ -416,7 +418,6 @@ class DraftBlockProposer: draft_num_tokens = bs * query_token_num draft_forward_batch = ForwardBatch( forward_mode=ForwardMode.TARGET_VERIFY, - out_cache_loc_is_physical=True, batch_size=bs, input_ids=draft_block_ids.flatten(), req_pool_indices=batch.req_pool_indices, @@ -434,6 +435,11 @@ class DraftBlockProposer: ), global_num_token_non_padded_cpu=draft_num_tokens, ) + # Hand-built batch bypasses ForwardBatch.init_new: rebind the write + # loc to the draft's kernel-facing ids (no-op on plain pools). + self.draft_model_runner.kv_index_translator.rebind_write_loc( + draft_forward_batch + ) self._fill_dp_moe_sync_metadata(draft_forward_batch, batch) graph_runner = self.draft_model_runner.decode_cuda_graph_runner if ( diff --git a/python/sglang/srt/speculative/dspark_components/dspark_kv_inject.py b/python/sglang/srt/speculative/dspark_components/dspark_kv_inject.py index 0499fc4784..00c4fb1f70 100644 --- a/python/sglang/srt/speculative/dspark_components/dspark_kv_inject.py +++ b/python/sglang/srt/speculative/dspark_components/dspark_kv_inject.py @@ -70,6 +70,16 @@ class TargetHiddenKvInjector: device=device, dtype=torch.int64, non_blocking=True ) + # On a translating pool the translate writes a new tensor, so the + # callers' locs stay virtual; on a plain pool it returns `cache_loc` + # itself. + translator = self.draft_model_runner.kv_index_translator + cache_loc = translator.translate_full_attn_ids(cache_loc) + if cache_loc_2d is not None: + # Callers pass `cache_loc` viewed [bs, verify_len]: reshape the + # translated copy rather than translate the same ids twice. + cache_loc_2d = cache_loc.reshape(cache_loc_2d.shape) + pool = self.draft_model_runner.token_to_kv_pool if hasattr(pool, "set_swa_key_buffer_radix_fused_norm_rope"): if target_hidden_is_projected: diff --git a/test/registered/unit/mem_cache/test_fused_draft_placement.py b/test/registered/unit/mem_cache/test_fused_draft_placement.py index 4b31cdd0a8..54df63e1a2 100644 --- a/test/registered/unit/mem_cache/test_fused_draft_placement.py +++ b/test/registered/unit/mem_cache/test_fused_draft_placement.py @@ -14,9 +14,10 @@ """`place_fused_draft`: which host/draft pairs fuse, and where each runner's layers land. -Every decline is the private-pool fallback, so a wrong answer never fails -the boot -- it silently changes what the draft binds and what the boot solve -prices. Pinned: +A decline keeps a DFLASH or DSPARK draft on its private pool (a DFLASH draft +on a mamba host is refused instead), and refuses an EAGLE draft at boot. A +wrong answer for a draft that keeps its pool silently changes what it binds +and what the boot solve prices. Pinned: - a replicated head under multi-layer EAGLE gets one lane RANGE per runner (one shared region would let the runners clobber each other's KV); - a per-depth head serves one depth per runner and needs one runner per @@ -24,6 +25,12 @@ prices. Pinned: - a draft with SWA or recurrent-state layers of its own, or asymmetric K/V rows, declines: the fused arm binds one dense pool over the host's full slots; + - a draft whose attention backend is off the translated MHA rails + declines: it would read the fused rows without the KV-index translator; + - so does a draft under --dcp-size > 1, where each rank's host rows hold + only its share of the tokens the replicated draft reads, and a draft + under HiCache, which builds its host pool off a device pool of its own; + - an explicit draft KV dtype unlike the host's declines; - the profile divides the draft's heads by attn_tp, as the target does; - a placement whose runner lane counts do not fill its region is refused; - the priced entry counts the layers THIS runner owns, not the whole model's. @@ -46,7 +53,7 @@ from sglang.srt.mem_cache.layout.fused_draft import ( draft_kv_profile, place_fused_draft, ) -from sglang.srt.runtime_context import get_parallel +from sglang.srt.runtime_context import get_parallel, override_platform from sglang.test.ci.ci_register import register_cpu_ci from sglang.test.test_utils import CustomTestCase @@ -238,21 +245,39 @@ class TestFusedEntryPricing(CustomTestCase): class TestFusedDraftDecision(CustomTestCase): """The target's boot decision over a host whose full sub-pool fuses.""" - def _decide(self, *, draft_kv_dtype=None, attention_arch=None): + def _decide( + self, + *, + algorithm="EAGLE", + draft_kv_dtype=None, + host_kv_dtype=_DTYPE, + kv_cache_dtype_flag="auto", + attention_arch=None, + draft_backend=None, + target_backends=("triton", "triton"), + dcp_size=1, + hicache=False, + retraction_backup=None, + ): from sglang.srt.configs.model_config import AttentionArch from sglang.srt.mem_cache import kv_cache_configurator as kvc + from sglang.srt.speculative import draft_worker_common cfg = kvc.KVCacheConfigurator.__new__(kvc.KVCacheConfigurator) cfg.is_hybrid_swa = True cfg.mambaish_config = None cfg.use_mla_backend = False cfg.is_draft_worker = False - cfg.spec_algorithm = SimpleNamespace(is_eagle=lambda: True) + cfg.spec_algorithm = SimpleNamespace( + is_eagle=lambda: algorithm == "EAGLE", + is_dflash_family=lambda: algorithm in ("DFLASH", "DSPARK"), + ) cfg.model_config = SimpleNamespace(is_multi_layer_eagle=False) - cfg.kv_cache_dtype = _DTYPE + cfg.kv_cache_dtype = host_kv_dtype cfg.spec_aux_config = SimpleNamespace( eagle_draft_num_layers=1, draft_kv_num_layers=1, + dflash_draft_num_layers=1, draft_model_config=SimpleNamespace( is_hybrid_swa=False, is_deepseek_v4_arch=False, @@ -264,15 +289,37 @@ class TestFusedDraftDecision(CustomTestCase): attention_arch=attention_arch or AttentionArch.MHA, ), ) - memory = SimpleNamespace(enable_unified_memory=True) + memory = SimpleNamespace( + enable_unified_memory=True, enable_hierarchical_cache=hicache + ) spec = SimpleNamespace( - speculative_num_steps=1, speculative_draft_kv_cache_dtype=draft_kv_dtype + speculative_num_steps=1, + speculative_draft_kv_cache_dtype=draft_kv_dtype, + speculative_draft_attention_backend=draft_backend, ) with ( patch.object(kvc, "get_memory", return_value=memory), + patch.object( + kvc, + "get_disagg", + return_value=SimpleNamespace( + disaggregation_decode_retraction_backup=retraction_backup + ), + ), patch.object(kvc, "get_spec", return_value=spec), + patch.object( + kvc, + "get_model", + return_value=SimpleNamespace(kv_cache_dtype=kv_cache_dtype_flag), + ), + patch.object(kvc, "attention_backends", return_value=target_backends), + patch.object(draft_worker_common, "get_spec", return_value=spec), + patch.object( + draft_worker_common, "attention_backends", return_value=target_backends + ), patch("sglang.srt.configs.hybrid_arch.mambaish_config", return_value=None), - get_parallel().override(attn_tp_size=1), + get_parallel().override(attn_tp_size=1, attn_dcp_size=dcp_size), + override_platform(is_xpu=False, is_hip=False), ): return cfg._fused_draft_decision() @@ -290,43 +337,120 @@ class TestFusedDraftDecision(CustomTestCase): def test_a_draft_kv_dtype_unlike_the_host_keeps_the_private_pool(self): """A fused draft stores its rows in the host's KV dtype; an explicit - draft dtype that differs declines instead of mis-typing those rows.""" + draft dtype that differs declines instead of mis-typing those rows, + and one that matches the host's fuses.""" self.assertIsNotNone(self._decide(draft_kv_dtype="auto").placement) declined = self._decide(draft_kv_dtype="fp8_e4m3") self.assertIsNone(declined.placement) self.assertIn("KV cache dtype", declined.declined) + for algorithm in ("EAGLE", "DFLASH"): + placed = self._decide( + algorithm=algorithm, + draft_kv_dtype="fp8_e4m3", + host_kv_dtype=torch.float8_e4m3fn, + kv_cache_dtype_flag="fp8_e4m3", + ) + self.assertIsNotNone(placed.placement, algorithm) + + def test_a_draft_off_the_translated_rails_keeps_the_private_pool(self): + """A fused draft reads its rows through the KV-index translator, which + only triton, flashinfer and fa3 carry on every draft path. The draft's + backend is the published one, a model hook's declaration included; + otherwise it is what the draft runner inherits from the target.""" + # Kimi-Linear + DSPARK on SM100, where a model hook declares trtllm_mha. + declined = self._decide(algorithm="DSPARK", draft_backend="trtllm_mha") + self.assertIsNone(declined.placement) + self.assertIn("trtllm_mha", declined.declined) + # A DFLASH-family draft runs the target's prefill backend, or the + # platform default when that is not a draft backend. + for target_backends, fuses in ( + (("fa4", "fa4"), False), + (("fa3", "flashmla"), True), + (("flashmla", "flashmla"), True), + ): + decision = self._decide(algorithm="DSPARK", target_backends=target_backends) + self.assertEqual(decision.placement is not None, fuses, target_backends) + # An EAGLE draft with no backend of its own runs the target's pair. + self.assertIsNone(self._decide(target_backends=("fa3", "flashmla")).placement) + + def test_dcp_keeps_the_private_pool(self): + """Under --dcp-size > 1 each rank's host rows hold only its share of + the widened id space, while the draft, outside the DCP group, reads + every token.""" + for algorithm in ("DSPARK", "EAGLE"): + declined = self._decide(algorithm=algorithm, dcp_size=2) + self.assertIsNone(declined.placement, algorithm) + self.assertIn("--dcp-size 2", declined.declined) + + def test_hierarchical_cache_keeps_the_private_pool(self): + """HiCache builds the draft's host pool off its own device pool, which + a fused draft does not have; DSPARK + HiCache keeps working on the + private pool.""" + declined = self._decide(algorithm="DSPARK", hicache=True) + self.assertIsNone(declined.placement) + self.assertIn("--enable-hierarchical-cache", declined.declined) + + def test_host_pool_retraction_keeps_the_private_pool(self): + """Host-pool decode retraction builds the draft's host pool off its + own device pool too; DSPARK with it keeps the private pool.""" + declined = self._decide(algorithm="DSPARK", retraction_backup="host_pool") + self.assertIsNone(declined.placement) + self.assertIn( + "--disaggregation-decode-retraction-backup=host_pool", declined.declined + ) class TestMambaHostPrivateDraftRefused(CustomTestCase): """A mamba host's unified buffer takes the whole KV budget, so a private - EAGLE draft pool on top of it would overcommit; the fused arm is the only - EAGLE arm such a host builds.""" + draft pool on top of it would overcommit; the fused arm is the only + EAGLE-family or DFLASH arm such a host builds. A DSPARK draft that does + not fuse keeps its private pool.""" - def _resolve(self, *, decision, eagle=True): + _DECLINED = "the draft's K/V rows are asymmetric" + + def _resolve(self, *, decision, algorithm="EAGLE"): from sglang.srt.mem_cache import kv_cache_configurator as kvc + from sglang.srt.speculative.spec_info import SpeculativeAlgorithm cfg = kvc.KVCacheConfigurator.__new__(kvc.KVCacheConfigurator) cfg.is_draft_worker = False - cfg.spec_algorithm = SimpleNamespace(is_eagle=lambda: eagle) + cfg.spec_algorithm = SpeculativeAlgorithm[algorithm] with patch.object( kvc.KVCacheConfigurator, "_fused_draft_decision", return_value=decision ): return cfg._fused_draft_for_mamba_factory() def test_a_declined_eagle_draft_is_refused(self): + for algorithm in ("EAGLE", "EAGLE3"): + with self.subTest(algorithm=algorithm): + with self.assertRaisesRegex(ValueError, "rows are asymmetric"): + self._resolve( + decision=FusedDraftDecision(declined=self._DECLINED), + algorithm=algorithm, + ) + + def test_a_declined_dflash_draft_is_refused_and_dspark_keeps_its_pool(self): + """A DFLASH decliner is refused like EAGLE's; a DSPARK decliner keeps + its private pool instead of failing the boot.""" + declined = FusedDraftDecision(declined=self._DECLINED) with self.assertRaisesRegex(ValueError, "rows are asymmetric"): - self._resolve( - decision=FusedDraftDecision( - declined="the draft's K/V rows are asymmetric" - ) - ) + self._resolve(decision=declined, algorithm="DFLASH") + self.assertIsNone(self._resolve(decision=declined, algorithm="DSPARK")) def test_a_placed_draft_and_other_algorithms_pass(self): placement = _place(_profile()).placement - self.assertIs( - self._resolve(decision=FusedDraftDecision(placement=placement)), placement + for algorithm in ("EAGLE", "DFLASH", "DSPARK"): + with self.subTest(algorithm=algorithm): + self.assertIs( + self._resolve( + decision=FusedDraftDecision(placement=placement), + algorithm=algorithm, + ), + placement, + ) + self.assertIsNone( + self._resolve(decision=FusedDraftDecision(), algorithm="NONE") ) - self.assertIsNone(self._resolve(decision=FusedDraftDecision(), eagle=False)) class TestSWAHostPrivateDraftRefused(CustomTestCase): diff --git a/test/registered/unit/mem_cache/test_kv_cache_configurator_draft_gate.py b/test/registered/unit/mem_cache/test_kv_cache_configurator_draft_gate.py index d5a2ac9831..b40273a815 100644 --- a/test/registered/unit/mem_cache/test_kv_cache_configurator_draft_gate.py +++ b/test/registered/unit/mem_cache/test_kv_cache_configurator_draft_gate.py @@ -241,7 +241,10 @@ class TestDraftBindingDispatch(CustomTestCase): max_total_num_tokens, kv_dtype=torch.bfloat16, state_layers=(), + req_to_token_pool="shared", ): + if req_to_token_pool == "shared": + req_to_token_pool = object() cfg = kcc.KVCacheConfigurator.__new__(kcc.KVCacheConfigurator) cfg.kv_cache_dtype = kv_dtype cfg.is_draft_worker = True @@ -268,6 +271,8 @@ class TestDraftBindingDispatch(CustomTestCase): def _capture(self, *, sizes, **kw): raise _CapturedSizes(sizes) + built_req_pool = SimpleNamespace(kind="private-compact") + with ( patch.object( kcc, @@ -294,10 +299,15 @@ class TestDraftBindingDispatch(CustomTestCase): "draft_state_layer_classes", return_value=list(state_layers), ), + patch.object( + kcc.KVCacheConfigurator, + "_build_req_to_token_pool", + lambda self, *, max_num_reqs: built_req_pool, + ), ): return cfg._init_pools( sizes=sizes, - req_to_token_pool=object(), + req_to_token_pool=req_to_token_pool, token_to_kv_pool_allocator=alloc, ) @@ -374,6 +384,33 @@ class TestDraftBindingDispatch(CustomTestCase): state_layers=["MambaMixer2"], ) + def test_dspark_draft_with_a_region_binds_the_fused_pool(self): + """DSPARK's draft KV fuses when the target resolved a region (its + block rows are indexed by the same token->page identity); the + region-less private arm above remains the automatic fallback.""" + alloc = self._swa_allocator(with_draft_region=True) + pools = self._run( + algorithm=SpeculativeAlgorithm.DSPARK, + alloc=alloc, + max_total_num_tokens=alloc.size_full, + ) + self.assertIsInstance(pools.token_to_kv_pool, UnifiedDraftKVPool) + + def test_compact_dflash_draft_fuses_with_a_private_req_table(self): + """Compact-window DFLASH passes req_to_token_pool=None (it keeps a + private table narrowing WHICH pages the draft reads) while the KV + itself stays fused: the fused arm must build that table instead of + refusing the None.""" + alloc = self._swa_allocator(with_draft_region=True) + pools = self._run( + algorithm=SpeculativeAlgorithm.DFLASH, + alloc=alloc, + max_total_num_tokens=alloc.size_full, + req_to_token_pool=None, + ) + self.assertIsInstance(pools.token_to_kv_pool, UnifiedDraftKVPool) + self.assertEqual(pools.req_to_token_pool.kind, "private-compact") + def test_eagle_draft_without_a_placement_falls_back_to_the_private_arm(self): """Target boot declines a placement for legitimate configurations (a draft with SWA layers of its own, asymmetric rows), so a diff --git a/test/registered/unit/mem_cache/test_kv_index_translator_draft_disposition.py b/test/registered/unit/mem_cache/test_kv_index_translator_draft_disposition.py index c634e9a5a0..2056a50d5a 100644 --- a/test/registered/unit/mem_cache/test_kv_index_translator_draft_disposition.py +++ b/test/registered/unit/mem_cache/test_kv_index_translator_draft_disposition.py @@ -142,7 +142,7 @@ def _source(allocator, pool_obj): ) -class TestKVIndexSourceDraftDisposition(unittest.TestCase): +class TestKVIndexTranslatorDraftDisposition(unittest.TestCase): def setUp(self): # `KVIndexTranslator.__init__` reads `attn_dcp_size`, a derived # parallel width that only exists once a config is published. @@ -222,6 +222,203 @@ class TestKVIndexSourceDraftDisposition(unittest.TestCase): src = _source(allocator, other_draft) self.assertFalse(src.is_translating) + def test_seq_len_delta_matches_widened_lens(self): + """``seq_len_delta=k`` must be byte-identical to building with + ``seq_lens + k`` -- the two spellings of the whole-sequence verify + widening. A kernel applying the delta to the page count but not the + loads (or vice versa) silently truncates the verify tail.""" + _, allocator, kvcache, _ = _build() + v = allocator.alloc(6 * _PS) + self.assertIsNotNone(v) + rt = torch.zeros((2, 16), dtype=torch.int32) + rt[0, : v.numel()] = v.to(torch.int32) + src = KVIndexTranslator( + req_to_token=rt, + token_to_kv_pool_allocator=allocator, + token_to_kv_pool=kvcache, + page_size=_PS, + device=_DEV, + ) + rpi = torch.tensor([0], dtype=torch.int64) + seq = torch.tensor([3], dtype=torch.int64) + delta = 2 * _PS + 1 + max_pages = -(-(3 + delta) // _PS) + widened = src.build_index_table( + req_pool_indices=rpi, + seq_lens=seq, + max_pages=max_pages, + seq_len_delta=delta, + ) + by_lens = src.build_index_table( + req_pool_indices=rpi, seq_lens=seq + delta, max_pages=max_pages + ) + torch.testing.assert_close(widened.ids, by_lens.ids, rtol=0, atol=0) + # The delta genuinely widened: entries exist past the unwidened prefix. + plain_pages = -(-3 // _PS) + self.assertTrue(bool((widened.ids[0, plain_pages:] > 0).any())) + + def test_widened_index_table_matches_widened_lens(self): + """`widened_index_table` (the verify entry point) must equal the + widened-lens build over the SAME batch: derive max_pages from the + widened max and forward the delta. Deriving max_pages from the + un-widened lens silently truncates the verify tail's pages.""" + _, allocator, kvcache, _ = _build() + v = allocator.alloc(6 * _PS) + self.assertIsNotNone(v) + rt = torch.zeros((2, 16), dtype=torch.int32) + rt[0, : v.numel()] = v.to(torch.int32) + src = KVIndexTranslator( + req_to_token=rt, + token_to_kv_pool_allocator=allocator, + token_to_kv_pool=kvcache, + page_size=_PS, + device=_DEV, + ) + rpi = torch.tensor([0], dtype=torch.int64) + seq = torch.tensor([3], dtype=torch.int64) + delta = 2 * _PS + 1 + fb = SimpleNamespace( + req_pool_indices=rpi, + seq_lens=seq, + seq_lens_cpu=seq.cpu(), + # `seq_lens_sum` is the liveness signal for seq_lens_cpu: it is a + # non-None but STALE slice on a gpu_only batch, so the build only + # trusts it when the sum is present. Without the field the stand-in + # batch falls back to the full req_to_token width. + seq_lens_sum=int(seq.sum()), + out_cache_loc=None, + spec_info=None, + ) + widened = src.widened_index_table(fb, seq_len_delta=delta) + max_pages = -(-(3 + delta) // _PS) + by_lens = src.build_index_table( + req_pool_indices=rpi, seq_lens=seq + delta, max_pages=max_pages + ) + self.assertEqual(widened.ids.shape, by_lens.ids.shape) + torch.testing.assert_close(widened.ids, by_lens.ids, rtol=0, atol=0) + + def test_target_hidden_writers_write_physical_ids(self): + """BUG REGRESSION. DFLASH and DSPARK do not compute their draft KV from + the draft's own forward -- they PROJECT the target's hidden states and + write them straight into the draft pool, at locs read off the target's + req_to_token (VIRTUAL). Under fusion the draft pool takes the target's + physical ids, so an untranslated write lands at the wrong row: the + draft attends over the wrong KV and accept length collapses to 1.0 + with no crash. Each writer must hand the pool translated ids and leave + the caller's locs virtual (the compact req_to_token rebuild re-reads + them).""" + from sglang.srt.speculative.dflash_worker_v2 import DFlashWorkerV2 + from sglang.srt.speculative.dspark_components.dspark_kv_inject import ( + TargetHiddenKvInjector, + ) + + class _Shift: + """A translating runner whose physical id is the virtual + 100.""" + + is_translating = True + + def translate_full_attn_ids(self, ids, *, out=None): + return ids + 100 + + virtual = torch.tensor([4, 5, 6, 9], dtype=torch.int64) + physical = virtual + 100 + hidden = torch.randn(4, 8) + positions = torch.arange(4) + commit_lens = torch.tensor([2, 1], dtype=torch.int32) + + writes = {} + + class _DflashPool: + def set_kv_buffer(self, layer, loc, k, v, k_scale, v_scale): + writes["loc"] = loc + + def set_kv_buffer_prefix_valid( + self, layer, cache_loc_2d, commit_lens, k, v, k_scale, v_scale + ): + writes["loc_2d"] = cache_loc_2d + + attn = SimpleNamespace( + kv_proj_only=lambda h: (h[:, :4], h[:, 4:]), + apply_k_norm=lambda k: k, + apply_k_rope=lambda pos, k: k, + num_kv_heads=1, + head_dim=4, + attn=SimpleNamespace(k_scale=None, v_scale=None), + ) + worker = SimpleNamespace( + model_runner=SimpleNamespace(device=torch.device(_DEV)), + draft_model_runner=SimpleNamespace( + kv_index_translator=_Shift(), token_to_kv_pool=_DflashPool() + ), + draft_model=SimpleNamespace( + project_target_hidden=lambda h: h, + prepare_context_hidden_for_kv=lambda layer, h: h, + layers=[SimpleNamespace(self_attn=attn)], + ), + draft_owns_attention=False, + lilicorr=None, + _use_fused_kv_materialize=False, + _fused_kv_helper=None, + ) + worker._append_target_hidden_sequential = lambda **kw: ( + DFlashWorkerV2._append_target_hidden_sequential(worker, **kw) + ) + + # Per-token writes (prefill). + cache_loc = virtual.clone() + DFlashWorkerV2._append_target_hidden_to_draft_kv_by_loc( + worker, target_hidden=hidden, cache_loc=cache_loc, positions=positions + ) + self.assertTrue(writes["loc"].physical) + torch.testing.assert_close(writes["loc"].loc, physical, rtol=0, atol=0) + torch.testing.assert_close(cache_loc, virtual, rtol=0, atol=0) + + # Prefix-valid writes (post-verify), from the 2-D view of the same ids. + cache_loc, cache_loc_2d = virtual.clone(), virtual.clone().view(2, 2) + DFlashWorkerV2._append_target_hidden_to_draft_kv_by_loc( + worker, + target_hidden=hidden, + cache_loc=cache_loc, + positions=positions, + cache_loc_2d=cache_loc_2d, + commit_lens=commit_lens, + ) + torch.testing.assert_close( + writes["loc_2d"], physical.view(2, 2), rtol=0, atol=0 + ) + torch.testing.assert_close(cache_loc_2d, virtual.view(2, 2), rtol=0, atol=0) + + # DSPARK's injector, on an MHA draft pool. + injected = {} + + def write_target_hidden_kv(**kwargs): + injected.update(kwargs) + + injector = TargetHiddenKvInjector( + draft_model=SimpleNamespace(write_target_hidden_kv=write_target_hidden_kv), + draft_model_runner=SimpleNamespace( + kv_index_translator=_Shift(), token_to_kv_pool=SimpleNamespace() + ), + model_runner=SimpleNamespace(device=torch.device(_DEV)), + device=torch.device(_DEV), + verify_num_draft_tokens=2, + block_pos_offsets=torch.arange(2), + ) + cache_loc, cache_loc_2d = virtual.clone(), virtual.clone().view(2, 2) + injector.inject_target_hidden( + target_hidden=hidden, + cache_loc=cache_loc, + positions=positions, + cache_loc_2d=cache_loc_2d, + commit_lens=commit_lens, + ) + torch.testing.assert_close(injected["cache_loc"], physical, rtol=0, atol=0) + torch.testing.assert_close( + injected["cache_loc_2d"], physical.view(2, 2), rtol=0, atol=0 + ) + torch.testing.assert_close(cache_loc, virtual, rtol=0, atol=0) + torch.testing.assert_close(cache_loc_2d, virtual.view(2, 2), rtol=0, atol=0) + def test_full_flat_v2p_per_disposition(self): """The flat-translate accessor must hand a kernel exactly what `translate_kv_loc` would use: the shared v2p table on the target and diff --git a/test/registered/unit/server_args/test_unified_memory_spec_gate.py b/test/registered/unit/server_args/test_unified_memory_spec_gate.py index 1e008d1d50..de06e543a7 100644 --- a/test/registered/unit/server_args/test_unified_memory_spec_gate.py +++ b/test/registered/unit/server_args/test_unified_memory_spec_gate.py @@ -13,21 +13,32 @@ # ============================================================================== """`--enable-unified-memory` speculative-decoding allow-list. -Two audited arms, each with its own constraints because each rides a different -draft-KV story: - * DSPARK: a chain draft whose KV lives in a pool of its own; verify runs on - every backend whose spec path builds through the KV-index translator. - * EAGLE/EAGLE3: the draft's KV lives FUSED inside the target's full-attention - page envelope, which only the hybrid-SWA unified composite provisions, so - the target family is constrained too. Its backends are the MHA-shaped - subset -- the MLA verify family cannot serve an MHA draft -- and they are - demanded EXPLICITLY, for the draft worker as well (it resolves its own - backend: explicit flag first, else it inherits the target's). +Three audited arms (see `handle_unified_memory_pool`), each with its own +backend constraints: + * DSPARK: the target verifies on the audited verify set (`triton` / + `trtllm_mla` / `cutedsl_mla` / `tokenspeed_mla` / `flashmla` / + `flashinfer` / `fa3`, which includes the MLA family). Its draft fuses + into the target's pages when the fused-draft decision allows, else keeps + a private pool, so the gate leaves the draft backend unconstrained. + * DFLASH: the target verifies on `triton` / `fa3` / `flashinfer`; the MLA + verify family must not leak into this arm. + * EAGLE/EAGLE3: unified targets only (hybrid-SWA or mamba hybrids, either + full-pool kind) -- the draft's KV lives fused inside the full pool's + page envelope (`DenseDraftRegion`), and a draft that does not fuse is + refused at boot. The target's verify set follows the + host kind: the audited verify set on an MLA host, `triton` / + `flashinfer` / `fa3` on an MHA host, and an unresolved backend is + refused. The draft worker (its backend resolves separately: explicit + flag first, else it inherits the target's) runs on `triton` / + `flashinfer` / `fa3`. -Pinned so no arm silently widens to an unaudited algorithm, tree shape, or -backend. The backend set in particular is a claim about code that exists: a -backend listed here MUST have a translated spec path, or a unified run on it -reads the pool with virtual ids and silently returns wrong tokens. +Every arm drafts a linear chain (`--speculative-eagle-topk` in {None, 1}). +Everything else (NGRAM / STANDALONE / registered customs) stays refused. +NGRAM's refusal is load-bearing, not pending: like tree verify it relocates +accepted tokens one at a time inside the target pool, which the unified +pool's page-granular `move_kv_cache` cannot express. Pinned so no arm silently +widens to an unaudited algorithm, family, tree shape, or backend -- and so one +arm's addition never perturbs another. python -m pytest test/registered/unit/server_args/test_unified_memory_spec_gate.py -v """ @@ -61,14 +72,14 @@ class _PlainHFConfig: def _accepts( algorithm: str | None, *, + is_hybrid_swa: bool = True, topk: int | None = 1, backend: str | None = "triton", - is_hybrid_swa: bool = True, - attention_arch: AttentionArch = AttentionArch.MHA, draft_backend: str | None = None, dcp_size: int = 1, retraction_backup: str | None = None, fields: dict | None = None, + attention_arch: AttentionArch = AttentionArch.MHA, ) -> bool: """Run just `handle_unified_memory_pool` against a minimal stand-in. @@ -110,7 +121,7 @@ def _accepts( class TestUnifiedMemorySpecGate(unittest.TestCase): - # Backends whose speculative verify path builds through the translator. + # Verify-audited backends for the DSPARK arm (includes the MLA family). DSPARK_BACKENDS = ( "triton", "trtllm_mla", @@ -120,11 +131,16 @@ class TestUnifiedMemorySpecGate(unittest.TestCase): "flashinfer", "fa3", ) + # The translated MHA rails: the EAGLE and DFLASH arms' target backends + # on an MHA host, and every fused draft's backend. + MHA_RAILS = ("triton", "flashinfer", "fa3") # Algorithms with no audited unified-pool verify rails. - # Backends the FUSED draft arm can verify on (MHA-shaped). - EAGLE_BACKENDS = ("triton", "flashinfer", "fa3") - # Algorithms with no audited unified-pool verify rails. - UNAUDITED_ALGORITHMS = ("DFLASH", "NGRAM", "STANDALONE") + # "NEXTN" is deliberately absent: the CLI alias collapses it to + # "EAGLE" in handle_speculative_decoding BEFORE this gate runs + # (arg_groups/pipeline.py orders the hooks), so the raw string can + # never reach the gate -- a case on it would test an impossible + # input. The aliased spelling is covered by the EAGLE cases. + UNAUDITED_ALGORITHMS = ("NGRAM", "STANDALONE") def test_dspark_admitted_on_every_audited_backend(self): """Each entry is a claim that the backend's spec verify path @@ -144,20 +160,21 @@ class TestUnifiedMemorySpecGate(unittest.TestCase): def test_tree_drafting_refused(self): """Tree verify needs a per-token move inside the TARGET pool, which the unified pool's page-granular `move_kv_cache` cannot express. - DSPARK is the only admitted algorithm today, so it is the only one - that can demonstrate the rule; the check itself is unconditional, so - it keeps holding as further arms are admitted.""" + DSPARK demonstrates the rule here; the check itself is unconditional, + so it holds for every admitted arm.""" for topk in (2, 4, 8): self.assertFalse(_accepts("DSPARK", topk=topk)) # The shape knob must not disturb spec-off. self.assertTrue(_accepts(None, topk=None)) def test_dspark_draft_backend_is_not_constrained(self): - """DSPARK's draft owns a KV pool indexed directly by virtual id, so - its translator is a passthrough and any draft backend reads correctly. - Model hooks declare one on the operator's behalf -- Kimi-Linear / - Kimi-K3 + DSPARK on SM100 declares `trtllm_mha` -- so refusing it - would refuse a configuration the operator never touched.""" + """The gate does not constrain DSPARK's draft backend: a draft whose + backend is off the translated rails keeps a private pool (the + fused-draft decision declines fusion), where its translator is a + passthrough and any backend reads correctly. Model hooks declare one + on the operator's behalf -- Kimi-Linear / Kimi-K3 + DSPARK on SM100 + declares `trtllm_mha` -- so refusing it would refuse a configuration + the operator never touched.""" for draft_backend in (None, *self.DSPARK_BACKENDS, "fa4", "trtllm_mha"): self.assertTrue( _accepts("DSPARK", draft_backend=draft_backend), @@ -197,16 +214,34 @@ class TestUnifiedMemorySpecGate(unittest.TestCase): ) ) + def test_dflash_admitted_only_on_its_verify_backends(self): + """DFLASH's target verifies on triton / fa3 / flashinfer. fa4 and + trtllm_mha have no translated spec verify path, and the MLA verify + family the DSPARK arm admits must not leak into this arm.""" + for backend in self.MHA_RAILS: + self.assertTrue( + _accepts("DFLASH", backend=backend), + f"DFLASH should pass on verify-audited backend {backend}", + ) + for backend in ("fa4", "trtllm_mha") + tuple( + b for b in self.DSPARK_BACKENDS if b not in self.MHA_RAILS + ): + self.assertFalse( + _accepts("DFLASH", backend=backend), + f"DFLASH must be refused on backend {backend}", + ) + def test_eagle_family_admitted_on_hybrid_swa(self): - """EAGLE/EAGLE3 chain on a hybrid-SWA target is the fused-draft-KV - configuration -- both spellings, resolved or unset topk, on every - MHA-shaped audited backend.""" + """EAGLE/EAGLE3 chain on a hybrid-SWA target with audited verify + backends is the fused-draft-KV configuration -- both spellings, + resolved or unset topk, every audited backend.""" for algorithm in ("EAGLE", "EAGLE3"): for topk in (None, 1): - for backend in self.EAGLE_BACKENDS: + for backend in self.MHA_RAILS: self.assertTrue( _accepts(algorithm, topk=topk, backend=backend), - f"{algorithm} topk={topk} backend={backend} should pass", + f"{algorithm} topk={topk} backend={backend} should " + "pass on a hybrid-SWA target", ) def test_eagle_refused_on_dense_targets(self): @@ -216,9 +251,9 @@ class TestUnifiedMemorySpecGate(unittest.TestCase): self.assertFalse(_accepts(algorithm, is_hybrid_swa=False)) def test_eagle_admitted_on_mamba_mha(self): - """A mamba hybrid off the MLA backend provisions the region in its - MHA full sub-pool; refusing it strands the whole mamba x EAGLE - matrix.""" + """A mamba hybrid off the MLA backend provisions the fused draft + region in its MHA full sub-pool; refusing it here strands the whole + mamba x EAGLE matrix.""" with patch.object(kv_cache_hook, "mambaish_config", return_value=object()): for algorithm in ("EAGLE", "EAGLE3"): self.assertTrue(_accepts(algorithm, is_hybrid_swa=False)) @@ -262,29 +297,42 @@ class TestUnifiedMemorySpecGate(unittest.TestCase): ) ) - def test_eagle_refused_unaudited_and_unset_backends(self): - """The MLA verify family must not leak into the MHA-shaped arm. A real - boot resolves the default backend before this gate runs, so it checks - that resolved default; an unresolved one is refused rather than - trusted.""" - for backend in ("fa4", "trtllm_mha", "trtllm_mla", "flashmla"): + def test_eagle_refused_tree_topk(self): + """Tree verify is not audited for the unified pool; only a linear + chain passes.""" + for topk in (2, 4, 8): + self.assertFalse(_accepts("EAGLE", topk=topk)) + + def test_eagle_refused_unaudited_backends(self): + """Unaudited backends stay out, and the MLA verify set from the + DSPARK arm must not leak into the EAGLE arm.""" + for backend in ("fa4", "trtllm_mha") + tuple( + b for b in self.DSPARK_BACKENDS if b not in self.MHA_RAILS + ): self.assertFalse(_accepts("EAGLE", backend=backend)) + + def test_eagle_refused_unset_backend(self): + """A real boot resolves the default backend before this gate runs, so + an unset one here is unresolved: the gate refuses it rather than + trusting it.""" self.assertFalse(_accepts("EAGLE", backend=None)) def test_eagle_draft_backend_pinned(self): """The draft worker resolves its own backend: unset inherits the - target's, explicit audited passes, anything else refuses.""" + target's (triton here), an explicit triton / flashinfer / fa3 passes, + and anything else refuses.""" self.assertTrue(_accepts("EAGLE", draft_backend=None)) - for draft_backend in self.EAGLE_BACKENDS: + for draft_backend in self.MHA_RAILS: self.assertTrue(_accepts("EAGLE", draft_backend=draft_backend)) for draft_backend in ("fa4", "trtllm_mha"): self.assertFalse(_accepts("EAGLE", draft_backend=draft_backend)) def test_hierarchical_cache_refused_with_an_eagle_draft(self): - """HiCache builds a draft host pool off the draft's device pool, and a - fused draft view has no transfer surface of its own: the page-envelope - host pool refuses per-layer draft loads. Without a draft, or with - DSPARK's private pool, HiCache is not this gate's to refuse.""" + """Under HiCache an EAGLE draft keeps a private pool, and an MTP + head's KV would be packed into the target's page-envelope host pool, + which refuses per-layer draft loads. Without a draft HiCache is not + this gate's to refuse, and with DSPARK HiCache declines draft fusion, + so the draft keeps its private pool.""" hicache = {"enable_hierarchical_cache": True} for algorithm in ("EAGLE", "EAGLE3"): self.assertFalse(_accepts(algorithm, fields=hicache)) @@ -292,10 +340,8 @@ class TestUnifiedMemorySpecGate(unittest.TestCase): self.assertTrue(_accepts("DSPARK", fields=hicache)) def test_pd_decode_refusals_raise_their_own_assertions(self): - """The PD-decode branches screen the model with `mambaish_config`. A - function-local import of that name further down made it local to the - whole handler, so these branches raised UnboundLocalError instead of - their refusal.""" + """The PD-decode branches screen the model with `mambaish_config` and + refuse with their own assertion, not an error from the screen.""" pd_decode = { "disaggregation_mode": "decode", "disaggregation_transfer_backend": "mooncake", @@ -314,17 +360,58 @@ class TestUnifiedMemorySpecGate(unittest.TestCase): _accepts(None, is_hybrid_swa=False, fields={**pd_decode, **extra}) ) + def test_host_pool_retraction_refused_with_an_eagle_draft(self): + """The host-pool retraction backup builds the draft's host pool off + its device pool, which an EAGLE draft, always fused on the unified + pool, does not have. Without a draft the backup is not this gate's to + refuse, and with DFLASH or DSPARK it declines draft fusion instead.""" + for algorithm in ("EAGLE", "EAGLE3"): + with self.subTest(algorithm=algorithm): + self.assertTrue(_accepts(algorithm)) + self.assertFalse(_accepts(algorithm, retraction_backup="host_pool")) + for algorithm in (None, "DFLASH", "DSPARK"): + with self.subTest(algorithm=algorithm): + self.assertTrue(_accepts(algorithm, retraction_backup="host_pool")) + + def test_dspark_arm_unchanged(self): + """The EAGLE addition must not perturb DSPARK: its MLA verify set + passes, its chain constraint holds, and unaudited backends refuse.""" + for backend in self.DSPARK_BACKENDS: + self.assertTrue( + _accepts("DSPARK", backend=backend), + f"DSPARK should pass on verify-audited backend {backend}", + ) + self.assertFalse(_accepts("DSPARK", backend="fa4")) + self.assertFalse(_accepts("DSPARK", topk=4)) + + def test_ngram_refused_because_it_relocates_target_kv_per_token(self): + """BUG REGRESSION. NGRAM was admitted on the reasoning that + it carries no draft KV, so only the target-verify rails matter. But a + tree-shaped drafter finalizes a batch through + `move_accept_tokens_to_target_kvcache`, which relocates INDIVIDUAL + accepted tokens inside the target pool -- and the unified pool's + `move_kv_cache` is compaction-only (whole page envelopes). Every + unified NGRAM cell died there: a reshape past the end on the MHA/mamba + hosts, and the SWA composite's explicit refusal on gpt-oss. Admitting + it again without a per-token move primitive re-breaks every family.""" + for backend in self.DSPARK_BACKENDS: + self.assertFalse( + _accepts("NGRAM", backend=backend), + f"NGRAM must stay refused (backend={backend})", + ) + def test_spec_off_admitted(self): """The gate constrains only speculative configurations; spec-off must - keep booting.""" - self.assertTrue(_accepts(None)) + keep booting regardless of family.""" + for is_hybrid_swa in (True, False): + self.assertTrue(_accepts(None, is_hybrid_swa=is_hybrid_swa)) def test_unaudited_algorithms_refused(self): """Every other algorithm stays out until its verify id rails are - audited -- on every backend.""" + audited -- on every family.""" for algorithm in self.UNAUDITED_ALGORITHMS: - for backend in ("triton", "fa3"): - self.assertFalse(_accepts(algorithm, backend=backend)) + for is_hybrid_swa in (True, False): + self.assertFalse(_accepts(algorithm, is_hybrid_swa=is_hybrid_swa)) if __name__ == "__main__": diff --git a/test/registered/unit/spec/test_dspark_target_hidden_projection.py b/test/registered/unit/spec/test_dspark_target_hidden_projection.py index 2f85aa8f0b..5ea002c44d 100644 --- a/test/registered/unit/spec/test_dspark_target_hidden_projection.py +++ b/test/registered/unit/spec/test_dspark_target_hidden_projection.py @@ -91,7 +91,12 @@ class DSparkTargetHiddenProjectionTest(CustomTestCase): pool = SimpleNamespace(set_kv_buffer=mock.Mock()) injector = TargetHiddenKvInjector( draft_model=draft_model, - draft_model_runner=SimpleNamespace(token_to_kv_pool=pool), + draft_model_runner=SimpleNamespace( + token_to_kv_pool=pool, + kv_index_translator=SimpleNamespace( + translate_full_attn_ids=lambda ids: ids + ), + ), model_runner=SimpleNamespace(device=torch.device("cpu")), device=torch.device("cpu"), verify_num_draft_tokens=2,