[unified-memory] Admit DFLASH and DSPARK with fused draft KV (#40492)

Co-authored-by: Caihua Li <caihua.li@bytedance.com>
Co-authored-by: Cheng Wan <cheng.wan@radixark.ai>
This commit is contained in:
caihuali95
2026-10-08 00:56:21 -07:00
committed by GitHub
co-authored by Caihua Li Cheng Wan
parent c2d491e38b
commit 508ddc859a
15 changed files with 778 additions and 185 deletions
+57 -28
View File
@@ -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)
@@ -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)
@@ -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(
@@ -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,
@@ -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
+2 -1
View File
@@ -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),
@@ -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
@@ -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
@@ -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 (
@@ -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: