feat(spec): verify qwen4_exp targets on qsa_sparse graphs with a PLE verify scratch

This commit is contained in:
Xiaoze Fan
2026-10-27 00:44:50 +00:00
parent 859961af7b
commit 059cf95de4
10 changed files with 187 additions and 40 deletions
+1
View File
@@ -155,6 +155,7 @@ def create_m3_sparse_backend(config: ModelConfig):
# 64-token pages: a 4-token compress group never straddles a page, so the
# compressed row of a group is page_base // 4 + block-in-page.
page_sizes=(64,),
uniform_extend_graph="device",
),
)
def create_qsa_sparse_backend(config: ModelConfig):
+14 -13
View File
@@ -145,6 +145,7 @@ class QSASparseAttnBackend(BaseAttnBackend):
# decode staging (static buffers under CUDA graphs; eager decode snapshots per step)
self._graph: dict[str, torch.Tensor] = {}
self.capture_bs: List[int] = []
self._capture_steps = 1
@staticmethod
def _qsa_group(config: ModelConfig):
@@ -242,7 +243,7 @@ class QSASparseAttnBackend(BaseAttnBackend):
md.block_table = self._graph["block_table"][:bs]
md.seq_lens = self._graph["kvlen"][:bs]
md.ring_slots = self._graph["table_idx"][:bs]
md.token_to_req = self._graph["token_to_req"][:bs]
md.token_to_req = self._graph["token_to_req"][: bs * self._capture_steps]
md.cu_seqlens = self._graph["cu_seqlens"][: bs + 1]
def _snapshot_decode(self, md: QSASparseMetadata, batch: Batch) -> None:
@@ -490,14 +491,14 @@ class QSASparseAttnBackend(BaseAttnBackend):
# ----- CUDA graph (decode) --------------------------------------------------------------
def init_capture_graph(self, max_seq_len: int, bs_list: List[int], steps: int = 1) -> None:
if steps != 1:
raise NotImplementedError("qsa_sparse captures decode graphs only")
self.capture_bs = sorted(bs_list)
self._capture_steps = steps
max_bs = max(bs_list)
rows = max_bs * steps
width = get_global_ctx().page_table.shape[1]
pages = -(-width // self.page_size)
columns = pages * self.cmp_page_size
chunk = max(1, min(max_bs, _LOGITS_WORKSPACE_BYTES // max(columns * 4, 1)))
chunk = max(1, min(rows, _LOGITS_WORKSPACE_BYTES // max(columns * 4, 1)))
topk_scratch = self._topk_scratch_width(columns)
def empty(*shape: int, dtype: torch.dtype) -> torch.Tensor:
@@ -507,15 +508,15 @@ class QSASparseAttnBackend(BaseAttnBackend):
"block_table": torch.zeros((max_bs, pages), dtype=torch.int32, device=self.device),
"kvlen": torch.zeros(max_bs, dtype=torch.int32, device=self.device),
"table_idx": torch.zeros(max_bs, dtype=torch.int32, device=self.device),
"token_to_req": torch.arange(max_bs, dtype=torch.int32, device=self.device),
"cu_seqlens": torch.arange(max_bs + 1, dtype=torch.int32, device=self.device),
"token_to_req": torch.arange(max_bs, dtype=torch.int32, device=self.device).repeat_interleave(steps),
"cu_seqlens": torch.arange(max_bs + 1, dtype=torch.int32, device=self.device) * steps,
"logits": empty(chunk, columns, dtype=torch.float32),
"visible": empty(max_bs, dtype=torch.int32),
"blocks": empty(max_bs, self.block_topk, dtype=torch.int32),
"indices": empty(max_bs, self.select_width, dtype=torch.int32),
"pooled": empty(max_bs, self.index_head_dim, dtype=self.dtype),
"first_pos": empty(max_bs, dtype=torch.int32),
"q_index": empty(max_bs, self.index_heads, self.index_head_dim, dtype=self.dtype),
"visible": empty(rows, dtype=torch.int32),
"blocks": empty(rows, self.block_topk, dtype=torch.int32),
"indices": empty(rows, self.select_width, dtype=torch.int32),
"pooled": empty(rows, self.index_head_dim, dtype=self.dtype),
"first_pos": empty(rows, dtype=torch.int32),
"q_index": empty(rows, self.index_heads, self.index_head_dim, dtype=self.dtype),
}
if topk_scratch:
self._graph["topk_scratch"] = empty(chunk, topk_scratch, dtype=torch.int32)
@@ -533,7 +534,7 @@ class QSASparseAttnBackend(BaseAttnBackend):
def prepare_for_replay(self, batch: Batch) -> None:
md = batch.attn_metadata
assert isinstance(md, QSASparseMetadata)
assert batch.active_table_idx is not None, "decode batch is missing its page-table rows"
assert batch.active_table_idx is not None, "graph batch is missing its page-table rows"
self._stage_decode(md, batch.padded_size, batch.active_table_idx.to(torch.int64))
def reset_capture(self) -> None:
+7 -1
View File
@@ -608,7 +608,13 @@ class Engine:
if rows > 1 and self.linear_state_pool is not None
else None
)
self.model_verify_scratch = None
from freetoken.models.blocks import SupportsVerifyScratch
self.model_verify_scratch = (
self.model.make_verify_scratch(config.max_running_req, rows, self.device, self.dtype)
if rows > 1 and isinstance(self.model, SupportsVerifyScratch)
else None
)
if self.spec is not None:
self.spec.attach(self)
+3
View File
@@ -136,6 +136,7 @@ def create_kv_pool(config, num_pages: int, device: torch.device, dtype: torch.dt
device=device,
dtype=dtype,
num_req_slots=config.max_running_req + 1, # + 1 for the dummy request row
num_speculative_tokens=getattr(config, "decode_rows_per_req", 1) - 1,
)
@@ -147,6 +148,7 @@ def create_kvcache_pool(
device: torch.device,
num_swa_tokens: int | None = None,
num_req_slots: int | None = None,
num_speculative_tokens: int = 0,
) -> BaseKVCachePool:
if model_config.has_swa_attention:
from .hybrid_swa_pool import HybridSWAKVCache
@@ -222,6 +224,7 @@ def create_kvcache_pool(
num_index_layers=spec.num_index_layers,
index_ratio=spec.index_ratio,
num_req_slots=num_req_slots,
ring_capacity=QSAKVCache.ring_capacity_for(spec.index_ratio, num_speculative_tokens),
layer_ids=spec.layer_ids,
mrope=model_config.model_is_mrope,
)
+2 -1
View File
@@ -173,7 +173,8 @@ class QSAKVCache(MHAKVCache):
if spec.attn_type is AttnType.QSA:
# One index-key row = all index layers at one position.
row = spec.index_head_dim * spec.num_index_layers * _INDEX_DTYPE_BYTES
fixed += num_req_slots * row * (cls.ring_capacity_for(spec.index_ratio) + 1)
ring = cls.ring_capacity_for(spec.index_ratio, getattr(config, "decode_rows_per_req", 1) - 1)
fixed += num_req_slots * row * (ring + 1)
if config.model_config.model_is_mrope:
per_token += _ROPE_POS_BYTES
return per_token * config.page_size, fixed, config.page_size, 0
+3 -2
View File
@@ -125,11 +125,12 @@ class ParallelLMHead(VocabParallelEmbedding):
return {} if result is None else result
@nvtx_annotate("LMHead")
def forward(self, x: torch.Tensor) -> torch.Tensor:
def forward(self, x: torch.Tensor, *, export_hidden: bool = True) -> torch.Tensor:
"""``export_hidden=False``: the model hands its own final hidden to ``batch.features``."""
ctx = get_global_ctx()
batch = ctx.batch
bs = batch.size
if (features := getattr(batch, "features", None)) is not None:
if export_hidden and (features := getattr(batch, "features", None)) is not None:
features.final_hidden(x)
if batch.is_prefill:
indices = batch.attn_metadata.get_last_indices(bs)
+10 -1
View File
@@ -55,7 +55,7 @@ class FeatureSink(Protocol):
wanted_layers: frozenset[int]
def final_hidden(self, x: torch.Tensor) -> None:
"""Every row's hidden state before the LM head; the first call in a forward wins, so a model may call it before the head does."""
"""Every row's final hidden state, once per forward: the LM head's input, or what the model hands over itself before the head."""
...
def layer_output(self, layer_id: int, x: torch.Tensor, num_streams: int = 1) -> None:
@@ -63,6 +63,15 @@ class FeatureSink(Protocol):
...
@runtime_checkable
class SupportsVerifyScratch(Protocol):
"""A model with per-request state outside the GDN pool: a verify forward leaves that state as it was and stages its windows in the scratch, which Engine.commit_verify commits."""
def make_verify_scratch(self, max_rows: int, steps: int, device: torch.device, dtype: torch.dtype):
"""An object with ``commit(pool, slots, counts, rows)``, or None when this model instance keeps no such state."""
...
def embed_input_ids(embed_tokens, input_ids: torch.Tensor, batch: Batch) -> torch.Tensor:
"""Token embeddings of the batch; on a chunk with multimodal rows, batch.mm_embeds' leading columns replace the rows batch.mm_rows."""
if batch.mm_embeds is None:
+20 -5
View File
@@ -124,9 +124,15 @@ class Qwen4ExpModel(BaseOP):
for layer in self.layers.op_list:
hidden = layer.forward(hidden, batch)
if meta is not None:
# single writer: the layers only read the context, so a second PLE layer's
# prefetch sees the un-rolled window
commit_ngram_context(meta, getattr(batch, "fla_metadata", None))
if getattr(batch, "phase", None) == "verify":
batch.verify.model_scratch.stash_ngram(meta)
else:
# single writer: the layers only read the context, so a second PLE layer's
# prefetch sees the un-rolled window
commit_ngram_context(meta, getattr(batch, "fla_metadata", None))
if (features := getattr(batch, "features", None)) is not None:
# a draft reads the residual streams before the final mix
features.final_hidden(hidden)
return self.hyper_connection_mixer.mix(hidden)[0]
@@ -188,7 +194,7 @@ class Qwen4ExpForCausalLM(BaseLLMModel):
disk_table = DiskRowTable(
resolve_row_source(engine_config.model_path),
constants,
max_graph_rows=max(256, engine_config.cuda_graph_max_bs or 0),
max_graph_rows=max(256, (engine_config.cuda_graph_max_bs or 0) * engine_config.decode_rows_per_req),
max_extend_tokens=engine_config.max_extend_tokens,
)
self._ple_table = disk_table
@@ -208,9 +214,18 @@ class Qwen4ExpForCausalLM(BaseLLMModel):
)
return table.bank.nbytes
def make_verify_scratch(self, max_rows: int, steps: int, device: torch.device, dtype: torch.dtype):
layers = self.model.ple_layers
if not layers:
return None
from .ple import PLEVerifyScratch
return PLEVerifyScratch(layers, max_rows, steps, device, dtype)
def forward(self) -> torch.Tensor:
batch = get_global_ctx().batch
return self.lm_head.forward(self.model.forward(batch.input_ids, batch))
# the model hands its pre-mix streams to batch.features itself
return self.lm_head.forward(self.model.forward(batch.input_ids, batch), export_hidden=False)
class Qwen4ExpForConditionalGeneration(QwenVLVisionMixin, Qwen4ExpForCausalLM):
+49
View File
@@ -617,6 +617,8 @@ class PLELayer(BaseOP):
fla = getattr(batch, "fla_metadata", None)
if fla is not None and fla.track_boundary_row is not None:
self._write_track_snapshot(states, x, fla)
if getattr(batch, "phase", None) == "verify":
return gated + self._verify_conv(x, meta, states, batch.verify.model_scratch)
return gated + self._short_conv(x, meta, states)
def _write_track_snapshot(self, states: torch.Tensor, x: torch.Tensor, fla) -> None:
@@ -667,6 +669,19 @@ class PLELayer(BaseOP):
)
return F.silu(out.to(x.dtype))
def _verify_conv(
self, x: torch.Tensor, meta: PLEMetadata, states: torch.Tensor, scratch: PLEVerifyScratch
) -> torch.Tensor:
"""The decode taps over every verify row with the live state read-only; the window goes to ``scratch`` for Engine.commit_verify."""
bs = meta.state_slots.numel()
steps = x.shape[0] // bs
history = scratch.conv[self.layer_id][:bs]
history[..., : self.state_len].copy_(self._read_state(meta, states, x.dtype))
history[..., self.state_len :].copy_(x.view(bs, steps, -1).transpose(1, 2))
window = history.unfold(2, self.state_len + 1, 1)[..., :: self.dilation].float()
out = (window * self.conv1d.weight.squeeze(1).float().unsqueeze(1)).sum(-1)
return F.silu(out.to(x.dtype)).transpose(1, 2).reshape(x.shape)
def _prefill_conv(
self, x: torch.Tensor, meta: PLEMetadata, states: torch.Tensor
) -> torch.Tensor:
@@ -716,6 +731,39 @@ class PLELayer(BaseOP):
return packed[:n_out], packed[n_out : n_out + n_state], packed[n_out + n_state :]
class PLEVerifyScratch:
"""A verify forward's PLE windows by verify-batch row: the old n-gram context then every verify token, and per layer the old conv history then every verify conv input."""
def __init__(self, layers: Sequence[PLELayer], max_rows: int, steps: int, device: torch.device, dtype: torch.dtype) -> None:
args = layers[0].args
self.ctx_len = args.ngram_size - 1
self.state_len = layers[0].state_len
self.ngram = torch.zeros(max_rows, self.ctx_len + steps, dtype=torch.int64, device=device)
self.conv = {
layer.layer_id: torch.zeros(max_rows, args.ple_state_width, layer.state_len + steps, dtype=dtype, device=device)
for layer in layers
}
def stash_ngram(self, meta: PLEMetadata) -> None:
bs = meta.state_slots.numel()
self.ngram[:bs, : self.ctx_len].copy_(meta.ngram_context)
self.ngram[:bs, self.ctx_len :].copy_(meta.input_ids.view(bs, -1))
def commit(self, pool, slots: List[int], counts: List[int], rows: List[int]) -> None:
"""Write each slot's n-gram context and conv history as they stand after its first ``counts`` verify tokens."""
device = self.ngram.device
rows_t = torch.tensor(rows, dtype=torch.int64, device=device)
slots_t = torch.tensor(slots, dtype=torch.int64, device=device)
n = torch.tensor(counts, dtype=torch.int64, device=device).unsqueeze(1)
context = pool.slot_state(PLE_NGRAM_STATE)
context.index_copy_(0, slots_t, self.ngram[rows_t].gather(1, n + torch.arange(self.ctx_len, device=device)).to(context.dtype))
cols = (n + torch.arange(self.state_len, device=device)).unsqueeze(1)
for layer_id, history in self.conv.items():
states = pool.slot_state(PLE_CONV_STATE, layer_id)
window = history[rows_t].gather(2, cols.expand(-1, history.shape[1], -1))
states.index_copy_(0, slots_t, window.to(states.dtype))
__all__ = [
"GpuResidentTable",
"NGramEmbedding",
@@ -723,6 +771,7 @@ __all__ = [
"PLELayer",
"PLEMetadata",
"PLETableBackend",
"PLEVerifyScratch",
"PinnedUVATable",
"build_ple_metadata",
"derive_ngram_hash_constants",