From 059cf95de416a7ad0d6deccc112b02df4018984f Mon Sep 17 00:00:00 2001 From: Xiaoze Fan Date: Mon, 26 Oct 2026 08:17:31 +0000 Subject: [PATCH] feat(spec): verify qwen4_exp targets on qsa_sparse graphs with a PLE verify scratch --- python/freetoken/attention/__init__.py | 1 + python/freetoken/attention/qsa_sparse.py | 27 +++--- python/freetoken/engine/engine.py | 8 +- python/freetoken/kvcache/__init__.py | 3 + python/freetoken/kvcache/qsa_pool.py | 3 +- python/freetoken/layers/embedding.py | 5 +- python/freetoken/models/blocks.py | 11 ++- python/freetoken/models/qwen4_exp/model.py | 25 ++++-- python/freetoken/models/qwen4_exp/ple.py | 49 +++++++++++ tests/spec/test_verify_contract.py | 95 ++++++++++++++++++---- 10 files changed, 187 insertions(+), 40 deletions(-) diff --git a/python/freetoken/attention/__init__.py b/python/freetoken/attention/__init__.py index 3957cff6..4ae81903 100644 --- a/python/freetoken/attention/__init__.py +++ b/python/freetoken/attention/__init__.py @@ -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): diff --git a/python/freetoken/attention/qsa_sparse.py b/python/freetoken/attention/qsa_sparse.py index 23089800..66481a74 100644 --- a/python/freetoken/attention/qsa_sparse.py +++ b/python/freetoken/attention/qsa_sparse.py @@ -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: diff --git a/python/freetoken/engine/engine.py b/python/freetoken/engine/engine.py index 62f2b7f9..51962201 100644 --- a/python/freetoken/engine/engine.py +++ b/python/freetoken/engine/engine.py @@ -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) diff --git a/python/freetoken/kvcache/__init__.py b/python/freetoken/kvcache/__init__.py index e0cf606d..8d038e2f 100644 --- a/python/freetoken/kvcache/__init__.py +++ b/python/freetoken/kvcache/__init__.py @@ -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, ) diff --git a/python/freetoken/kvcache/qsa_pool.py b/python/freetoken/kvcache/qsa_pool.py index 7de70977..84cab5d9 100644 --- a/python/freetoken/kvcache/qsa_pool.py +++ b/python/freetoken/kvcache/qsa_pool.py @@ -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 diff --git a/python/freetoken/layers/embedding.py b/python/freetoken/layers/embedding.py index 469b752d..5f786e51 100644 --- a/python/freetoken/layers/embedding.py +++ b/python/freetoken/layers/embedding.py @@ -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) diff --git a/python/freetoken/models/blocks.py b/python/freetoken/models/blocks.py index 67c6a549..5e714728 100644 --- a/python/freetoken/models/blocks.py +++ b/python/freetoken/models/blocks.py @@ -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: diff --git a/python/freetoken/models/qwen4_exp/model.py b/python/freetoken/models/qwen4_exp/model.py index 4eb69165..1ba7da05 100644 --- a/python/freetoken/models/qwen4_exp/model.py +++ b/python/freetoken/models/qwen4_exp/model.py @@ -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): diff --git a/python/freetoken/models/qwen4_exp/ple.py b/python/freetoken/models/qwen4_exp/ple.py index c944c494..36ee3b8a 100644 --- a/python/freetoken/models/qwen4_exp/ple.py +++ b/python/freetoken/models/qwen4_exp/ple.py @@ -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", diff --git a/tests/spec/test_verify_contract.py b/tests/spec/test_verify_contract.py index 39fb3e92..c1cc4d35 100644 --- a/tests/spec/test_verify_contract.py +++ b/tests/spec/test_verify_contract.py @@ -1,10 +1,11 @@ """A k+1-row verify step commits exactly what k+1 decode steps would: with drafts taken from a plain greedy run and wrong at a different place each step (so every accept count occurs), speculative decoding must reproduce that run token for token. -A tiny hybrid (GatedDeltaNet + attention) model with dummy weights, served end to end through the scheduler; the drafts come from a stub proposer, so this pins the target side alone. -A verify row and a decode step run different GEMM and attention shapes, so their logits can differ by an ulp: the runs may part at a near tie, and the test checks they part only there. fp16 keeps such ties rare (bf16 has 3 fewer mantissa bits). +Tiny hybrid models with dummy weights, served end to end through the scheduler: qwen3_5 (GatedDeltaNet + attention) and qwen4_exp (GatedDeltaNet + QSA, PLE, hyper-connections). The drafts come from a stub proposer, so this pins the target side alone. +A verify row and a decode step run different GEMM and attention shapes, so their logits can differ by an ulp: the runs may part at a near tie, and the test checks they part only there. fp16 keeps such ties rare (bf16 has 3 fewer mantissa bits), and fan-in scaled dummy weights keep the activations O(1), so ulp noise does not grow through the layers. """ import json +import math import os import shutil import subprocess @@ -34,6 +35,7 @@ from freetoken.spec import runner as R from freetoken.spec.proposer import Proposer model, out, reference, kwargs = sys.argv[1], sys.argv[2], sys.argv[3], json.loads(sys.argv[4]) +dtype = getattr(torch, kwargs.pop("dtype")) # (uid, output index) -> top-2 token ids and logits of the row that picked it top2 = {} @@ -101,9 +103,47 @@ class OracleProposer(Proposer): return SpecProposal(torch.tensor(drafts, dtype=torch.int64, device=rows.device)) +def fan_in_scaled(tensor): + # unit-variance dummy matrices grow the activations by sqrt(fan_in) per layer, until fp16 noise decides the argmax + if tensor.is_floating_point() and tensor.dim() >= 2: + tensor.mul_(tensor.shape[-1] ** -0.5) + return tensor + + +dummy_state = E._make_dummy_weight_state_dict +E._make_dummy_weight_state_dict = lambda *args, **kwargs: { + name: fan_in_scaled(tensor) for name, tensor in dummy_state(*args, **kwargs).items()} +create_model = E.create_model + + +def create_model_with_ple_rows(*args, **kwargs): + # imported here, once CUDA is up + from freetoken.models.qwen4_exp import ple + from freetoken.moe import expert_banks + + dummy_fill = expert_banks._dummy_fill + + def scaled_fill(role, tensor): + dummy_fill(role, tensor) + if not role.endswith(("_scale", "_global")): + fan_in_scaled(tensor) + + expert_banks._dummy_fill = scaled_fill + + # seeded PLE rows in place of the dummy zeros, so the PLE path carries signal + class RandomTable(ple.GpuResidentTable): + def __init__(self, num_rows, head_dim, dtype=torch.bfloat16): + generator = torch.Generator(device="cuda").manual_seed(0) + super().__init__(torch.randn(num_rows, head_dim, generator=generator, device="cuda", dtype=dtype)) + + ple.ZeroTable = RandomTable + return create_model(*args, **kwargs) + + +E.create_model = create_model_with_ple_rows if reference != "-": PROPOSERS.register("oracle")("__main__:OracleProposer") -llm = LLM(model_path=model, dtype=torch.float16, use_dummy_weight=True, max_running_req=4, **kwargs) +llm = LLM(model_path=model, dtype=dtype, use_dummy_weight=True, **{"max_running_req": 4, **kwargs}) prompts = [llm.tokenizer.encode(p) for p in ("The capital of France is", "1, 2, 3, 4,", "def fibonacci(n):")] params = [SamplingParams(temperature=0.0, max_tokens=n, ignore_eos=True, presence_penalty=p, frequency_penalty=p) for n, p in ((48, 0.0), (37, 0.6), (41, 0.0))] @@ -112,22 +152,40 @@ json.dump({"outputs": [r["token_ids"] for r in res], "top2": [[u, i, *t] for (u, """ -def _tiny_model(path: str) -> str: +def _tiny_model(path: str, family: str) -> str: os.makedirs(path, exist_ok=True) for name in ("tokenizer.json", "tokenizer_config.json", "vocab.json", "merges.txt"): if os.path.exists(os.path.join(TOKENIZER_SOURCE, name)): shutil.copy(os.path.join(TOKENIZER_SOURCE, name), path) - config = { - "architectures": ["Qwen3_5ForCausalLM"], "model_type": "qwen3_5_text", "vocab_size": 248320, - "hidden_size": 256, "intermediate_size": 512, "num_hidden_layers": 4, + text = { + "vocab_size": 248320, "hidden_size": 256, "num_hidden_layers": 4, "layer_types": ["linear_attention", "linear_attention", "linear_attention", "full_attention"], - "full_attention_interval": 4, "num_attention_heads": 4, "num_key_value_heads": 2, "head_dim": 64, + "full_attention_interval": 4, "num_attention_heads": 4, "num_key_value_heads": 2, "linear_conv_kernel_dim": 4, "linear_key_head_dim": 32, "linear_num_key_heads": 2, - "linear_num_value_heads": 4, "linear_value_head_dim": 32, "attn_output_gate": True, "hidden_act": "silu", + "linear_num_value_heads": 4, "linear_value_head_dim": 32, "hidden_act": "silu", "rms_norm_eps": 1e-6, "max_position_embeddings": 4096, "tie_word_embeddings": False, "eos_token_id": 248044, - "rope_parameters": {"rope_type": "default", "rope_theta": 10000000, "partial_rotary_factor": 0.25, - "mrope_section": [3, 3, 2], "mrope_interleaved": True}, } + if family == "qwen3_5": + config = { + "architectures": ["Qwen3_5ForCausalLM"], "model_type": "qwen3_5_text", **text, + "intermediate_size": 512, "head_dim": 64, "attn_output_gate": True, + "rope_parameters": {"rope_type": "default", "rope_theta": 10000000, "partial_rotary_factor": 0.25, + "mrope_section": [3, 3, 2], "mrope_interleaved": True}, + } + else: + # the shipping QSA geometry (head_dim 256, index head_dim 128, ratio 4), scaled-down widths + text.update({ + "model_type": "qwen4_exp_text", "head_dim": 256, + "rope_parameters": {"rope_type": "default", "rope_theta": 10000000, "partial_rotary_factor": 0.25, + "mrope_section": [11, 11, 10], "mrope_interleaved": True}, + "num_experts": 8, "num_experts_per_tok": 2, "moe_intermediate_size": 64, "shared_expert_intermediate_size": 64, + "output_gate_type": "sigmoid", "indexer_n_heads": 4, "indexer_kv_heads": 1, "indexer_head_dim": 128, + "indexer_budget": 2048, "indexer_compress_ratio": 4, "hc_count": 4, "hc_lowrank": 16, + "ple_layer_ids": [2], "ple_embed_dim": 64, "ple_conv_kernel_size": 4, "ngram_size": 3, "heads_per_ngram": 2, + "ngram_vocab_size_base": 1000, "make_ngram_vocab_size_divisible_by": 8, "split_ngram_parts": 4, + }) + config = {"architectures": ["Qwen4ExpForConditionalGeneration"], "model_type": "qwen4_exp", + "tie_word_embeddings": False, "text_config": text} with open(os.path.join(path, "config.json"), "w") as f: json.dump(config, f) return path @@ -142,12 +200,14 @@ def _run(model: str, out: str, reference: str, **kwargs) -> dict: @pytest.mark.parametrize("graphs", [True, False]) -@pytest.mark.parametrize("backend", ["fa", "triton"]) -def test_verify_steps_reproduce_greedy_decode(tmp_path, backend, graphs): +@pytest.mark.parametrize("family, backend", [("qwen3_5", "fa"), ("qwen3_5", "triton"), ("qwen4_exp", "qsa_sparse")]) +def test_verify_steps_reproduce_greedy_decode(tmp_path, family, backend, graphs): if backend == "fa": pytest.importorskip("sgl_kernel") - model = _tiny_model(str(tmp_path / "model")) - kwargs = {"attention_backend": backend, "cuda_graph_max_bs": 4 if graphs else 0} + model = _tiny_model(str(tmp_path / "model"), family) + dtype = "float16" + # resident experts take the model dtype + kwargs = {"attention_backend": backend, "cuda_graph_max_bs": 4 if graphs else 0, "dtype": dtype, "moe_strategy": "fused"} reference = _run(model, str(tmp_path / "decode.json"), "-", **kwargs) spec = _run(model, str(tmp_path / "spec.json"), str(tmp_path / "decode.json"), speculative_algorithm="oracle", speculative_num_steps=K, **kwargs) @@ -157,10 +217,11 @@ def test_verify_steps_reproduce_greedy_decode(tmp_path, backend, graphs): split = next((i for i, (a, b) in enumerate(zip(want, got)) if a != b), len(want)) agreed += split if split < len(want): - # same prefix, so both runs must rank the two tokens top-2 and within two fp16 ulps of logits in [64, 128) + # same prefix, so both runs must rank the two tokens top-2 and within two ulps of each other pair = {want[split], got[split]} for run in (reference, spec): a, b, va, vb = next(t[2:] for t in run["top2"] if t[:2] == [uid, split]) - assert {a, b} == pair and va - vb <= 0.125, f"request {uid} parts at {split}: top-2 {(a, b)} gap {va - vb}" + ulp = 2.0 ** (math.floor(math.log2(abs(va) or 1.0)) - (10 if dtype == "float16" else 7)) + assert {a, b} == pair and va - vb <= 2 * ulp, f"request {uid} parts at {split}: top-2 {(a, b)} gap {va - vb}" # most of the run must still be compared, or a tie early in every request would hide a bug assert agreed >= 0.5 * sum(map(len, reference["outputs"]))