Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 41 additions & 0 deletions python/sglang/srt/models/dflash.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@
can_dflash_slice_qkv_weight,
get_dflash_attention_sliding_window_size,
get_dflash_layer_types,
is_dflash_domino_projector,
parse_dflash_draft_config,
)
from sglang.srt.utils import is_npu
Expand Down Expand Up @@ -349,6 +350,43 @@ def __init__(self, config, quant_config=None, prefix: str = "") -> None:

self.block_size = draft_config.resolve_block_size(default=16)

# Optional Domino projector (GRU prefix encoder + MLP that emits a per-step
# bias on top of the target lm_head logits). Older checkpoints used
# projector_type=causal_v5; public checkpoints use projector_type=domino.
self.projector_type: Optional[str] = draft_config.projector_type
self.pure_draft_prefix_len: int = int(draft_config.pure_draft_prefix_len)
self.shift_label: bool = bool(draft_config.shift_label)
self.gru_hidden_dim: Optional[int] = draft_config.gru_hidden_dim
self.emb_dim: Optional[int] = draft_config.emb_dim

if is_dflash_domino_projector(self.projector_type):
if self.gru_hidden_dim is None or self.emb_dim is None:
raise ValueError(
"DFLASH Domino requires gru_hidden_dim and emb_dim. "
f"gru_hidden_dim={self.gru_hidden_dim}, emb_dim={self.emb_dim}."
)
vocab_size = int(getattr(config, "vocab_size", 0))
if vocab_size <= 0:
raise ValueError(
f"DFLASH Domino requires positive vocab_size, got {vocab_size}."
)
self.prefix_gru = nn.GRU(
input_size=hidden_size,
hidden_size=int(self.gru_hidden_dim),
num_layers=1,
batch_first=True,
bias=False,
)
self.embed_proj = nn.Sequential(
nn.Linear(
hidden_size + int(self.gru_hidden_dim),
int(self.emb_dim),
bias=False,
),
nn.SiLU(),
nn.Linear(int(self.emb_dim), vocab_size, bias=False),
)

def get_attention_sliding_window_size(self) -> Optional[int]:
return get_dflash_attention_sliding_window_size(self.config)

Expand Down Expand Up @@ -455,5 +493,8 @@ def resolve_param_name(name: str) -> Optional[str]:
weight_loader = getattr(param, "weight_loader", default_weight_loader)
weight_loader(param, loaded_weight)

if hasattr(self, "prefix_gru") and self.prefix_gru is not None:
self.prefix_gru.flatten_parameters()


EntryClass = DFlashDraftModel
90 changes: 87 additions & 3 deletions python/sglang/srt/speculative/dflash_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,10 @@

import logging
from collections.abc import Sequence
from dataclasses import dataclass
from numbers import Integral
from typing import Any, List, Optional, Tuple

import msgspec
import torch
import torch.nn.functional as F

Expand All @@ -17,8 +17,21 @@

DEFAULT_DFLASH_MASK_TOKEN = "<|MASK|>"

# Projectors supported by the SGLang DFlash inference path. The public Domino
# checkpoints use projector_type="domino" for the GRU-prefix + MLP bias path.
# Keep causal_v5 as a backward-compatible alias for older internal checkpoints.
_DFLASH_DOMINO_PROJECTORS = frozenset({"domino", "causal_v5"})
_DFLASH_SUPPORTED_PROJECTORS: frozenset[Optional[str]] = frozenset(
{None, *_DFLASH_DOMINO_PROJECTORS}
)

logger = logging.getLogger(__name__)


def is_dflash_domino_projector(projector_type: Optional[str]) -> bool:
return projector_type in _DFLASH_DOMINO_PROJECTORS


_DFLASH_SAMPLING_VERIFY_AVAILABLE = False
_DFLASH_CHAIN_VERIFY_BUFFERS: dict[tuple[Optional[int], int], dict[str, Any]] = {}
_DFLASH_VERIFY_SKIP_CUSTOM_MASK_BACKENDS = frozenset(
Expand Down Expand Up @@ -415,14 +428,18 @@ def _parse_optional_int(
return parsed


@dataclass(frozen=True)
class DFlashDraftConfig:
class DFlashDraftConfig(msgspec.Struct, frozen=True):
num_hidden_layers: Optional[int]
num_target_layers: Optional[int]
block_size: Optional[int]
target_layer_ids: Optional[List[int]]
mask_token: str
mask_token_id: Optional[int]
projector_type: Optional[str] = None
gru_hidden_dim: Optional[int] = None
emb_dim: Optional[int] = None
pure_draft_prefix_len: int = 0
shift_label: bool = False

def require_num_layers(self) -> int:
if self.num_hidden_layers is None:
Expand Down Expand Up @@ -541,13 +558,80 @@ def parse_dflash_draft_config(*, draft_hf_config: Any) -> DFlashDraftConfig:
f"got {mask_token_id}."
)

projector_type = dflash_cfg.get("projector_type", None)
if projector_type is not None:
if not isinstance(projector_type, str) or not projector_type:
raise ValueError(
"DFLASH dflash_config.projector_type must be a non-empty string, "
f"got {projector_type!r}."
)
if projector_type not in _DFLASH_SUPPORTED_PROJECTORS:
raise ValueError(
"DFLASH dflash_config.projector_type is not supported by SGLang yet. "
f"Got projector_type={projector_type!r}, "
f"supported={sorted(p for p in _DFLASH_SUPPORTED_PROJECTORS if p is not None)}."
)

# Domino fields. emb_dim is top-level on the HF config (not inside dflash_config).
gru_hidden_dim = _parse_optional_int(
dflash_cfg.get("gru_hidden_dim", None),
field_name="DFLASH dflash_config.gru_hidden_dim",
min_value=1,
)
emb_dim = _parse_optional_int(
_cfg_get(draft_text_config, "emb_dim", None),
field_name="DFLASH emb_dim",
min_value=1,
)

pure_draft_prefix_len_raw = dflash_cfg.get("pure_draft_prefix_len", 0)
parsed_pure_draft_prefix_len = _parse_optional_int(
pure_draft_prefix_len_raw,
field_name="DFLASH dflash_config.pure_draft_prefix_len",
min_value=0,
)
pure_draft_prefix_len = (
0 if parsed_pure_draft_prefix_len is None else int(parsed_pure_draft_prefix_len)
)

shift_label_raw = dflash_cfg.get("shift_label", False)
if not isinstance(shift_label_raw, bool):
raise ValueError(
"DFLASH dflash_config.shift_label must be a bool, "
f"got {shift_label_raw!r} (type={type(shift_label_raw).__name__})."
)
shift_label = bool(shift_label_raw)

if is_dflash_domino_projector(projector_type):
if gru_hidden_dim is None:
raise ValueError(
"DFLASH Domino requires dflash_config.gru_hidden_dim to be set."
)
if emb_dim is None:
raise ValueError(
"DFLASH Domino requires top-level config.emb_dim to be set."
)
# The current SGLang adapter supports both shift_label=True and
# shift_label=False Domino/causal_v5 alignment, while still assuming the
# single pure-draft prefix token.
if pure_draft_prefix_len != 1:
raise NotImplementedError(
"DFLASH Domino currently requires dflash_config.pure_draft_prefix_len=1, "
f"got {pure_draft_prefix_len}."
)

return DFlashDraftConfig(
num_hidden_layers=num_hidden_layers,
num_target_layers=num_target_layers,
block_size=block_size,
target_layer_ids=parsed_target_layer_ids,
mask_token=mask_token,
mask_token_id=mask_token_id,
projector_type=projector_type,
gru_hidden_dim=gru_hidden_dim,
emb_dim=emb_dim,
pure_draft_prefix_len=pure_draft_prefix_len,
shift_label=shift_label,
)


Expand Down
61 changes: 57 additions & 4 deletions python/sglang/srt/speculative/dflash_worker_v2.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,9 +28,12 @@
can_dflash_use_fused_qkv_proj,
compute_dflash_correct_drafts_and_bonus,
compute_dflash_sampling_correct_drafts_and_bonus,
is_dflash_domino_projector,
is_dflash_sampling_verify_available,
parse_dflash_draft_config,
)
from sglang.srt.speculative.domino_helper import DFlashDominoHelper
from sglang.srt.speculative.domino_rollout import DFlashDominoRollout
from sglang.srt.speculative.eagle_info_v2 import assign_extend_cache_locs_func
from sglang.srt.speculative.spec_info import SpeculativeAlgorithm
from sglang.srt.speculative.spec_utils import assign_req_to_token_pool_func
Expand Down Expand Up @@ -184,6 +187,39 @@ def __init__(
)
self.speculative_num_draft_tokens = int(self.block_size)

# Optional Domino projector rollout. Only created when the draft model
# carries a Domino projector; ordinary DFLASH draft selection is left
# untouched. The rollout owns the Domino-specific draft-token generation
# and currently supports CUDA + TP=1 only.
self.domino_helper: Optional[DFlashDominoHelper] = (
DFlashDominoHelper(self.draft_model)
if is_dflash_domino_projector(
getattr(self.draft_model, "projector_type", None)
)
else None
)
if self.domino_helper is not None:
# Fail early (at server init) for unsupported parallelism instead of
# raising deep inside the first decode step. The selected draft token
# feeds the next GRU step, so TP>1 would need per-step cross-rank
# synchronization that this first port does not implement.
domino_tp_size = int(get_tp_group().world_size)
if domino_tp_size != 1:
raise NotImplementedError(
"DFLASH Domino projector currently supports TP=1 only, got "
f"tp_size={domino_tp_size}. Launch with --tp-size 1 "
"(alias --tensor-parallel-size 1), or use a non-Domino DFLASH "
"draft model for TP>1."
)
self.domino_rollout: Optional[DFlashDominoRollout] = (
DFlashDominoRollout(
domino_helper=self.domino_helper,
block_size=self.block_size,
)
if self.domino_helper is not None
else None
)

self._mask_token = draft_config.mask_token
self._mask_token_id_override = draft_config.mask_token_id
self._mask_token_id = self._resolve_mask_token_id(
Expand Down Expand Up @@ -1490,10 +1526,27 @@ def forward_batch_generation(
if draft_hidden is None:
raise RuntimeError("DFLASH draft model returned no hidden states.")
draft_hidden = draft_hidden.view(bs, int(self.block_size), -1)
draft_next = self._greedy_sample_from_vocab_parallel_head(
hidden_states=draft_hidden[:, 1:, :].reshape(-1, draft_hidden.shape[-1]),
lm_head=lm_head,
).view(bs, int(self.block_size) - 1)

if is_dflash_domino_projector(
getattr(self.draft_model, "projector_type", None)
):
if self.domino_rollout is None:
raise RuntimeError(
"DFLASH Domino projector requires an initialized Domino rollout."
)
draft_next = self.domino_rollout.rollout_draft_block(
draft_hidden=draft_hidden,
verified_id=block_ids[:, 0],
target_model=target_model,
lm_head=lm_head,
)
else:
draft_next = self._greedy_sample_from_vocab_parallel_head(
hidden_states=draft_hidden[:, 1:, :].reshape(
-1, draft_hidden.shape[-1]
),
lm_head=lm_head,
).view(bs, int(self.block_size) - 1)

draft_tokens = self._draft_block_tokens_buf[:bs]
draft_tokens[:, 0].copy_(block_ids[:, 0])
Expand Down
111 changes: 111 additions & 0 deletions python/sglang/srt/speculative/domino_helper.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,111 @@
from __future__ import annotations

import torch

from sglang.srt.speculative.dflash_utils import is_dflash_domino_projector


class DFlashDominoHelper:
"""Helper for Domino projector rollout state and GRU utilities.

The draft model owns ``prefix_gru`` and ``embed_proj`` directly so checkpoint
parameter names remain unchanged. This helper keeps Domino-specific rollout
logic out of the base DFLASH model file.
"""

def __init__(self, draft_model) -> None:
self.draft_model = draft_model
self._rollout_state_cache = None
self._gru_input_table_cache = None

def _check_projector(self) -> None:
if not is_dflash_domino_projector(
getattr(self.draft_model, "projector_type", None)
):
raise RuntimeError("Domino helper called on a non-Domino draft model.")
if not hasattr(self.draft_model, "prefix_gru") or not hasattr(
self.draft_model, "embed_proj"
):
raise RuntimeError("Domino draft model is missing prefix_gru/embed_proj.")

def init_gru_hidden(self, prefix_embeds: torch.Tensor) -> torch.Tensor:
"""Run the Domino prefix GRU over ``prefix_embeds``."""

self._check_projector()
prefix_embeds = prefix_embeds.contiguous()
gru = self.draft_model.prefix_gru
hidden_size = int(gru.hidden_size)
h = torch.zeros(
(prefix_embeds.shape[0], hidden_size),
dtype=prefix_embeds.dtype,
device=prefix_embeds.device,
)
w_ih = gru.weight_ih_l0.to(dtype=prefix_embeds.dtype)
w_hh = gru.weight_hh_l0.to(dtype=prefix_embeds.dtype)
b_ih = gru.bias_ih_l0.to(dtype=prefix_embeds.dtype) if gru.bias else None
b_hh = gru.bias_hh_l0.to(dtype=prefix_embeds.dtype) if gru.bias else None

for step in range(prefix_embeds.shape[1]):
gi = torch.nn.functional.linear(prefix_embeds[:, step, :], w_ih, b_ih)
gh = torch.nn.functional.linear(h, w_hh, b_hh)
r = torch.sigmoid(gi[:, :hidden_size] + gh[:, :hidden_size])
z = torch.sigmoid(
gi[:, hidden_size : 2 * hidden_size]
+ gh[:, hidden_size : 2 * hidden_size]
)
n = torch.tanh(gi[:, 2 * hidden_size :] + r * gh[:, 2 * hidden_size :])
h = (1.0 - z) * n + z * h
return h

def get_rollout_state(self) -> dict:
"""Return cached weight views used by the optimized Domino rollout loop."""

if self._rollout_state_cache is not None:
return self._rollout_state_cache

self._check_projector()
fc1 = self.draft_model.embed_proj[0]
fc2 = self.draft_model.embed_proj[2]
hidden_dim = int(self.draft_model.config.hidden_size)

w_z = fc1.weight[:, :hidden_dim].detach()
w_s = fc1.weight[:, hidden_dim:].detach()
b1 = fc1.bias.detach() if fc1.bias is not None else None

gru = self.draft_model.prefix_gru
w_ih = gru.weight_ih_l0.detach()
w_hh = gru.weight_hh_l0.detach()
b_ih = gru.bias_ih_l0.detach() if gru.bias else None
b_hh = gru.bias_hh_l0.detach() if gru.bias else None

self._rollout_state_cache = {
"w_z": w_z,
"w_s": w_s,
"w_s_hh_T": torch.cat([w_s.T, w_hh.T], dim=1).contiguous(),
"b1": b1,
"fc2_weight": fc2.weight.detach(),
"fc2_bias": fc2.bias.detach() if fc2.bias is not None else None,
"w_ih": w_ih,
"w_hh": w_hh,
"b_ih": b_ih,
"b_hh": b_hh,
"gru_hidden_size": int(gru.hidden_size),
}
return self._rollout_state_cache

def get_gru_input_proj_table(self, embed_weight: torch.Tensor) -> torch.Tensor:
"""Return [vocab, 3*gru_hidden] table: embed_weight @ W_ih.T + b_ih."""

cached = self._gru_input_table_cache
if cached is not None and cached["weight_ptr"] == embed_weight.data_ptr():
return cached["table"]

state = self.get_rollout_state()
table = torch.nn.functional.linear(
embed_weight, state["w_ih"], state["b_ih"]
).contiguous()
self._gru_input_table_cache = {
"weight_ptr": embed_weight.data_ptr(),
"table": table,
}
return table
Loading
Loading