From 60311040a65361b632d7cb003ddcec373319019e Mon Sep 17 00:00:00 2001 From: Joshua Calafato Date: Mon, 23 Nov 2026 16:56:12 +0000 Subject: [PATCH 1/3] feat(qwen3_8): adapt dense decoding to Edge-LLM 0.12 Map ordinary, DFlash2, DSpark and Domino requests to compatible Edge or native execution. Preserve checkpoint precision, distinguish chain and tree verification, and reject an unsupported draft before loading target-only plans. Signed-off-by: Joshua Calafato --- families/qwen3_8/cli.json | 14 +- families/qwen3_8/cli.py | 5 +- families/qwen3_8/config.py | 22 ++ families/qwen3_8/domino.py | 201 ++++++++++ families/qwen3_8/draft.py | 83 +++-- families/qwen3_8/edge_llm/README.md | 146 +++++++- families/qwen3_8/edge_llm/builder.py | 346 ++++++++++++++---- families/qwen3_8/edge_llm/cli.py | 2 +- families/qwen3_8/edge_llm/config.py | 10 +- families/qwen3_8/edge_llm/dispatch.py | 145 +++++--- families/qwen3_8/engine_builder.py | 15 +- families/qwen3_8/model.py | 55 ++- families/qwen3_8/native_media.py | 2 +- families/qwen3_8/quantization.py | 64 +++- families/qwen3_8/runtime/CMakeLists.txt | 4 + families/qwen3_8/runtime/dflash2.cpp | 30 +- families/qwen3_8/runtime/dflash2.h | 10 +- families/qwen3_8/runtime/dflash2_tree.cpp | 80 ++++ families/qwen3_8/runtime/dflash2_tree.h | 17 + families/qwen3_8/runtime/domino.cpp | 233 ++++++++++++ families/qwen3_8/runtime/domino.h | 34 ++ families/qwen3_8/runtime/dspark.cpp | 7 +- families/qwen3_8/runtime/dspark.h | 6 +- .../qwen3_8/runtime/edge_llm/Adapter.cmake | 19 +- families/qwen3_8/runtime/edge_llm/adapter.cpp | 136 ++++++- families/qwen3_8/runtime/edge_llm/contract.h | 4 + families/qwen3_8/runtime/edge_llm/media.h | 5 +- families/qwen3_8/runtime/edge_llm/request.h | 4 + families/qwen3_8/runtime/external_draft.h | 17 +- families/qwen3_8/runtime/pipeline.cpp | 26 +- families/qwen3_8/runtime/plugin.cpp | 58 ++- families/qwen3_8/runtime/sampler.cpp | 7 + families/qwen3_8/runtime/sampler.h | 1 + .../qwen3_8/tests/test_checkpoint_mapper.py | 40 +- families/qwen3_8/tests/test_engine_builder.py | 12 + families/qwen3_8/tests/test_support.py | 63 +++- families/qwen3_8/vision.py | 2 +- website/docs/features/model-families.md | 25 +- 38 files changed, 1659 insertions(+), 291 deletions(-) create mode 100644 families/qwen3_8/domino.py create mode 100644 families/qwen3_8/runtime/dflash2_tree.cpp create mode 100644 families/qwen3_8/runtime/dflash2_tree.h create mode 100644 families/qwen3_8/runtime/domino.cpp create mode 100644 families/qwen3_8/runtime/domino.h diff --git a/families/qwen3_8/cli.json b/families/qwen3_8/cli.json index 0da20016ce..310f65b8cf 100644 --- a/families/qwen3_8/cli.json +++ b/families/qwen3_8/cli.json @@ -114,7 +114,8 @@ "none", "nvfp4", "fp8", - "int4_awq" + "int4_awq", + "int4_gptq" ] }, { @@ -142,10 +143,21 @@ "choices": [ "dspark", "dflash", + "dflash_tree", + "domino", + "domino_tree", "mtp" ], "help": "Explicit execution mode; MTP uses an embedded draft, external companions are explicit" }, + { + "name": "edge_builder_python", + "flags": [ + "--edge-builder-python" + ], + "type": "path", + "help": "Absolute Python interpreter for the optional Edge builder" + }, { "name": "companion", "flags": [ diff --git a/families/qwen3_8/cli.py b/families/qwen3_8/cli.py index f8fc9b36f9..ef1ae0db25 100644 --- a/families/qwen3_8/cli.py +++ b/families/qwen3_8/cli.py @@ -43,6 +43,7 @@ def build( fp32_layers: list[int] | tuple[int, ...] = (), quantization: str | None = None, mtp_seq_len: int | None = None, execution_variant: str | None = None, companion: list[str] | tuple[str, ...] = (), + edge_builder_python: Path | None = None, prefill_chunk_len: int | None = None, ) -> int: """Run the declared owner command; help never imports this handler.""" @@ -61,7 +62,7 @@ def build( prefill_chunk_len=prefill_chunk_len, mtp_seq_len=mtp_seq_len, ) - if execution is not None: - request = with_execution(request, execution) + if execution is not None or edge_builder_python is not None: + request = with_execution(request, execution, edge_builder_python=edge_builder_python) build_bundle(request, output) return 0 diff --git a/families/qwen3_8/config.py b/families/qwen3_8/config.py index 9ba70ea29c..5c4e26107d 100644 --- a/families/qwen3_8/config.py +++ b/families/qwen3_8/config.py @@ -10,6 +10,28 @@ from pathlib import Path +def compressed_int4_fp8_kv(raw: dict) -> bool: + """Recognize the weight-only, symmetric group-128 recipe with static FP8 cache.""" + qc = raw.get("quantization_config") + if not isinstance(qc, dict) or qc.get("quant_method") != "compressed-tensors": + return False + groups, kv = qc.get("config_groups"), qc.get("kv_cache_scheme") + if (qc.get("format") != "pack-quantized" or qc.get("quantization_status") != "compressed" + or not isinstance(groups, dict) or len(groups) != 1 or not isinstance(kv, dict)): + return False + group = next(iter(groups.values())) + if (not isinstance(group, dict) or group.get("targets") != ["Linear"] + or group.get("input_activations") is not None or group.get("output_activations") is not None): + return False + weights = group.get("weights") + return (isinstance(weights, dict) and weights.get("type") == "int" and weights.get("num_bits") == 4 + and weights.get("symmetric") is True and weights.get("dynamic") is False + and weights.get("strategy") == "group" and weights.get("group_size") == 128 + and weights.get("actorder") in (None, "static") + and kv.get("type") == "float" and kv.get("num_bits") == 8 and kv.get("strategy") == "tensor" + and kv.get("symmetric") is True and kv.get("dynamic") is False) + + def _token_id(value: object) -> int: """Normalize a config token id to an int, using -1 for "unset". diff --git a/families/qwen3_8/domino.py b/families/qwen3_8/domino.py new file mode 100644 index 0000000000..520f152d19 --- /dev/null +++ b/families/qwen3_8/domino.py @@ -0,0 +1,201 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Native Qwen3.6 Domino correction. The target owns its token embedding.""" +from __future__ import annotations + +from dataclasses import dataclass + +import numpy as np +import tensorrt as trt + +from . import draft, graph_ops + + +@dataclass(frozen=True) +class DominoConfig: + raw: dict + feature_layers: tuple[int, ...] + hidden: int + vocab: int + layers: int + heads: int + kv_heads: int + head_dim: int + intermediate: int + mask_token: int + epsilon: float + rank: int + state: int + shift_label: bool + pool_size: int + query_rows: int = 16 + + @classmethod + def from_dict(cls, raw, target): + policy = raw.get("dflash_config") or {} + h, v, layers = raw["hidden_size"], raw["vocab_size"], raw["num_hidden_layers"] + taps = tuple(policy.get("target_layer_ids", ())) + if (raw.get("architectures") != ["DFlashDraftModel"] or raw.get("block_size") != 16 + or policy.get("projector_type") != "domino" or policy.get("pure_draft_prefix_len") != 1 + or type(policy.get("shift_label")) is not bool + or (h, v, raw.get("num_target_layers")) != + (target["hidden_size"], target["vocab_size"], target["num_hidden_layers"]) + or not taps or len(set(taps)) != len(taps) + or any(type(i) is not int or not 0 <= i < target["num_hidden_layers"] for i in taps) + or raw.get("quantization_config") or target.get("quantization_config") + or raw.get("attention_bias", False) or raw.get("hidden_act") != "silu" + or raw.get("sliding_window") or raw.get("use_sliding_window") + or raw.get("layer_types") != ["full_attention"] * layers): + raise ValueError("Unsupported Qwen3.6 Domino companion or target contract") + heads, kv, dim = raw["num_attention_heads"], raw["num_key_value_heads"], raw["head_dim"] + width, rank, state = raw["intermediate_size"], policy["emb_dim"], policy["gru_hidden_dim"] + mask, eps = policy["mask_token_id"], raw["rms_norm_eps"] + if (min(h, v, layers, heads, kv, dim, width, rank, state) <= 0 or heads % kv + or dim % 2 or state % 2 or rank % 2 or not 0 <= mask < v + or not np.isfinite(eps) or eps <= 0): + raise ValueError("Invalid Qwen3.6 Domino dimensions") + return cls(raw, taps, h, v, layers, heads, kv, dim, width, mask, eps, rank, state, + policy["shift_label"], min(v, 2048)) + + +def load_draft_weights(model_dir, config): + specs = list(draft.block_weight_shapes(config)) + h, state, rank = config.hidden, config.state, config.rank + specs.extend([ + ("prefix_gru.weight_ih_l0", (3 * state, h), False), + ("prefix_gru.weight_hh_l0", (3 * state, state), False), + ("embed_proj.0.weight", (rank, h + state), False), + ("embed_proj.2.weight", (config.vocab, rank), False), + ]) + return draft.load_block_weights(model_dir, specs) + + +def build_draft_engine(config, weights, target_lm_head, max_cache_length, *, quant_ctx=None, + verbose=False, debug_layer_outputs=False): + if quant_ctx is not None or target_lm_head is None: + raise ValueError("The Qwen3.6 Domino target needs its original dense LM head") + + def outputs(net, hidden): + tensors = add_candidate_pool(net, hidden, target_lm_head, weights["embed_proj.0.weight"], + weights["embed_proj.2.weight"], config.pool_size, + shift_label=config.shift_label) + return dict(zip(("pool_ids", "pool_base_logits", "pool_codebook", "proposal_zproj"), tensors)) + + return draft.build_block_engine(config, weights, max_cache_length, outputs, verbose=verbose, + debug_layer_outputs=debug_layer_outputs) + + +def build_correction_engine(weight_ih, weight_hh, proj_state, pool_size, *, verbose=False): + """Advance the bias-free GRU by one token and score the next proposal pool. + + Both greedy schedules seed an all-zero state with the confirmed anchor and + the first, uncorrected proposal. The released sidecar stores each target + embedding's input projection in FP16; project just the requested token and + round at the same boundary instead of duplicating that vocabulary table. + """ + if any(w.ndim != 2 or w.dtype != np.float16 for w in (weight_ih, weight_hh, proj_state)): + raise ValueError("Domino correction weights must be FP16 matrices") + gates, hidden = weight_hh.shape + width, emb = weight_ih.shape + rank, state = proj_state.shape + if (min(hidden, emb, rank, pool_size) <= 0 or width != gates or gates != 3 * hidden + or state != hidden or hidden % 2 or rank % 2): + raise ValueError("Domino correction dimensions do not match the trained GRU and projection") + log = trt.Logger(trt.Logger.VERBOSE if verbose else trt.Logger.WARNING) + builder = trt.Builder(log) + net = builder.create_network(1 << int(trt.NetworkDefinitionCreationFlag.STRONGLY_TYPED)) + config = builder.create_builder_config() + config.builder_optimization_level = 3 + config.clear_flag(trt.BuilderFlag.TF32) + + def const(value): + a = np.ascontiguousarray(value) + return graph_ops.add_constant(net, a.shape, a, dtype=a.dtype.type) + + def cast(x, dtype): + return x if x.dtype == dtype else net.add_cast(x, dtype).get_output(0) + + def fp32(x): + return cast(x, trt.float32) + + def linear(x, weights): + return net.add_matrix_multiply(fp32(x), trt.MatrixOperation.NONE, fp32(weights), + trt.MatrixOperation.TRANSPOSE).get_output(0) + + def op(x, y, kind): + return net.add_elementwise(x, y, kind).get_output(0) + + def gate(x, i): + return net.add_slice(x, (0, i * hidden), (1, hidden), (1, 1)).get_output(0) + + def act(x, kind): + return net.add_activation(x, kind).get_output(0) + + half = trt.float16 + ew, ac = trt.ElementWiseOperation, trt.ActivationType + embedding = net.add_input("token_embedding", half, (1, emb)) + prev = net.add_input("previous_state", half, (1, hidden)) + zproj = net.add_input("z_projection", half, (1, rank)) + book = net.add_input("pool_codebook", half, (pool_size, rank)) + base = net.add_input("base_scores", trt.float32, (1, pool_size)) + x = fp32(cast(linear(embedding, const(weight_ih)), half)) + hx = linear(prev, const(weight_hh)) + reset = act(op(gate(x, 0), gate(hx, 0), ew.SUM), ac.SIGMOID) + update = act(op(gate(x, 1), gate(hx, 1), ew.SUM), ac.SIGMOID) + new = act(op(gate(x, 2), op(reset, gate(hx, 2), ew.PROD), ew.SUM), ac.TANH) + one = const(np.ones((1, 1), dtype=np.float32)) + next_state = cast(op(op(op(one, update, ew.SUB), new, ew.PROD), + op(update, fp32(prev), ew.PROD), ew.SUM), half) + z = op(fp32(zproj), linear(next_state, const(proj_state)), ew.SUM) + correction = op(z, act(z, ac.SIGMOID), ew.PROD) + corrected = op(base, linear(correction, book), ew.SUM) + for name, tensor in (("next_state", next_state), ("corrected_pool_scores", corrected)): + tensor.name = name + net.mark_output(tensor) + engine = builder.build_serialized_network(net, config) + if engine is None: + raise RuntimeError("Failed to build native Qwen3.6 Domino correction engine") + return bytes(engine) + + +def add_candidate_pool(net, block_hidden, lm_head, embed_proj, codebook, pool_size, *, shift_label): + """Build the released shared candidate pool; never take independent top-k at each position. + + block_hidden is post-normalization FP16. The original Qwen3.6 target LM head + is unquantized. z uses the first, hidden-size slice of embed_proj.0; its + state slice is used by the separate recurrent correction engine. + """ + block, hidden = map(int, block_hidden.shape) + head_dim, vocab = lm_head.shape + rank, combined = embed_proj.shape + if (block != 16 or block_hidden.dtype != trt.float16 or hidden != head_dim + or combined <= hidden or codebook.shape != (vocab, rank) + or any(w.dtype != np.float16 for w in (lm_head, embed_proj, codebook)) + or not 0 < pool_size <= min(vocab, 3840)): + raise ValueError("Invalid Qwen Domino block, shared pool or projection geometry") + + def constant(a): + a = np.ascontiguousarray(a) + return graph_ops.add_constant(net, a.shape, a, dtype=a.dtype.type) + + def matmul(x, w): + return net.add_matrix_multiply(x, trt.MatrixOperation.NONE, constant(w), + trt.MatrixOperation.TRANSPOSE).get_output(0) + + rows = block - 1 + proposal = net.add_slice(block_hidden, (0 if shift_label else 1, 0), + (rows, hidden), (1, 1)).get_output(0) + # The target mapper already stored [hidden, vocab] contiguously. + scores = net.add_matrix_multiply(proposal, trt.MatrixOperation.NONE, constant(lm_head), + trt.MatrixOperation.NONE).get_output(0) + logits = net.add_cast(scores, trt.float32).get_output(0) + peaks = net.add_reduce(logits, trt.ReduceOperation.MAX, 1, True).get_output(0) + pool = net.add_topk(peaks, trt.TopKOperation.MAX, pool_size, 2).get_output(1) + flatten = net.add_shuffle(pool) + flatten.reshape_dims = (pool_size,) + ids = flatten.get_output(0) + scores = net.add_gather(logits, ids, 1).get_output(0) + pool_book = net.add_gather(constant(codebook), ids, 0).get_output(0) + z_rows = net.add_slice(proposal, (1, 0), (rows - 1, hidden), (1, 1)).get_output(0) + return ids, scores, pool_book, matmul(z_rows, embed_proj[:, :hidden]) diff --git a/families/qwen3_8/draft.py b/families/qwen3_8/draft.py index d96ec72f48..7f2ec4f983 100644 --- a/families/qwen3_8/draft.py +++ b/families/qwen3_8/draft.py @@ -137,51 +137,69 @@ def correction(rotations): ) -def load_draft_weights(model_dir: Path, config: DraftConfig): - """Read dense draft tensors once, preserving the upstream FP16 export rounding.""" - readers = _open_safetensors(model_dir) - weights = {} - - def load(name, shape, projection=False): - value = _load_tensor(readers, name) - if value.shape != shape: - raise ValueError(f"{name}: expected {shape}, got {value.shape}") - weights[name] = np.ascontiguousarray(value.T if projection else value, dtype=np.float16) - - h, v, d = config.hidden, config.vocab, config.head_dim - load("fc.weight", (h, len(config.feature_layers) * h), True) - load("hidden_norm.weight", (h,)) - load("norm.weight", (h,)) +def block_weight_shapes(config): + """Dense DFlash backbone used by this family's DSpark and Domino drafts.""" + h, d = config.hidden, config.head_dim + yield "fc.weight", (h, len(config.feature_layers) * h), True + yield "hidden_norm.weight", (h,), False + yield "norm.weight", (h,), False for i in range(config.layers): prefix = f"layers.{i}" for norm in ("input_layernorm", "post_attention_layernorm"): - load(f"{prefix}.{norm}.weight", (h,)) - for projection, out_size, in_size in ( + yield f"{prefix}.{norm}.weight", (h,), False + for proj, out_size, in_size in ( ("q_proj", config.heads * d, h), ("k_proj", config.kv_heads * d, h), ("v_proj", config.kv_heads * d, h), ("o_proj", h, config.heads * d), ): - load(f"{prefix}.self_attn.{projection}.weight", (out_size, in_size), True) + yield f"{prefix}.self_attn.{proj}.weight", (out_size, in_size), True for norm in ("q_norm", "k_norm"): - load(f"{prefix}.self_attn.{norm}.weight", (d,)) - for projection, out_size, in_size in ( + yield f"{prefix}.self_attn.{norm}.weight", (d,), False + for proj, out_size, in_size in ( ("gate_proj", config.intermediate, h), ("up_proj", config.intermediate, h), ("down_proj", h, config.intermediate), ): - load(f"{prefix}.mlp.{projection}.weight", (out_size, in_size), True) - load("markov_head.markov_w1.weight", (v, config.markov_rank)) - load("markov_head.markov_w2.weight", (v, config.markov_rank), True) - if config.confidence: - width = h + (config.markov_rank if config.confidence_with_markov else 0) - load("confidence_head.proj.weight", (1, width), True) - load("confidence_head.proj.bias", (1,)) + yield f"{prefix}.mlp.{proj}.weight", (out_size, in_size), True + + +def load_block_weights(model_dir, specs): + """Read each named draft tensor once, rounding to the released export precision.""" + readers = _open_safetensors(model_dir) if _has_tensor(readers, "lm_head.weight") or _has_tensor(readers, "embed_tokens.weight"): - raise ValueError("Qwen3.8 DSpark requires the inherited target head and embeddings") + raise ValueError("Qwen block draft requires the inherited target head and embeddings") + weights = {} + for name, shape, transpose in specs: + value = _load_tensor(readers, name) + if value.shape != shape: + raise ValueError(f"{name}: expected {shape}, got {value.shape}") + weights[name] = np.ascontiguousarray(value.T if transpose else value, dtype=np.float16) return weights +def load_draft_weights(model_dir: Path, config: DraftConfig): + specs = list(block_weight_shapes(config)) + shape = (config.vocab, config.markov_rank) + specs.extend([("markov_head.markov_w1.weight", shape, False), + ("markov_head.markov_w2.weight", shape, True)]) + if config.confidence: + width = config.hidden + (config.markov_rank if config.confidence_with_markov else 0) + specs.extend([("confidence_head.proj.weight", (1, width), True), + ("confidence_head.proj.bias", (1,), False)]) + return load_block_weights(model_dir, specs) + + def build_draft_engine( config, weights, target_lm_head, max_cache_length, *, quant_ctx=None, verbose=False, debug_layer_outputs=False ): + def outputs(network, hidden): + head = graph_blocks.make_matmul_fn(network, np.float16, quant_ctx) + logits = head(hidden, config.hidden, config.vocab, target_lm_head, "w_lm_head") + return {"draft_hidden": hidden, "draft_logits": network.add_cast(logits, trt.float32).get_output(0)} + + return build_block_engine(config, weights, max_cache_length, outputs, verbose=verbose, + debug_layer_outputs=debug_layer_outputs) + + +def build_block_engine(config, weights, max_cache_length, outputs, *, verbose=False, debug_layer_outputs=False): """Build the real block draft, with no plugins, ONNX or target substitution.""" if max_cache_length < config.query_rows: raise ValueError("Native Qwen3.8 draft context is smaller than its proposal block") @@ -364,12 +382,9 @@ def project(value, name, out_width, nrows=rows): hidden = binary(hidden, down, trt.ElementWiseOperation.SUM) debug(hidden, f"layer_{i}") hidden = norm(hidden, weights["norm.weight"], h) - hidden.name = "draft_hidden" - network.mark_output(hidden) - head = graph_blocks.make_matmul_fn(network, np.float16, quant_ctx) - logits = cast(head(hidden, h, config.vocab, target_lm_head, "w_lm_head"), trt.float32) - logits.name = "draft_logits" - network.mark_output(logits) + for name, tensor in outputs(network, hidden).items(): + tensor.name = name + network.mark_output(tensor) plan = builder.build_serialized_network(network, build_config) if plan is None: raise RuntimeError("Native Qwen3.8 draft engine build failed") diff --git a/families/qwen3_8/edge_llm/README.md b/families/qwen3_8/edge_llm/README.md index 04b2dbbecb..67ad327f5a 100644 --- a/families/qwen3_8/edge_llm/README.md +++ b/families/qwen3_8/edge_llm/README.md @@ -2,8 +2,8 @@ This family owns checkpoint admission, build options, command mapping, bundle assets, runtime orchestration, and validation. Shared code contains no Edge -selection. The optional SDK uses official Edge-LLM **0.11.0**, revision -`95515c2f87fba8982db5a519f9022277667b3cc9`. +selection. The default SDK remains Edge-LLM **0.11.0**; **0.12.0** is a +build-time opt-in. An installed runtime links one release, not both. A compatible installed Python wheel is preferred. Discovery checks the actual builder or ONNX exporter needed by the request, rather than accepting a version @@ -11,7 +11,127 @@ string alone. Matching source-installed SDK Python is the fallback. Python package discovery does not replace the native CMake SDK dependency. Builds are native; cross compilation is not supported. -## Executed Edge configurations +## Opt in to Edge-LLM 0.12 + +Follow the [SDK provisioning guide](../../../cmake/edge_llm/README.md) with +`TRTMC_ENABLE_EDGELLM=ON` and `TRTMC_EDGELLM_RELEASE=0.12.0`. Paired +builds need `TRTMC_EDGELLM_ONNX=ON`. If the exporter uses its own Python +environment, pass its absolute interpreter path with `--edge-builder-python`; +this does not replace the linked SDK or change Model Connect's Transformers pin. + +| Build request | 0.12 mapping | +| --- | --- | +| Ordinary FP16, original dense 27B or supported prepared NVFP4 | Direct Edge build; no companion. Request the vision-language task explicitly for image input. | +| Mixed NVFP4 + DSpark or DFlash2 | Select `dspark` for DSpark, or `dflash` (chain) / `dflash_tree` (tree) for DFlash2. Pass the matching unquantized draft. | +| Original Qwen3.6-27B + Domino | Select `domino` for a block-16 chain or `domino_tree` for a 60-node tree. Both use the same draft and require greedy decoding. | +| Original or signed INT4 Qwen3.8-27B + DFlash2 | Select `dflash` or `dflash_tree`. For signed INT4 with implicit zero points, the 0.12 base exporter is incompatible; MC warns and uses native TRT with the same target and draft. | + +Use `--execution-variant dflash_tree` for the 0.12 greedy DFlash2 +selector tree (top 4, verify 32). Unlike the chain, the native tree scores +each depth's candidates conditioned on their actual predecessor. DFlash2 +chain results do not validate this separate profile. + +For the original Qwen3.6-27B Domino chain, both Edge and native matched the +FP32 chat and raw reference tokens. On the raw request the released Edge +runtime reproduced the result with five verification rounds; native accepted +10 of 75 proposed tokens over five rounds. Tested separately, the 60-node +Domino tree also matched the same-backend ordinary target and the independent +FP32 tokens on both requests. Native accepted 10 draft tokens across five raw +rounds (295 candidate nodes); the Edge runtime reported a 60-node, top-4 tree. +The stock Edge runner reproduced the raw text over five verification rounds. +Both Model Connect routes explicitly rejected a stochastic sampling request. + +The Domino mapping uses the published original target and draft. A calibrated +Domino pair is not covered by these native or Edge results. + +The Model Connect package does not ship target or draft weights. Supply local +checkpoints under their publishers' terms. + +For example, with the two checkpoints already present locally: + +```sh +trtmc qwen3_8 build /models/Qwen3.6-27B --task text_generation \ + --precision fp16 --max-sequence-length 256 --execution-variant domino_tree \ + --companion draft=/models/qwen3.6-27B-domino -o domino-tree.bundle +trtmc run domino-tree.bundle --prompt "The capital of France is" \ + --temperature 0 --top-k 1 --top-p 1 --max-new-tokens 16 +``` + +**Mapping is not qualification.** On the mixed 27B target, ordinary, DSpark +and DFlash2 builds ran on both Edge and native TRT. All three chat cases passed. +For the raw-text case, Edge had normalized edit distance 0.21875 against the +0.15 limit on all three; replay with the stock Edge runtime produced the same +text. Native DFlash2 matched the reference, while native ordinary and DSpark +missed the raw-text gate. Ordinary image cases also missed the gate. Accuracy +failures remain executable. + +On the uniform Inferact NVFP4 checkpoint, both 4096-token vision builds ran +all four requests on SM120. Both matched the chat and raw FP32 reference token +IDs. Single-image / ordered-image distances were 0.211 / 0.202 on Edge and +0.492 / 0.469 on native, above the unchanged 0.15 limit. The independent FP32 +reference used the uniform target weights, not the mixed checkpoint. These +image results are not an upstream-only attribution. + +On the original unquantized Qwen3.8-27B checkpoint, ordinary FP16 Edge and +native builds both ran raw text, chat, one image, and two ordered images. Both +text cases matched the independent FP32 reference token for token. The image +cases did not meet the same 0.15 limit: one-image / two-image distances were +0.484 / 0.287 on Edge and 0.290 / 0.333 on native. These visual routes remain +available; this is not a visual accuracy qualification. The released Edge +runtime emitted the same text as Model Connect for both image requests +when run directly on the same engine. + +The original-checkpoint results use +[Qwen3.6-27B at `1cda14dd7`](https://huggingface.co/Qwen/Qwen3.6-27B/tree/1cda14dd71a3f47115850eb790f416f165da1cb5) and +[Qwen3.8-27B at `37561816e`](https://huggingface.co/Qwen/Qwen3.8-27B/tree/37561816e66b5b9153b1b64c10968c18c1e6f4a0). +These model runs do not replace the registered premerge tests. + +For original Qwen3.6-27B ordinary FP16 on GB300, both backends matched the +FP32 chat and raw tokens. Ordered images passed (normalized edit distance +0.101 on Edge, 0.087 on native). For the single image, both backends returned +identical token IDs but missed the 0.15 gate (0.357). The released Edge +runner reproduced that text on the same engine. A separate HF FP16 run matched +all 128 HF FP32 tokens; both Model Connect routes first differed at token index +45 from both HF runs. This result does not qualify +the single-image case or establish a TensorRT compiler defect. + +For the original Qwen3.8-27B target paired with the DFlash2 chain, omit +`--quantization` or use `--quantization none`. Both Edge and native TRT built +the pair on GB300 and matched the independent FP32 token IDs for chat and raw +text. The Edge runtime selected DFlash decoding; native accepted 10 of 36 +proposals over six rounds on the raw request. The Edge verification count was +not measured for this pair. + +For the signed INT4 target and DFlash2 chain, the standalone Edge +exporter reproduced the packed-zero-point failure. On a GB300 the native +fallback built and ran the original pair, with real draft proposals. Chat and +raw output matched the independently decoded FP32 target token for token. +This verifies native execution for those two requests, not Edge execution. + +### DFlash2 tree results on 0.12 + +These are greedy, batch-1, TP1 chat and raw-text requests on GB300, using the +same unquantized `z-lab/Qwen3.8-27B-DFlash2` draft. The independent target +reference is specific to each checkpoint. A stock replay compares runtime +paths; it is not a substitute for the independent reference. + +| Target | Edge route | Native TensorRT route | +| --- | --- | --- | +| `Qwen/Qwen3.8-27B` (original) | Exact FP32 tokens on both requests. Stock raw matched over four verification rounds. | Both requests matched FP32; 12 candidate tokens accepted in four raw rounds. | +| `RadixArk/Qwen3.8-27B-NVFP4` (mixed) | Exact FP32 tokens on both requests. Stock raw matched over four verification rounds. | Chat exact; raw NED 0.21875 exceeds 0.15. Accepted 13 candidate tokens in three raw rounds. | +| `RedHatAI/Qwen3.8-27B-INT4` (signed) | Not run: the same base exporter used by the chain fails on implicit zero points. | MC warned and selected native. Both requests matched FP32 exactly; 12 candidate tokens accepted in four raw rounds. | + +All five measured routes rejected stochastic decoding as required by this +tree. On the original target, each tree also matched the ordinary target and +chain on the same GPU for these requests. The ordinary models were separately +compiled vision-capable bundles, not identical target engines. + +On the mixed target, the native tree and a separately compiled native ordinary +target emitted identical raw tokens; the native chain matched FP32. The Edge +chain and tree were measured on different GPUs. Neither comparison isolates a +scheduler defect or establishes a speedup. + +## Previously executed Edge 0.11 configurations | Source checkpoint | Execution | Local build profile | | --- | --- | --- | @@ -92,10 +212,9 @@ mapped interface, not additional locally executed model tests. DFlash2 uses Edge's public `dflash` mode. Paired builds invoke the official ONNX exporter and native engine builder for both engines. They include required -embedding, selector/head, tokenizer, and prompt-template assets. Runtime -verification uses size 8, drafting top-K 1/step 1, and DSpark scheduling off; -the draft architecture selects the appropriate block semantics. DFlash2 DDTree -is not supported. The mapped DSpark context range is 9–1024 tokens; DFlash2 is +embedding, selector/head, tokenizer, and prompt-template assets. The `dflash` chain uses verification size 8 and drafting top-K 1. +The **0.11 Edge runtime** does not support DFlash2 tree decoding. With the +0.12 SDK, select `dflash_tree` for the greedy 32-node tree described above. The mapped DSpark context range is 9–1024 tokens; DFlash2 is 9–4096, also bounded by source metadata. Ordinary builds map the official Python builder and native C++ runtime. TP2 @@ -223,8 +342,9 @@ Native DFlash2 uses an eight-row bidirectional draft with grouped dynamic convolution, a sliding attention window, and seven prediction rows. The inherited target LM head retains its exact quantization. A separate TensorRT selector uses the original predecessor/successor codebooks and FP32 conditional scoring over -sixteen candidates. C++ proposal sampling and target verification preserve the -requested sampling controls; rejected proposals never enter target state. +sixteen candidates. The chain supports proposal sampling; the tree accepts only +greedy decoding and scores children conditioned on their actual predecessor. +On either path, rejected proposals never enter target state. The retained DFlash2 companion built natively at FP16/TP1/context-256 on SM120, using the already-validated mixed-NVFP4 target engine and identical target feature @@ -318,7 +438,7 @@ results; no new calibration was performed. Broader workloads, contexts, and platforms remain unqualified. Unsupported requests fail explicitly rather than becoming ordinary text or a different parallelism. -## Edge evidence and remaining limits +## Edge 0.11 evidence and remaining limits All comparisons retain the owning NED **0.15** gate. Exact agreement with direct Edge is transport parity, not an independent quality result. @@ -358,14 +478,14 @@ Tested source revisions: - DSpark: `b9a5dbdf03bc999c6c73c426b19c2d9041cea393`. - DFlash2: `50307d4c4cde6860d4eee73e2547cd786fe8e8a4`. -Original-weight DFlash2 remains outside this adapter's current admission and -has no executed result. Its initial admission decision used a 48 GiB device +The 0.11 Edge adapter did not admit original-weight DFlash2 and has no +executed result for that profile. See the 0.12 results above. Its initial admission decision used a 48 GiB device budget and roughly 57.6 GB of FP16 text/draft source weights, not an observed GPU OOM or measured engine allocation. Larger-memory devices are now available, so that historical budget is not a current hardware blocker or an intrinsic model restriction. The pinned ONNX builder rejects speculative TP greater than one; neither that constraint nor native integration controls qualify this -currently unmapped profile. +0.11 profile. The additional INT4 DFlash2 and uniform NVFP4/INT4-AWQ MTP mappings have not been validated with full prepared checkpoints. Their Edge mappings delegate to diff --git a/families/qwen3_8/edge_llm/builder.py b/families/qwen3_8/edge_llm/builder.py index 6e9e239856..94c3e31032 100644 --- a/families/qwen3_8/edge_llm/builder.py +++ b/families/qwen3_8/edge_llm/builder.py @@ -5,7 +5,9 @@ from __future__ import annotations +from importlib.metadata import PackageNotFoundError, distribution import json +import logging from pathlib import Path import shutil import subprocess @@ -13,7 +15,13 @@ from tensorrt_model_connect.build import cmake_prefixes, detect_local_platform, subprocess_environment -EDGE_REVISION = "95515c2f87fba8982db5a519f9022277667b3cc9" +from ..config import compressed_int4_fp8_kv + +# One C++ SDK per installation; the manifest is its build-time receipt. +_RELEASES = { + "0.11.0": (1, "revision", "95515c2f87fba8982db5a519f9022277667b3cc9", "experimental.builder.cli"), + "0.12.0": (2, "release_revision", "513dcd18291e587c80928911a480761352f3c2d8", "tensorrt_edgellm.builder.cli"), +} def local_target() -> dict: @@ -21,6 +29,48 @@ def local_target() -> dict: return detect_local_platform() +def _package_prefixes(*, report_conflict: bool = False) -> list[Path]: + """Use the active wheel's SDK with its native runner, or standalone prefixes.""" + try: + package = distribution("tensorrt-model-connect") + except PackageNotFoundError: + return cmake_prefixes() + module_dir = Path(package.locate_file("tensorrt_model_connect")) + receipt = module_dir / "share/trtmc/edge-llm.json" + if (module_dir / "bin/trtmc").is_file() and (receipt.exists() or receipt.is_symlink()): + if report_conflict: + for prefix in cmake_prefixes(): + other = prefix / "share/trtmc/edge-llm.json" + if other.is_file() and other.resolve() != receipt.resolve(): + logging.getLogger(__name__).warning( + "Cannot use standalone Edge SDK at %s with the installed Model Connect runner; " + "using its packaged SDK at %s. To change SDKs, install a matching Model " + "Connect wheel or use the matching standalone builder and runner together.", + prefix, module_dir, + ) + break + return [module_dir] + return cmake_prefixes() + + +def selected_release() -> str | None: + """Identify the selected SDK; prepare validates the complete receipt before use.""" + for prefix in _package_prefixes(): + receipt = prefix / "share/trtmc/edge-llm.json" + if receipt.is_file(): + try: + manifest = json.loads(receipt.read_text(encoding="utf-8")) + if not isinstance(manifest, dict): + raise ValueError("expected an SDK manifest object") + return manifest.get("version") + except (OSError, ValueError) as error: + logging.getLogger(__name__).warning( + "Cannot identify the Qwen3.8 Edge SDK: %s. Using native TensorRT.", error + ) + return None + return None + + def installed_package(target: dict) -> dict: """Resolve CMake installation via standard prefixes; never install anything. @@ -34,21 +84,30 @@ def installed_package(target: dict) -> dict: FileNotFoundError: No CMake installation or required artifact exists. ValueError: Pin, architecture, SDK or contained-path contract differs. """ - for prefix in cmake_prefixes(): + for prefix in _package_prefixes(report_conflict=True): manifest = prefix / "share/trtmc/edge-llm.json" if not manifest.is_file(): continue package = json.loads(manifest.read_text(encoding="utf-8")) - if package.get("schema_version") != 1 or package.get("revision") != EDGE_REVISION: - raise ValueError(f"Edge package has an unsupported revision/schema: {manifest}") - if package.get("version") != "0.11.0" or package.get("arch") != target["arch"]: + release = _RELEASES.get(package.get("version")) + if release is None or package.get("schema_version") != release[0]: + raise ValueError(f"Unsupported Edge package release or schema: {manifest}") + revision_key, pinned = release[1:3] + allowed = (pinned, None) if package["version"] == "0.12.0" else (pinned,) + if revision_key not in package or package[revision_key] not in allowed: + raise ValueError(f"Unsupported Edge package source revision: {manifest}") + if package.get("arch") != target["arch"]: raise ValueError("Edge package version/architecture differs from executing worker") if target["sm"] not in package.get("architectures", []): raise ValueError("Edge package was not built for this local GPU") cuda_version = ".".join(str(package.get("cuda_version", "")).split(".")[:2]) - if cuda_version != target["cuda_version"] or package.get("tensorrt_version") != target["tensorrt_version"]: + if ( + cuda_version != target["cuda_version"] + or package.get("tensorrt_version") != target["tensorrt_version"] + ): raise ValueError("Edge package CUDA/TensorRT differs from executing worker") - for name in ("python", "plugin") + (("onnx_builder",) if package.get("onnx") else ()): + for name in ("plugin", *(("python",) if package["version"] == "0.11.0" else ()), + *(("onnx_builder",) if package.get("onnx") else ())): relative = Path(package[name]) path = (prefix / relative).resolve() if relative.is_absolute() or not path.is_relative_to(prefix.resolve()): @@ -56,21 +115,36 @@ def installed_package(target: dict) -> dict: if not path.is_file(): raise FileNotFoundError(f"Edge package {name} is missing: {path}") package[name] = str(path) + package["install_prefix"] = str(prefix.resolve()) return package - raise FileNotFoundError("Edge-LLM is not installed; enable the optional Edge-LLM CMake dependency " - "and set CMAKE_PREFIX_PATH to its install prefix") - + raise FileNotFoundError( + "Edge-LLM is not installed; enable the optional Edge-LLM CMake dependency " + "and set CMAKE_PREFIX_PATH to its install prefix" + ) -def builder_python(package: dict, target: dict, *, onnx: bool = False) -> str: - """Use installed 0.11.0 Python tools when compatible, otherwise the SDK Python. +def builder_python(package: dict, target: dict, requested: Path | None = None, *, onnx: bool = False) -> str: + """Select a verified builder interpreter for the chosen native SDK release. The native SDK remains required. This only discovers an interpreter; it never installs packages or substitutes the wheel's runtime for the C++ SDK. - Probe the requested builder API, not only the package version. An - incompatible ambient install is ignored. + An incompatible ambient install is ignored. """ - interpreter = sys.executable + version = package.get("version", "0.11.0") + if onnx: + module = "tensorrt_edgellm.onnx.cli" if version == "0.12.0" else "tensorrt_edgellm.scripts.export" + else: + module = _RELEASES[version][3] + interpreter = sys.executable if requested is None else str(requested) + # Probe distribution identity and entry-point presence, not the full model + # stack. The real builder imports the entry point once and reports any + # missing dependency through the normal native-fallback path. + entry_check = ( + "from importlib.metadata import version; from importlib.util import find_spec; " + "assert version('transformers') == '5.17.0'; " + f"assert find_spec('{module}') is not None; " + if version == "0.12.0" else f"import {module}; " + ) try: if not Path(interpreter).is_absolute() or not Path(interpreter).is_file(): raise ValueError("Edge builder Python must be an existing absolute interpreter path") @@ -80,21 +154,25 @@ def builder_python(package: dict, target: dict, *, onnx: bool = False) -> str: "-I", "-c", "import json, tensorrt, tensorrt_edgellm; " - + ("import tensorrt_edgellm.scripts.export; " if onnx - else "from experimental.builder.cli import main; ") - + "print(json.dumps([tensorrt_edgellm.__version__, tensorrt.__version__]))", + f"{entry_check}" + "print(json.dumps([tensorrt_edgellm.__version__, tensorrt.__version__]))", ], check=True, capture_output=True, text=True, timeout=30, ) - if json.loads(probe.stdout) != ["0.11.0", target["tensorrt_version"]]: + if json.loads(probe.stdout) != [version, target["tensorrt_version"]]: raise ValueError( - "Edge builder Python must match Edge 0.11.0 and the native TensorRT SDK" + f"Edge builder Python must match Edge {version} and the native TensorRT SDK" ) - except (OSError, ValueError, subprocess.SubprocessError): - return package["python"] + except (OSError, ValueError, subprocess.SubprocessError) as error: + if requested is None and version == "0.11.0" and package.get("python"): + return package["python"] + raise ValueError( + f"Pass --edge-builder-python with an interpreter matching Edge {version} and the native TensorRT SDK. " + "To select another Edge release, use a matching Model Connect wheel or standalone builder and runner." + ) from error return interpreter @@ -159,10 +237,70 @@ def prepared_checkpoint_quantization(model_dir: Path, raw: dict) -> str | None: return declared[0] -def paired_checkpoint_quantization(model_dir: Path, raw: dict, variant: str) -> str | None: - """Keep DSpark mixed-only; DFlash2 additionally maps official INT4-AWQ.""" - if checkpoint_quantization(model_dir, raw) == "nvfp4": +def ordinary_quantization(model_dir: Path, raw: dict, *, current: bool) -> str | None: + """Preserve original, mixed FP8/NVFP4 and the listed uniform NVFP4 recipe.""" + value = checkpoint_quantization(model_dir, raw) + if value is None and current and prepared_checkpoint_quantization(model_dir, raw) == "nvfp4": return "nvfp4" + return value + + +def dense_swish_27b(raw: dict) -> bool: + """Identify the documented dense 27B target, not other Swish model sizes.""" + config = raw.get("text_config", raw) + return (isinstance(config, dict) and raw.get("model_type") == "qwen3_5" + and config.get("output_gate_type") == "swish" and "mlp_only_layers" not in config + and not config.get("num_experts") + and config.get("linear_key_head_dim") == config.get("linear_value_head_dim") == 128 + and tuple(config.get(key) for key in ( + "num_hidden_layers", "hidden_size", "intermediate_size", + "num_attention_heads", "num_key_value_heads", "vocab_size", + )) == (64, 5120, 17408, 24, 4, 248320)) + + +def implicit_packed_zero_points(model_dir: Path, raw: dict) -> bool: + """Edge 0.12 GPTQ repacking reads qzeros even for implicit symmetric zeros.""" + if not compressed_int4_fp8_kv(raw): + return False + index = model_dir / "model.safetensors.index.json" + if index.is_file(): + keys = set(json.loads(index.read_text(encoding="utf-8"))["weight_map"]) + else: + from safetensors import safe_open + keys = set() + for shard in model_dir.glob("*.safetensors"): + with safe_open(shard, framework="np") as source: + keys.update(source.keys()) + for key in keys: + if not key.startswith(("model.language_model.layers.", "model.layers.")) or not key.endswith(".weight_packed"): + continue + layer = key.removesuffix(".weight_packed") + if layer + ".qzeros" not in keys and layer + ".weight_zero_point" not in keys: + return True + return False + + +def paired_checkpoint_quantization(model_dir: Path, raw: dict, variant: str, *, + include_current: bool = False) -> str | None: + """DSpark requires mixed NVFP4; DFlash2 also admits prepared AWQ or the original 27B.""" + if variant not in {"dspark", "dflash", "dflash_tree", "domino", "domino_tree"}: + return None + value = checkpoint_quantization(model_dir, raw) + if variant in {"domino", "domino_tree"}: + return value if include_current and value == "none" and dense_swish_27b(raw) else None + if variant == "dflash_tree": + if not include_current: + return None + variant = "dflash" # Same target/draft weights, different verification profile. + if value == "nvfp4": + return value + if variant == "dflash" and include_current and dense_swish_27b(raw): + if value == "none": + return value + if compressed_int4_fp8_kv(raw) and not any( + (model_dir / name).exists() for name in ("hf_quant_config.json", "quantize_config.json", "quant_config.json") + ): + return "int4_gptq" if variant == "dflash" and prepared_checkpoint_quantization(model_dir, raw) == "int4_awq": return "int4_awq" return None @@ -201,24 +339,32 @@ def _prepare_paired_onnx(request, raw: dict, target: dict, staging: Path, log_pa padding or weight conversion is needed, and baked weights are not bundled twice. Both plans and their complete runtime assets must exist to publish. """ - if variant not in {"dspark", "dflash"}: + if variant not in {"dspark", "dflash", "dflash_tree", "domino", "domino_tree"}: raise ValueError("Unsupported Qwen3.8 ONNX paired variant") - maximum = 1024 if variant == "dspark" else 4096 - block = 7 if variant == "dspark" else 8 - tree = 8 if variant == "dspark" else 16 + domino = variant in {"domino", "domino_tree"} + dflash_tree = variant == "dflash_tree" + method = "domino" if domino else "dflash" if dflash_tree else variant + maximum = {"dspark": 1024, "dflash": 4096, "domino": 2048}[method] + max_input = 1024 if domino else maximum + block = 16 if domino else (7 if variant == "dspark" else 8) + tree = 60 if domino else 32 if dflash_tree else 8 if variant == "dspark" else 16 + draft_slots = {"dspark": 7, "dflash": 16, "domino": 60}[method] package = installed_package(target) if package.get("onnx") is not True: raise ValueError("Qwen3.8 paired execution requires an ONNX-enabled Edge SDK") source, draft_dir = Path(request.model_dir).resolve(), draft_dir.resolve() - quantization = paired_checkpoint_quantization(source, raw, variant) + version = package.get("version", "0.11.0") + current = version == "0.12.0" + quantization = paired_checkpoint_quantization(source, raw, variant, include_current=current) if quantization is None: - raise ValueError("Qwen3.8 paired execution requires mixed NVFP4 or documented DFlash2 INT4-AWQ") + raise ValueError("Unsupported Qwen3.8 target checkpoint for this paired Edge release") if not list(source.glob("*.safetensors")) or not list(draft_dir.glob("*.safetensors")): raise ValueError("Qwen3.8 paired execution requires both local safetensors checkpoints") config = raw.get("text_config", raw) limit = request.max_sequence_length or min(int(config["max_position_embeddings"]), 256) - if not 8 < limit <= maximum: - raise ValueError(f"Qwen3.8 {variant} requires capacity above 8 and at most {maximum}") + minimum = 16 if domino else 9 + if not minimum <= limit <= maximum: + raise ValueError(f"Qwen3.8 {variant} requires capacity above {minimum - 1} and at most {maximum}") checkpoint = staging / "edge_llm/checkpoint" checkpoint.mkdir(parents=True) for name in ("config.json", "tokenizer.json", "tokenizer_config.json", "generation_config.json", @@ -228,21 +374,35 @@ def _prepare_paired_onnx(request, raw: dict, target: dict, staging: Path, log_pa (checkpoint / "draft").mkdir() shutil.copy2(draft_dir / "config.json", checkpoint / "draft/config.json") engine, onnx = staging / "edge_llm/engine", staging / "onnx" + python = builder_python(package, target, getattr(request, "edge_builder_python", None), onnx=True) env = subprocess_environment( {"EDGELLM_PLUGIN_PATH": package["plugin"]}, prepend_paths={"LD_LIBRARY_PATH": str(Path(package["plugin"]).parent)}, ) - for role, subdirectory, flag in (("draft", f"{variant}_draft", "--specDraft"), + for role, subdirectory, flag in (("draft", ("dflash_draft" if domino else f"{method}_draft"), "--specDraft"), ("base", "llm", "--specBase")): - commands = [ - [builder_python(package, target, onnx=True), "-I", "-m", "tensorrt_edgellm.scripts.export", - str(source), str(onnx), f"--{variant}-{role}", f"--{variant}-draft-dir", str(draft_dir), - "--skip-visual", "--skip-audio"], - [package["onnx_builder"], "--onnxDir", str(onnx / subdirectory), - "--engineDir", str(engine), flag, "--maxInputLen", str(min(limit, maximum)), - "--maxKVCacheCapacity", str(limit), "--maxBatchSize", "1", - "--maxVerifyTreeSize", str(tree), "--maxDraftTreeSize", str(block if variant == "dspark" else tree)], - ] + if current: + exporter = [python, "-I", "-c", "from tensorrt_edgellm.onnx.cli import main; main()", + str(source), str(onnx), f"--{method}-{role}", f"--{method}-draft-dir", str(draft_dir), + "--dtype", "float16"] + if role == "base": + exporter += ["--components", "thinker"] + compiler = [package["onnx_builder"], "--onnx-dir", str(onnx / subdirectory), + "--engine-dir", str(engine), "--max-input-len", str(min(limit, max_input)), + "--max-kv-cache-capacity", str(limit), "--max-batch-size", "1"] + compiler += (["--spec-base", "--max-spec-verify-tokens", str(tree)] if role == "base" else + ["--spec-draft", "--max-spec-draft-tokens", str(draft_slots)]) + commands = [exporter, compiler] + else: + commands = [ + [python, "-I", "-m", "tensorrt_edgellm.scripts.export", + str(source), str(onnx), f"--{method}-{role}", f"--{method}-draft-dir", str(draft_dir), + "--skip-visual", "--skip-audio"], + [package["onnx_builder"], "--onnxDir", str(onnx / subdirectory), + "--engineDir", str(engine), flag, "--maxInputLen", str(min(limit, max_input)), + "--maxKVCacheCapacity", str(limit), "--maxBatchSize", "1", + "--maxVerifyTreeSize", str(tree), "--maxDraftTreeSize", str(block if variant == "dspark" else tree)], + ] with log_path.open("a", encoding="utf-8") as log: for command in commands: log.write(json.dumps(command) + "\n") @@ -251,7 +411,7 @@ def _prepare_paired_onnx(request, raw: dict, target: dict, staging: Path, log_pa cwd=staging, env=env) shutil.rmtree(onnx) # Only this preparation's successfully consumed intermediates. with log_path.open("a", encoding="utf-8") as log: - subprocess.run([package["python"], "-I", "-c", _PROMPT_PROGRAM, + subprocess.run([python, "-I", "-c", _PROMPT_PROGRAM, "--model-dir", str(checkpoint), "--engine-dir", str(engine)], check=True, stdout=log, stderr=subprocess.STDOUT, cwd=staging, env=env) required = ("spec_base.engine", "spec_draft.engine", "base_config.json", "draft_config.json", @@ -259,13 +419,30 @@ def _prepare_paired_onnx(request, raw: dict, target: dict, staging: Path, log_pa "chat_template.jinja", "trtmc_single_user_prompts.json") if variant == "dspark": required += ("dspark_heads.safetensors", "dspark_heads_info.json") + if domino: + required += ("domino_heads.safetensors",) + if current and method == "dflash": + required += ("dflash2_selector.safetensors",) for name in required: if not (engine / name).is_file() or (engine / name).stat().st_size == 0: raise ValueError(f"Edge ONNX builder did not produce required artifact: {name}") for role in ("base", "draft"): built = json.loads((engine / f"{role}_config.json").read_text(encoding="utf-8")) - if (built.get("spec_decode_type") != variant - or built.get(f"{variant}_config", {}).get("block_size") != block): + if domino: + from ..domino import DominoConfig + expected = DominoConfig.from_dict(json.loads((draft_dir / "config.json").read_text()), config) + correction = built.get("dflash_config", {}) + fields = {"block_size": 16, "version": 1, "projector_type": "domino", "prefix_len": 1, + "supports_probabilistic_sampling": False, "mask_token_id": expected.mask_token, + "pool_size": expected.pool_size, "proj_dim": expected.rank, "gru_hidden_dim": expected.state, + "shift_label": expected.shift_label, "heads_file": "domino_heads.safetensors", + "target_layer_ids": list(expected.feature_layers)} + if built.get("spec_decode_type") != "domino" or any( + correction.get(key) != value for key, value in fields.items()): + raise ValueError(f"Edge {role} did not retain the requested Domino correction contract") + continue + if (built.get("spec_decode_type") != method + or built.get(f"{method}_config", {}).get("block_size") != block): raise ValueError(f"Edge ONNX builder returned a different {variant} contract") files = {} for directory in (engine, checkpoint): @@ -275,10 +452,15 @@ def _prepare_paired_onnx(request, raw: dict, target: dict, staging: Path, log_pa if path.is_file(): files[path.relative_to(staging).as_posix()] = path return files, { - "version": 1, "edge_revision": EDGE_REVISION, "target": target, "precision": "fp16", - "max_sequence_length": limit, "max_input_length": min(limit, maximum), "max_batch_size": 1, + "version": 1, "edge_release": version, + "edge_revision": package.get(_RELEASES[version][1], _RELEASES[version][2]), "target": target, "precision": "fp16", + "max_sequence_length": limit, "max_input_length": min(limit, max_input), "max_batch_size": 1, "checkpoint_quantization": quantization, "artifacts": list(files), - "execution_variant": variant, "builder_flow": "onnx", f"{variant}_block_size": block, + "execution_variant": variant, "builder_flow": "onnx", + **({"domino_block_size": 16, "domino_top_k": 4 if variant == "domino_tree" else 1, + "domino_verify": 60 if variant == "domino_tree" else 16} if domino + else {"dflash_block_size": block, "dflash_top_k": 4, "dflash_verify": 32} if dflash_tree + else {f"{variant}_block_size": block}), } @@ -289,6 +471,19 @@ def prepare_dspark(request, raw: dict, target: dict, staging: Path, log_path: Pa return _prepare_paired_onnx(request, raw, target, staging, log_path, draft_dir, "dspark") +def prepare_dflash_tree(request, raw: dict, target: dict, staging: Path, log_path: Path, draft_dir: Path): + """DFlash2 selector DDTree: same block-8 draft, 32 verification nodes.""" + return _prepare_paired_onnx(request, raw, target, staging, log_path, draft_dir, "dflash_tree") + + +def prepare_domino(request, raw: dict, target: dict, staging: Path, log_path: Path, draft_dir: Path): + return _prepare_paired_onnx(request, raw, target, staging, log_path, draft_dir, "domino") + + +def prepare_domino_tree(request, raw: dict, target: dict, staging: Path, log_path: Path, draft_dir: Path): + return _prepare_paired_onnx(request, raw, target, staging, log_path, draft_dir, "domino_tree") + + def prepare_dflash(request, raw: dict, target: dict, staging: Path, log_path: Path, draft_dir: Path) -> tuple[dict, dict]: """The DFlash2 checkpoint selects V2 under the upstream public dflash mode.""" @@ -346,6 +541,14 @@ def runtime_checkpoint_files(source: Path, config: dict, *, embedded_mtp: bool = return files +def prepare_fp16(request, raw: dict, target: dict, staging: Path, log_path: Path, + draft_dir: Path | None = None) -> tuple[dict, dict]: + """Build an original dense target on one device with the 0.12 direct builder.""" + if draft_dir is not None or request.tensor_parallel_size != 1: + raise ValueError("Qwen3.8 ordinary FP16 requires TP1 without a draft") + return _prepare_ordinary(request, raw, target, staging, log_path, "none") + + def prepare_tp2(request, raw: dict, target: dict, staging: Path, log_path: Path, draft_dir: Path | None = None) -> tuple[dict, dict]: """Map the ordinary dense 27B request to both official direct-builder ranks.""" @@ -378,29 +581,42 @@ def _prepare_ordinary(request, raw: dict, target: dict, staging: Path, log_path: """Map one family-owned ordinary profile to the unchanged Edge builder.""" package = installed_package(target) source = Path(request.model_dir).resolve() - classify = prepared_checkpoint_quantization if variant == "mtp" else checkpoint_quantization - if classify(source, raw) != quantization or not list(source.glob("*.safetensors")): + version = package.get("version", "0.11.0") + current = version == "0.12.0" + classified = (prepared_checkpoint_quantization(source, raw) if variant == "mtp" else + ordinary_quantization(source, raw, current=current)) + if classified != quantization or not list(source.glob("*.safetensors")): raise ValueError("Qwen3.8 ordinary Edge build requires matching original safetensors weights") parallel = request.tensor_parallel_size config = raw.get("text_config", raw) visual = request.task == "vision_language_generation" limit = request.max_sequence_length or min(int(config["max_position_embeddings"]), 4096 if visual else 256) - input_limit = min(limit, 2048) + # Multiple images share the text context; 1280 bounds each image, not their sum. + input_limit = limit if current and visual and parallel == 1 and variant == "autoregressive" else min(limit, 2048) engine = staging / "edge_llm/engine" - python = builder_python(package, target) + requested = getattr(request, "edge_builder_python", None) + python = builder_python(package, target, requested) if requested is not None else builder_python(package, target) + direct = f"from {_RELEASES[version][3]} import main; main()" command = [ python, "-I", "-c", - "from experimental.builder.cli import main; main()", - "--model-dir", str(source), "--engine-dir", str(engine), "--components", "llm", + direct, + "--model-dir", str(source), "--engine-dir", str(engine), + "--components", "all" if current and parallel == 1 and visual else "llm", # auto preserves per-layer FP8/NVFP4 and upstream KV-scale detection. "--plugin-path", package["plugin"], "--dense", "fp16" if quantization == "none" else "auto", "--max-input-len", str(input_limit), "--max-kv-cache-capacity", str(limit), "--max-batch-size", "1", "--tp-size", str(parallel), ] + if current and parallel == 1: + command.extend(["--externalize-weights", "all"]) + if visual: + command.extend(["--min-image-tokens", "128", "--max-image-tokens", str(input_limit), + "--max-image-tokens-per-image", "1280"]) if variant == "mtp": if limit <= 4: raise ValueError("MTP capacity must exceed its four verification positions") - command.extend(["--spec-type", "mtp", "--max-verify-tree-size", "4", "--max-draft-tree-size", "4"]) + command.extend(["--spec-type", "mtp", "--max-spec-verify-tokens" if current else "--max-verify-tree-size", "4", + "--max-spec-draft-tokens" if current else "--max-draft-tree-size", "4"]) if request.verbose: command.append("--verbose") with log_path.open("a", encoding="utf-8") as log: @@ -410,10 +626,10 @@ def _prepare_ordinary(request, raw: dict, target: dict, staging: Path, log_path: log.flush() subprocess.run(rank_command, check=True, stdout=log, stderr=subprocess.STDOUT, cwd=staging) - if visual: + if visual and not (current and parallel == 1): # The official builder admits TP only for LLM; visual runs at TP1. visual_command = [ - python, "-I", "-c", "from experimental.builder.cli import main; main()", + python, "-I", "-c", direct, "--model-dir", str(source), "--engine-dir", str(engine), "--components", "visual", "--dense", "fp16", "--tp-size", "1", "--max-batch-size", "1", "--plugin-path", package["plugin"], @@ -442,13 +658,18 @@ def _prepare_ordinary(request, raw: dict, target: dict, staging: Path, log_path: if path.is_file(): files[path.relative_to(staging).as_posix()] = path built_config = json.loads((engine / config_name).read_text()) - files.update(runtime_checkpoint_files(source, built_config, embedded_mtp=variant == "mtp")) + if current and parallel == 1: + # With externalized weights, the engine reads original shards by tensor name. + files.update({f"edge_llm/checkpoint/{p.name}": p for p in source.glob("*.safetensors")}) + else: + files.update(runtime_checkpoint_files(source, built_config, embedded_mtp=variant == "mtp")) if variant == "mtp": draft_config = json.loads((engine / "draft_config.json").read_text()) if any(config.get("spec_decode_type") != "mtp" for config in (built_config, draft_config)): raise ValueError("Edge builder returned a different speculative contract") - files.update(runtime_checkpoint_files(source, draft_config, embedded_mtp=True)) - if visual: + if not current: + files.update(runtime_checkpoint_files(source, draft_config, embedded_mtp=True)) + if visual and not (current and parallel == 1): visual_config = json.loads((engine / "visual/config.json").read_text()) files.update(runtime_checkpoint_files(source, visual_config)) # Metadata stays byte-for-byte original; baked projection-weight shards need @@ -458,7 +679,8 @@ def _prepare_ordinary(request, raw: dict, target: dict, staging: Path, log_path: or path.name in {"merges.txt", "vocab.txt"}): files[f"edge_llm/checkpoint/{path.name}"] = path return files, { - "version": 1, "edge_revision": EDGE_REVISION, "target": target, "precision": "fp16", + "version": 1, "edge_release": version, + "edge_revision": package.get(_RELEASES[version][1], _RELEASES[version][2]), "target": target, "precision": "fp16", "max_sequence_length": limit, "max_input_length": input_limit, "max_batch_size": 1, "checkpoint_quantization": quantization, "artifacts": list(files), "execution_variant": variant, "builder_flow": "experimental", diff --git a/families/qwen3_8/edge_llm/cli.py b/families/qwen3_8/edge_llm/cli.py index 7b9298f024..f3a03ffb0a 100644 --- a/families/qwen3_8/edge_llm/cli.py +++ b/families/qwen3_8/edge_llm/cli.py @@ -16,7 +16,7 @@ def execution_inputs( if companion: raise ValueError("--companion requires --execution-variant") return None - if execution_variant not in ["dspark", "dflash", "mtp"]: + if execution_variant not in ["dspark", "dflash", "dflash_tree", "domino", "domino_tree", "mtp"]: raise ValueError("unsupported qwen3_8 execution variant") checkpoints = [] for value in companion: diff --git a/families/qwen3_8/edge_llm/config.py b/families/qwen3_8/edge_llm/config.py index 44a4ba17da..32a0cf7e5c 100644 --- a/families/qwen3_8/edge_llm/config.py +++ b/families/qwen3_8/edge_llm/config.py @@ -69,21 +69,29 @@ class Qwen38BuildRequest(BuildRequest): """Ordinary build inputs plus an explicitly requested Qwen38 execution recipe.""" execution: BuildExecutionInputs | None = None + edge_builder_python: Path | None = None def __post_init__(self) -> None: super().__post_init__() if self.family != "qwen3_8": raise ValueError("Qwen38BuildRequest requires the qwen3_8 family") + if self.edge_builder_python is not None and ( + not isinstance(self.edge_builder_python, Path) or not self.edge_builder_python.is_absolute() + ): + raise ValueError("edge_builder_python must be an absolute interpreter path") if self.execution is not None: if not isinstance(self.execution, BuildExecutionInputs): raise TypeError("execution must be BuildExecutionInputs") self.execution.validate_local() -def with_execution(request: BuildRequest, execution: BuildExecutionInputs) -> Qwen38BuildRequest: +def with_execution( + request: BuildRequest, execution: BuildExecutionInputs | None, *, edge_builder_python: Path | None = None, +) -> Qwen38BuildRequest: """Preserve supported ordinary request fields and callback identity.""" request = coerce_request(request) return Qwen38BuildRequest( **{field.name: getattr(request, field.name) for field in fields(BuildRequest)}, execution=execution, + edge_builder_python=edge_builder_python or getattr(request, "edge_builder_python", None), ) diff --git a/families/qwen3_8/edge_llm/dispatch.py b/families/qwen3_8/edge_llm/dispatch.py index 7d849c27df..e2c4466494 100644 --- a/families/qwen3_8/edge_llm/dispatch.py +++ b/families/qwen3_8/edge_llm/dispatch.py @@ -38,24 +38,18 @@ } -def ordinary_candidate(request, raw: dict, *, embedded_mtp: bool = False) -> bool: +def ordinary_candidate(request, raw: dict, *, embedded_mtp: bool = False, current: bool = False) -> bool: """Admit dense Swish 27B FP16 TP2 or original mixed-NVFP4 TP1.""" config = raw.get("text_config", raw) if not isinstance(config, dict): return False - classify = edge_llm.prepared_checkpoint_quantization if embedded_mtp else edge_llm.checkpoint_quantization - quantization = classify(Path(request.model_dir), raw) - shape = tuple(config.get(key) for key in ( - "num_hidden_layers", "hidden_size", "intermediate_size", - "num_attention_heads", "num_key_value_heads", "vocab_size", - )) + source = Path(request.model_dir) + quantization = (edge_llm.prepared_checkpoint_quantization(source, raw) if embedded_mtp else + edge_llm.ordinary_quantization(source, raw, current=current)) return ( - raw.get("model_type") == "qwen3_5" - and shape == (64, 5120, 17408, 24, 4, 248320) - and config.get("output_gate_type") == "swish" and "mlp_only_layers" not in config - and config.get("linear_key_head_dim") == config.get("linear_value_head_dim") == 128 - and not config.get("num_experts") + edge_llm.dense_swish_27b(raw) and ((quantization, request.tensor_parallel_size) in {("none", 2), ("nvfp4", 1)} + or (current and not embedded_mtp and (quantization, request.tensor_parallel_size) == ("none", 1)) or (embedded_mtp and (quantization, request.tensor_parallel_size) == ("int4_awq", 1))) and request.quantization in {None, quantization} and request.backend == "trt" @@ -71,7 +65,11 @@ def ordinary_candidate(request, raw: dict, *, embedded_mtp: bool = False) -> boo def request_matches(request, execution_variant: str = "dspark") -> bool: """Validate mapped request controls independently of checkpoint metadata.""" - quantizations = {None, "nvfp4", "int4_awq"} if execution_variant == "dflash" else {None, "nvfp4"} + quantizations = {None, "nvfp4"} + if execution_variant in {"dflash", "dflash_tree"}: + quantizations |= {"none", "int4_awq", "int4_gptq"} + if execution_variant in {"domino", "domino_tree"}: + quantizations = {None, "none"} return ( request.backend == "trt" and request.task == "text_generation" and request.precision.lower() == "fp16" @@ -82,18 +80,18 @@ def request_matches(request, execution_variant: str = "dspark") -> bool: ) -def candidate(request, raw: dict, execution_variant: str = "dspark") -> bool: +def candidate(request, raw: dict, execution_variant: str = "dspark", *, include_current: bool = False) -> bool: """Return whether this family's model/request contract can delegate to Edge.""" config = raw.get("text_config", raw) source_quantization = edge_llm.paired_checkpoint_quantization( - Path(request.model_dir), raw, execution_variant) + Path(request.model_dir), raw, execution_variant, include_current=include_current) return ( isinstance(config, dict) and raw.get("model_type") == "qwen3_5" and ("output_gate_type" in config and "mlp_only_layers" not in config) and config.get("linear_key_head_dim") == config.get("linear_value_head_dim") == 128 and not config.get("num_experts") - and source_quantization in {"nvfp4", "int4_awq"} + and source_quantization is not None and request.quantization in {None, source_quantization} and request_matches(request, execution_variant) ) @@ -123,8 +121,15 @@ def build(request, writer, native, *, draft_dir: Path | None = None, config = raw.get("text_config", raw) if not isinstance(config, dict): raise ValueError("checkpoint text_config must contain an object") - admitted = (candidate(request, raw, execution_variant) if draft_dir is not None else - ordinary_candidate(request, raw, embedded_mtp=execution_variant == "mtp")) + current = edge_llm.selected_release() == "0.12.0" + admitted = (candidate(request, raw, execution_variant, include_current=current) if draft_dir is not None else + ordinary_candidate(request, raw, embedded_mtp=execution_variant == "mtp", current=current)) + if (current and admitted and draft_dir is not None and execution_variant in {"dflash", "dflash_tree"} + and edge_llm.implicit_packed_zero_points(Path(request.model_dir), raw)): + _LOG.warning("Edge 0.12 cannot export this packed INT4 target with implicit zero points; " + "using the native DFlash2 route with the same checkpoint and companion") + native(request, writer) + return if not admitted: native(request, writer) return @@ -147,10 +152,20 @@ def build(request, writer, native, *, draft_dir: Path | None = None, paired_routes = DFLASH_EDGE_DISPATCH if execution_variant == "dflash" else EDGE_DISPATCH routes = (MTP_EDGE_DISPATCH if execution_variant == "mtp" else paired_routes if draft_dir is not None else ORDINARY_EDGE_DISPATCH) - if draft_dir is None and execution_variant != "mtp": - key += (request.tensor_parallel_size, - edge_llm.checkpoint_quantization(Path(request.model_dir), raw)) - adapter = routes.get(key) + ordinary = draft_dir is None and execution_variant != "mtp" + if ordinary: + quant = edge_llm.ordinary_quantization(Path(request.model_dir), raw, current=current) + key += (request.tensor_parallel_size, quant) + if current and ordinary and target["os"] == "linux" and request.tensor_parallel_size == 1: + # installed_package validates the actual target against the SDK's compiled architectures. + adapter = {"none": edge_llm.prepare_fp16, "nvfp4": edge_llm.prepare_nvfp4}.get(quant) + elif current and draft_dir is not None and target["os"] == "linux": + adapter = {"dflash": edge_llm.prepare_dflash, "dflash_tree": edge_llm.prepare_dflash_tree, + "dspark": edge_llm.prepare_dspark, + "domino": edge_llm.prepare_domino, + "domino_tree": edge_llm.prepare_domino_tree}.get(execution_variant) + else: + adapter = routes.get(key) if adapter is not None: files, marker = adapter(request, raw, target, Path(directory), log_path, draft_dir) except Exception as error: @@ -209,46 +224,52 @@ def native_mtp(original_request, original_writer): build(request, writer, native_mtp, execution_variant="mtp") return - if execution.variant not in {"dspark", "dflash"} or tuple(x.role for x in execution.checkpoints) != ("draft",): - raise ValueError("Qwen3.8 paired execution requires variant=dspark or dflash and one draft checkpoint") + if execution.variant not in {"dspark", "dflash", "dflash_tree", "domino", "domino_tree"} or tuple(x.role for x in execution.checkpoints) != ("draft",): + raise ValueError("Qwen3.8 paired execution requires DSpark, DFlash2 or Domino and one draft checkpoint") if request.precision.lower() != "fp16": raise ValueError("Qwen3.8 paired execution requires --precision fp16; the native default is unchanged") if not request_matches(request, execution.variant): raise ValueError( "Qwen3.8 paired execution requires backend=trt, text_generation, batch/TP/CP=1, " - "quantization unset or nvfp4 (also int4_awq for DFlash2), and no dynamic KV, FP32 layers, graph or media overrides" + "quantization unset or nvfp4 for mixed targets, none for original targets, " + "or int4_awq/int4_gptq for matching DFlash2 targets, with no dynamic KV, FP32 layers, graph or media overrides" ) draft_dir = execution.checkpoints[0].model_dir raw = json.loads((request.model_dir / "config.json").read_text()) draft = json.loads((draft_dir / "config.json").read_text()) - if not candidate(request, raw, execution.variant): - raise ValueError("The retained Qwen3.8 pair requires a matching mixed-NVFP4 base (or official INT4-AWQ for DFlash2)") + if not candidate(request, raw, execution.variant, include_current=True): + raise ValueError("Qwen3.8 requires a matching mixed-NVFP4 base, or an original 27B or matched prepared INT4 base for DFlash2") base = raw.get("text_config", raw) variant = execution.variant - architecture = "DSparkDraftModel" if variant == "dspark" else "DFlash2DraftModel" - if not isinstance(draft, dict) or draft.get("architectures") != [architecture]: - raise ValueError(f"Expected a {architecture} companion") - for name in ("hidden_size", "vocab_size"): - if type(draft.get(name)) is not int or draft[name] != base.get(name): - raise ValueError(f"Qwen3.8 paired execution base and draft disagree on {name}") - if draft.get("num_target_layers") != base.get("num_hidden_layers"): - raise ValueError("Qwen3.8 paired execution target layer count differs from base") - config = draft.get(f"{variant}_config") - block = 7 if variant == "dspark" else 8 - if not isinstance(config, dict) or config.get("block_size", draft.get("block_size")) != block: - raise ValueError(f"Qwen3.8 {variant} requires its documented block{block} profile") - layers = config.get("target_layer_ids", draft.get("target_layer_ids")) - if (not isinstance(layers, list) or not layers - or any(type(i) is not int or not 0 <= i < base["num_hidden_layers"] for i in layers) - or len(set(layers)) != len(layers)): - raise ValueError("Invalid Qwen3.8 paired execution target layer IDs") - mask = config.get("mask_token_id", draft.get("mask_token_id")) - if type(mask) is not int or not 0 <= mask < base["vocab_size"]: - raise ValueError("Invalid Qwen3.8 paired execution mask token") + if variant in {"domino", "domino_tree"}: + from ..domino import DominoConfig + DominoConfig.from_dict(draft, base) + else: + architecture = "DSparkDraftModel" if variant == "dspark" else "DFlash2DraftModel" + if not isinstance(draft, dict) or draft.get("architectures") != [architecture]: + raise ValueError(f"Expected a {architecture} companion") + for name in ("hidden_size", "vocab_size"): + if type(draft.get(name)) is not int or draft[name] != base.get(name): + raise ValueError(f"Qwen3.8 paired execution base and draft disagree on {name}") + if draft.get("num_target_layers") != base.get("num_hidden_layers"): + raise ValueError("Qwen3.8 paired execution target layer count differs from base") + config = draft.get("dspark_config" if variant == "dspark" else "dflash_config") + block = 7 if variant == "dspark" else 8 + if not isinstance(config, dict) or config.get("block_size", draft.get("block_size")) != block: + raise ValueError(f"Qwen3.8 {variant} requires its documented block{block} profile") + layers = config.get("target_layer_ids", draft.get("target_layer_ids")) + if (not isinstance(layers, list) or not layers + or any(type(i) is not int or not 0 <= i < base["num_hidden_layers"] for i in layers) + or len(set(layers)) != len(layers)): + raise ValueError("Invalid Qwen3.8 paired execution target layer IDs") + mask = config.get("mask_token_id", draft.get("mask_token_id")) + if type(mask) is not int or not 0 <= mask < base["vocab_size"]: + raise ValueError("Invalid Qwen3.8 paired execution mask token") limit = request.max_sequence_length or min(base["max_position_embeddings"], 256) - maximum = 1024 if variant == "dspark" else 4096 - if not 8 < limit <= maximum: - raise ValueError(f"Qwen3.8 {variant} requires max_sequence_length above 8 and at most {maximum}") + maximum = {"dspark": 1024, "dflash": 4096, "dflash_tree": 4096, "domino": 2048, "domino_tree": 2048}[variant] + minimum = 16 if variant in {"domino", "domino_tree"} else 9 + if not minimum <= limit <= maximum: + raise ValueError(f"Qwen3.8 {variant} requires max_sequence_length above {minimum - 1} and at most {maximum}") capacity = draft.get("max_position_embeddings") if type(capacity) is not int or not 8 < limit <= capacity: raise ValueError("Requested context exceeds companion draft capacity or block minimum") @@ -262,15 +283,25 @@ def native_pair(original_request, original_writer): from dataclasses import replace from ..model import _build_native - # Admission established a mixed-NVFP4 target or the documented DFlash2 - # AWQ target. A generic mixed-format probe may return None; do not erase - # the admitted format or replace the requested pair with base decoding. - source_format = edge_llm.prepared_checkpoint_quantization( - Path(original_request.model_dir), raw) or "nvfp4" + # The companion was validated against this target. Preserve both the + # requested decoding algorithm and the actual source arithmetic. + source_format = edge_llm.paired_checkpoint_quantization( + Path(original_request.model_dir), raw, variant, include_current=True) + if source_format is None: + raise ValueError("Qwen3.8 paired target format no longer matches its build request") options = {"draft_dir": draft_dir} - if variant == "dflash": + quant = raw.get("quantization_config") or {} + scheme = quant.get("kv_cache_scheme") or {} + # The 0.12 ONNX grouped-NVFP4 reader honors declared FP8 KV even + # without per-attention scales (unlike its direct builder and 0.11). + if (source_format == "nvfp4" and edge_llm.selected_release() != "0.11.0" + and quant.get("config_groups") and isinstance(scheme, dict) + and scheme.get("type") == "float" and scheme.get("num_bits") == 8): + options["paired_fp8_kv"] = True + if variant != "dspark": options["draft_variant"] = variant - _build_native(replace(original_request, quantization=source_format), original_writer, **options) + _build_native(replace(original_request, quantization=None if source_format == "none" else source_format), + original_writer, **options) if variant == "dspark": build(request, writer, native_pair, draft_dir=draft_dir) diff --git a/families/qwen3_8/engine_builder.py b/families/qwen3_8/engine_builder.py index e835dd1063..c563c83920 100644 --- a/families/qwen3_8/engine_builder.py +++ b/families/qwen3_8/engine_builder.py @@ -93,7 +93,7 @@ import numpy as np import tensorrt as trt -from .config import ModelConfig +from .config import ModelConfig, compressed_int4_fp8_kv from .checkpoint_mapper import ( WeightDict, _open_safetensors, @@ -154,14 +154,14 @@ def cast_all(tensors): ) -def _load_fp8_kv_scales(readers, layer_types: list[str]) -> dict: +def _load_fp8_kv_scales(readers, layer_types: list[str], *, compressed=False, paired_fp8_kv=False) -> dict: """Match Edge detection from exported LLM scale tensors, not quant metadata.""" prefixes = { f"layer.{i}": f"model.language_model.layers.{i}.self_attn" for i, kind in enumerate(layer_types) if kind == "attention" } prefixes["mtp_layer"] = "mtp.layers.0.self_attn" - if not any(_has_tensor(readers, f"{prefix}.k_proj.k_scale") + if not compressed and not paired_fp8_kv and not any(_has_tensor(readers, f"{prefix}.k_proj.k_scale") for prefix in prefixes.values()): return {"_fp8_kv_cache": False} result = {"_fp8_kv_cache": True} @@ -171,6 +171,10 @@ def _load_fp8_kv_scales(readers, layer_types: list[str]) -> dict: # enabled globally. Preserve actual exported scalars without calibration. for projection in ("q", "k", "v"): key = f"{prefix}.{projection}_proj.{projection}_scale" + if compressed and projection in ("k", "v") and name != "mtp_layer": + key = f"{prefix}.{projection}_scale" + if not _has_tensor(readers, key): + raise ValueError(f"Missing compressed FP8 attention scale: {key}") value = np.asarray(_load_tensor(readers, key)) if _has_tensor(readers, key) else np.array(1.0) if value.size != 1 or not np.isfinite(value).all() or (value <= 0).any(): raise ValueError(f"Invalid Qwen3.8 FP8 attention scale: {key}") @@ -189,7 +193,7 @@ def _owned(quant_ctx, name: str) -> bool: class Qwen38Model: def load_weights( self, model_dir: str, config: ModelConfig, *, precision: str = "fp32", - quant_ctx=None, readers=None, + quant_ctx=None, readers=None, paired_fp8_kv: bool = False, ) -> WeightDict: model_dir_path = Path(model_dir) if readers is None: @@ -240,7 +244,8 @@ def load_weights( text_cfg.get("rope_theta", config.rope_theta)) weights = WeightDict() - weights.update(_load_fp8_kv_scales(readers, layer_types)) + weights.update(_load_fp8_kv_scales( + readers, layer_types, compressed=compressed_int4_fp8_kv(config.raw), paired_fp8_kv=paired_fp8_kv)) # Embedding embed_key = "model.language_model.embed_tokens.weight" diff --git a/families/qwen3_8/model.py b/families/qwen3_8/model.py index a6f19cb9df..6150bcfca1 100644 --- a/families/qwen3_8/model.py +++ b/families/qwen3_8/model.py @@ -216,7 +216,7 @@ def _gpu_memory_bytes() -> int | None: def _build_native(request, writer, *, require_mtp: bool = False, draft_dir: Path | None = None, - draft_variant: str = "dspark") -> None: + draft_variant: str = "dspark", paired_fp8_kv: bool = False) -> None: """Build the requested family-native topology without precision or task downgrade.""" if request.dynamic_kv_cache: raise NotImplementedError("qwen3_8 does not support dynamic_kv_cache") @@ -236,14 +236,14 @@ def _build_native(request, writer, *, require_mtp: bool = False, draft_dir: Path raise NotImplementedError("qwen3_8 requires max_batch_size=1") if request.tensor_parallel_size not in (1, 2) or request.context_parallel_size != 1: raise NotImplementedError("qwen3_8 native supports TP1/TP2 and CP1") - if request.quantization not in {None, "none", "nvfp4", "fp8", "int4_awq"}: + if request.quantization not in {None, "none", "nvfp4", "fp8", "int4_awq", "int4_gptq"}: raise NotImplementedError( f"qwen3_8 does not support quantization={request.quantization!r}") model_dir = Path(request.model_dir) config = ModelConfig.from_dir(model_dir) quantization = _native_quantization(request.quantization, model_dir, config.raw) - quantized = quantization in {"nvfp4", "fp8", "int4_awq"} + quantized = quantization in {"nvfp4", "fp8", "int4_awq", "int4_gptq"} text_config = config.raw.get("text_config", config.raw) if ( not isinstance(text_config, dict) @@ -283,10 +283,18 @@ def _build_native(request, writer, *, require_mtp: bool = False, draft_dir: Path from . import draft as draft_implementation draft_config = draft_implementation.DraftConfig.from_dict(draft_raw, text_config) maximum = 1024 - elif draft_variant == "dflash": + elif draft_variant in {"dflash", "dflash_tree"}: from . import dflash2 as draft_implementation draft_config = draft_implementation.DFlash2Config.from_dict(draft_raw, text_config) maximum = 4096 + elif draft_variant in {"domino", "domino_tree"}: + from . import domino as draft_implementation + if quantized: + raise ValueError("Qwen3.6 Domino requires the original target checkpoint") + draft_config = draft_implementation.DominoConfig.from_dict(draft_raw, text_config) + maximum = 2048 + if max_sequence_length < draft_config.query_rows: + raise ValueError("Qwen3.6 Domino requires its complete block of 16") else: raise ValueError("Unknown Qwen3.8 native external draft variant") if not 8 < max_sequence_length <= min(maximum, draft_raw.get("max_position_embeddings", maximum)): @@ -310,16 +318,20 @@ def _build_native(request, writer, *, require_mtp: bool = False, draft_dir: Path if quantization == "nvfp4": from .quantization import calibrate_qwen3_8_nvfp4 quant_ctx = calibrate_qwen3_8_nvfp4(model_dir, config, graph_ops, readers=readers) - elif quantization == "int4_awq": - from .quantization import load_qwen3_8_awq - quant_ctx = load_qwen3_8_awq(model_dir, config, graph_ops, readers=readers) + elif quantization in {"int4_awq", "int4_gptq"}: + from .config import compressed_int4_fp8_kv + from .quantization import load_qwen3_8_group_int4 + compressed = quantization == "int4_gptq" + if compressed and (draft_dir is None or draft_variant not in {"dflash", "dflash_tree"} or not compressed_int4_fp8_kv(config.raw)): + raise ValueError("Qwen3.8 compressed INT4 requires its prepared group-128 DFlash2 target") + quant_ctx = load_qwen3_8_group_int4(model_dir, config, graph_ops, readers=readers, compressed=compressed) else: from .quantization import calibrate_qwen3_8_fp8 quant_ctx = calibrate_qwen3_8_fp8(model_dir, config, graph_ops, readers=readers) weights = model.load_weights( str(model_dir), config, precision=precision, - quant_ctx=quant_ctx, readers=readers) + quant_ctx=quant_ctx, readers=readers, paired_fp8_kv=paired_fp8_kv) # A 27B checkpoint's host weights plus TensorRT's device copy exceed a 128 GB unified-memory GPU. spill_if_large(weights, request.output_path) # Embedded draft weights alone do not request speculative execution. @@ -413,18 +425,27 @@ def _build_native(request, writer, *, require_mtp: bool = False, draft_dir: Path import numpy as np draft_weights = draft_implementation.load_draft_weights(Path(draft_dir), draft_config) - prefix = "native_dspark" if draft_variant == "dspark" else "native_dflash2" - writer.add_bytes(f"{prefix}.plan", draft_implementation.build_draft_engine( - draft_config, draft_weights, weights.get("w_lm_head"), max_sequence_length, - quant_ctx=quant_ctx, verbose=bool(request.verbose), - )) + prefix = {"dspark": "native_dspark", "dflash": "native_dflash2", "dflash_tree": "native_dflash2", + "domino": "native_domino", "domino_tree": "native_domino"}[draft_variant] metadata = { "schema_version": 1, "hidden_size": draft_config.hidden, "vocab_size": draft_config.vocab, "max_cache_length": max_sequence_length, - "feature_layers": list(draft_config.feature_layers), "rows": draft_config.query_rows, - "mask_token_id": draft_config.mask_token, + "feature_layers": list(draft_config.feature_layers), } - if draft_variant == "dspark": + writer.add_bytes(f"{prefix}.plan", draft_implementation.build_draft_engine( + draft_config, draft_weights, weights.get("w_lm_head"), max_sequence_length, + quant_ctx=quant_ctx, verbose=bool(request.verbose), + )) + metadata.update(rows=draft_config.query_rows, mask_token_id=draft_config.mask_token) + if draft_variant in {"domino", "domino_tree"}: + h = draft_config.hidden + writer.add_bytes(f"{prefix}_correction.plan", draft_implementation.build_correction_engine( + draft_weights["prefix_gru.weight_ih_l0"], draft_weights["prefix_gru.weight_hh_l0"], + draft_weights["embed_proj.0.weight"][:, h:], draft_config.pool_size, + verbose=bool(request.verbose))) + metadata.update(pool=draft_config.pool_size, rank=draft_config.rank, state=draft_config.state, + top_k=4 if draft_variant == "domino_tree" else 1) + elif draft_variant == "dspark": writer.add_bytes(f"{prefix}_heads.plan", draft_implementation.build_markov_engine( draft_config, draft_weights, verbose=bool(request.verbose))) metadata.update(sample_from_anchor=draft_config.sample_from_anchor, @@ -434,6 +455,8 @@ def _build_native(request, writer, *, require_mtp: bool = False, draft_dir: Path draft_config, draft_weights, verbose=bool(request.verbose))) metadata.update(window=draft_config.window, rank=draft_config.selector_rank, top_k=draft_config.selector_top_k) + if draft_variant == "dflash_tree": + metadata.update(schema_version=2, tree_top_k=4, verify_tokens=32) # Host-resident lookup avoids another vocabulary-sized GPU table/engine. writer.add_bytes(f"{prefix}_embeddings.bin", np.asarray(weights["embedding"], dtype=np.float16).tobytes()) diff --git a/families/qwen3_8/native_media.py b/families/qwen3_8/native_media.py index 27ed2b7546..fbbbb33b60 100644 --- a/families/qwen3_8/native_media.py +++ b/families/qwen3_8/native_media.py @@ -160,6 +160,6 @@ def native_media_metadata(model_dir: Path, raw: dict, hidden: int, capacity: int "schema_version": 1, "patch": vision.patch, "temporal": vision.temporal, "merge": vision.merge, "positions": vision.positions, "head_dim": vision.head_dim, "hidden": vision.output, "theta": vision.theta, "mean": image["image_mean"], "stddev": image["image_std"], "min_tokens": 128, "max_tokens": 1280, - "input_limit": min(capacity, 2048), "capacity": capacity, "precision": precision, + "input_limit": capacity, "capacity": capacity, "precision": precision, "token_ids": ids, "prompts": provider_recipes(tokenizer), } diff --git a/families/qwen3_8/quantization.py b/families/qwen3_8/quantization.py index 4de4046c00..34f364c762 100644 --- a/families/qwen3_8/quantization.py +++ b/families/qwen3_8/quantization.py @@ -148,7 +148,7 @@ class _FP8Weight: @dataclass(frozen=True) -class _AWQWeight: +class _GroupInt4Weight: """Signed INT4 codes, repacked losslessly along contiguous input channels.""" packed: np.ndarray # [out, in // 2], low nibble first @@ -161,7 +161,7 @@ class _AWQWeight: @dataclass(frozen=True) class _LayerScales: input_scale: float | None - weight: _NVFP4Weight | _FP8Weight | _AWQWeight + weight: _NVFP4Weight | _FP8Weight | _GroupInt4Weight class _NVFP4Format: @@ -285,8 +285,8 @@ def scale_const(value: float): ) -class _AWQFormat: - name = "int4_awq" +class _GroupInt4Format: + name = "group_int4" @staticmethod def wrap_matmul(network, activation, scales, *, dtype, graph_ops, keep_alive): @@ -323,8 +323,8 @@ def _wrap_matmul(network, activation, scales: _LayerScales, *, dtype, graph_ops, fmt = _NVFP4Format elif isinstance(scales.weight, _FP8Weight): fmt = _FP8Format - elif isinstance(scales.weight, _AWQWeight): - fmt = _AWQFormat + elif isinstance(scales.weight, _GroupInt4Weight): + fmt = _GroupInt4Format else: raise TypeError(f"Unsupported quantized weight type: {type(scales.weight)!r}") return fmt.wrap_matmul( @@ -444,7 +444,7 @@ def _read_fp8_weight(readers, hf_prefix: str) -> _FP8Weight | None: out_features=out_features, in_features=in_features) -def _read_awq_weight(readers, hf_prefix: str) -> _AWQWeight | None: +def _read_awq_weight(readers, hf_prefix: str) -> _GroupInt4Weight | None: """Read ModelOpt W4A16_AWQ, not the unrelated GPTQ/AutoAWQ layouts.""" key = hf_prefix + ".weight" if not _has_tensor(readers, key): @@ -475,7 +475,31 @@ def _read_awq_weight(readers, hf_prefix: str) -> _AWQWeight | None: codes[0::2] = packed & 15 codes[1::2] = packed >> 4 contiguous = np.ascontiguousarray(codes[:, 0::2] | (codes[:, 1::2] << 4)) - return _AWQWeight(contiguous, np.ascontiguousarray(scale), smooth, n, k) + return _GroupInt4Weight(contiguous, np.ascontiguousarray(scale), smooth, n, k) + + +def _read_compressed_int4(readers, prefix: str): + """Repack compressed-tensors offset-binary nibbles as TRT signed INT4; never recalibrate.""" + key = prefix + ".weight_packed" + if not _has_tensor(readers, key): + return None + if any(_has_tensor(readers, prefix + suffix) for suffix in ( + ".weight_g_idx", ".weight_zero_point", ".pre_quant_scale", ".weight")): + raise ValueError(f"{prefix}: expected symmetric contiguous INT4 groups without a permutation") + raw = _get_raw_tensor(readers, key) + shape = _get_raw_tensor(readers, prefix + ".weight_shape") + if raw.dtype != torch.int32 or raw.ndim != 2 or shape.dtype != torch.int64 or shape.shape != (2,): + raise ValueError(f"{prefix}: invalid compressed INT4 container or logical shape") + n, k = map(int, shape.tolist()) + scale = _to_numpy_fp32(_get_raw_tensor(readers, prefix + ".weight_scale")) + if (min(n, k) <= 0 or k % 128 or tuple(raw.shape) != (n, k // 8) + or scale.shape != (n, k // 128) or not np.isfinite(scale).all() or np.any(scale <= 0)): + raise ValueError(f"{prefix}: expected group-128 INT4 packed weights and positive scales") + # Each little-endian word contains eight input-channel codes: 0..15 means + # -8..7. Flip the sign bit of each nibble, retaining order for TRT INT4. + words = raw.contiguous().numpy().astype(" _NVFP4Weight | _FP8Weight | None: @@ -489,10 +513,10 @@ def _read_prepared_weight(readers, hf_prefix: str) -> _NVFP4Weight | _FP8Weight def _read_prepared_weight_split_q( - readers, hf_prefix: str, num_heads: int, head_dim: int, *, awq: bool = False, + readers, hf_prefix: str, num_heads: int, head_dim: int, *, read_weight=_read_prepared_weight, ): """Split Q and gate rows without decoding/requantizing either packed format.""" - weight = (_read_awq_weight if awq else _read_prepared_weight)(readers, hf_prefix) + weight = read_weight(readers, hf_prefix) if weight is None: return None, None attn_size = num_heads * head_dim @@ -509,7 +533,7 @@ def part(gate: bool): fields = {"packed": split(weight.packed, gate), "out_features": attn_size} if isinstance(weight, _NVFP4Weight): fields["block_scale_f8"] = split(weight.block_scale_f8, gate) - elif isinstance(weight, _AWQWeight): + elif isinstance(weight, _GroupInt4Weight): fields["block_scale"] = split(weight.block_scale, gate) return replace(weight, **fields) @@ -868,8 +892,10 @@ def calibrate_qwen3_8_nvfp4( ) -def load_qwen3_8_awq(model_dir: Path, config, graph_ops, *, readers=None) -> Qwen38QuantContext: - """Reuse prepared target and embedded-draft AWQ tensors without calibration.""" +def load_qwen3_8_group_int4(model_dir: Path, config, graph_ops, *, readers=None, compressed=False) -> Qwen38QuantContext: + """Map each prepared projection once; preserve unquantized exclusions and original scales.""" + read_weight = _read_compressed_int4 if compressed else _read_awq_weight + consumed = set() if readers is None: readers = _open_safetensors(Path(model_dir)) scales = {} @@ -879,17 +905,19 @@ def load_qwen3_8_awq(model_dir: Path, config, graph_ops, *, readers=None) -> Qwe ("linear_attn.in_proj_b", "deltanet_b_proj")) def add(hf_prefix, name): - weight = _read_awq_weight(readers, hf_prefix) + weight = read_weight(readers, hf_prefix) if weight is not None: scales[name] = _LayerScales(None, weight) + consumed.add(hf_prefix) def layer(hf_prefix, name): for source, target in simple: add(f"{hf_prefix}.{source}", f"{name}.{target}") query, gate = _read_prepared_weight_split_q( readers, f"{hf_prefix}.self_attn.q_proj", config.num_attention_heads, - config.head_dim, awq=True) + config.head_dim, read_weight=read_weight) if query is not None: + consumed.add(f"{hf_prefix}.self_attn.q_proj") scales[f"{name}.w_q"] = _LayerScales(None, query) scales[f"{name}.w_gate_attn"] = _LayerScales(None, gate) @@ -898,6 +926,10 @@ def layer(hf_prefix, name): add("lm_head", "w_lm_head") add("mtp.fc", "mtp_layer.fc") layer("mtp.layers.0", "mtp_layer") + if compressed: + source = {key.removesuffix(".weight_packed") for key in readers.tensor_map if key.endswith(".weight_packed")} + if source != consumed: + raise ValueError("Native compressed INT4 contains unmapped packed projections") if not scales: - raise ValueError("Native INT4-AWQ requires a prepared ModelOpt W4A16_AWQ checkpoint") + raise ValueError("Native grouped INT4 requires prepared projection weights") return Qwen38QuantContext(profile=_Profile(scales), graph_ops=graph_ops) diff --git a/families/qwen3_8/runtime/CMakeLists.txt b/families/qwen3_8/runtime/CMakeLists.txt index 6d2764967d..76783f06c2 100644 --- a/families/qwen3_8/runtime/CMakeLists.txt +++ b/families/qwen3_8/runtime/CMakeLists.txt @@ -8,7 +8,9 @@ add_library(trtmc_model_qwen3_8 SHARED kv_cache.cpp mtp_scheduler.cpp dspark.cpp + domino.cpp dflash2.cpp + dflash2_tree.cpp pipeline.cpp native_visual.cpp native_media.cpp @@ -68,7 +70,9 @@ if(TRTMC_BUILD_TESTS) kv_cache.cpp mtp_scheduler.cpp dspark.cpp + domino.cpp dflash2.cpp + dflash2_tree.cpp pipeline.cpp prefill_runner.cpp native_visual.cpp diff --git a/families/qwen3_8/runtime/dflash2.cpp b/families/qwen3_8/runtime/dflash2.cpp index cf070b56db..cfece44eb7 100644 --- a/families/qwen3_8/runtime/dflash2.cpp +++ b/families/qwen3_8/runtime/dflash2.cpp @@ -4,6 +4,8 @@ */ #include "families/qwen3_8/runtime/dflash2.h" +#include "families/qwen3_8/runtime/dflash2_tree.h" + #include #include #include @@ -103,6 +105,11 @@ Qwen38DFlash2::Qwen38DFlash2(Qwen38DFlash2Config config, std::unique_ptr(cap) * feature_width_); } +void Qwen38DFlash2::validate_sampling(const Qwen38SamplingParams& sampling) const { + if (config_.tree && !qwen38_greedy_distribution(sampling)) + throw std::invalid_argument("Qwen3.8 DFlash2 DDTree supports greedy decoding only"); +} + void Qwen38DFlash2::reset(ITrtModule& target, std::size_t prompt_length, int32_t max_new_tokens) { if (prompt_length == 0 || max_new_tokens < 0 || prompt_length > static_cast(config_.capacity) || @@ -123,10 +130,9 @@ void Qwen38DFlash2::observe(ITrtModule& target) { ++seen_; } -std::vector Qwen38DFlash2::propose(int32_t anchor, - const Qwen38SamplingParams& sampling, - const std::vector& /*history*/, - int32_t budget, uint64_t& rng) { +Qwen38DraftRound Qwen38DFlash2::propose(int32_t anchor, const Qwen38SamplingParams& sampling, + const std::vector& /*history*/, int32_t budget, + uint64_t& rng) { if (anchor < 0 || anchor >= config_.vocab || seen_ <= 0 || seen_ >= config_.capacity || budget <= 0) throw std::invalid_argument("Qwen3.8 DFlash2 invalid proposal state"); @@ -164,10 +170,7 @@ std::vector Qwen38DFlash2::propose(int32_t anchor, download(ids.data(), *draft_, "candidate_ids", ids.size() * sizeof(int32_t)); download(unary.data(), *draft_, "unary_values", unary.size() * sizeof(float)); download(projected.data(), *draft_, "projected_hidden", projected.size() * sizeof(uint16_t)); - std::vector proposals; - int32_t previous = anchor; - for (int32_t row = 0; row < std::min(7, budget); ++row) { - std::vector candidates(ids.begin() + row * k, ids.begin() + (row + 1) * k); + auto select = [&](int32_t row, int32_t previous, std::vector& candidates) { // Check before the selector's GPU gathers to avoid out-of-range reads. auto unique = candidates; std::sort(unique.begin(), unique.end()); @@ -183,6 +186,17 @@ std::vector Qwen38DFlash2::propose(int32_t anchor, selector_->sync(); std::vector scores(k); download(scores.data(), *selector_, "selector_scores", scores.size() * sizeof(float)); + return scores; + }; + if (config_.tree) { + validate_sampling(sampling); + return qwen38_dflash2_tree(anchor, ids, select); + } + std::vector proposals; + int32_t previous = anchor; + for (int32_t row = 0; row < std::min(7, budget); ++row) { + std::vector candidates(ids.begin() + row * k, ids.begin() + (row + 1) * k); + const auto scores = select(row, previous, candidates); auto probabilities = qwen38_dflash2_probabilities(scores, candidates, v, sampling); previous = qwen38_draw_probabilities(probabilities, rng); proposals.push_back({previous, std::move(probabilities)}); diff --git a/families/qwen3_8/runtime/dflash2.h b/families/qwen3_8/runtime/dflash2.h index 0540fd30df..d7f836aeed 100644 --- a/families/qwen3_8/runtime/dflash2.h +++ b/families/qwen3_8/runtime/dflash2.h @@ -10,6 +10,7 @@ namespace trtmc { struct Qwen38DFlash2Config { int32_t hidden, vocab, capacity, feature_count, mask_token, window, rank, top_k; + bool tree{false}; }; // DFlash2 proposals use temperature on selector top-16, not target top-p/min-p // or repetition filters. Target verification retains all requested filters. @@ -20,12 +21,13 @@ class Qwen38DFlash2 final : public Qwen38ExternalDraft { public: Qwen38DFlash2(Qwen38DFlash2Config config, std::unique_ptr draft, std::unique_ptr selector, std::vector embeddings); + void validate_sampling(const Qwen38SamplingParams& sampling) const override; void reset(ITrtModule& target, std::size_t prompt_length, int32_t max_new_tokens) override; void observe(ITrtModule& target) override; - std::vector propose(int32_t anchor, const Qwen38SamplingParams& sampling, - const std::vector& history, int32_t budget, - uint64_t& rng) override; - const char* name() const override { return "DFlash2"; } + Qwen38DraftRound propose(int32_t anchor, const Qwen38SamplingParams& sampling, + const std::vector& history, int32_t budget, + uint64_t& rng) override; + const char* name() const override { return config_.tree ? "DFlash2 DDTree" : "DFlash2"; } private: Qwen38DFlash2Config config_; diff --git a/families/qwen3_8/runtime/dflash2_tree.cpp b/families/qwen3_8/runtime/dflash2_tree.cpp new file mode 100644 index 0000000000..b2639e453b --- /dev/null +++ b/families/qwen3_8/runtime/dflash2_tree.cpp @@ -0,0 +1,80 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + */ +#include "families/qwen3_8/runtime/dflash2_tree.h" + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace trtmc { +Qwen38VerifyTree qwen38_dflash2_tree(int32_t anchor, const std::vector& ids, + const Qwen38DFlash2Select& select) { + constexpr int k = 16; + if (ids.size() != 7 * k) + throw std::invalid_argument("DFlash2 DDTree requires seven selector rows of width 16"); + // Each child distribution is conditional on its own predecessor, not the + // greedy spine's token. Repeated (row, predecessor) states share scores. + using Children = std::array, 4>; + std::map, Children> cache; + struct Prefix { + int32_t parent, token, depth, slot; + float logp; + bool operator<(const Prefix& rhs) const { + if (logp != rhs.logp) + return logp < rhs.logp; + if (parent != rhs.parent) + return parent > rhs.parent; + return slot > rhs.slot; + } + }; + std::priority_queue frontier; + auto expand = [&](int32_t parent, int32_t token, int32_t depth, float logp) { + if (depth == 7) + return; + auto [it, fresh] = cache.try_emplace({depth, token}); + if (fresh) { + std::vector candidates(ids.begin() + depth * k, ids.begin() + (depth + 1) * k); + const auto scores = select(depth, token, candidates); + if (scores.size() != k || !std::all_of(scores.begin(), scores.end(), + [](float x) { return std::isfinite(x); })) + throw std::runtime_error("Non-finite DFlash2 selector tree score"); + std::vector slots(k); + std::iota(slots.begin(), slots.end(), 0); + std::partial_sort(slots.begin(), slots.begin() + 4, slots.end(), [&](int a, int b) { + return scores[a] == scores[b] ? candidates[a] < candidates[b] + : scores[a] > scores[b]; + }); + const float max = scores[slots[0]]; + float mass = 0; + for (float score : scores) + mass += std::exp(score - max); + const float normalizer = std::log(mass); + for (int i = 0; i < 4; ++i) { + const int slot = slots[i]; + it->second[i] = {candidates[slot], (scores[slot] - max) - normalizer}; + } + } + for (int i = 0; i < 4; ++i) { + const auto& child = it->second[i]; + frontier.push({parent, child.first, depth + 1, i, logp + child.second}); + } + }; + Qwen38VerifyTree tree{{anchor, -1}}; + expand(0, anchor, 0, 0); + while (tree.size() < 32 && !frontier.empty()) { + const auto node = frontier.top(); + frontier.pop(); + tree.push_back({node.token, node.parent}); + if (tree.size() < 32) + expand(static_cast(tree.size()) - 1, node.token, node.depth, node.logp); + } + return tree; +} +} // namespace trtmc diff --git a/families/qwen3_8/runtime/dflash2_tree.h b/families/qwen3_8/runtime/dflash2_tree.h new file mode 100644 index 0000000000..7178b1c1e1 --- /dev/null +++ b/families/qwen3_8/runtime/dflash2_tree.h @@ -0,0 +1,17 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + */ +#pragma once +#include "families/qwen3_8/runtime/external_draft.h" + +#include + +namespace trtmc { +// Score the block-8 checkpoint's 16 candidates at a depth given one actual predecessor. +// TensorRT's selector input binding borrows the candidate storage during this call. +using Qwen38DFlash2Select = std::function(int32_t depth, int32_t predecessor, + std::vector& candidates)>; +Qwen38VerifyTree qwen38_dflash2_tree(int32_t anchor, const std::vector& ids, + const Qwen38DFlash2Select& select); +} // namespace trtmc diff --git a/families/qwen3_8/runtime/domino.cpp b/families/qwen3_8/runtime/domino.cpp new file mode 100644 index 0000000000..77ac86ee12 --- /dev/null +++ b/families/qwen3_8/runtime/domino.cpp @@ -0,0 +1,233 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + */ +#include "families/qwen3_8/runtime/domino.h" + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace trtmc { +namespace { +void require_tensor(ITrtModule& module, const char* name, DType dtype, + const std::vector& shape, bool input) { + if (!(input ? module.has_input(name) : module.has_output(name)) || + module.tensor_dtype(name) != dtype || module.tensor_shape(name) != shape) + throw std::runtime_error(std::string("Qwen3.6 Domino tensor mismatch: ") + name); +} +void download(void* destination, ITrtModule& module, const char* name, std::size_t bytes) { + auto* source = module.device_ptr(name); + if (!source) + throw std::runtime_error(std::string("Qwen3.6 Domino missing output: ") + name); + const auto status = cudaMemcpy(destination, source, bytes, cudaMemcpyDeviceToHost); + if (status != cudaSuccess) + throw std::runtime_error(std::string("Qwen3.6 Domino transfer failed: ") + + cudaGetErrorString(status)); +} +Tensor host(void* data, std::vector shape, DType dtype) { + Tensor tensor; + tensor.data = data; + tensor.shape = std::move(shape); + tensor.dtype = dtype; + return tensor; +} +} // namespace + +Qwen38Domino::Qwen38Domino(Qwen38DominoConfig config, std::unique_ptr draft, + std::unique_ptr correction, std::vector embeddings) + : config_(config), draft_(std::move(draft)), correction_(std::move(correction)), + embeddings_(std::move(embeddings)), + feature_width_(static_cast(config.hidden) * config.feature_count) { + if (config.hidden <= 0 || config.vocab < 16 || config.capacity < 16 || + config.feature_count <= 0 || config.mask_token < 0 || config.mask_token >= config.vocab || + config.pool != std::min(config.vocab, 2048) || config.rank <= 0 || config.state <= 0 || + (config.top_k != 1 && config.top_k != 4) || !draft_ || !draft_->ok() || !correction_ || + !correction_->ok()) + throw std::invalid_argument("Invalid native Qwen3.6 Domino bundle geometry/engines"); + if (embeddings_.size() != + static_cast(config.vocab) * config.hidden * sizeof(uint16_t)) + throw std::invalid_argument("Qwen3.6 Domino target embedding size mismatch"); + const int64_t h = config.hidden, cap = config.capacity, k = config.pool, r = config.rank; + require_tensor(*draft_, "inputs_embeds", DType::kFloat16, {16, h}, true); + require_tensor(*draft_, "draft_positions", DType::kInt32, {16}, true); + require_tensor(*draft_, "target_hidden", DType::kFloat16, + {cap, static_cast(feature_width_)}, true); + require_tensor(*draft_, "draft_attention_mask", DType::kFloat32, {16, cap + 16}, true); + require_tensor(*draft_, "pool_ids", DType::kInt32, {k}, false); + require_tensor(*draft_, "pool_base_logits", DType::kFloat32, {15, k}, false); + require_tensor(*draft_, "pool_codebook", DType::kFloat16, {k, r}, false); + require_tensor(*draft_, "proposal_zproj", DType::kFloat16, {14, r}, false); + require_tensor(*correction_, "token_embedding", DType::kFloat16, {1, h}, true); + require_tensor(*correction_, "previous_state", DType::kFloat16, {1, config.state}, true); + require_tensor(*correction_, "next_state", DType::kFloat16, {1, config.state}, false); + require_tensor(*correction_, "pool_codebook", DType::kFloat16, {k, r}, true); + require_tensor(*correction_, "z_projection", DType::kFloat16, {1, r}, true); + require_tensor(*correction_, "base_scores", DType::kFloat32, {1, k}, true); + require_tensor(*correction_, "corrected_pool_scores", DType::kFloat32, {1, k}, false); + features_.resize(static_cast(cap) * feature_width_); +} + +void Qwen38Domino::validate_sampling(const Qwen38SamplingParams& sampling) const { + if (!qwen38_greedy_distribution(sampling)) + throw std::invalid_argument("Qwen3.6 Domino supports greedy decoding only"); +} + +void Qwen38Domino::reset(ITrtModule& target, std::size_t prompt_length, int32_t max_new_tokens) { + if (prompt_length == 0 || max_new_tokens < 0 || + prompt_length > static_cast(config_.capacity) || + static_cast(max_new_tokens) > + static_cast(config_.capacity) - prompt_length) + throw std::invalid_argument("Qwen3.6 Domino prompt and generation exceed bundle capacity"); + require_tensor(target, "draft_features", DType::kFloat16, + {1, static_cast(feature_width_)}, false); + seen_ = 0; + std::fill(features_.begin(), features_.end(), 0); +} +void Qwen38Domino::observe(ITrtModule& target) { + if (seen_ >= config_.capacity) + throw std::runtime_error("Qwen3.6 Domino feature capacity exceeded"); + target.sync(); + download(features_.data() + static_cast(seen_) * feature_width_, target, + "draft_features", feature_width_ * sizeof(uint16_t)); + ++seen_; +} + +Qwen38DraftRound Qwen38Domino::propose(int32_t anchor, const Qwen38SamplingParams& sampling, + const std::vector& /*history*/, int32_t budget, + uint64_t& /*rng*/) { + validate_sampling(sampling); + if (anchor < 0 || anchor >= config_.vocab || seen_ <= 0 || seen_ >= config_.capacity || + budget <= 0) + throw std::invalid_argument("Qwen3.6 Domino invalid proposal state"); + const int32_t rows = 16, cap = config_.capacity, h = config_.hidden, v = config_.vocab; + std::vector embeddings(static_cast(rows) * h); + for (int32_t i = 0; i < rows; ++i) { + const auto token = i == 0 ? anchor : config_.mask_token; + std::memcpy(embeddings.data() + static_cast(i) * h, + embeddings_.data() + static_cast(token) * h * sizeof(uint16_t), + static_cast(h) * sizeof(uint16_t)); + } + std::vector positions(rows); + std::iota(positions.begin(), positions.end(), seen_); + std::vector mask(static_cast(rows) * (cap + rows), + -std::numeric_limits::infinity()); + for (int32_t i = 0; i < rows; ++i) { + auto* row = mask.data() + static_cast(i) * (cap + rows); + std::fill(row, row + seen_, 0); + std::fill(row + cap, row + cap + rows, 0); + } + draft_->forward_async({ + {"inputs_embeds", host(embeddings.data(), {rows, h}, DType::kFloat16)}, + {"draft_positions", host(positions.data(), {rows}, DType::kInt32)}, + {"target_hidden", + host(features_.data(), {cap, static_cast(feature_width_)}, DType::kFloat16)}, + {"draft_attention_mask", host(mask.data(), {rows, cap + rows}, DType::kFloat32)}, + }); + draft_->sync(); + const int32_t k = config_.pool, r = config_.rank, s = config_.state; + std::vector ids(k); + std::vector scores(15 * k); + std::vector book(static_cast(k) * r), z(14 * r), state(s, 0); + download(ids.data(), *draft_, "pool_ids", k * sizeof(int32_t)); + download(scores.data(), *draft_, "pool_base_logits", scores.size() * sizeof(float)); + download(book.data(), *draft_, "pool_codebook", book.size() * sizeof(uint16_t)); + download(z.data(), *draft_, "proposal_zproj", z.size() * sizeof(uint16_t)); + auto sorted = ids; + std::sort(sorted.begin(), sorted.end()); + if (sorted.front() < 0 || sorted.back() >= v || + std::adjacent_find(sorted.begin(), sorted.end()) != sorted.end()) + throw std::runtime_error("Invalid Qwen3.6 Domino candidate IDs"); + + auto best = [&](int row) { + const auto first = scores.begin() + row * k; + if (!std::all_of(first, first + k, [](float f) { return std::isfinite(f); })) + throw std::runtime_error("Non-finite Qwen3.6 Domino pool score"); + // A tied score selects the first pool slot, not the smallest token ID. + return ids[std::max_element(first, first + k) - first]; + }; + auto advance = [&](int32_t token, int row, bool emit_scores) { + auto* emb = embeddings_.data() + static_cast(token) * h * sizeof(uint16_t); + auto* logits = scores.data() + row * k; + correction_->forward_async({ + {"token_embedding", host(emb, {1, h}, DType::kFloat16)}, + {"previous_state", host(state.data(), {1, s}, DType::kFloat16)}, + {"pool_codebook", host(book.data(), {k, r}, DType::kFloat16)}, + {"z_projection", host(z.data() + (row - 1) * r, {1, r}, DType::kFloat16)}, + {"base_scores", host(logits, {1, k}, DType::kFloat32)}, + }); + correction_->sync(); + download(state.data(), *correction_, "next_state", s * sizeof(uint16_t)); + if (emit_scores) + download(logits, *correction_, "corrected_pool_scores", k * sizeof(float)); + }; + // The GRU is seeded once per round, not carried through verification. + auto token = best(0); + advance(anchor, 1, false); + constexpr int depth_limit = 15; + for (int row = 1; row < depth_limit; ++row) { + advance(token, row, true); + token = best(row); + } + + // DDTree expands depth-wise distributions produced by the greedy GRU + // rollout. It does not rerun that GRU separately for every alternative. + struct Candidate { + int32_t token; + float logp; + }; + std::vector> depths; + for (int row = 0; row < depth_limit; ++row) { + const auto* base = scores.data() + row * k; + std::vector slots(k); + std::iota(slots.begin(), slots.end(), 0); + std::partial_sort( + slots.begin(), slots.begin() + config_.top_k, slots.end(), + [&](auto a, auto b) { return base[a] == base[b] ? a < b : base[a] > base[b]; }); + const float max = base[slots[0]]; + float mass = 0; + for (int col = 0; col < k; ++col) + mass += std::exp(base[col] - max); + const float logmass = std::log(mass); + auto& level = depths.emplace_back(); + for (int slot = 0; slot < config_.top_k; ++slot) { + const auto col = slots[slot]; + level.push_back({ids[col], (base[col] - max) - logmass}); + } + } + Qwen38VerifyTree tree{{anchor, -1}}; + struct Frontier { + int depth; + int next; + float logp; + }; + std::vector nodes{{0, 0, 0}}; + const int verify = config_.top_k == 1 ? 16 : 60; + while (static_cast(tree.size()) < verify) { + int parent = -1; + float highest = -std::numeric_limits::infinity(); + for (int i = 0; i < static_cast(nodes.size()); ++i) { + const auto& n = nodes[i]; + if (n.depth == depth_limit || n.next == config_.top_k) + continue; + const auto value = n.logp + depths[n.depth][n.next].logp; + if (value > highest) { + highest = value; + parent = i; + } + } + if (parent < 0) + break; + auto& n = nodes[parent]; + tree.push_back({depths[n.depth][n.next++].token, parent}); + const int child_depth = n.depth + 1; + nodes.push_back({child_depth, 0, highest}); + } + return tree; +} +} // namespace trtmc diff --git a/families/qwen3_8/runtime/domino.h b/families/qwen3_8/runtime/domino.h new file mode 100644 index 0000000000..19e050e71c --- /dev/null +++ b/families/qwen3_8/runtime/domino.h @@ -0,0 +1,34 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + */ +#pragma once +#include "families/qwen3_8/runtime/external_draft.h" + +#include + +namespace trtmc { +struct Qwen38DominoConfig { + int32_t hidden, vocab, capacity, feature_count, mask_token, pool, rank, state, top_k; +}; +class Qwen38Domino final : public Qwen38ExternalDraft { + public: + Qwen38Domino(Qwen38DominoConfig config, std::unique_ptr draft, + std::unique_ptr correction, std::vector embeddings); + void validate_sampling(const Qwen38SamplingParams& sampling) const override; + void reset(ITrtModule& target, std::size_t prompt_length, int32_t max_new_tokens) override; + void observe(ITrtModule& target) override; + Qwen38DraftRound propose(int32_t anchor, const Qwen38SamplingParams& sampling, + const std::vector& history, int32_t budget, + uint64_t& rng) override; + const char* name() const override { return "Domino"; } + + private: + Qwen38DominoConfig config_; + std::unique_ptr draft_, correction_; + std::vector embeddings_; + std::vector features_; + std::size_t feature_width_; + int32_t seen_{0}; +}; +} // namespace trtmc diff --git a/families/qwen3_8/runtime/dspark.cpp b/families/qwen3_8/runtime/dspark.cpp index 67e932e727..7f40c86940 100644 --- a/families/qwen3_8/runtime/dspark.cpp +++ b/families/qwen3_8/runtime/dspark.cpp @@ -89,10 +89,9 @@ void Qwen38DSpark::observe(ITrtModule& target) { ++seen_; } -std::vector Qwen38DSpark::propose(int32_t anchor, - const Qwen38SamplingParams& sampling, - const std::vector& history, - int32_t budget, uint64_t& rng) { +Qwen38DraftRound Qwen38DSpark::propose(int32_t anchor, const Qwen38SamplingParams& sampling, + const std::vector& history, int32_t budget, + uint64_t& rng) { if (anchor < 0 || anchor >= config_.vocab || seen_ <= 0 || seen_ >= config_.capacity || budget <= 0) throw std::invalid_argument("Qwen3.8 DSpark invalid proposal state"); diff --git a/families/qwen3_8/runtime/dspark.h b/families/qwen3_8/runtime/dspark.h index 6f1d33c59d..f8548ada8e 100644 --- a/families/qwen3_8/runtime/dspark.h +++ b/families/qwen3_8/runtime/dspark.h @@ -26,9 +26,9 @@ class Qwen38DSpark final : public Qwen38ExternalDraft { std::unique_ptr heads, std::vector embeddings); void reset(ITrtModule& target, std::size_t prompt_length, int32_t max_new_tokens) override; void observe(ITrtModule& target) override; - std::vector propose(int32_t anchor, const Qwen38SamplingParams& sampling, - const std::vector& history, int32_t budget, - uint64_t& rng) override; + Qwen38DraftRound propose(int32_t anchor, const Qwen38SamplingParams& sampling, + const std::vector& history, int32_t budget, + uint64_t& rng) override; const char* name() const override { return "DSpark"; } private: diff --git a/families/qwen3_8/runtime/edge_llm/Adapter.cmake b/families/qwen3_8/runtime/edge_llm/Adapter.cmake index 8b96763a68..5ee8da6ca6 100644 --- a/families/qwen3_8/runtime/edge_llm/Adapter.cmake +++ b/families/qwen3_8/runtime/edge_llm/Adapter.cmake @@ -2,8 +2,17 @@ # SPDX-License-Identifier: Apache-2.0 # Complete-network offload is family-owned and absent from native-only builds. -if(TARGET EdgeLLM::Core) - if(NOT TARGET EdgeLLM::Plugin) +if(TARGET TensorRTEdgeLLM::Core) + set(_qwen38_sdk TensorRTEdgeLLM) + target_compile_definitions(trtmc_model_qwen3_8 PRIVATE TRTMC_QWEN38_EDGE_012=1) +elseif(TARGET EdgeLLM::Core) + set(_qwen38_sdk EdgeLLM) +else() + return() +endif() + +if(TARGET ${_qwen38_sdk}::Core) + if(NOT TARGET ${_qwen38_sdk}::Plugin) message(FATAL_ERROR "Qwen38 Edge adapter requires the complete EdgeLLM package (Core and Plugin)") endif() target_sources(trtmc_model_qwen3_8 PRIVATE @@ -11,7 +20,7 @@ if(TARGET EdgeLLM::Core) "${CMAKE_CURRENT_LIST_DIR}/device_link.cu" ) target_compile_definitions(trtmc_model_qwen3_8 PRIVATE TRTMC_HAS_EDGE_LLM=1) - target_link_libraries(trtmc_model_qwen3_8 PRIVATE EdgeLLM::Core) + target_link_libraries(trtmc_model_qwen3_8 PRIVATE ${_qwen38_sdk}::Core) set_target_properties(trtmc_model_qwen3_8 PROPERTIES CUDA_ARCHITECTURES "${EdgeLLM_CUDA_ARCHITECTURE}" CUDA_SEPARABLE_COMPILATION ON @@ -19,10 +28,10 @@ if(TARGET EdgeLLM::Core) ) endif() -if(TARGET EdgeLLM::Core) +if(TARGET ${_qwen38_sdk}::Core) add_custom_command(TARGET trtmc_model_qwen3_8 POST_BUILD COMMAND ${CMAKE_COMMAND} -E copy_if_different - $ $ + $ $ VERBATIM ) endif() diff --git a/families/qwen3_8/runtime/edge_llm/adapter.cpp b/families/qwen3_8/runtime/edge_llm/adapter.cpp index 461920323b..55eb9712cb 100644 --- a/families/qwen3_8/runtime/edge_llm/adapter.cpp +++ b/families/qwen3_8/runtime/edge_llm/adapter.cpp @@ -5,16 +5,24 @@ #include "families/qwen3_8/runtime/edge_llm/adapter.h" #include "families/qwen3_8/runtime/edge_llm/media.h" +#include "families/qwen3_8/runtime/sampler.h" #include #include +#include #include #include #include #include +#ifdef TRTMC_QWEN38_EDGE_012 +#include +#include +#include +#else #include #include #include +#endif #include #include #include @@ -175,7 +183,12 @@ std::unique_ptr load_plugin() { std::string(dlerror())); using Initialize = bool (*)(void*, const char*); auto initialize = reinterpret_cast(dlsym(plugin.get(), "initEdgellmPlugins")); - if (!initialize || !initialize(static_cast(&trt_edgellm::gLogger), "")) +#ifdef TRTMC_QWEN38_EDGE_012 + auto* logger = static_cast(&trt_edgellm::TrtLogger::instance()); +#else + auto* logger = static_cast(&trt_edgellm::gLogger); +#endif + if (!initialize || !initialize(logger, "")) throw std::runtime_error("Cannot initialize Qwen3.8 Edge plugin"); return plugin; } @@ -198,7 +211,11 @@ std::unique_ptr make_runtime(const Artifacts& artifacts, const nlohmann::json& marker, cudaStream_t stream) { if (marker.value("tensor_parallel_size", 1) == 2) { using Runtime = trt_edgellm::rt::LLMInferenceRuntime; +#ifdef TRTMC_QWEN38_EDGE_012 + trt_edgellm::rt::DeploymentOptions config{}; +#else Runtime::ParallelExecutionConfig config{}; +#endif config.parallelConfig.tensorParallelSize = 2; config.parallelConfig.launchMode = trt_edgellm::rt::ParallelLaunchMode::kThread; config.checkpointDir = artifacts.checkpoint(); @@ -206,9 +223,15 @@ make_runtime(const Artifacts& artifacts, const nlohmann::json& marker, cudaStrea marker.value("task", "text_generation") == "vision_language_generation" ? artifacts.engine() : ""; +#ifdef TRTMC_QWEN38_EDGE_012 + config.engineDir = artifacts.engine(); + config.multimodalEngineDir = multimodal; + return std::make_unique(std::move(config)); +#else return std::make_unique(artifacts.engine(), multimodal, std::unordered_map{}, std::move(config)); +#endif } if (marker.value("execution_variant", "") == "autoregressive") { const auto multimodal = @@ -220,11 +243,30 @@ make_runtime(const Artifacts& artifacts, const nlohmann::json& marker, cudaStrea trt_edgellm::rt::ContextCacheConfig{}, artifacts.checkpoint()); } trt_edgellm::rt::SpecDecodeDraftingConfig drafting{}; - drafting.draftingTopK = 1; const bool mtp = marker.value("execution_variant", "") == "mtp"; drafting.draftingStep = mtp ? 3 : 1; +#ifdef TRTMC_QWEN38_EDGE_012 + const bool domino = marker.value("execution_variant", "") == "domino" || + marker.value("execution_variant", "") == "domino_tree"; + drafting.draftTopK = 1; + drafting.verifyTokens = mtp ? 4 : 8; + if (marker.value("execution_variant", "") == "dflash_tree") { + drafting.draftTopK = marker.at("dflash_top_k").get(); + drafting.verifyTokens = marker.at("dflash_verify").get(); + } + if (domino) { + drafting.draftTopK = marker.at("domino_top_k").get(); + drafting.proposalTokens = 15; + drafting.verifyTokens = marker.at("domino_verify").get(); + } + // DFlash2 takes its fixed proposal block from its checkpoint, not an override. + if (marker.value("execution_variant", "") == "dspark") + drafting.proposalTokens = 7; +#else + drafting.draftingTopK = 1; drafting.verifySize = mtp ? 4 : 8; drafting.dflashBlockSize = marker.value("execution_variant", "") == "dflash" ? 8 : 0; +#endif drafting.dsparkSchedulerMode = trt_edgellm::rt::DSparkSchedulerMode::kOff; drafting.dsparkConfidenceThreshold = 0.0F; drafting.dsparkMinProposalLen = 1; @@ -255,7 +297,13 @@ class EdgeTask final : public ITextGeneration, visual_(marker.value("task", "text_generation") == "vision_language_generation"), parallel_(marker.value("tensor_parallel_size", 1) == 2), paired_(marker.value("execution_variant", "") == "dspark" || - marker.value("execution_variant", "") == "dflash") { + marker.value("execution_variant", "") == "dflash_tree" || + marker.value("execution_variant", "") == "dflash" || + marker.value("execution_variant", "") == "domino" || + marker.value("execution_variant", "") == "domino_tree"), + domino_(marker.value("execution_variant", "") == "domino" || + marker.value("execution_variant", "") == "domino_tree"), + dflash_tree_(marker.value("execution_variant", "") == "dflash_tree") { if (!paired_) return; std::ifstream input(fs::path(artifacts_.engine()) / "trtmc_single_user_prompts.json"); @@ -328,6 +376,19 @@ class EdgeTask final : public ITextGeneration, auto bytes = image_bytes(pixels, height, width); if (!bytes.empty() && !visual_) throw std::invalid_argument("Qwen3.8 text bundle does not contain a visual engine"); + if (domino_ || dflash_tree_) { + validate_generation(config); + // Do not silently switch these explicitly greedy profiles to vanilla decoding. + const bool edge_samples = + config.temperature >= 1e-3F && config.top_k != 1 && + (config.top_k > 1 || config.top_p < 1.0F - 1e-6F || + (config.temperature > 1e-3F && std::fabs(config.temperature - 1.0F) > 1e-3F)); + if (edge_samples || + !qwen38_greedy_distribution(qwen38_sampling_params_from_config(config, {}))) + throw std::invalid_argument( + domino_ ? "Qwen3.6 Domino supports greedy decoding only" + : "Qwen3.8 DFlash2 DDTree supports greedy decoding only"); + } auto effective = config; std::string source_prompt = prompt; if (config.use_chat_template && paired_) { @@ -340,7 +401,7 @@ class EdgeTask final : public ITextGeneration, make_request(source_prompt, effective, default_max_new_tokens(), !bytes.empty()); if (!bytes.empty()) { trt_edgellm::rt::Tensor tensor({1, height, width, 3}, trt_edgellm::rt::DeviceType::kCPU, - nvinfer1::DataType::kUINT8); + EdgeDataType::kUINT8); std::memcpy(tensor.rawPointer(), bytes.data(), bytes.size()); request.requests.front().imageBuffers.emplace_back(std::move(tensor)); } @@ -395,6 +456,8 @@ class EdgeTask final : public ITextGeneration, bool visual_; bool parallel_; bool paired_; + bool domino_; + bool dflash_tree_; nlohmann::json source_prompts_; std::mutex mutex_; }; @@ -403,7 +466,14 @@ class EdgeTask final : public ITextGeneration, ITask* create(const BundleReader& bundle) { const auto bytes = bundle.read_section("edge_llm.json"); const auto marker = nlohmann::json::parse(bytes.begin(), bytes.end()); - if (marker.at("version") != 1 || marker.at("edge_revision") != kRevision || + const auto& revision = marker.at("edge_revision"); +#ifdef TRTMC_QWEN38_EDGE_012 + const bool compatible = + marker.at("edge_release") == "0.12.0" && (revision.is_null() || revision == kRevision); +#else + const bool compatible = revision == kRevision; +#endif + if (marker.at("version") != 1 || !compatible || marker.at("max_sequence_length").get() <= 1 || marker.at("max_input_length").get() <= 0 || marker.at("max_input_length").get() > marker.at("max_sequence_length").get() || @@ -428,19 +498,53 @@ ITask* create(const BundleReader& bundle) { throw std::runtime_error("Unsupported Qwen3.8 Edge task contract"); const auto quantization = marker.value("checkpoint_quantization", ""); const auto sm = marker.at("target").at("sm").get(); - const bool ordinary = variant == "autoregressive" && - marker.value("builder_flow", "") == "experimental" && - marker.at("max_input_length").get() <= 2048 && - marker.at("target").at("arch") == "x86_64" && - ((parallel == 2 && quantization == "none" && sm == 80) || - (parallel == 1 && quantization == "nvfp4" && sm == 120)); + bool valid_ordinary_input = marker.at("max_input_length").get() <= 2048; +#ifdef TRTMC_QWEN38_EDGE_012 + valid_ordinary_input = + valid_ordinary_input || (task == "vision_language_generation" && parallel == 1); +#endif + const bool ordinary = + variant == "autoregressive" && marker.value("builder_flow", "") == "experimental" && + valid_ordinary_input && + (parallel == 2 + ? (marker.at("target").at("arch") == "x86_64" && quantization == "none" && sm == 80) +#ifdef TRTMC_QWEN38_EDGE_012 + : (parallel == 1 && (quantization == "nvfp4" || quantization == "none"))); +#else + : (parallel == 1 && marker.at("target").at("arch") == "x86_64" && + quantization == "nvfp4" && sm == 120)); +#endif + bool paired_format = + quantization == "nvfp4" || (variant == "dflash" && quantization == "int4_awq"); +#ifdef TRTMC_QWEN38_EDGE_012 + paired_format = paired_format || (variant == "dflash" && + (quantization == "none" || quantization == "int4_gptq")); +#else + paired_format = paired_format && marker.at("target").at("arch") == "x86_64" && sm == 120; +#endif + bool domino = false, dflash_tree = false; +#ifdef TRTMC_QWEN38_EDGE_012 + dflash_tree = variant == "dflash_tree" && marker.value("dflash_block_size", 0) == 8 && + marker.value("dflash_top_k", 0) == 4 && marker.value("dflash_verify", 0) == 32 && + (quantization == "none" || quantization == "nvfp4" || + quantization == "int4_awq" || quantization == "int4_gptq"); + paired_format = paired_format || dflash_tree; + const bool tree = variant == "domino_tree"; + domino = (tree || variant == "domino") && quantization == "none" && + marker.value("domino_block_size", 0) == 16 && + marker.value("domino_top_k", 0) == (tree ? 4 : 1) && + marker.value("domino_verify", 0) == (tree ? 60 : 16) && + marker.at("max_sequence_length").get() >= 16 && + marker.at("max_input_length").get() <= 1024; + paired_format = paired_format || domino; +#endif const bool paired = - valid_execution_variant(variant, marker.value(variant + "_block_size", 0)) && - parallel == 1 && marker.value("builder_flow", "") == "onnx" && - (quantization == "nvfp4" || (variant == "dflash" && quantization == "int4_awq")) && + (domino || dflash_tree || + valid_execution_variant(variant, marker.value(variant + "_block_size", 0))) && + parallel == 1 && marker.value("builder_flow", "") == "onnx" && paired_format && marker.at("max_sequence_length").get() > 8 && - marker.at("max_sequence_length").get() <= (variant == "dspark" ? 1024 : 4096) && - marker.at("target").at("arch") == "x86_64" && marker.at("target").at("sm") == 120; + marker.at("max_sequence_length").get() <= + (domino ? 2048 : (variant == "dspark" ? 1024 : 4096)); const bool mtp = variant == "mtp" && parallel == 1 && (quantization == "nvfp4" || quantization == "int4_awq") && sm == 120 && marker.at("target").at("arch") == "x86_64" && diff --git a/families/qwen3_8/runtime/edge_llm/contract.h b/families/qwen3_8/runtime/edge_llm/contract.h index 215b8f76cf..a883e84738 100644 --- a/families/qwen3_8/runtime/edge_llm/contract.h +++ b/families/qwen3_8/runtime/edge_llm/contract.h @@ -16,7 +16,11 @@ namespace trtmc::qwen3_8::edge_llm { +#ifdef TRTMC_QWEN38_EDGE_012 +inline constexpr const char* kRevision = "513dcd18291e587c80928911a480761352f3c2d8"; +#else inline constexpr const char* kRevision = "95515c2f87fba8982db5a519f9022277667b3cc9"; +#endif /// DSpark proposal length excludes the one additional verification token. inline bool valid_execution_variant(const std::string& variant, int block_size) { diff --git a/families/qwen3_8/runtime/edge_llm/media.h b/families/qwen3_8/runtime/edge_llm/media.h index b0d76a160d..7338856eed 100644 --- a/families/qwen3_8/runtime/edge_llm/media.h +++ b/families/qwen3_8/runtime/edge_llm/media.h @@ -15,6 +15,7 @@ namespace trtmc::qwen3_8::edge_llm { namespace api = trtmc::internal; namespace edge = trt_edgellm::rt; +using EdgeDataType = decltype(edge::Tensor{}.getDataType()); /// These defaults match the legacy text API; media requires the provider template. inline Span fields(bool media) { @@ -78,7 +79,7 @@ inline edge::imageUtils::ImageData image_buffer(const api::ImageView& image) { throw std::invalid_argument("Qwen3.8 RGB storage does not match its dimensions"); const auto count = static_cast(pixels * 3); edge::Tensor tensor({1, image.height, image.width, 3}, edge::DeviceType::kCPU, - nvinfer1::DataType::kUINT8); + EdgeDataType::kUINT8); auto* out = tensor.dataPointer(); if (image.format == api::ImageFormat::UInt8) { std::memcpy(out, image.data, count); @@ -110,7 +111,7 @@ inline edge::imageUtils::ImageData video_buffer(const api::VideoView& video) { if (count > static_cast(INT64_MAX) / stride) throw std::invalid_argument("Qwen3.8 video dimensions overflow"); edge::Tensor tensor({static_cast(count), first.height, first.width, 3}, - edge::DeviceType::kCPU, nvinfer1::DataType::kUINT8); + edge::DeviceType::kCPU, EdgeDataType::kUINT8); auto* output = tensor.dataPointer(); std::memcpy(output, first.data(), stride); for (std::size_t i = 1; i < count; ++i) { diff --git a/families/qwen3_8/runtime/edge_llm/request.h b/families/qwen3_8/runtime/edge_llm/request.h index 55ad2cbc06..0eaa9b0d90 100644 --- a/families/qwen3_8/runtime/edge_llm/request.h +++ b/families/qwen3_8/runtime/edge_llm/request.h @@ -6,7 +6,11 @@ #include "families/qwen3_8/runtime/edge_llm/contract.h" +#ifdef TRTMC_QWEN38_EDGE_012 +#include +#else #include +#endif namespace trtmc::qwen3_8::edge_llm { diff --git a/families/qwen3_8/runtime/external_draft.h b/families/qwen3_8/runtime/external_draft.h index d8dc01f542..abdb064024 100644 --- a/families/qwen3_8/runtime/external_draft.h +++ b/families/qwen3_8/runtime/external_draft.h @@ -7,6 +7,7 @@ #include "trtmc/runtime/trt_module.h" #include +#include #include namespace trtmc { @@ -14,17 +15,25 @@ struct Qwen38DraftProposal { int32_t token; std::vector probabilities; }; +// The verifier follows target samples through the retained proposal tree. A chain +// carries proposal probabilities instead and uses rejection sampling. +struct Qwen38VerifyNode { + int32_t token; + int32_t parent; +}; +using Qwen38VerifyTree = std::vector; +using Qwen38DraftRound = std::variant, Qwen38VerifyTree>; // Qwen-owned external draft contract. Target verification and confirmed-state // observation are identical; each companion owns its own proposal computation. class Qwen38ExternalDraft { public: virtual ~Qwen38ExternalDraft() = default; + virtual void validate_sampling(const Qwen38SamplingParams&) const {} virtual void reset(ITrtModule& target, std::size_t prompt_length, int32_t max_new_tokens) = 0; virtual void observe(ITrtModule& target) = 0; - virtual std::vector propose(int32_t anchor, - const Qwen38SamplingParams& sampling, - const std::vector& history, - int32_t budget, uint64_t& rng) = 0; + virtual Qwen38DraftRound propose(int32_t anchor, const Qwen38SamplingParams& sampling, + const std::vector& history, int32_t budget, + uint64_t& rng) = 0; virtual const char* name() const = 0; }; } // namespace trtmc diff --git a/families/qwen3_8/runtime/pipeline.cpp b/families/qwen3_8/runtime/pipeline.cpp index 375f99a6fb..c2a41ade59 100644 --- a/families/qwen3_8/runtime/pipeline.cpp +++ b/families/qwen3_8/runtime/pipeline.cpp @@ -450,6 +450,7 @@ std::vector RecurrentPipeline::generate_external_draft(const std::vector& input_ids, int32_t max_new_tokens, const Qwen38SamplingParams& params) { + external_draft_->validate_sampling(params); external_draft_->reset(*decoder_, input_ids.size(), max_new_tokens); state_->reset(); state_->bind_to(*decoder_); @@ -475,8 +476,31 @@ RecurrentPipeline::generate_external_draft(const std::vector& input_ids while (!ended()) { const int32_t remaining = max_new_tokens - static_cast(output.size() - input_ids.size()); - auto proposals = external_draft_->propose(output.back(), params, output, remaining, rng); + auto round = external_draft_->propose(output.back(), params, output, remaining, rng); ++rounds; + if (const auto* tree = std::get_if(&round)) { + if (tree->empty() || tree->front().parent != -1 || tree->front().token != output.back()) + throw std::runtime_error( + "Qwen3.8 speculative tree does not begin at the confirmed anchor"); + proposed += static_cast(tree->size()) - 1; + int32_t parent = 0; + while (!ended()) { + run_step(output.back(), logits); + external_draft_->observe(*decoder_); + const int32_t token = qwen38_draw_probabilities(distribution(), rng); + output.push_back(token); + const auto child = + std::find_if(tree->begin() + 1, tree->end(), [&](const auto& node) { + return node.parent == parent && node.token == token; + }); + if (child == tree->end()) + break; + ++accepted_count; + parent = static_cast(child - tree->begin()); + } + continue; + } + const auto& proposals = std::get>(round); proposed += static_cast(proposals.size()); bool rejected = false; for (const auto& proposal : proposals) { diff --git a/families/qwen3_8/runtime/plugin.cpp b/families/qwen3_8/runtime/plugin.cpp index 7fb689249a..5508e9d323 100644 --- a/families/qwen3_8/runtime/plugin.cpp +++ b/families/qwen3_8/runtime/plugin.cpp @@ -5,6 +5,7 @@ #include "families/qwen3_8/runtime/chat_templates.h" #include "families/qwen3_8/runtime/dflash2.h" +#include "families/qwen3_8/runtime/domino.h" #include "families/qwen3_8/runtime/dspark.h" #include "families/qwen3_8/runtime/hybrid_state.h" #include "families/qwen3_8/runtime/mtp_scheduler.h" @@ -300,7 +301,11 @@ ITask* create_native(const FamilyContext& context, const RuntimeConfig& config, const auto layers = require_value>(j, "feature_layers"); auto sorted = layers; std::sort(sorted.begin(), sorted.end()); - if (!j.is_object() || j.size() != 10 || require_value(j, "schema_version") != 1 || + const auto schema = require_value(j, "schema_version"); + const bool tree = schema == 2; + if (!j.is_object() || !(schema == 1 || tree) || j.size() != (tree ? 12U : 10U) || + (tree && (require_value(j, "tree_top_k") != 4 || + require_value(j, "verify_tokens") != 32)) || require_value(j, "hidden_size") != config.hidden_size || require_value(j, "vocab_size") != config.vocab_size || require_value(j, "max_cache_length") != config.max_cache_length || @@ -317,6 +322,7 @@ ITask* create_native(const FamilyContext& context, const RuntimeConfig& config, require_value(j, "window"), require_value(j, "rank"), require_value(j, "top_k"), + tree, }; auto draft = load_engine(context.backend, require_section(context.reader, "native_dflash2.plan"), @@ -329,6 +335,41 @@ ITask* create_native(const FamilyContext& context, const RuntimeConfig& config, require_section(context.reader, "native_dflash2_embeddings.bin")); } + if (context.reader.find_section("native_domino.json")) { + if (external_draft || config.has_mtp || config.precision != "fp16") + throw std::runtime_error( + "Qwen3.6 Domino requires FP16 without another speculative variant"); + const auto j = + nlohmann::json::parse(require_text_section(context.reader, "native_domino.json")); + auto taps = require_value>(j, "feature_layers"); + std::sort(taps.begin(), taps.end()); + if (!j.is_object() || j.size() != 11 || require_value(j, "schema_version") != 1 || + require_value(j, "hidden_size") != config.hidden_size || + require_value(j, "vocab_size") != config.vocab_size || + require_value(j, "max_cache_length") != config.max_cache_length || + require_value(j, "rows") != 16 || taps.empty() || taps.front() < 0 || + taps.back() >= config.num_layers || + std::adjacent_find(taps.begin(), taps.end()) != taps.end()) + throw std::runtime_error("Invalid Qwen3.6 Domino metadata/target agreement"); + Qwen38DominoConfig geometry{config.hidden_size, + config.vocab_size, + config.max_cache_length, + static_cast(taps.size()), + require_value(j, "mask_token_id"), + require_value(j, "pool"), + require_value(j, "rank"), + require_value(j, "state"), + require_value(j, "top_k")}; + external_draft = std::make_unique( + geometry, + load_engine(context.backend, require_section(context.reader, "native_domino.plan"), + "qwen3_8 Domino draft"), + load_engine(context.backend, + require_section(context.reader, "native_domino_correction.plan"), + "qwen3_8 Domino correction"), + require_section(context.reader, "native_domino_embeddings.bin")); + } + RecurrentGenConfig generation; generation.vocab_size = config.vocab_size; generation.id_bos = config.bos_token_id; @@ -366,10 +407,23 @@ ITask* create(const FamilyContext& context) { "-DTRTMC_ENABLE_EDGELLM=ON; rebuild and install Model Connect"); #endif } + // A bundle with an unknown external draft must not silently run target-only. + for (const auto& section : context.reader.info().sections) { + const auto& name = section.name; + if (name.compare(0, 7, "native_") != 0 || name.size() <= 12 || + name.compare(name.size() - 5, 5, ".json") != 0) + continue; + const auto prefix = name.substr(0, name.size() - 5); + if (context.reader.find_section(prefix + "_embeddings.bin") && + name != "native_dspark.json" && name != "native_dflash2.json" && + name != "native_domino.json") + throw std::runtime_error("Unsupported Qwen native draft: " + prefix); + } const auto config = parse_runtime_config(context.reader); if (config.tensor_parallel_size == 2) { if (context.reader.find_section("native_dspark.json") || - context.reader.find_section("native_dflash2.json")) + context.reader.find_section("native_dflash2.json") || + context.reader.find_section("native_domino.json")) throw std::runtime_error("Qwen native TP2 does not map speculative companions"); // The factory can be called again after a failed request. FamilyContext // borrows a reader used only during loading; retain its cheap metadata/path diff --git a/families/qwen3_8/runtime/sampler.cpp b/families/qwen3_8/runtime/sampler.cpp index f048f8a4ad..bd7128f6a4 100644 --- a/families/qwen3_8/runtime/sampler.cpp +++ b/families/qwen3_8/runtime/sampler.cpp @@ -267,6 +267,13 @@ void qwen38_apply_repetition_penalty(std::vector& logits, float penalty, } } +bool qwen38_greedy_distribution(const Qwen38SamplingParams& params) { + const float top_p = sanitized_top_p(params.top_p); + return greedy_equivalent(params) || (params.top_k == 1 && !top_p_enabled(top_p)) || + (params.top_k <= 1 && top_p >= 1.0F - kSamplingEpsilon && + sanitized_min_p(params.min_p) <= 0.0F && params.seed < 0); +} + std::vector qwen38_probabilities(const float* logits, int32_t vocab_size, const Qwen38SamplingParams& params) { if (vocab_size <= 0 || !logits) diff --git a/families/qwen3_8/runtime/sampler.h b/families/qwen3_8/runtime/sampler.h index 79b1e0e225..23f666e4f1 100644 --- a/families/qwen3_8/runtime/sampler.h +++ b/families/qwen3_8/runtime/sampler.h @@ -54,6 +54,7 @@ void qwen38_apply_repetition_penalty(std::vector& logits, float penalty, const std::vector& token_history); // The exact existing target filters, exposed for family-owned rejection sampling. +bool qwen38_greedy_distribution(const Qwen38SamplingParams& params); std::vector qwen38_probabilities(const float* logits, int32_t vocab_size, const Qwen38SamplingParams& params); double qwen38_uniform(uint64_t& rng); diff --git a/families/qwen3_8/tests/test_checkpoint_mapper.py b/families/qwen3_8/tests/test_checkpoint_mapper.py index 5f79db086e..0a8e8a3788 100644 --- a/families/qwen3_8/tests/test_checkpoint_mapper.py +++ b/families/qwen3_8/tests/test_checkpoint_mapper.py @@ -11,14 +11,15 @@ from families.qwen3_8 import checkpoint_mapper as mapper -@pytest.mark.parametrize("format_name", ["nvfp4", "fp8", "int4_awq"]) +@pytest.mark.parametrize("format_name", ["nvfp4", "fp8", "int4_awq", "int4_gptq"]) def test_prepared_q_gate_split_retains_exact_source_bytes(monkeypatch, format_name) -> None: import torch from families.qwen3_8 import quantization as quant name = "model.language_model.layers.0.self_attn.q_proj" - width = 128 if format_name == "int4_awq" else 16 - if format_name == "int4_awq": + group_int4 = format_name in ("int4_awq", "int4_gptq") + width = 128 if group_int4 else 16 + if group_int4: codes = np.arange(8 * width, dtype=np.uint16).reshape(8, width).astype(np.uint8) & 15 # Vary output rows too, so mixing adjacent rows cannot accidentally pass. codes = (codes + np.arange(8, dtype=np.uint8)[:, None]) & 15 @@ -36,11 +37,22 @@ def test_prepared_q_gate_split_retains_exact_source_bytes(monkeypatch, format_na tensors[name + ".weight_scale_2"] = torch.tensor([0.125]) if format_name == "int4_awq": tensors[name + ".pre_quant_scale"] = torch.linspace(0.5, 1.5, width) - else: + elif not group_int4: expected_packed = values.view(torch.uint8).numpy() + if format_name == "int4_gptq": + # Independent representation: offset-binary codes packed LSB-first in + # INT32 words along input channels, not ModelOpt's output-row layout. + signed = codes.astype(np.int32) + signed[signed >= 8] -= 16 + words = np.sum((signed.reshape(8, -1, 8) + 8).astype(np.uint32) + << (4 * np.arange(8, dtype=np.uint32)), axis=2, dtype=np.uint32) + tensors = {name + ".weight_packed": torch.from_numpy(words.view(np.int32)), + name + ".weight_scale": scales, name + ".weight_shape": torch.tensor([8, width])} monkeypatch.setattr(quant, "_has_tensor", lambda _, key: key in tensors) monkeypatch.setattr(quant, "_get_raw_tensor", lambda _, key: tensors[key]) - query, gate = quant._read_prepared_weight_split_q([], name, 2, 2, awq=format_name == "int4_awq") + read = {"int4_awq": quant._read_awq_weight, "int4_gptq": quant._read_compressed_int4}.get( + format_name, quant._read_prepared_weight) + query, gate = quant._read_prepared_weight_split_q([], name, 2, 2, read_weight=read) for result, rows in ((query, [0, 1, 4, 5]), (gate, [2, 3, 6, 7])): assert result.out_features == 4 and result.in_features == width np.testing.assert_array_equal(result.packed, expected_packed[rows]) @@ -48,10 +60,13 @@ def test_prepared_q_gate_split_retains_exact_source_bytes(monkeypatch, format_na assert isinstance(result, quant._NVFP4Weight) assert result.global_scale == 0.125 np.testing.assert_array_equal(result.block_scale_f8, scales.view(torch.uint8).numpy()[rows]) - elif format_name == "int4_awq": - assert isinstance(result, quant._AWQWeight) + elif group_int4: + assert isinstance(result, quant._GroupInt4Weight) np.testing.assert_array_equal(result.block_scale, scales.numpy()[rows]) - np.testing.assert_array_equal(result.pre_quant_scale, tensors[name + ".pre_quant_scale"].numpy()) + if format_name == "int4_awq": + np.testing.assert_array_equal(result.pre_quant_scale, tensors[name + ".pre_quant_scale"].numpy()) + else: + assert result.pre_quant_scale is None else: assert isinstance(result, quant._FP8Weight) assert result.weight_scale == 0.25 @@ -61,6 +76,11 @@ def test_prepared_q_gate_split_retains_exact_source_bytes(monkeypatch, format_na with pytest.raises(ValueError, match="expected FP8"): quant._read_prepared_weight([], name) + if format_name == "int4_gptq": + tensors[name + ".weight_g_idx"] = torch.arange(width) + with pytest.raises(ValueError, match="without a permutation"): + read([], name) + if format_name == "int4_awq": tensors[name + ".weight_scale"] = torch.ones(8, 2) with pytest.raises(ValueError, match="group-128"): @@ -108,14 +128,14 @@ def test_embedded_draft_keeps_its_own_quantization(monkeypatch, tmp_path, format monkeypatch.setattr(quant, "_get_raw_tensor", lambda _, key: tensors[key]) config = SimpleNamespace(num_hidden_layers=0, hidden_size=hidden, intermediate_size=hidden, vocab_size=hidden, num_attention_heads=2, head_dim=head_dim) - loader = quant.load_qwen3_8_awq if format_name == "int4_awq" else quant.calibrate_qwen3_8_nvfp4 + loader = quant.load_qwen3_8_group_int4 if format_name == "int4_awq" else quant.calibrate_qwen3_8_nvfp4 context = loader(tmp_path, config, None, readers=[]) expected = {"fc", "w_q", "w_gate_attn", "w_k", "w_v", "w_o", "w_gate", "w_up", "w_down"} assert set(context.profile.scales) == {"mtp_layer." + name for name in expected} for item in context.profile.scales.values(): if format_name == "int4_awq": assert item.input_scale is None # W4A16 does not quantize activations. - assert isinstance(item.weight, quant._AWQWeight) + assert isinstance(item.weight, quant._GroupInt4Weight) np.testing.assert_array_equal(item.weight.pre_quant_scale, 0.75) else: assert item.input_scale == 0.25 diff --git a/families/qwen3_8/tests/test_engine_builder.py b/families/qwen3_8/tests/test_engine_builder.py index 4aa9e06433..7de7f925f2 100644 --- a/families/qwen3_8/tests/test_engine_builder.py +++ b/families/qwen3_8/tests/test_engine_builder.py @@ -363,6 +363,8 @@ def test_load_weights_without_quant_ctx_loads_everything(monkeypatch) -> None: # layers/projections lacking a scale tensor. config.raw["quantization_config"] = {"kv_cache_quant_algo": "FP8"} assert not engine_builder.Qwen38Model().load_weights("unused", config)["_fp8_kv_cache"] + paired = engine_builder._load_fp8_kv_scales([], ["linear", "attention"], paired_fp8_kv=True) + assert paired["_fp8_kv_cache"] and paired["layer.1.kv_scales"] == (1.0, 1.0, 1.0) key = "model.language_model.layers.1.self_attn.k_proj.k_scale" _catalog[key] = np.array([0.125], dtype=np.float32) _catalog[key.replace("k_proj.k_scale", "v_proj.v_scale")] = np.array([0.25]) @@ -371,6 +373,16 @@ def test_load_weights_without_quant_ctx_loads_everything(monkeypatch) -> None: assert loaded_weights["layer.1.kv_scales"] == (1.0, 0.125, 0.25) assert loaded_weights["mtp_layer.kv_scales"] == (1.0, 1.0, 1.0) import pytest + # Compressed-tensors stores the calibrated K/V scalars on the attention + # module rather than on its K and V projections; never replace them by 1. + short = "model.language_model.layers.1.self_attn." + _catalog[short + "k_scale"] = np.array([0.5]) + _catalog[short + "v_scale"] = np.array([0.75]) + compressed = engine_builder._load_fp8_kv_scales([], ["linear", "attention"], compressed=True) + assert compressed["_fp8_kv_cache"] and compressed["layer.1.kv_scales"] == (1.0, 0.5, 0.75) + del _catalog[short + "k_scale"] + with pytest.raises(ValueError, match="Missing compressed FP8 attention scale"): + engine_builder._load_fp8_kv_scales([], ["linear", "attention"], compressed=True) for invalid in (np.array([0.0]), np.array([float("nan")]), np.array([1.0, 2.0])): _catalog[key] = invalid with pytest.raises(ValueError, match="FP8 attention scale"): diff --git a/families/qwen3_8/tests/test_support.py b/families/qwen3_8/tests/test_support.py index ba86f1e9ba..83360f9f08 100644 --- a/families/qwen3_8/tests/test_support.py +++ b/families/qwen3_8/tests/test_support.py @@ -116,9 +116,9 @@ def test_edge_cli_help_is_family_owned(tmp_path, capsys): build_cli.main(["qwen3_8", "build", str(source), "--help"]) assert caught.value.code == 0 help_text = capsys.readouterr().out - assert "--execution-variant {dspark,dflash,mtp}" in help_text + assert "--execution-variant {dspark,dflash,dflash_tree,domino,domino_tree,mtp}" in help_text assert "--companion" in help_text - assert "--quantization {none,nvfp4,fp8,int4_awq}" in help_text + assert "--quantization {none,nvfp4,fp8,int4_awq,int4_gptq}" in help_text @pytest.mark.parametrize("vision", [False, True]) @@ -340,7 +340,7 @@ def _dspark_pair_request(tmp_path, variant="dspark"): "architectures": ["DSparkDraftModel" if variant == "dspark" else "DFlash2DraftModel"], "hidden_size": 16, "vocab_size": 32, "num_target_layers": 8, "max_position_embeddings": 4096, - f"{variant}_config": {"block_size": 7 if variant == "dspark" else 8, + ("dspark_config" if variant == "dspark" else "dflash_config"): {"block_size": 7 if variant == "dspark" else 8, "target_layer_ids": [1], "mask_token_id": 3}, })) return ( @@ -374,7 +374,8 @@ def test_dspark_request_errors_precede_adapter_work(tmp_path, monkeypatch, overr @pytest.mark.parametrize("variant, limit, quantization", [ ("dspark", 9, "nvfp4"), ("dspark", 1024, "nvfp4"), ("dflash", 9, "nvfp4"), - ("dflash", 4096, "nvfp4"), ("dflash", 9, "int4_awq"), ("dflash", 4096, "int4_awq")]) + ("dflash", 4096, "nvfp4"), ("dflash", 9, "int4_awq"), ("dflash", 4096, "int4_awq"), + ("dflash", 9, None), ("dflash", 4096, None), ("dflash_tree", 256, "nvfp4"), ("dflash_tree", 4096, None)]) def test_dspark_capacity_boundaries_keep_the_requested_pair(tmp_path, monkeypatch, variant, limit, quantization): from dataclasses import replace from families.qwen3_8.edge_llm import dispatch @@ -391,6 +392,35 @@ def test_dspark_capacity_boundaries_keep_the_requested_pair(tmp_path, monkeypatc "quantization": {"quant_algo": "W4A16_AWQ", "group_size": 128, "kv_cache_quant_algo": None}, })) + if quantization == "nvfp4" and variant == "dflash": + import json + raw = json.loads((request.model_dir / "config.json").read_text()) + assert not dispatch.candidate(replace(request, quantization="none"), raw, variant, + include_current=True) + if quantization is None: + import json + from families.qwen3_8.edge_llm import builder + + path = request.model_dir / "config.json" + raw = json.loads(path.read_text()) + del raw["quantization_config"] + (request.model_dir / "hf_quant_config.json").unlink() + assert not dispatch.candidate(request, raw, variant, include_current=True) + raw.update(output_gate_type="swish", hidden_size=5120, vocab_size=248320, + num_hidden_layers=64, intermediate_size=17408, num_attention_heads=24, + num_key_value_heads=4) + path.write_text(json.dumps(raw)) + companion = execution.checkpoints[0].model_dir / "config.json" + draft = json.loads(companion.read_text()) + draft.update(hidden_size=5120, vocab_size=248320, num_target_layers=64) + companion.write_text(json.dumps(draft)) + assert builder.paired_checkpoint_quantization(request.model_dir, raw, variant) is None + assert dispatch.candidate(request, raw, variant, include_current=True) + assert dispatch.candidate(replace(request, quantization="none"), raw, variant, + include_current=True) + assert not dispatch.candidate(request, raw, "dspark", include_current=True) + assert not dispatch.candidate(replace(request, quantization="nvfp4"), raw, variant, + include_current=True) seen = [] native_seen = [] from families.qwen3_8 import model @@ -404,7 +434,7 @@ def build(original, writer, native, *, draft_dir, execution_variant="dspark"): assert native_seen[-1][0].max_sequence_length == limit assert native_seen[-1][0].quantization == quantization expected = {"draft_dir": execution.checkpoints[0].model_dir} - if variant == "dflash": + if variant in {"dflash", "dflash_tree"}: expected["draft_variant"] = variant assert native_seen[-1][1] == expected seen.append(original) @@ -693,7 +723,8 @@ def test_paired_draft_contract_rejected_before_export(tmp_path, monkeypatch, var @pytest.mark.parametrize("onnx", [False, True]) @pytest.mark.parametrize("available", [False, True]) -def test_builder_interpreter_checks_requested_api(monkeypatch, onnx, available): +@pytest.mark.parametrize("version", ["0.11.0", "0.12.0"]) +def test_builder_interpreter_checks_requested_api(monkeypatch, onnx, available, version): import json import subprocess from types import SimpleNamespace @@ -701,16 +732,26 @@ def test_builder_interpreter_checks_requested_api(monkeypatch, onnx, available): def probe(command, **options): assert command[1:3] == ["-I", "-c"] - assert ("tensorrt_edgellm.scripts.export" in command[3]) is onnx - assert ("experimental.builder.cli" in command[3]) is not onnx + modules = { + "0.11.0": ("experimental.builder.cli", "tensorrt_edgellm.scripts.export"), + "0.12.0": ("tensorrt_edgellm.builder.cli", "tensorrt_edgellm.onnx.cli"), + } + assert modules[version][int(onnx)] in command[3] + assert modules[version][int(not onnx)] not in command[3] + assert ("5.17.0" in command[3]) == (version == "0.12.0") assert options["timeout"] == 30 if not available: raise subprocess.CalledProcessError(1, command) - return SimpleNamespace(stdout=json.dumps(["0.11.0", "test-trt"])) + return SimpleNamespace(stdout=json.dumps([version, "test-trt"])) monkeypatch.setattr(builder.subprocess, "run", probe) - result = builder.builder_python({"python": "/sdk/python"}, {"tensorrt_version": "test-trt"}, onnx=onnx) - assert result == (builder.sys.executable if available else "/sdk/python") + package = {"version": version, "python": "/sdk/python"} + if not available and version == "0.12.0": + with pytest.raises(ValueError, match="--edge-builder-python"): + builder.builder_python(package, {"tensorrt_version": "test-trt"}, onnx=onnx) + else: + result = builder.builder_python(package, {"tensorrt_version": "test-trt"}, onnx=onnx) + assert result == (builder.sys.executable if available else "/sdk/python") @pytest.mark.parametrize("edge", [False, True]) diff --git a/families/qwen3_8/vision.py b/families/qwen3_8/vision.py index 14629a99bc..31371d2c9b 100644 --- a/families/qwen3_8/vision.py +++ b/families/qwen3_8/vision.py @@ -125,7 +125,7 @@ def linear(name, out_width, in_width): if prepared is None or (prepared.out_features, prepared.in_features) != (out_width, in_width): raise ValueError(f"Invalid prepared Qwen visual projection: {source}") input_scale = quant._read_input_scale(readers, source) - if not isinstance(prepared, quant._AWQWeight) and input_scale is None: + if not isinstance(prepared, quant._GroupInt4Weight) and input_scale is None: raise ValueError(f"Missing prepared visual activation scale: {source}") scales[name] = quant._LayerScales(input_scale, prepared) else: diff --git a/website/docs/features/model-families.md b/website/docs/features/model-families.md index 231e343e78..806dff5a8b 100644 --- a/website/docs/features/model-families.md +++ b/website/docs/features/model-families.md @@ -97,12 +97,15 @@ and do not imply that CI executes the paired cases. ### Qwen3.6 / Qwen3.8 Edge-LLM execution -The family owns ordinary original-weight FP16 TP2, ordinary mixed-NVFP4 TP1, -and explicit DSpark/DFlash2 ONNX execution through the optional Edge-LLM 0.11.0 -SDK. Use `trtmc qwen3_8 build MODEL -o model.bundle`; offline help and options -use the existing [family CLI protocol](../extend/family-cli.md), not shared -parser extensions. For a pair, add `--execution-variant dspark` or `dflash` and -`--companion draft=/path/to/draft`. +Use `trtmc qwen3_8 build MODEL -o model.bundle`. The default Edge SDK +remains 0.11.0; a runtime compiled against 0.12.0 adds opt-in routes for +dense 27B original and prepared checkpoints. Use the +[family CLI](../extend/family-cli.md) to select a companion explicitly: +`--execution-variant dspark|dflash|dflash_tree|domino|domino_tree` and +`--companion draft=/path/to/draft`. DFlash2 tree and Domino are 0.12 Edge routes; +Domino and DFlash2 tree support greedy decoding only. See the +[0.12 recipe and validation scope](https://github.com/NVIDIA/TensorRT-Model-Connect/blob/main/families/qwen3_8/edge_llm/README.md#opt-in-to-edge-llm-012). +A mapped route is not an accuracy qualification. An ordinary build (no `--execution-variant`) of a checkpoint that carries MTP weights builds only the base engine. Add `--mtp-seq-len N` (N >= 2: one real @@ -117,13 +120,13 @@ or accuracy qualification. For MTP, use `--execution-variant mtp` without an external companion. Prepared checkpoint metadata must match the owning recipe; Model Connect does not calibrate or quantize weights during this integration. -Local text requests include exact independent FP32 matches, with separate -quality failures retained. Qwen3.8 original single-image passed; ordered-image +For the earlier **0.11** runs, local text requests included exact independent FP32 +matches, with separate quality failures retained. Qwen3.8 original single-image passed; ordered-image and video accuracy failed. Mixed-NVFP4 ordinary and both paired raw-text profiles build and run, matching direct Edge exactly, but fail the independent FP32 NED gate. Accuracy failures remain executable and are not described as fully qualified. Original-weight speculative -execution and batch-8 MTP remain outside this adapter's mapped scope. +execution and batch-8 MTP were not validated by those 0.11 results. Provision the [native SDK](../user-guides/configure-runtime.md#optional-native-edge-llm-sdk). See the [owning recipe](https://github.com/NVIDIA/TensorRT-Model-Connect/blob/main/families/qwen3_8/edge_llm/README.md) @@ -136,8 +139,8 @@ profile results do not imply registered CI or catalog-wide qualification. Without compatible Edge offload, the owner constructs TensorRT graphs directly and runs them through the Model Connect C++ runtime, without native ONNX export. Prepared source quantization and exported FP8 KV scales are preserved. Native -paths cover ordinary text/media, embedded MTP, complete DSpark/DFlash2 companions, -and original FP16 TP2; they do not silently substitute target-only decoding. +paths cover ordinary text/media, embedded MTP, DSpark, DFlash2 chain/tree, +Domino chain/tree, and original FP16 TP2. Paired builds do not substitute target-only decoding. Exact full-checkpoint and small integration results are distinguished in the [family recipe](https://github.com/NVIDIA/TensorRT-Model-Connect/blob/main/families/qwen3_8/edge_llm/README.md#native-fallback). From 5dd2c26b90774212822bce9fc66ea4a55a8c8ba9 Mon Sep 17 00:00:00 2001 From: Joshua Calafato Date: Mon, 23 Nov 2026 17:41:57 +0000 Subject: [PATCH 2/3] fix(qwen3_8): honor draft profiles and manifests Count the anchor input row for 0.12 DSpark companions that do not sample from it. Refuse unknown native manifests even when they omit the embeddings sidecar, instead of silently loading a target-only pipeline. Signed-off-by: Joshua Calafato --- families/qwen3_8/edge_llm/builder.py | 8 ++++++ families/qwen3_8/runtime/plugin.cpp | 11 ++++---- families/qwen3_8/tests/test_support.py | 39 ++++++++++++++++++++++++++ 3 files changed, 52 insertions(+), 6 deletions(-) diff --git a/families/qwen3_8/edge_llm/builder.py b/families/qwen3_8/edge_llm/builder.py index 94c3e31032..eb4b08c916 100644 --- a/families/qwen3_8/edge_llm/builder.py +++ b/families/qwen3_8/edge_llm/builder.py @@ -355,6 +355,14 @@ def _prepare_paired_onnx(request, raw: dict, target: dict, staging: Path, log_pa source, draft_dir = Path(request.model_dir).resolve(), draft_dir.resolve() version = package.get("version", "0.11.0") current = version == "0.12.0" + if current and variant == "dspark": + # The 0.12 draft profile counts query rows, not just proposed tokens. + draft = json.loads((draft_dir / "config.json").read_text(encoding="utf-8")) + sample_from_anchor = (draft.get("dspark_config") or {}).get( + "sample_from_anchor", draft.get("sample_from_anchor", True)) + if not isinstance(sample_from_anchor, bool): + raise ValueError("DSpark sample_from_anchor must be boolean") + draft_slots = block + (not sample_from_anchor) quantization = paired_checkpoint_quantization(source, raw, variant, include_current=current) if quantization is None: raise ValueError("Unsupported Qwen3.8 target checkpoint for this paired Edge release") diff --git a/families/qwen3_8/runtime/plugin.cpp b/families/qwen3_8/runtime/plugin.cpp index 5508e9d323..c43867f5e9 100644 --- a/families/qwen3_8/runtime/plugin.cpp +++ b/families/qwen3_8/runtime/plugin.cpp @@ -410,14 +410,13 @@ ITask* create(const FamilyContext& context) { // A bundle with an unknown external draft must not silently run target-only. for (const auto& section : context.reader.info().sections) { const auto& name = section.name; - if (name.compare(0, 7, "native_") != 0 || name.size() <= 12 || + if (name.compare(0, 7, "native_") != 0 || name.size() < 12 || name.compare(name.size() - 5, 5, ".json") != 0) continue; - const auto prefix = name.substr(0, name.size() - 5); - if (context.reader.find_section(prefix + "_embeddings.bin") && - name != "native_dspark.json" && name != "native_dflash2.json" && - name != "native_domino.json") - throw std::runtime_error("Unsupported Qwen native draft: " + prefix); + if (name != "native_visual.json" && name != "native_dspark.json" && + name != "native_dflash2.json" && name != "native_domino.json") + throw std::runtime_error("Unsupported Qwen native draft: " + + name.substr(0, name.size() - 5)); } const auto config = parse_runtime_config(context.reader); if (config.tensor_parallel_size == 2) { diff --git a/families/qwen3_8/tests/test_support.py b/families/qwen3_8/tests/test_support.py index 83360f9f08..d746c49f39 100644 --- a/families/qwen3_8/tests/test_support.py +++ b/families/qwen3_8/tests/test_support.py @@ -721,6 +721,45 @@ def test_paired_draft_contract_rejected_before_export(tmp_path, monkeypatch, var dispatch.build_paired(request, None, execution) +@pytest.mark.parametrize("root_anchor,nested_anchor,expected", [ + (None, None, 7), (False, None, 8), (True, False, 8), (False, True, 7), +]) +def test_dspark_012_draft_compiler_reserves_anchor_input(tmp_path, monkeypatch, root_anchor, nested_anchor, expected): + """Open the real family build path, stopping before executing the draft compiler.""" + import json + from families.qwen3_8.edge_llm import builder + + request, execution = _dspark_pair_request(tmp_path) + draft = execution.checkpoints[0].model_dir + for directory in (request.model_dir, draft): + (directory / "model.safetensors").touch() + draft_config = json.loads((draft / "config.json").read_text()) + if root_anchor is not None: + draft_config["sample_from_anchor"] = root_anchor + if nested_anchor is not None: + draft_config["dspark_config"]["sample_from_anchor"] = nested_anchor + (draft / "config.json").write_text(json.dumps(draft_config)) + monkeypatch.setattr(builder, "installed_package", lambda _: { + "onnx": True, "version": "0.12.0", "onnx_builder": "compiler", "plugin": "/sdk/plugin", + }) + monkeypatch.setattr(builder, "builder_python", lambda *args, **kwargs: "exporter") + + class ReachedCompiler(Exception): + pass + + def record(argv, **kwargs): + if argv[0] == "compiler": + assert "--spec-draft" in argv + assert argv[argv.index("--max-spec-draft-tokens") + 1] == str(expected) + raise ReachedCompiler + assert "--dspark-draft" in argv + + monkeypatch.setattr(builder.subprocess, "run", record) + raw = json.loads((request.model_dir / "config.json").read_text()) + with pytest.raises(ReachedCompiler): + builder.prepare_dspark(request, raw, {}, tmp_path / "stage", tmp_path / "build.log", draft) + + @pytest.mark.parametrize("onnx", [False, True]) @pytest.mark.parametrize("available", [False, True]) @pytest.mark.parametrize("version", ["0.11.0", "0.12.0"]) From 0d3a53987c64f3bbcb11be8761f38ebd4efde44e Mon Sep 17 00:00:00 2001 From: Joshua Calafato Date: Tue, 24 Nov 2026 07:18:16 +0000 Subject: [PATCH 3/3] fix(qwen3_8): preserve explicit MTP verification windows Route native MTP windows away from base-only Edge engines. Reject requests that select both an embedded window and an external draft instead of ignoring one decoding mode. Signed-off-by: Joshua Calafato --- families/qwen3_8/edge_llm/README.md | 7 +++++-- families/qwen3_8/edge_llm/dispatch.py | 5 ++++- families/qwen3_8/tests/test_support.py | 11 ++++++++++- 3 files changed, 19 insertions(+), 4 deletions(-) diff --git a/families/qwen3_8/edge_llm/README.md b/families/qwen3_8/edge_llm/README.md index 67ad327f5a..b08f0cbbea 100644 --- a/families/qwen3_8/edge_llm/README.md +++ b/families/qwen3_8/edge_llm/README.md @@ -258,8 +258,11 @@ do not qualify a full checkpoint or assert FP8 support on every GPU. An ordinary request does not enable speculative execution merely because its checkpoint contains draft weights. `--execution-variant mtp` maps to the native draft and verification graphs with three draft tokens and four verification -positions. The ordinary native `--mtp-seq-len N` option keeps its requested count. That mapping and uniform projection loading have contract coverage, -not full uniform-checkpoint MTP model qualification. +positions. Without an execution variant, `--mtp-seq-len N` selects native MTP +with the requested count; the ordinary Edge engine cannot verify draft tokens. +Do not combine this option with an external draft. The mapping and uniform +projection loading have contract coverage, not full uniform-checkpoint MTP +model qualification. The existing chunked-prefill implementation remains available for compatible TP1 text requests, including ordinary embedded-MTP requests. Explicit diff --git a/families/qwen3_8/edge_llm/dispatch.py b/families/qwen3_8/edge_llm/dispatch.py index e2c4466494..c1c1fabee2 100644 --- a/families/qwen3_8/edge_llm/dispatch.py +++ b/families/qwen3_8/edge_llm/dispatch.py @@ -41,7 +41,8 @@ def ordinary_candidate(request, raw: dict, *, embedded_mtp: bool = False, current: bool = False) -> bool: """Admit dense Swish 27B FP16 TP2 or original mixed-NVFP4 TP1.""" config = raw.get("text_config", raw) - if not isinstance(config, dict): + # Ordinary Edge engines do not contain the native MTP draft and verifier. + if not isinstance(config, dict) or (request.mtp_seq_len is not None and not embedded_mtp): return False source = Path(request.model_dir) quantization = (edge_llm.prepared_checkpoint_quantization(source, raw) if embedded_mtp else @@ -224,6 +225,8 @@ def native_mtp(original_request, original_writer): build(request, writer, native_mtp, execution_variant="mtp") return + if request.mtp_seq_len is not None: + raise ValueError("--mtp-seq-len selects embedded MTP and cannot be combined with an external draft") if execution.variant not in {"dspark", "dflash", "dflash_tree", "domino", "domino_tree"} or tuple(x.role for x in execution.checkpoints) != ("draft",): raise ValueError("Qwen3.8 paired execution requires DSpark, DFlash2 or Domino and one draft checkpoint") if request.precision.lower() != "fp16": diff --git a/families/qwen3_8/tests/test_support.py b/families/qwen3_8/tests/test_support.py index d746c49f39..ae17990bf2 100644 --- a/families/qwen3_8/tests/test_support.py +++ b/families/qwen3_8/tests/test_support.py @@ -541,6 +541,11 @@ def test_declared_build_matches_legacy_request(tmp_path, monkeypatch, options): original = captured[0] assert dispatch.ordinary_candidate(original, raw) assert dispatch.ordinary_candidate(replace(original, quantization=None), raw) + mtp_request = replace(original, mtp_seq_len=3) + assert not dispatch.ordinary_candidate(mtp_request, raw, current=True) + native = [] + dispatch.build(mtp_request, None, lambda request, _: native.append(request)) + assert native == [mtp_request] for overrides in ({"quantization": "none"}, {"quantization": "fp8"}, {"tensor_parallel_size": 2}, {"precision": "bf16"}): assert not dispatch.ordinary_candidate(replace(original, **overrides), raw) @@ -703,6 +708,7 @@ def test_declared_help_is_offline_and_dependency_free(): ("hidden_size", 32, "disagree on hidden_size"), ("num_target_layers", 9, "layer count"), ("block_size", 6, "documented block"), + ("mtp_seq_len", 3, "cannot be combined with an external draft"), ]) def test_paired_draft_contract_rejected_before_export(tmp_path, monkeypatch, variant, field, value, error): import json @@ -711,7 +717,10 @@ def test_paired_draft_contract_rejected_before_export(tmp_path, monkeypatch, var request, execution = _dspark_pair_request(tmp_path, variant) path = execution.checkpoints[0].model_dir / "config.json" draft = json.loads(path.read_text()) - if field == "block_size": + if field == "mtp_seq_len": + from dataclasses import replace + request = replace(request, mtp_seq_len=value) + elif field == "block_size": draft[f"{variant}_config"][field] = value else: draft[field] = value