From 56b36b678e26e05dfd55b449c22d2e631dc51df5 Mon Sep 17 00:00:00 2001 From: chaofengw Date: Mon, 23 Nov 2026 12:46:44 +0000 Subject: [PATCH 1/3] perf(qwen3_5_moe): prefill prompts in chunks of up to 64 rows Single-GPU GPTQ bundles now ship prefill.plan next to engine.plan. The runtime feeds text and media prompt rows to it up to 64 per call and decodes with engine.plan. Before, every prompt token ran through the one-token decode engine. - deltanet_rows.py (from qwen3_5): the gated delta rule over a chunk of rows, continuing the recurrent and conv state. - moe.add_dense_moe_rows: the routed GPTQ experts stacked into three W4A16 GEMMs. Each row runs every expert; only the routed ones contribute, with the one-token path's routing. - Full attention over cache plus chunk with a causal mask; per-row MRoPE tables; media feature rows and rotary offsets per chunk. - The prefill engine builds at optimization level 2. Level 1 drops the INT4 dequantize-GEMM fusion and expands the stacked experts to FP16 on every launch, about 4x slower. - The engine is built only when two copies of the weights fit in 80% of the GPU memory. MTP, draft and multi-GPU bundles, and checkpoints whose experts are not GPTQ, keep the single-engine layout. Signed-off-by: chaofengw --- families/qwen3_5_moe/deltanet_rows.py | 319 ++++++++++ families/qwen3_5_moe/graph_blocks.py | 15 +- families/qwen3_5_moe/moe.py | 112 ++++ families/qwen3_5_moe/native_model.py | 569 +++++++++++++++--- families/qwen3_5_moe/runtime/hybrid_state.cpp | 12 + families/qwen3_5_moe/runtime/hybrid_state.h | 2 + .../qwen3_5_moe/runtime/inference_state.h | 15 + families/qwen3_5_moe/runtime/kv_cache.cpp | 13 + families/qwen3_5_moe/runtime/kv_cache.h | 3 + families/qwen3_5_moe/runtime/pipeline.cpp | 113 +++- families/qwen3_5_moe/runtime/pipeline.h | 13 +- families/qwen3_5_moe/runtime/plugin.cpp | 25 +- .../qwen3_5_moe/tests/test_prefill_rows.py | 145 +++++ families/qwen3_5_moe/vision.py | 23 + website/docs/features/model-families.md | 4 + 15 files changed, 1270 insertions(+), 113 deletions(-) create mode 100644 families/qwen3_5_moe/deltanet_rows.py create mode 100644 families/qwen3_5_moe/tests/test_prefill_rows.py diff --git a/families/qwen3_5_moe/deltanet_rows.py b/families/qwen3_5_moe/deltanet_rows.py new file mode 100644 index 0000000000..23fb322e37 --- /dev/null +++ b/families/qwen3_5_moe/deltanet_rows.py @@ -0,0 +1,319 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Gated DeltaNet mixer over ``S`` rows in one launch (chunked delta rule). + +The single-token decoder applies, per head and token ``t``:: + + S_t = exp(g_t) S_{t-1} + k_t u_t^T, u_t = beta_t (v_t - exp(g_t) S_{t-1}^T k_t) + o_t = S_t^T q_t + +For a chunk of ``S`` tokens with cumulative decay ``gamma_t = sum_{i<=t} g_i`` +and ``Gamma_t = exp(gamma_t)`` this is equivalent to:: + + (I + A) U = beta V - diag(beta Gamma) K S_0, + A_ij = beta_i exp(gamma_i - gamma_j) k_i.k_j for j < i, else 0 + O = diag(Gamma) Q S_0 + (exp(gamma_t - gamma_i) q_t.k_i)_{i<=t} U + S_S = exp(gamma_S) S_0 + (K * exp(gamma_S - gamma))^T U + +``I + A`` is unit lower triangular. It is inverted by 2x2 block inversion on +a fixed ``SOLVE_ROWS`` padding (the padded rows are identity), batched over +the blocks of each level. This stays accurate where a single Neumann product +over 32 or more rows does not (nearly identical keys with beta close to one). +""" + +from __future__ import annotations + +import math + +import numpy as np +import tensorrt as trt + +# Static size of the padded triangular solve; it bounds the prefill rows. +SOLVE_ROWS = 64 +# Diagonal blocks of this size are inverted with a Neumann product. +_SOLVE_LEAF = 8 + + +def _const(network, values: np.ndarray) -> trt.ITensor: + values = np.ascontiguousarray(values) + return network.add_constant(values.shape, trt.Weights(values)).get_output(0) + + +def _i64(network, values) -> trt.ITensor: + return _const(network, np.asarray(values, dtype=np.int64)) + + +def _ew(network, a, b, op) -> trt.ITensor: + return network.add_elementwise(a, b, op).get_output(0) + + +def _mm(network, a, b, transpose_a=False, transpose_b=False) -> trt.ITensor: + op_a = trt.MatrixOperation.TRANSPOSE if transpose_a else trt.MatrixOperation.NONE + op_b = trt.MatrixOperation.TRANSPOSE if transpose_b else trt.MatrixOperation.NONE + return network.add_matrix_multiply(a, op_a, b, op_b).get_output(0) + + +def _shuffle(network, tensor, reshape=None, transpose=None) -> trt.ITensor: + layer = network.add_shuffle(tensor) + if transpose is not None: + layer.first_transpose = transpose + if reshape is not None: + layer.reshape_dims = reshape + return layer.get_output(0) + + +def row_count(network, tensor: trt.ITensor) -> trt.ITensor: + """Length of axis 0 as an int64 ``[1]`` shape tensor.""" + shape = network.add_shape(tensor).get_output(0) + return network.add_slice(shape, (0,), (1,), (1,)).get_output(0) + + +def _dims(network, parts) -> trt.ITensor: + tensors = [p if isinstance(p, trt.ITensor) else _i64(network, [p]) for p in parts] + joined = network.add_concatenation(tensors) + joined.axis = 0 + return joined.get_output(0) + + +def dynamic_slice(network, tensor, start, size) -> trt.ITensor: + """Slice with static or shape-tensor start and size entries.""" + rank = len(start) + layer = network.add_slice(tensor, (0,) * rank, (1,) * rank, (1,) * rank) + if any(isinstance(s, trt.ITensor) for s in start): + layer.set_input(1, _dims(network, start)) + else: + layer.start = tuple(start) + layer.set_input(2, _dims(network, size)) + return layer.get_output(0) + + +def _block_rows(network, matrix, heads: int, blocks: int, size: int, pairs: np.ndarray): + """Blocks ``(r, c)`` of ``[heads, blocks*size, blocks*size]`` with ``pairs[r, c] = 1``, summed over c. + + Returns ``[heads, blocks, size, size]``: row block ``r`` holds the selected block of that row. + """ + split = _shuffle(network, matrix, reshape=(heads, blocks, size, blocks, size)) + mask = _const(network, pairs.astype(np.float32).reshape(1, blocks, 1, blocks, 1)) + selected = _ew(network, split, mask, trt.ElementWiseOperation.PROD) + return network.add_reduce( + selected, trt.ReduceOperation.SUM, 1 << 3, keep_dims=False + ).get_output(0) + + +def _pair_half(network, tensor, heads: int, pairs: int, size: int, index: int) -> trt.ITensor: + """``[heads, 2*pairs, size, size]`` -> block ``index`` (0 or 1) of each pair.""" + grouped = _shuffle(network, tensor, reshape=(heads, pairs, 2, size, size)) + half = network.add_slice( + grouped, (0, 0, index, 0, 0), (heads, pairs, 1, size, size), (1, 1, 1, 1, 1) + ).get_output(0) + return _shuffle(network, half, reshape=(heads, pairs, size, size)) + + +def _inverse_unit_lower(network, lower: trt.ITensor, heads: int, size: int) -> trt.ITensor: + """Inverse of a static ``[heads, size, size]`` unit lower-triangular matrix. + + All ``_SOLVE_LEAF`` diagonal blocks are inverted at once with a Neumann + product, then each level merges pairs of blocks with + ``[[T11, 0], [-T22 L21 T11, T22]]``, batched over the pairs, so the + graph has a handful of matmuls per level rather than per block. + """ + sum_op = trt.ElementWiseOperation.SUM + leaf = min(_SOLVE_LEAF, size) + if size % leaf or (size // leaf) & (size // leaf - 1): + raise ValueError("the triangular solve size must be a power-of-two multiple of the leaf") + blocks = size // leaf + diagonal = _block_rows(network, lower, heads, blocks, leaf, np.eye(blocks)) + identity = _const(network, np.eye(leaf, dtype=np.float32)[None, None]) + # (I - N)^-1 = (I + N)(I + N^2)(I + N^4)... with N = I - D nilpotent. + nilpotent = _ew(network, identity, diagonal, trt.ElementWiseOperation.SUB) + inverse = _ew(network, identity, nilpotent, sum_op) + power = nilpotent + for _ in range(max(0, math.ceil(math.log2(leaf)) - 1)): + power = _mm(network, power, power) + inverse = _mm(network, inverse, _ew(network, identity, power, sum_op)) + width = leaf + while blocks > 1: + pairs = blocks // 2 + below = np.zeros((blocks, blocks)) + below[np.arange(1, blocks, 2), np.arange(0, blocks, 2)] = 1.0 + lower_left = _pair_half( + network, + _block_rows(network, lower, heads, blocks, width, below), + heads, + pairs, + width, + 1, + ) + upper = _pair_half(network, inverse, heads, pairs, width, 0) + bottom_right = _pair_half(network, inverse, heads, pairs, width, 1) + corner = network.add_unary( + _mm(network, _mm(network, bottom_right, lower_left), upper), trt.UnaryOperation.NEG + ).get_output(0) + zeros = _const(network, np.zeros((heads, pairs, width, width), dtype=np.float32)) + top = network.add_concatenation([upper, zeros]) + top.axis = 3 + bottom = network.add_concatenation([corner, bottom_right]) + bottom.axis = 3 + merged = network.add_concatenation([top.get_output(0), bottom.get_output(0)]) + merged.axis = 2 + inverse = merged.get_output(0) + blocks, width = pairs, width * 2 + return _shuffle(network, inverse, reshape=(heads, size, size)) + + +def add_chunked_delta_rule( + network: trt.INetworkDefinition, + *, + q: trt.ITensor, + k: trt.ITensor, + v: trt.ITensor, + g: trt.ITensor, + beta: trt.ITensor, + state: trt.ITensor, + num_heads: int, + head_dim: int, +) -> tuple[trt.ITensor, trt.ITensor]: + """Gated delta rule over one chunk, all tensors FP32. + + ``q``/``k``/``v`` are head-major ``[H, S, D]`` (``q`` already scaled), + ``g``/``beta`` are ``[H, S]`` and ``state`` is ``[H, D_k, D_v]``. + Returns ``(outputs [H, S, D_v], final state [H, D_k, D_v])``. + """ + sum_op, prod_op = trt.ElementWiseOperation.SUM, trt.ElementWiseOperation.PROD + rows = row_count(network, _shuffle(network, g, transpose=(1, 0))) + + axis = network.add_constant((), np.array(1, dtype=np.int32)).get_output(0) + gamma = network.add_cumulative(g, axis, trt.CumulativeOperation.SUM, False, False).get_output(0) + gamma_rows = _shuffle(network, gamma, reshape=(0, 0, 1)) # [H, S, 1] + gamma_cols = _shuffle(network, gamma, reshape=(0, 1, -1)) # [H, 1, S] + # exp(gamma_i - gamma_j) for j <= i; the exponent is clamped at zero so the + # masked upper triangle cannot overflow before it is multiplied by zero. + diff = _ew(network, gamma_rows, gamma_cols, trt.ElementWiseOperation.SUB) + diff = _ew( + network, + diff, + _const(network, np.zeros((1, 1, 1), np.float32)), + trt.ElementWiseOperation.MIN, + ) + decay = network.add_unary(diff, trt.UnaryOperation.EXP).get_output(0) + + def mask(offset: int) -> trt.ITensor: + full = np.tril(np.ones((SOLVE_ROWS, SOLVE_ROWS), np.float32), offset)[None] + return dynamic_slice(network, _const(network, full), (0, 0, 0), (1, rows, rows)) + + decay_strict = _ew(network, decay, mask(-1), prod_op) + decay_inclusive = _ew(network, decay, mask(0), prod_op) + + beta_rows = _shuffle(network, beta, reshape=(0, 0, 1)) # [H, S, 1] + a_matrix = _ew( + network, + _ew(network, beta_rows, decay_strict, prod_op), + _mm(network, k, k, transpose_b=True), + prod_op, + ) + padded = network.add_slice(a_matrix, (0, 0, 0), (num_heads, SOLVE_ROWS, SOLVE_ROWS), (1, 1, 1)) + padded.mode = trt.SampleMode.FILL + padded.set_input(4, network.add_constant((), np.array(0.0, dtype=np.float32)).get_output(0)) + lower = _ew( + network, + _const(network, np.eye(SOLVE_ROWS, dtype=np.float32)[None]), + padded.get_output(0), + sum_op, + ) + inverse = dynamic_slice( + network, + _inverse_unit_lower(network, lower, num_heads, SOLVE_ROWS), + (0, 0, 0), + (num_heads, rows, rows), + ) + + gamma_exp = network.add_unary(gamma_rows, trt.UnaryOperation.EXP).get_output(0) # [H, S, 1] + history = _mm(network, k, state) # [H, S, D_v]: S_0^T k_i + rhs = _ew( + network, + _ew(network, beta_rows, v, prod_op), + _ew(network, _ew(network, beta_rows, gamma_exp, prod_op), history, prod_op), + trt.ElementWiseOperation.SUB, + ) + updates = _mm(network, inverse, rhs) # U: [H, S, D_v] + + scores = _ew(network, decay_inclusive, _mm(network, q, k, transpose_b=True), prod_op) + outputs = _ew( + network, + _ew(network, gamma_exp, _mm(network, q, state), prod_op), + _mm(network, scores, updates), + sum_op, + ) + + # gamma_S is the last cumulative sum, not a separate reduction: summed in + # another order it can exceed gamma_i by many ulps at large |g|, and + # exp(gamma_S - gamma_i) would then overflow. A float running sum of + # non-positive terms never increases, and the clamp keeps the exponent at + # most zero regardless. + last = _ew(network, rows, _i64(network, [1]), trt.ElementWiseOperation.SUB) + total = dynamic_slice(network, gamma, (_i64(network, [0]), last), (num_heads, 1)) # [H, 1] + tail = network.add_unary( + _ew( + network, + _ew( + network, + _shuffle(network, total, reshape=(0, 0, 1)), + gamma_rows, + trt.ElementWiseOperation.SUB, + ), + _const(network, np.zeros((1, 1, 1), np.float32)), + trt.ElementWiseOperation.MIN, + ), + trt.UnaryOperation.EXP, + ).get_output(0) # exp(gamma_S - gamma_i): [H, S, 1] + carried = _ew( + network, + network.add_unary( + _shuffle(network, total, reshape=(0, 1, 1)), trt.UnaryOperation.EXP + ).get_output(0), + state, + prod_op, + ) + final_state = _ew( + network, + carried, + _mm(network, _ew(network, k, tail, prod_op), updates, transpose_a=True), + sum_op, + ) + return outputs, final_state + + +def add_short_conv_rows( + network: trt.INetworkDefinition, + *, + columns: trt.ITensor, + conv_state: trt.ITensor, + weight: trt.ITensor, + channels: int, + kernel: int, +) -> tuple[trt.ITensor, trt.ITensor]: + """Causal depthwise conv over ``columns`` ``[C, S]`` with a ``[C, kernel]`` history. + + The history holds the last ``kernel`` inputs (newest last). Output column + ``t`` is ``sum_j weight[:, j] * window[:, t + j]`` over + ``window = [history[:, 1:], columns]``; the new history is the last + ``kernel`` columns of the window. Returns ``(outputs [C, S], history)``. + """ + rows = row_count(network, _shuffle(network, columns, transpose=(1, 0))) + if kernel > 1: + past = network.add_slice(conv_state, (0, 1), (channels, kernel - 1), (1, 1)).get_output(0) + window = network.add_concatenation([past, columns]) + window.axis = 1 + window = window.get_output(0) + else: + window = columns + total = None + for tap in range(kernel): + tap_weight = network.add_slice(weight, (0, tap), (channels, 1), (1, 1)).get_output(0) + shifted = dynamic_slice(network, window, (0, tap), (channels, rows)) + term = _ew(network, shifted, tap_weight, trt.ElementWiseOperation.PROD) + total = term if total is None else _ew(network, total, term, trt.ElementWiseOperation.SUM) + last = _ew(network, rows, _i64(network, [1]), trt.ElementWiseOperation.SUB) + history = dynamic_slice(network, window, (_i64(network, [0]), last), (channels, kernel)) + return total, history diff --git a/families/qwen3_5_moe/graph_blocks.py b/families/qwen3_5_moe/graph_blocks.py index 0862c0142d..baad6d8158 100644 --- a/families/qwen3_5_moe/graph_blocks.py +++ b/families/qwen3_5_moe/graph_blocks.py @@ -99,9 +99,16 @@ def apply_norm( return graph_ops.add_rms_norm(network, inp, hidden_size, gamma, eps_tensor, dtype=dtype) -def add_sparse_mlp(network, inp, *, weights, prefix, hidden_size, mlp_size, dtype=np.float32): - """Apply this family's sparse/shared MLP; normalization/residual stay in the decoder.""" - from .moe import add_sparse_moe +def add_sparse_mlp(network, inp, *, weights, prefix, hidden_size, mlp_size, dtype=np.float32, rows=False): + """Apply this family's sparse/shared MLP; normalization/residual stay in the decoder. + + ``rows`` marks a prefill graph over ``S`` token rows: GPTQ experts then run as three dense W4A16 GEMMs + (``moe.add_dense_moe_rows``), whose stacked weights stay in ``weights["_prefill_keep"]`` until the build. + """ + from .moe import add_dense_moe_rows, add_sparse_moe, dense_rows_supported del hidden_size, mlp_size, dtype - return add_sparse_moe(network, inp, weights[f"{prefix}.moe"]) + moe = weights[f"{prefix}.moe"] + if rows and dense_rows_supported(moe): + return add_dense_moe_rows(network, inp, moe, weights.setdefault("_prefill_keep", [])) + return add_sparse_moe(network, inp, moe) diff --git a/families/qwen3_5_moe/moe.py b/families/qwen3_5_moe/moe.py index e7d8980a79..3622404b1d 100644 --- a/families/qwen3_5_moe/moe.py +++ b/families/qwen3_5_moe/moe.py @@ -403,3 +403,115 @@ def expert(value, item): binary(shared, gate, trt.ElementWiseOperation.PROD), trt.ElementWiseOperation.SUM, ) + + +def dense_rows_supported(weights: MoEWeights) -> bool: + """Whether :func:`add_dense_moe_rows` can run these experts: every routed projection is GPTQ.""" + return all( + isinstance(getattr(item, name), PackedLinear) and getattr(item, name).format == "gptq" + for item in weights.experts + for name in ("gate", "up", "down") + ) + + +@dataclass(frozen=True) +class _StackedExperts: + """All routed experts as three GPTQ projections: gate and up over every expert's outputs, down over every + expert's inputs. Group-128 blocks stay inside one expert, so the INT4 codes and FP16 scales are unchanged.""" + + gate: PackedLinear + up: PackedLinear + down: PackedLinear + + +def _stack_experts(weights: MoEWeights) -> _StackedExperts: + def outputs(matrices): + return PackedLinear("gptq", np.ascontiguousarray(np.concatenate([m.packed for m in matrices], 0)), + np.ascontiguousarray(np.concatenate([m.scales for m in matrices], 0))) + + def inputs(matrices): + return PackedLinear("gptq", np.ascontiguousarray(np.concatenate([m.packed for m in matrices], 1)), + np.ascontiguousarray(np.concatenate([m.scales for m in matrices], 1))) + + return _StackedExperts(outputs([e.gate for e in weights.experts]), outputs([e.up for e in weights.experts]), + inputs([e.down for e in weights.experts])) + + +def add_dense_moe_rows(network, hidden, weights: MoEWeights, keep: list): + """MoE over ``S`` token rows (prefill) with every expert in three W4A16 GEMMs. + + The routing is that of :func:`_add_sparse_moe_selected` (FP32 softmax over the router logits, top-k, + renormalized). Each row then runs every expert, so the experts' INT4 weights are read once per launch + instead of once per token: unselected experts are zeroed with a select (their FP16 intermediate may + overflow) before the routing weights scale the down-projection inputs, and the down GEMM sums the + selected experts. ``keep`` holds the stacked projections until the engine is built. + """ + dtype = hidden.dtype + hidden_size, count = weights.router.shape + topk = weights.top_k + stacked = _stack_experts(weights) + keep.append(stacked) + width = stacked.gate.shape[1] // count + + def cast(x, d): + return x if x.dtype == d else network.add_cast(x, d).get_output(0) + + def const(x): + x = np.array(x, copy=True, order="C") + keep.append(x) + return network.add_constant(x.shape, x).get_output(0) + + def binary(a, b, op): + return network.add_elementwise(a, b, op).get_output(0) + + def reshape(x, shape): + op = network.add_shuffle(x) + op.reshape_dims = shape + return op.get_output(0) + + def linear(x, w): + if isinstance(w, PackedLinear): + return w.matmul(network, x, *w.shape) + return network.add_matrix_multiply( + x, trt.MatrixOperation.NONE, cast(const(w), dtype), trt.MatrixOperation.NONE + ).get_output(0) + + def activated(x): + x = cast(x, trt.float32) + return cast(binary(x, network.add_activation(x, trt.ActivationType.SIGMOID).get_output(0), + trt.ElementWiseOperation.PROD), dtype) + + router = network.add_matrix_multiply( + cast(hidden, trt.float32), trt.MatrixOperation.NONE, + cast(cast(const(weights.router), dtype), trt.float32), trt.MatrixOperation.NONE, + ).get_output(0) + sm = network.add_softmax(cast(cast(router, dtype), trt.float32)) + sm.axes = 1 << 1 + top = network.add_topk(sm.get_output(0), trt.TopKOperation.MAX, topk, 1 << 1) + probs, indices = top.get_output(0), top.get_output(1) + denom = network.add_reduce(probs, trt.ReduceOperation.SUM, 1 << 1, True).get_output(0) + probs = cast(binary(probs, denom, trt.ElementWiseOperation.DIV), dtype) + # Routing weight of every expert per row, [S, E, 1]; zero for the unselected ones. + chosen = binary(reshape(indices, (-1, topk, 1)), const(np.arange(count, dtype=np.int32).reshape(1, 1, count)), + trt.ElementWiseOperation.EQUAL) + weighted = network.add_select(chosen, reshape(probs, (-1, topk, 1)), + cast(const(np.zeros((1, 1, 1), np.float32)), dtype)).get_output(0) + scores = reshape(network.add_reduce(weighted, trt.ReduceOperation.SUM, 1 << 1, False).get_output(0), + (-1, count, 1)) + selected = network.add_reduce(cast(chosen, trt.int32), trt.ReduceOperation.MAX, 1 << 1, False).get_output(0) + selected = cast(reshape(selected, (-1, count, 1)), trt.bool) + + gate = reshape(linear(hidden, stacked.gate), (-1, count, width)) + up = reshape(linear(hidden, stacked.up), (-1, count, width)) + expert_inputs = binary(activated(gate), up, trt.ElementWiseOperation.PROD) + expert_inputs = network.add_select(selected, expert_inputs, + cast(const(np.zeros((1, 1, 1), np.float32)), dtype)).get_output(0) + expert_inputs = binary(expert_inputs, scores, trt.ElementWiseOperation.PROD) + routed = linear(reshape(expert_inputs, (-1, count * width)), stacked.down) + + gate = linear(hidden, weights.shared.gate) + up = linear(hidden, weights.shared.up) + shared = linear(binary(activated(gate), up, trt.ElementWiseOperation.PROD), weights.shared.down) + shared_gate = cast(network.add_activation(cast(linear(hidden, weights.shared_gate), trt.float32), + trt.ActivationType.SIGMOID).get_output(0), dtype) + return binary(routed, binary(shared, shared_gate, trt.ElementWiseOperation.PROD), trt.ElementWiseOperation.SUM) diff --git a/families/qwen3_5_moe/native_model.py b/families/qwen3_5_moe/native_model.py index 7fdbcf9a04..18ae341f27 100644 --- a/families/qwen3_5_moe/native_model.py +++ b/families/qwen3_5_moe/native_model.py @@ -29,11 +29,18 @@ ) from . import graph_ops from . import graph_blocks +from . import deltanet_rows from .quantization import ( PackedLinear, load_attention_kv_scales, load_fp8_kv_scales, load_projection, prepared_format, prepare_fp8_cache, ) +# Prefill engine rows; the chunked delta rule pads its solve to this size. +PREFILL_MAX_TOKENS = deltanet_rows.SOLVE_ROWS +PREFILL_OPT_TOKENS = 32 +PREFILL_OPTIMIZATION_LEVEL = 2 + + def _projection_matmul(network, dtype): """Use the same original/prepared projections in target and draft graphs.""" def matmul(lhs, lhs_width, rhs_width, rhs_weights, _name): @@ -426,8 +433,21 @@ def build_engine( media_inputs: bool = False, export_hidden_state: bool = False, feature_layers: tuple[int, ...] = (), + prefill_rows: int | None = None, ) -> memoryview: - """Build hybrid TRT engine with DeltaNet + attention layers.""" + """Build hybrid TRT engine with DeltaNet + attention layers. + + ``prefill_rows`` builds the prefill engine of a split bundle instead: ``S`` prompt rows with one profile + ``1..prefill_rows``, DeltaNet as one chunked delta rule, attention over the cache plus the chunk and + GPTQ experts as dense W4A16 GEMMs. Media rows take per-row visual embeddings and MRoPE offsets. Its + logits come from the last row; present K/V cover all rows and the recurrent outputs hold the state + after the last row. Decoding stays on the one-token engine. + """ + if prefill_rows is not None and (export_hidden_state or feature_layers or debug_layer_outputs): + raise NotImplementedError("Qwen3.5-MoE prefill engines have no hidden-state, draft or debug outputs") + if prefill_rows is not None and not 1 <= prefill_rows <= PREFILL_MAX_TOKENS: + raise ValueError(f"Qwen3.5-MoE prefill_rows must be in 1..{PREFILL_MAX_TOKENS}") + sequence_length = None if prefill_rows else 1 hidden = config.hidden_size vocab = config.vocab_size num_layers = config.num_hidden_layers @@ -478,12 +498,30 @@ def build_engine( builder.max_threads = min(8, os.cpu_count() or 1) network = builder.create_network(1 << int(trt.NetworkDefinitionCreationFlag.STRONGLY_TYPED)) trt_config = builder.create_builder_config() - trt_config.builder_optimization_level = 1 + # Level 1 skips the INT4 dequantize-GEMM fusion, so the prefill engine's stacked GPTQ experts would be + # expanded to FP16 in memory on every launch (about 4x slower); level 2 keeps them as W4A16 GEMMs. + trt_config.builder_optimization_level = PREFILL_OPTIMIZATION_LEVEL if prefill_rows else 1 # --- Inputs --- - token_id = network.add_input("token_id", trt.int32, (1,)) - position_id = network.add_input("position_id", trt.int32, (1,)) - attention_mask = network.add_input("attention_mask", trt.float32, (1, attention_window)) + row_dim = -1 if prefill_rows else 1 + token_id = network.add_input("token_id", trt.int32, (row_dim,)) + position_id = network.add_input("position_id", trt.int32, (row_dim,)) + attention_mask = network.add_input( + "attention_mask", trt.float32, (row_dim, -1 if prefill_rows else attention_window) + ) + profile = None + if prefill_rows: + max_rows = min(prefill_rows, max_cache_length) + opt_rows = min(PREFILL_OPT_TOKENS, max_rows) + profile = builder.create_optimization_profile() + for name in ("token_id", "position_id"): + profile.set_shape(name, (1,), (opt_rows,), (max_rows,)) + profile.set_shape( + "attention_mask", + (1, max_cache_length + 1), + (opt_rows, max_cache_length + opt_rows), + (max_rows, max_cache_length + max_rows), + ) # DeltaNet state inputs (conv + ssm per DeltaNet layer) conv_state_inputs = [] @@ -573,7 +611,26 @@ def build_engine( ) rotary_position = position_id - if media_inputs: + if media_inputs and prefill_rows: + from .vision import add_mrope_prompt_rows + offsets = network.add_input("rotary_position_offsets", trt.int32, (-1, 3)) + for name, size in (("rotary_position_offsets", 3),): + profile.set_shape(name, (1, size), (opt_rows, size), (max_rows, size)) + column = network.add_shuffle(position_id) + column.reshape_dims = (-1, 1) + coordinates = network.add_elementwise( + column.get_output(0), offsets, trt.ElementWiseOperation.SUM).get_output(0) + text = config.raw.get("text_config", config.raw) + rope = text.get("rope_parameters") or text.get("rope_scaling") or {} + cos_half_tensor, sin_half_tensor = add_mrope_prompt_rows( + network, cos_half_tensor, sin_half_tensor, coordinates, + rope, rotary_embedding_dim // 2, work_np_dtype, + ) + # Row i of the per-row tables belongs to row i: positions relative to the first row. + first = network.add_slice(position_id, (0,), (1,), (1,)).get_output(0) + rotary_position = network.add_elementwise( + position_id, first, trt.ElementWiseOperation.SUB).get_output(0) + elif media_inputs: from .vision import add_mrope_rows offsets = network.add_input("rotary_position_offsets", trt.int32, (3,)) coordinates = network.add_elementwise(position_id, offsets, trt.ElementWiseOperation.SUM).get_output(0) @@ -589,10 +646,15 @@ def build_engine( gather = network.add_gather(embedding_table, token_id, 0) hidden_state = gather.get_output(0) if media_inputs: - visual = network.add_input("visual_embedding", work_trt_dtype, (1, hidden)) - selector = network.add_input("use_visual_embedding", trt.int32, (1, 1)) + visual = network.add_input("visual_embedding", work_trt_dtype, (row_dim, hidden)) + selector = network.add_input("use_visual_embedding", trt.int32, (row_dim, 1)) + if prefill_rows: + profile.set_shape("visual_embedding", (1, hidden), (opt_rows, hidden), (max_rows, hidden)) + profile.set_shape("use_visual_embedding", (1, 1), (opt_rows, 1), (max_rows, 1)) use_visual = network.add_cast(selector, trt.bool).get_output(0) hidden_state = network.add_select(use_visual, visual, hidden_state).get_output(0) + if profile is not None: + trt_config.add_optimization_profile(profile) if debug_layer_outputs: _mark_debug_output(network, hidden_state, "debug_embed") @@ -637,6 +699,7 @@ def layer_cast(tensor): head_dim=deltanet_head_dim, mlp_size=mlp_size, dtype=layer_np_dtype, + sequence_length=sequence_length, ) hidden_state = result["hidden"] present_conv_outputs.append(result["present_conv"]) @@ -668,6 +731,7 @@ def layer_cast(tensor): max_cache_length=max_cache_length, mlp_size=mlp_size, dtype=layer_np_dtype, + sequence_length=sequence_length, ) hidden_state = result["hidden"] present_k_outputs.append(result["present_k"]) @@ -691,6 +755,15 @@ def layer_cast(tensor): target_features.name = "target_hidden" network.mark_output(target_features) + if prefill_rows: + # Only the last row can affect the next token. + last = network.add_elementwise( + deltanet_rows.row_count(network, hidden_state), + graph_ops.add_constant(network, (1,), np.array([1], dtype=np.int64), dtype=np.int64), + trt.ElementWiseOperation.SUB, + ).get_output(0) + hidden_state = deltanet_rows.dynamic_slice(network, hidden_state, (last, 0), (1, hidden)) + # --- Final norm --- if hidden_state.dtype != work_trt_dtype: hidden_state = network.add_cast(hidden_state, work_trt_dtype).get_output(0) @@ -756,7 +829,11 @@ def layer_cast(tensor): file=sys.stderr, ) - plan = builder.build_serialized_network(network, trt_config) + try: + plan = builder.build_serialized_network(network, trt_config) + finally: + # The prefill graph's stacked expert copies are needed only while TensorRT builds. + weights.pop("_prefill_keep", None) if plan is None: raise RuntimeError("TensorRT engine build failed") @@ -1466,8 +1543,9 @@ def _add_deltanet_layer( head_dim: int, mlp_size: int, dtype: np.dtype = np.float32, + sequence_length: int | None = 1, ) -> dict[str, trt.ITensor]: - """Add one Gated DeltaNet layer (single-step decode). + """Add one Gated DeltaNet layer over one row, or ``S`` rows when ``sequence_length`` is None. DeltaNet uses delta-rule linear attention with: - Conv1d on QKV projection output @@ -1479,8 +1557,6 @@ def _add_deltanet_layer( Returns: {hidden, present_conv, present_ssm} """ - qk_dim = num_kv_heads * head_dim # Q and K dimension before Compact GQA/MQA K/V - # ===== 1. RMSNorm ===== normed = graph_ops.add_rms_norm( network, hidden, hidden_size, weights[f"{prefix}.input_norm"], eps_tensor, dtype=dtype @@ -1512,6 +1588,149 @@ def _add_deltanet_layer( network, normed, hidden_size, num_heads, weights[f"{prefix}.deltanet_b_proj"], dtype=dtype ) + mixer = _add_deltanet_mixer_rows if sequence_length is None else _add_deltanet_mixer_step + mixer_output, present_conv, present_ssm = mixer( + network, + qkv=qkv, + a_raw=a_raw, + b_raw=b_raw, + conv_state_in=conv_state_in, + ssm_state_in=ssm_state_in, + weights=weights, + prefix=prefix, + d_inner=d_inner, + d_conv=d_conv, + conv_dim=conv_dim, + num_heads=num_heads, + num_kv_heads=num_kv_heads, + head_dim=head_dim, + dtype=dtype, + ) + + # ===== 10. Gated RMSNorm per-head: weight * norm(output) * silu(z) ===== + # The reference recurrent kernel returns the attention output in the model + # storage dtype before Qwen3_5RMSNormGated casts it back to FP32. + recurrent_output = mixer_output + rows = 1 if sequence_length is not None else -1 + head_shape = (num_heads, head_dim) if sequence_length is not None else (-1, num_heads, head_dim) + if recurrent_output.dtype != hidden.dtype: + recurrent_output = network.add_cast(recurrent_output, hidden.dtype).get_output(0) + + # HF norm operates per head_v_dim: reshape to [num_heads, head_dim], norm, reshape back + deltanet_norm_w = weights[f"{prefix}.deltanet_norm"] + # Use same eps as HF Qwen3_5RMSNormGated (config.rms_norm_eps = 1e-6) + eps_small = graph_ops.add_constant( + network, (1, 1), np.array([1e-6], dtype=np.float32), dtype=np.float32 + ) + + # Reshape output and z to [num_heads, head_dim] for per-head norm + output_heads = network.add_shuffle(recurrent_output) + output_heads.reshape_dims = head_shape + norm_input = output_heads.get_output(0) + norm_output_dtype = norm_input.dtype + if dtype != np.float32: + norm_input = network.add_cast(norm_input, trt.float32).get_output(0) + + # Per-head RMSNorm: norm each head independently + sq = network.add_elementwise(norm_input, norm_input, trt.ElementWiseOperation.PROD) + head_axis = len(head_shape) - 1 + mean = network.add_reduce( + sq.get_output(0), trt.ReduceOperation.AVG, 1 << head_axis, keep_dims=True + ) + if head_axis == 2: + eps_small = network.add_shuffle(eps_small) + eps_small.reshape_dims = (1, 1, 1) + eps_small = eps_small.get_output(0) + denom_in = network.add_elementwise(mean.get_output(0), eps_small, trt.ElementWiseOperation.SUM) + sqrt_l = network.add_unary(denom_in.get_output(0), trt.UnaryOperation.SQRT) + recip = network.add_unary(sqrt_l.get_output(0), trt.UnaryOperation.RECIP) + normalized = network.add_elementwise( + norm_input, recip.get_output(0), trt.ElementWiseOperation.PROD + ) + + # Reshape back and apply weight + norm_flat = network.add_shuffle(normalized.get_output(0)) + norm_flat.reshape_dims = (rows, d_inner) + gamma_t = graph_ops.add_constant(network, (1, d_inner), deltanet_norm_w, dtype=np.float32) + normed_output = network.add_elementwise( + norm_flat.get_output(0), gamma_t, trt.ElementWiseOperation.PROD + ) + normed_output_tensor = normed_output.get_output(0) + if normed_output_tensor.dtype != norm_output_dtype: + normed_output_tensor = network.add_cast(normed_output_tensor, norm_output_dtype).get_output( + 0 + ) + + # Gate: multiply by silu(z) + z_activated = graph_ops.add_activation(network, z, "silu", dtype=dtype) + gated = network.add_elementwise( + normed_output_tensor, z_activated, trt.ElementWiseOperation.PROD + ) + + # ===== 11. Output projection + residual ===== + out = graph_ops.add_matmul_rhs_constant( + network, + gated.get_output(0), + d_inner, + hidden_size, + weights[f"{prefix}.deltanet_out_proj"], + dtype=dtype, + ) + + residual = network.add_elementwise(hidden, out, trt.ElementWiseOperation.SUM) + hidden_after_attn = residual.get_output(0) + + # ===== 12. Post-attention norm + SwiGLU MLP + residual ===== + post_normed = graph_ops.add_rms_norm( + network, + hidden_after_attn, + hidden_size, + weights[f"{prefix}.post_attn_norm"], + eps_tensor, + dtype=dtype, + ) + + mlp_out = graph_blocks.add_sparse_mlp( + network, + post_normed, + weights=weights, + prefix=prefix, + hidden_size=hidden_size, + mlp_size=mlp_size, + dtype=dtype, + rows=sequence_length is None, + ) + + mlp_residual = network.add_elementwise(hidden_after_attn, mlp_out, trt.ElementWiseOperation.SUM) + + return { + "hidden": mlp_residual.get_output(0), + "present_conv": present_conv, + "present_ssm": present_ssm, + } + + +def _add_deltanet_mixer_step( + network: trt.INetworkDefinition, + *, + qkv: trt.ITensor, + a_raw: trt.ITensor, + b_raw: trt.ITensor, + conv_state_in: trt.ITensor, + ssm_state_in: trt.ITensor, + weights: WeightDict, + prefix: str, + d_inner: int, + d_conv: int, + conv_dim: int, + num_heads: int, + num_kv_heads: int, + head_dim: int, + dtype: np.dtype, +) -> tuple[trt.ITensor, trt.ITensor, trt.ITensor]: + """Conv step and delta-rule update for one token: ``(output [1, d_inner], conv, ssm)``.""" + qk_dim = num_kv_heads * head_dim # Q and K dimension before Compact GQA/MQA K/V + # ===== 3. Conv1d step on QKV ===== # conv_state_in: [conv_dim, d_conv] # qkv: [1, conv_dim] -> [conv_dim, 1] @@ -1722,97 +1941,132 @@ def recurrent_cast(tensor: trt.ITensor) -> trt.ITensor: output_flat = network.add_shuffle(output_3d.get_output(0)) output_flat.reshape_dims = (1, d_inner) - # ===== 10. Gated RMSNorm per-head: weight * norm(output) * silu(z) ===== - # The reference recurrent kernel returns the attention output in the model - # storage dtype before Qwen3_5RMSNormGated casts it back to FP32. - recurrent_output = output_flat.get_output(0) - if recurrent_output.dtype != hidden.dtype: - recurrent_output = network.add_cast(recurrent_output, hidden.dtype).get_output(0) + return output_flat.get_output(0), present_conv, present_ssm - # HF norm operates per head_v_dim: reshape to [num_heads, head_dim], norm, reshape back - deltanet_norm_w = weights[f"{prefix}.deltanet_norm"] - # Use same eps as HF Qwen3_5RMSNormGated (config.rms_norm_eps = 1e-6) - eps_small = graph_ops.add_constant( - network, (1, 1), np.array([1e-6], dtype=np.float32), dtype=np.float32 - ) - # Reshape output and z to [num_heads, head_dim] for per-head norm - output_heads = network.add_shuffle(recurrent_output) - output_heads.reshape_dims = (num_heads, head_dim) - norm_input = output_heads.get_output(0) - norm_output_dtype = norm_input.dtype - if dtype != np.float32: - norm_input = network.add_cast(norm_input, trt.float32).get_output(0) +def _add_deltanet_mixer_rows( + network: trt.INetworkDefinition, + *, + qkv: trt.ITensor, + a_raw: trt.ITensor, + b_raw: trt.ITensor, + conv_state_in: trt.ITensor, + ssm_state_in: trt.ITensor, + weights: WeightDict, + prefix: str, + d_inner: int, + d_conv: int, + conv_dim: int, + num_heads: int, + num_kv_heads: int, + head_dim: int, + dtype: np.dtype, +) -> tuple[trt.ITensor, trt.ITensor, trt.ITensor]: + """Conv and delta rule over ``S`` rows in one launch: ``(output [S, d_inner], conv, ssm)``. - # Per-head RMSNorm: norm each head independently - sq = network.add_elementwise(norm_input, norm_input, trt.ElementWiseOperation.PROD) - mean = network.add_reduce(sq.get_output(0), trt.ReduceOperation.AVG, 1 << 1, keep_dims=True) - denom_in = network.add_elementwise(mean.get_output(0), eps_small, trt.ElementWiseOperation.SUM) - sqrt_l = network.add_unary(denom_in.get_output(0), trt.UnaryOperation.SQRT) - recip = network.add_unary(sqrt_l.get_output(0), trt.UnaryOperation.RECIP) - normalized = network.add_elementwise( - norm_input, recip.get_output(0), trt.ElementWiseOperation.PROD - ) + Same arithmetic as :func:`_add_deltanet_mixer_step` applied token by token; + the recurrence runs as one chunk (see :mod:`.deltanet_rows`). + """ + qk_dim = num_kv_heads * head_dim - # Reshape back and apply weight - norm_flat = network.add_shuffle(normalized.get_output(0)) - norm_flat.reshape_dims = (1, d_inner) - gamma_t = graph_ops.add_constant(network, (1, d_inner), deltanet_norm_w, dtype=np.float32) - normed_output = network.add_elementwise( - norm_flat.get_output(0), gamma_t, trt.ElementWiseOperation.PROD - ) - normed_output_tensor = normed_output.get_output(0) - if normed_output_tensor.dtype != norm_output_dtype: - normed_output_tensor = network.add_cast(normed_output_tensor, norm_output_dtype).get_output( - 0 - ) + def shuffle(tensor, reshape=None, transpose=None): + layer = network.add_shuffle(tensor) + if transpose is not None: + layer.first_transpose = transpose + if reshape is not None: + layer.reshape_dims = reshape + return layer.get_output(0) - # Gate: multiply by silu(z) - z_activated = graph_ops.add_activation(network, z, "silu", dtype=dtype) - gated = network.add_elementwise( - normed_output_tensor, z_activated, trt.ElementWiseOperation.PROD - ) + def fp32(tensor): + return tensor if tensor.dtype == trt.float32 else network.add_cast(tensor, trt.float32).get_output(0) - # ===== 11. Output projection + residual ===== - out = graph_ops.add_matmul_rhs_constant( + conv_w = graph_ops.add_constant( + network, (conv_dim, d_conv), weights[f"{prefix}.conv1d_weight"], dtype=dtype + ) + conv_columns, present_conv = deltanet_rows.add_short_conv_rows( network, - gated.get_output(0), - d_inner, - hidden_size, - weights[f"{prefix}.deltanet_out_proj"], - dtype=dtype, + columns=shuffle(qkv, transpose=(1, 0)), + conv_state=conv_state_in, + weight=conv_w, + channels=conv_dim, + kernel=d_conv, + ) + conv_out = graph_ops.add_bias_sum( + network, shuffle(conv_columns, transpose=(1, 0)), conv_dim, + weights[f"{prefix}.conv1d_bias"], dtype=dtype, ) + activated = graph_ops.add_activation(network, conv_out, "silu", dtype=dtype) + rows = deltanet_rows.row_count(network, activated) - residual = network.add_elementwise(hidden, out, trt.ElementWiseOperation.SUM) - hidden_after_attn = residual.get_output(0) + def columns(offset, width): + return deltanet_rows.dynamic_slice(network, activated, (0, offset), (rows, width)) - # ===== 12. Post-attention norm + SwiGLU MLP + residual ===== - post_normed = graph_ops.add_rms_norm( - network, - hidden_after_attn, - hidden_size, - weights[f"{prefix}.post_attn_norm"], - eps_tensor, - dtype=dtype, + q_normed = graph_ops.add_l2_norm( + network, shuffle(columns(0, qk_dim), reshape=(-1, num_kv_heads, head_dim)), 2, + eps=1e-6, dtype=dtype, ) - - mlp_out = graph_blocks.add_sparse_mlp( - network, - post_normed, - weights=weights, - prefix=prefix, - hidden_size=hidden_size, - mlp_size=mlp_size, - dtype=dtype, + k_normed = graph_ops.add_l2_norm( + network, shuffle(columns(qk_dim, qk_dim), reshape=(-1, num_kv_heads, head_dim)), 2, + eps=1e-6, dtype=dtype, ) + heads_per_group = num_heads // num_kv_heads - mlp_residual = network.add_elementwise(hidden_after_attn, mlp_out, trt.ElementWiseOperation.SUM) + def expand_heads(tensor): + # [S, kv_heads, D] -> [S, heads, D], head = kv_head * heads_per_group + g. + if heads_per_group == 1: + return tensor + tile = graph_ops.add_constant( + network, (1, 1, heads_per_group, 1), + np.ones((1, 1, heads_per_group, 1), dtype=dtype), dtype=dtype, + ) + tiled = network.add_elementwise( + shuffle(tensor, reshape=(-1, num_kv_heads, 1, head_dim)), tile, + trt.ElementWiseOperation.PROD, + ).get_output(0) + return shuffle(tiled, reshape=(-1, num_heads, head_dim)) - return { - "hidden": mlp_residual.get_output(0), - "present_conv": present_conv, - "present_ssm": present_ssm, - } + def head_major(tensor): + return shuffle(fp32(tensor), transpose=(1, 0, 2)) # [H, S, D] + + q_scale = graph_ops.add_constant( + network, (1, 1, 1), np.array([[[1.0 / np.sqrt(head_dim)]]], dtype=np.float32), + dtype=np.float32, + ) + q_heads = network.add_elementwise( + head_major(expand_heads(q_normed)), q_scale, trt.ElementWiseOperation.PROD + ).get_output(0) + k_heads = head_major(expand_heads(k_normed)) + v_heads = head_major(shuffle(columns(2 * qk_dim, d_inner), reshape=(-1, num_heads, head_dim))) + + # Decay g = A * softplus(a + dt_bias) and beta = sigmoid(b), FP32, [H, S]. + a_const = graph_ops.add_constant(network, (1, num_heads), weights[f"{prefix}.A"], dtype=np.float32) + dt_bias = graph_ops.add_constant( + network, (1, num_heads), weights[f"{prefix}.dt_bias"], dtype=np.float32 + ) + biased = network.add_elementwise(fp32(a_raw), dt_bias, trt.ElementWiseOperation.SUM).get_output(0) + one = graph_ops.add_constant(network, (1, 1), np.array([1.0], dtype=np.float32), dtype=np.float32) + softplus = network.add_unary( + network.add_elementwise( + network.add_unary(biased, trt.UnaryOperation.EXP).get_output(0), one, + trt.ElementWiseOperation.SUM, + ).get_output(0), + trt.UnaryOperation.LOG, + ).get_output(0) + decay = network.add_elementwise(a_const, softplus, trt.ElementWiseOperation.PROD).get_output(0) + beta = fp32(network.add_activation(b_raw, trt.ActivationType.SIGMOID).get_output(0)) + + outputs, present_ssm = deltanet_rows.add_chunked_delta_rule( + network, + q=q_heads, + k=k_heads, + v=v_heads, + g=shuffle(decay, transpose=(1, 0)), + beta=shuffle(beta, transpose=(1, 0)), + state=fp32(ssm_state_in), + num_heads=num_heads, + head_dim=head_dim, + ) + return shuffle(outputs, transpose=(1, 0, 2), reshape=(-1, d_inner)), present_conv, present_ssm def _add_grouped_attention(network, q, k, v, mask, num_heads, kv_heads, head_dim, window): @@ -1853,6 +2107,53 @@ def cast(tensor, dtype): return reshape(cast(context, work_dtype), (1, num_heads * head_dim)) +def _add_grouped_attention_rows(network, q, k, v, mask, num_heads, kv_heads, head_dim): + """Grouped attention of ``S`` query rows over the cache plus their own rows (prefill). + + Same arithmetic as :func:`_add_grouped_attention`: compute-dtype Q pre-scale, FP32 scores and + softmax, FP32 context. ``mask`` is ``[S, cache + S]`` and holds the causal prefix of every row. + """ + def reshape(tensor, shape): + layer = network.add_shuffle(tensor) + layer.reshape_dims = shape + return layer.get_output(0) + + def transpose(tensor, order): + layer = network.add_shuffle(tensor) + layer.first_transpose = order + return layer.get_output(0) + + def cast(tensor, dtype): + return tensor if tensor.dtype == dtype else network.add_cast(tensor, dtype).get_output(0) + + work_dtype = q.dtype + groups = num_heads // kv_heads + scale = graph_ops.add_constant(network, (1, 1, 1), np.array([[[head_dim ** -0.5]]], np.float32)) + queries = network.add_elementwise(reshape(q, (-1, num_heads, head_dim)), cast(scale, work_dtype), + trt.ElementWiseOperation.PROD).get_output(0) + # [S, H, D] -> [kv, g, S, D]; keys/values [W, kv, D] -> [kv, 1, W, D]. + queries = transpose(reshape(queries, (-1, kv_heads, groups, head_dim)), (1, 2, 0, 3)) + keys = transpose(reshape(k, (-1, kv_heads, 1, head_dim)), (1, 2, 0, 3)) + values = transpose(reshape(v, (-1, kv_heads, 1, head_dim)), (1, 2, 0, 3)) + scores = network.add_matrix_multiply(cast(queries, trt.float32), trt.MatrixOperation.NONE, + cast(keys, trt.float32), trt.MatrixOperation.TRANSPOSE).get_output(0) + # [S, W] -> [1, 1, S, W]: both sizes are runtime dimensions. + mask_shape = network.add_concatenation([ + graph_ops.add_constant(network, (2,), np.ones(2, np.int64), dtype=np.int64), + network.add_shape(mask).get_output(0), + ]).get_output(0) + mask_4d = network.add_shuffle(cast(mask, trt.float32)) + mask_4d.set_input(1, mask_shape) + scores = network.add_elementwise(scores, mask_4d.get_output(0), trt.ElementWiseOperation.SUM).get_output(0) + softmax = network.add_softmax(scores) + softmax.axes = 1 << 3 + probabilities = cast(softmax.get_output(0), work_dtype) + context = network.add_matrix_multiply(cast(probabilities, trt.float32), trt.MatrixOperation.NONE, + cast(values, trt.float32), trt.MatrixOperation.NONE).get_output(0) + # [kv, g, S, D] -> [S, kv, g, D] -> [S, H * D] + return reshape(transpose(cast(context, work_dtype), (2, 0, 1, 3)), (-1, num_heads * head_dim)) + + def _add_full_attention_layer( *, network: trt.INetworkDefinition, @@ -1876,6 +2177,7 @@ def _add_full_attention_layer( max_cache_length: int, mlp_size: int, dtype: np.dtype = np.float32, + sequence_length: int | None = 1, ) -> dict[str, trt.ITensor]: """Add one full self-attention layer with output gating. @@ -1885,9 +2187,13 @@ def _add_full_attention_layer( - Output gating: context * sigmoid(gate) BEFORE o_proj - SwiGLU MLP after attention + ``sequence_length`` None runs ``S`` runtime rows over the cache plus their own causal prefix + (prefill); the attention mask is then ``[S, cache + S]``. + Returns: {hidden, present_k, present_v} """ attention_window = max_cache_length + 1 + rows = -1 if sequence_length is None else sequence_length # Pre-attention norm normed = graph_blocks.apply_norm( @@ -1916,12 +2222,14 @@ def _add_full_attention_layer( q_norm = weights.get(f"{prefix}.q_norm") if q_norm is not None: q = graph_ops.add_rms_norm_per_head( - network, q, num_heads, head_dim, q_norm, eps_tensor, dtype=dtype + network, q, num_heads, head_dim, q_norm, eps_tensor, dtype=dtype, + sequence_length=sequence_length, ) k_norm = weights.get(f"{prefix}.k_norm") if k_norm is not None: k = graph_ops.add_rms_norm_per_head( - network, k, num_kv_heads, head_dim, k_norm, eps_tensor, dtype=dtype + network, k, num_kv_heads, head_dim, k_norm, eps_tensor, dtype=dtype, + sequence_length=sequence_length, ) # Native RoPE @@ -1934,6 +2242,7 @@ def _add_full_attention_layer( sin_half_tensor, position_id, rotary_embedding_dim, + sequence_length=sequence_length, ) k = graph_ops.add_apply_rope_native( network, @@ -1944,6 +2253,7 @@ def _add_full_attention_layer( sin_half_tensor, position_id, rotary_embedding_dim, + sequence_length=sequence_length, ) # Q stays in compute precision for one-token decoding. K/V are stored @@ -1957,9 +2267,9 @@ def _add_full_attention_layer( # Reshape K, V for concatenation k_reshape = network.add_shuffle(k) - k_reshape.reshape_dims = (1, kv_attention_size) + k_reshape.reshape_dims = (rows, kv_attention_size) v_reshape = network.add_shuffle(v) - v_reshape.reshape_dims = (1, kv_attention_size) + v_reshape.reshape_dims = (rows, kv_attention_size) # Concatenate with cache all_k = network.add_concatenation([cache_k, k_reshape.get_output(0)]) @@ -1967,11 +2277,17 @@ def _add_full_attention_layer( all_v = network.add_concatenation([cache_v, v_reshape.get_output(0)]) all_v.axis = 0 - mask_4d = graph_ops.add_2d_mask_to_4d(network, attention_mask) - context_flat = _add_grouped_attention( - network, q, all_k.get_output(0), all_v.get_output(0), mask_4d, - num_heads, num_kv_heads, head_dim, attention_window, - ) + if sequence_length is None: + context_flat = _add_grouped_attention_rows( + network, q, all_k.get_output(0), all_v.get_output(0), attention_mask, + num_heads, num_kv_heads, head_dim, + ) + else: + mask_4d = graph_ops.add_2d_mask_to_4d(network, attention_mask) + context_flat = _add_grouped_attention( + network, q, all_k.get_output(0), all_v.get_output(0), mask_4d, + num_heads, num_kv_heads, head_dim, attention_window, + ) # Gate: applied BEFORE o_proj (HF order) gate_attn_w = weights.get(f"{prefix}.w_gate_attn") @@ -2012,6 +2328,7 @@ def _add_full_attention_layer( hidden_size=hidden_size, mlp_size=mlp_size, dtype=dtype, + rows=sequence_length is None, ) mlp_residual = network.add_elementwise(hidden_after_attn, mlp_out, trt.ElementWiseOperation.SUM) @@ -2061,6 +2378,51 @@ def _runtime_config(model_dir: Path, config: ModelConfig, model: _Qwen35MoeModel +# Share of GPU memory that the decode and prefill engines' weights may take together. +_TWO_ENGINE_MEMORY_FRACTION = 0.8 + + +def _two_engines_fit(weight_bytes: int, gpu_bytes: int | None) -> bool: + """Whether the prefill engine, which carries its own copy of every weight, fits beside the decode engine. + + Without it, prompts run through the decode engine one token at a time (the bundle stays loadable). An + unknown GPU capacity keeps that single-engine layout. + """ + if gpu_bytes is None: + print("Skipping the prefill engine: the GPU memory could not be queried", file=sys.stderr) + return False + if 2 * weight_bytes <= gpu_bytes * _TWO_ENGINE_MEMORY_FRACTION: + return True + print(f"Skipping the prefill engine: the decode and prefill engines need about {2 * weight_bytes / 1024**3:.0f} " + f"GiB of weights and the GPU has {gpu_bytes / 1024**3:.0f} GiB; prompts run through the decode engine", + file=sys.stderr) + return False + + +def _checkpoint_bytes(model_dir: Path) -> int: + """Size of the checkpoint's weight files: what each engine carries, packed experts included.""" + return sum(path.stat().st_size for path in Path(model_dir).glob("*.safetensors")) + + +def _dense_prefill_experts(weights) -> bool: + """Whether every MoE layer's routed experts can run as dense W4A16 GEMMs over prefill rows (GPTQ).""" + from .moe import MoEWeights, dense_rows_supported + + layers = [value for value in weights.values() if isinstance(value, MoEWeights)] + return bool(layers) and all(dense_rows_supported(layer) for layer in layers) + + +def _gpu_memory_bytes() -> int | None: + """Total memory of the current CUDA device, or None when no device can be queried.""" + try: + import torch + except ImportError: + return None + if not torch.cuda.is_available(): + return None + return int(torch.cuda.get_device_properties(torch.cuda.current_device()).total_memory) + + def _build_native(request: "BuildRequest", writer: "BundleWriter", *, require_mtp: bool = False, draft_dir: Path | None = None, draft_variant: str = "dflash") -> None: """Build one Qwen3.5-MoE hybrid bundle through family-owned code only.""" @@ -2143,6 +2505,10 @@ def _build_native(request: "BuildRequest", writer: "BundleWriter", *, require_mt compact_fp16=precision == "fp16") if require_mtp: model._load_mtp_weights(readers, weights, config) + # Single-GPU GPTQ bundles add an engine that prefills the prompt (text and media rows) in chunks. + split = (not require_mtp and draft_config is None and int(request.tensor_parallel_size or 1) == 1 + and _dense_prefill_experts(weights) + and _two_engines_fit(_checkpoint_bytes(model_dir), _gpu_memory_bytes())) plan = model.build_engine( config, weights, @@ -2157,6 +2523,11 @@ def _build_native(request: "BuildRequest", writer: "BundleWriter", *, require_mt writer.add_bytes("engine.plan", plan) del plan # The section is staged; do not retain a full plan during the next build. + if split: + writer.add_bytes("prefill.plan", model.build_engine( + config, weights, max_sequence_length, precision=precision, + verbose=bool(request.verbose), media_inputs=visual, prefill_rows=PREFILL_MAX_TOKENS, + )) if require_mtp: # Preserve the admitted three draft steps plus one target anchor. writer.add_bytes("mtp_engine.plan", model.build_mtp_engine( @@ -2201,7 +2572,7 @@ def _build_native(request: "BuildRequest", writer: "BundleWriter", *, require_mt model, precision=precision, max_cache_length=max_sequence_length, - decoder_engine_layout="single", + decoder_engine_layout="split" if split else "single", **({"has_mtp": True, "mtp_num_draft_tokens": 3} if require_mtp else {}), **({"kv_cache_quantization": "fp8"} if weights.get("_fp8_kv_cache", False) else {}), ), diff --git a/families/qwen3_5_moe/runtime/hybrid_state.cpp b/families/qwen3_5_moe/runtime/hybrid_state.cpp index f46865fa6b..e0d13ee518 100644 --- a/families/qwen3_5_moe/runtime/hybrid_state.cpp +++ b/families/qwen3_5_moe/runtime/hybrid_state.cpp @@ -32,6 +32,18 @@ void Qwen35MoeHybridState::advance(int32_t n_tokens) { ssm_->advance(n_tokens); } +void Qwen35MoeHybridState::bind_prefill(ITrtModule& module) { + // The prefill context reads the shared caches and recurrent state; its + // present K/V rows stay in its own buffers until commit_prefill(). + kv_->bind_cache_inputs(module); + ssm_->bind_to(module); +} + +void Qwen35MoeHybridState::commit_prefill(ITrtModule& module, int32_t rows) { + kv_->append_prefill_from(module, rows); + ssm_->advance(rows); +} + int32_t Qwen35MoeHybridState::position() const { return kv_->position(); } diff --git a/families/qwen3_5_moe/runtime/hybrid_state.h b/families/qwen3_5_moe/runtime/hybrid_state.h index 174e335695..a12badc1ee 100644 --- a/families/qwen3_5_moe/runtime/hybrid_state.h +++ b/families/qwen3_5_moe/runtime/hybrid_state.h @@ -22,6 +22,8 @@ class Qwen35MoeHybridState final : public Qwen35MoeInferenceState { void bind_to(ITrtModule& module) override; void prepare_step(TensorMap& inputs, int32_t seq_len = 1) override; void advance(int32_t n_tokens = 1) override; + void bind_prefill(ITrtModule& module) override; + void commit_prefill(ITrtModule& module, int32_t rows) override; int32_t position() const override; int32_t max_length() const override; int32_t num_layers() const override; diff --git a/families/qwen3_5_moe/runtime/inference_state.h b/families/qwen3_5_moe/runtime/inference_state.h index 7a167a127d..bcf5c1f709 100644 --- a/families/qwen3_5_moe/runtime/inference_state.h +++ b/families/qwen3_5_moe/runtime/inference_state.h @@ -28,6 +28,7 @@ #include #include +#include namespace trtmc { @@ -69,6 +70,20 @@ class Qwen35MoeInferenceState { // State types that do not distinguish the phases can ignore this. virtual void mark_prefill_complete() {} + // Bind a multi-row prefill context (a second profile of the decoder + // engine) to the same caches and recurrent state as bind_to(). + virtual void bind_prefill(ITrtModule& module) { + (void)module; + throw std::runtime_error("this Qwen3.5 state does not support batched prefill"); + } + + // Commit the `rows` tokens a bind_prefill() context just processed. + virtual void commit_prefill(ITrtModule& module, int32_t rows) { + (void)module; + (void)rows; + throw std::runtime_error("this Qwen3.5 state does not support batched prefill"); + } + // --- Queries --- // Current sequence position (0 = empty, increments with advance()). diff --git a/families/qwen3_5_moe/runtime/kv_cache.cpp b/families/qwen3_5_moe/runtime/kv_cache.cpp index 2eb374d66e..0524999ed4 100644 --- a/families/qwen3_5_moe/runtime/kv_cache.cpp +++ b/families/qwen3_5_moe/runtime/kv_cache.cpp @@ -250,6 +250,19 @@ void Qwen35MoeKvCache::append_prefill_kv(const std::vector& prefill position_ += seq_len; } +void Qwen35MoeKvCache::append_prefill_from(const ITrtModule& module, int32_t seq_len) { + std::vector keys(static_cast(num_layers_)); + std::vector values(static_cast(num_layers_)); + for (int32_t i = 0; i < num_layers_; ++i) { + const auto layer = static_cast(i); + keys[layer] = module.device_ptr(names_.present_k[layer]); + values[layer] = module.device_ptr(names_.present_v[layer]); + if (keys[layer] == nullptr || values[layer] == nullptr) + throw std::runtime_error("qwen3_5_moe prefill context has no present K/V output"); + } + append_prefill_kv(keys, values, seq_len); +} + void Qwen35MoeKvCache::set_position(int32_t position) { position_ = std::max(0, std::min(position, max_length_)); } diff --git a/families/qwen3_5_moe/runtime/kv_cache.h b/families/qwen3_5_moe/runtime/kv_cache.h index 434a49587d..cf5301362a 100644 --- a/families/qwen3_5_moe/runtime/kv_cache.h +++ b/families/qwen3_5_moe/runtime/kv_cache.h @@ -80,6 +80,9 @@ class Qwen35MoeKvCache : public Qwen35MoeInferenceState { void append_prefill_kv(const std::vector& prefill_k, const std::vector& prefill_v, int32_t seq_len); + // Append the first `seq_len` present K/V rows a prefill context produced. + void append_prefill_from(const ITrtModule& module, int32_t seq_len); + // Move the logical cache length without touching device memory. Stale rows // remain masked out by subsequent prepare_step calls. void set_position(int32_t position); diff --git a/families/qwen3_5_moe/runtime/pipeline.cpp b/families/qwen3_5_moe/runtime/pipeline.cpp index e488e47cd4..599f4f6264 100644 --- a/families/qwen3_5_moe/runtime/pipeline.cpp +++ b/families/qwen3_5_moe/runtime/pipeline.cpp @@ -31,14 +31,26 @@ RecurrentPipeline::RecurrentPipeline(std::unique_ptr decoder, const char* name, std::shared_ptr tokenizer, std::string model_id_str, std::unique_ptr mtp_scheduler, - std::unique_ptr paired_draft) + std::unique_ptr paired_draft, + std::unique_ptr prefill) : decoder_(std::move(decoder)), state_(std::move(state)), config_(config), stream_(stream), name_(name), tokenizer_(std::move(tokenizer)), model_id_(std::move(model_id_str)), - mtp_scheduler_(std::move(mtp_scheduler)), paired_draft_(std::move(paired_draft)) { + mtp_scheduler_(std::move(mtp_scheduler)), paired_draft_(std::move(paired_draft)), + prefill_(std::move(prefill)) { if (mtp_scheduler_ && paired_draft_) throw std::runtime_error("Qwen3.5-MoE cannot combine MTP and external draft schedulers"); if (!decoder_ || !decoder_->ok()) throw std::runtime_error(std::string(name_) + ": invalid decoder module"); + if (prefill_) { + if (!prefill_->ok() || mtp_scheduler_ || paired_draft_) + throw std::runtime_error(std::string(name_) + + ": batched prefill needs a plain decoder"); + const auto rows = prefill_->input_profile_shape("token_id", prefill_->profile_idx(), + ProfileShapeSelector::kMax); + if (rows.size() != 1 || rows[0] < 1) + throw std::runtime_error(std::string(name_) + ": invalid prefill token profile"); + prefill_rows_ = static_cast(std::min(rows[0], state_->max_length())); + } // Inspect declared inputs rather than optional Edge metadata. Older text // bundles remain loadable and never receive media-only bindings. int media_bindings = 0; @@ -74,6 +86,12 @@ RecurrentPipeline::RecurrentPipeline(std::unique_ptr decoder, (media_inputs_ && (mtp_scheduler_->media_dtype() != media_dtype_ || mtp_scheduler_->hidden_size() != media_hidden_size_)))) throw std::runtime_error("Qwen3.5-MoE MTP and target media inputs disagree"); + // A media decoder's prefill engine takes the same media inputs per row. + if (prefill_ && media_inputs_ != (prefill_->has_input("visual_embedding") && + prefill_->has_input("use_visual_embedding") && + prefill_->has_input("rotary_position_offsets"))) + throw std::runtime_error(std::string(name_) + + ": prefill and decoder engines disagree on media inputs"); } static std::vector encode_prompt(const ITokenizer& tokenizer, @@ -215,10 +233,14 @@ std::vector RecurrentPipeline::generate_from_ids(const std::vector(input_ids.size()) <= state_->max_length()) { + run_prefill_chunks(input_ids, logits); + } else { + for (const auto token : input_ids) + run_step(token, logits); + } auto t_prefill_end = SteadyClock::now(); // ── Decode phase ── @@ -458,6 +480,85 @@ void RecurrentPipeline::report_timing(SteadyClock::time_point t_prefill_start, } } +void RecurrentPipeline::run_prefill_chunks(const std::vector& input_ids, + std::vector& logits) { + const auto total = static_cast(input_ids.size()); + state_->bind_prefill(*prefill_); + // Per-row media inputs of one chunk (forward_async copies them before it returns). + std::vector visual; + std::vector use_visual; + std::vector offsets; + try { + for (int32_t start = 0; start < total; start += prefill_rows_) { + const int32_t rows = std::min(prefill_rows_, total - start); + TensorMap inputs; + inputs["token_id"] = + Tensor{const_cast(input_ids.data() + start), {rows}, DType::kInt32}; + state_->prepare_step(inputs, rows); + if (media_inputs_) + prepare_prefill_media(inputs, start, rows, visual, use_visual, offsets); + prefill_->forward_async(inputs); + state_->commit_prefill(*prefill_, rows); + } + } catch (...) { + // Queued chunks may still read the request's tokens: drain them before the error + // releases the request. A failure of the drain must not replace the original error. + try { + prefill_->sync(); + } catch (...) { + } + throw; + } + prefill_->sync(); + const auto* device_logits = prefill_->device_ptr("logits"); + if (device_logits == nullptr) + throw std::runtime_error(std::string(name_) + ": prefill context has no logits output"); + logits.resize(static_cast(config_.vocab_size)); + const cudaError_t copied = cudaMemcpy(logits.data(), device_logits, + logits.size() * sizeof(float), cudaMemcpyDeviceToHost); + if (copied != cudaSuccess) + throw std::runtime_error(std::string(name_) + + ": failed to copy prefill logits: " + cudaGetErrorString(copied)); +} + +void RecurrentPipeline::prepare_prefill_media(TensorMap& inputs, int32_t start, int32_t rows, + std::vector& visual, + std::vector& use_visual, + std::vector& offsets) const { + // Row i of the chunk is prompt position start + i: the same inputs run_step() gives that token. + const std::size_t row_bytes = zero_visual_.size(); + visual.assign(static_cast(rows) * row_bytes, 0); + use_visual.assign(static_cast(rows), 0); + offsets.assign(static_cast(rows) * 3, 0); + for (int32_t i = 0; i < rows; ++i) { + const auto position = static_cast(start + i); + const auto row = static_cast(i); + if (media_prompt_ == nullptr) + continue; + const auto& prompt = *media_prompt_; + if (position < prompt.positions.size()) { + for (std::size_t axis = 0; axis < 3; ++axis) + offsets[row * 3 + axis] = + prompt.positions[position][axis] - static_cast(position); + const auto feature = prompt.feature_rows[position]; + if (feature >= 0) { + use_visual[row] = 1; + std::memcpy(visual.data() + row * row_bytes, + prompt.features.data() + static_cast(feature) * row_bytes, + row_bytes); + } + } else { + const auto shift = + prompt.decode_position - static_cast(prompt.positions.size()); + for (std::size_t axis = 0; axis < 3; ++axis) + offsets[row * 3 + axis] = shift; + } + } + inputs["visual_embedding"] = Tensor{visual.data(), {rows, media_hidden_size_}, media_dtype_}; + inputs["use_visual_embedding"] = Tensor{use_visual.data(), {rows, 1}, DType::kInt32}; + inputs["rotary_position_offsets"] = Tensor{offsets.data(), {rows, 3}, DType::kInt32}; +} + void RecurrentPipeline::run_step(int32_t token_id, std::vector& logits, std::vector* hidden_state_out) { auto t0 = SteadyClock::now(); diff --git a/families/qwen3_5_moe/runtime/pipeline.h b/families/qwen3_5_moe/runtime/pipeline.h index 441d9ee67b..560e627df6 100644 --- a/families/qwen3_5_moe/runtime/pipeline.h +++ b/families/qwen3_5_moe/runtime/pipeline.h @@ -53,7 +53,8 @@ class RecurrentPipeline final : public ITextGeneration { std::shared_ptr tokenizer = nullptr, std::string model_id_str = "", std::unique_ptr mtp_scheduler = nullptr, - std::unique_ptr paired_draft = nullptr); + std::unique_ptr paired_draft = nullptr, + std::unique_ptr prefill = nullptr); TextResult generate(const std::string& prompt, const TextGenerationConfig& cfg = {}) override; int32_t default_max_new_tokens() const override { return 128; } @@ -78,6 +79,9 @@ class RecurrentPipeline final : public ITextGeneration { std::string model_id_; std::unique_ptr mtp_scheduler_; std::unique_ptr paired_draft_; + // Multi-row prefill engine (split bundles only); decoding stays on decoder_. + std::unique_ptr prefill_; + int32_t prefill_rows_{0}; bool media_inputs_{false}; int32_t media_hidden_size_{0}; DType media_dtype_{DType::kFloat16}; @@ -97,6 +101,13 @@ class RecurrentPipeline final : public ITextGeneration { const Qwen35MoeSamplingParams& params); void run_step(int32_t token_id, std::vector& logits, std::vector* hidden_state_out = nullptr); + // Feed the prompt to prefill_ in chunks of up to prefill_rows_ tokens and + // return the logits of the last token. + void run_prefill_chunks(const std::vector& input_ids, std::vector& logits); + // Media inputs of prefill rows [start, start + rows): visual rows, selectors and MRoPE offsets. + void prepare_prefill_media(TensorMap& inputs, int32_t start, int32_t rows, + std::vector& visual, std::vector& use_visual, + std::vector& offsets) const; void* hidden_state_device_ptr_{nullptr}; std::size_t hidden_state_numel_{0}; diff --git a/families/qwen3_5_moe/runtime/plugin.cpp b/families/qwen3_5_moe/runtime/plugin.cpp index b21f7c2ce5..bce6398bd8 100644 --- a/families/qwen3_5_moe/runtime/plugin.cpp +++ b/families/qwen3_5_moe/runtime/plugin.cpp @@ -48,6 +48,8 @@ struct RuntimeConfig { bool has_mtp; std::int32_t mtp_num_draft_tokens; std::int32_t tensor_parallel_size; + // A second engine prefills prompt chunks; decoding stays on engine.plan. + bool split; }; template @@ -90,8 +92,9 @@ RuntimeConfig parse_runtime_config(const BundleReader& bundle) { (json.contains("has_mtp") ? 2 : 0) + static_cast(json.contains("tensor_parallel_size"))) throw std::runtime_error("qwen3_5_moe runtime.json has an unexpected field set"); - if (require_value(json, "decoder_engine_layout") != "single") - throw std::runtime_error("qwen3_5_moe requires decoder_engine_layout='single'"); + const auto layout = require_value(json, "decoder_engine_layout"); + if (layout != "single" && layout != "split") + throw std::runtime_error("qwen3_5_moe requires decoder_engine_layout 'single' or 'split'"); RuntimeConfig config{ require_value(json, "hidden_size"), @@ -120,7 +123,10 @@ RuntimeConfig parse_runtime_config(const BundleReader& bundle) { json.contains("tensor_parallel_size") ? require_value(json, "tensor_parallel_size") : 1, + layout == "split", }; + if (config.split && (config.tensor_parallel_size != 1 || config.has_mtp)) + throw std::runtime_error("qwen3_5_moe split bundles are single-GPU without MTP"); const auto layer_types = require_value>(json, "layer_types"); if (config.hidden_size <= 0 || config.num_layers <= 0 || config.num_attention_heads <= 0 || config.num_key_value_heads <= 0 || config.head_dim <= 0 || config.vocab_size <= 0 || @@ -165,6 +171,18 @@ ITask* create_native(const FamilyContext& context, const RuntimeConfig& config) if (!decoder || !decoder->ok()) throw std::runtime_error("Qwen3.5-MoE native decoder failed to load"); decoder->set_timing_label("qwen3_5_moe decoder"); + std::unique_ptr prefill; + if (config.split) { + // The prefill engine shares the decoder's stream so state copies stay ordered. + ModuleCreateOptions prefill_options; + prefill_options.stream = decoder->stream(); + const auto prefill_plan = require_section(context.reader, "prefill.plan"); + prefill = context.backend.create_module(prefill_plan.data(), prefill_plan.size(), + prefill_options); + if (!prefill || !prefill->ok()) + throw std::runtime_error("Qwen3.5-MoE native prefill engine failed to load"); + prefill->set_timing_label("qwen3_5_moe prefill"); + } const cudaStream_t stream = decoder->stream(); const std::int32_t kv_dim = config.num_key_value_heads / config.tensor_parallel_size * config.head_dim; @@ -226,7 +244,8 @@ ITask* create_native(const FamilyContext& context, const RuntimeConfig& config) auto tokenizer = create_tokenizer(context.reader); auto pipeline = std::make_unique( std::move(decoder), std::move(state), std::move(generation), stream, "Qwen3.5-MoE", - tokenizer, std::string{}, std::move(mtp_scheduler), std::move(paired_draft)); + tokenizer, std::string{}, std::move(mtp_scheduler), std::move(paired_draft), + std::move(prefill)); if (context.reader.find_section("native_visual.json")) { auto visual = load_engine(context.backend, require_section(context.reader, "native_visual.plan"), diff --git a/families/qwen3_5_moe/tests/test_prefill_rows.py b/families/qwen3_5_moe/tests/test_prefill_rows.py new file mode 100644 index 0000000000..3c37afcb5e --- /dev/null +++ b/families/qwen3_5_moe/tests/test_prefill_rows.py @@ -0,0 +1,145 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Qwen3.5-MoE prefill rows against the one-token graphs: dense W4A16 experts, per-row MRoPE, the split rule.""" + +from __future__ import annotations + +import numpy as np +import pytest + +trt = pytest.importorskip("tensorrt") + +from families.qwen3_5_moe import moe, native_model, vision # noqa: E402 +from families.qwen3_5_moe.quantization import gptq_projection # noqa: E402 + +HIDDEN, WIDTH, EXPERTS, TOP_K, ROWS = 256, 128, 8, 2, 6 + + +def _gptq(rng, k: int, n: int): + qweight = rng.integers(0, 2**32, size=(k // 8, n), dtype=np.uint64).astype(np.uint32).view(np.int32) + qzeros = np.full((k // 128, n // 8), 0x88888888, np.uint32).view(np.int32) + scales = (rng.uniform(0.5, 1.5, (k // 128, n)) / 64).astype(np.float16) + return gptq_projection(qweight, qzeros, scales, (np.arange(k) // 128).astype(np.int32)) + + +def _experts(rng) -> moe.MoEWeights: + experts = tuple( + moe.ExpertWeights(_gptq(rng, HIDDEN, WIDTH), _gptq(rng, HIDDEN, WIDTH), _gptq(rng, WIDTH, HIDDEN)) + for _ in range(EXPERTS) + ) + shared = moe.ExpertWeights(*( + (rng.standard_normal(shape) * 0.05).astype(np.float32) + for shape in ((HIDDEN, WIDTH), (HIDDEN, WIDTH), (WIDTH, HIDDEN)) + )) + return moe.MoEWeights( + router=rng.standard_normal((HIDDEN, EXPERTS)).astype(np.float32), + experts=experts, + shared=shared, + shared_gate=(rng.standard_normal((HIDDEN, 1)) * 0.05).astype(np.float32), + top_k=TOP_K, + ) + + +def _run(build, inputs: dict[str, np.ndarray]) -> np.ndarray: + """Build ``build(network, tensors) -> output`` over runtime-row inputs and run it once.""" + torch = pytest.importorskip("torch") + if not torch.cuda.is_available(): + pytest.skip("requires CUDA") + logger = trt.Logger(trt.Logger.WARNING) + builder = trt.Builder(logger) + network = builder.create_network(1 << int(trt.NetworkDefinitionCreationFlag.STRONGLY_TYPED)) + config = builder.create_builder_config() + profile = builder.create_optimization_profile() + tensors = {} + for name, value in inputs.items(): + dtype = {np.float16: trt.float16, np.float32: trt.float32, np.int32: trt.int32}[value.dtype.type] + tensors[name] = network.add_input(name, dtype, (-1, *value.shape[1:])) + profile.set_shape(name, (1, *value.shape[1:]), value.shape, value.shape) + config.add_optimization_profile(profile) + output = build(network, tensors) + if output.dtype != trt.float32: + output = network.add_cast(output, trt.float32).get_output(0) + output.name = "output" + network.mark_output(output) + engine = trt.Runtime(logger).deserialize_cuda_engine(builder.build_serialized_network(network, config)) + context = engine.create_execution_context() + bound = {} + for name, value in inputs.items(): + bound[name] = torch.from_numpy(value).cuda() + context.set_input_shape(name, value.shape) + context.set_tensor_address(name, bound[name].data_ptr()) + result = torch.empty(tuple(context.get_tensor_shape("output")), dtype=torch.float32, device="cuda") + context.set_tensor_address("output", result.data_ptr()) + assert context.execute_async_v3(torch.cuda.current_stream().cuda_stream) + torch.cuda.synchronize() + return result.cpu().numpy() + + +@pytest.mark.gpu +@pytest.mark.trt +def test_dense_w4a16_experts_match_the_per_token_selected_experts(): + """Every row runs every expert, and only the routed ones contribute, as on the one-token path.""" + rng = np.random.default_rng(0) + weights = _experts(rng) + rows = (rng.standard_normal((ROWS, HIDDEN)) * 0.5).astype(np.float16) + keep: list = [] + dense = _run(lambda network, x: moe.add_dense_moe_rows(network, x["rows"], weights, keep), {"rows": rows}) + selected = _run(lambda network, x: moe.add_sparse_moe(network, x["rows"], weights), {"rows": rows}) + assert keep, "the stacked experts must outlive the network" + assert np.abs(dense - selected).max() <= 1e-2 * np.abs(selected).max() + + +def test_only_gptq_experts_take_the_dense_prefill_path(): + rng = np.random.default_rng(1) + weights = _experts(rng) + assert moe.dense_rows_supported(weights) + assert native_model._dense_prefill_experts({"layer.0.moe": weights, "embedding": np.zeros(2)}) + original = moe.ExpertWeights(*(np.zeros(shape, np.float32) for shape in ((HIDDEN, WIDTH),) * 2 + ((WIDTH, HIDDEN),))) + mixed = moe.MoEWeights(weights.router, (original,) + weights.experts[1:], weights.shared, weights.shared_gate, TOP_K) + assert not moe.dense_rows_supported(mixed) + assert not native_model._dense_prefill_experts({"layer.0.moe": weights, "layer.1.moe": mixed}) + assert not native_model._dense_prefill_experts({"embedding": np.zeros(2)}) + + +@pytest.mark.gpu +@pytest.mark.trt +def test_per_row_mrope_tables_equal_the_one_token_tables(): + rng = np.random.default_rng(2) + half, window = 8, 40 + rope = {"mrope_section": [2, 3, 3], "mrope_interleaved": True} + cosine = rng.standard_normal((window, half)).astype(np.float32) + sine = rng.standard_normal((window, half)).astype(np.float32) + coordinates = rng.integers(0, window, size=(ROWS, 3)).astype(np.int32) + + def constants(network): + return (network.add_constant(cosine.shape, cosine).get_output(0), + network.add_constant(sine.shape, sine).get_output(0)) + + def rows(network, x): + cos, sin = vision.add_mrope_prompt_rows(network, *constants(network), x["coordinates"], rope, half, + np.float32) + return network.add_concatenation([cos, sin]).get_output(0) + + got = _run(rows, {"coordinates": coordinates}) + for row in range(ROWS): + + def one(network, x): + coordinate = network.add_shuffle(x["coordinate"]) + coordinate.reshape_dims = (3,) + cos, sin = vision.add_mrope_rows(network, *constants(network), coordinate.get_output(0), rope, half, + np.float32) + return network.add_concatenation([cos, sin]).get_output(0) + + want = _run(one, {"coordinate": coordinates[row:row + 1]}) + np.testing.assert_array_equal(got[[row, ROWS + row]], want) + + +def test_the_prefill_engine_is_built_only_when_a_second_weight_copy_fits(tmp_path): + gib = 1024**3 + assert native_model._two_engines_fit(20 * gib, 121 * gib) # 35B-A3B GPTQ on a 128 GB unified-memory GPU + assert not native_model._two_engines_fit(67 * gib, 121 * gib) # the BF16 original: decode engine alone + assert not native_model._two_engines_fit(2 * gib, None) # no device to ask: keep the single-engine layout + for name, size in (("model-00001.safetensors", 3), ("model-00002.safetensors", 5), ("config.json", 7)): + (tmp_path / name).write_bytes(b"x" * size) + assert native_model._checkpoint_bytes(tmp_path) == 8 diff --git a/families/qwen3_5_moe/vision.py b/families/qwen3_5_moe/vision.py index 0abc8d0148..373656066c 100644 --- a/families/qwen3_5_moe/vision.py +++ b/families/qwen3_5_moe/vision.py @@ -318,3 +318,26 @@ def add_mrope_rows(network, cosine, sine, coordinates, rope, half_dim, dtype): selected = network.add_elementwise(rows, mask, trt.ElementWiseOperation.PROD).get_output(0) outputs.append(network.add_reduce(selected, trt.ReduceOperation.SUM, 1, keep_dims=True).get_output(0)) return tuple(outputs) + + +def add_mrope_prompt_rows(network, cosine, sine, coordinates, rope, half_dim, dtype): + """Per-row MRoPE tables for ``S`` prompt rows: ``coordinates`` ``[S, 3]`` -> ``[S, half_dim]`` each, + the same section routing as :func:`add_mrope_rows`.""" + sections = rope.get("mrope_section") + if (not isinstance(sections, (list, tuple)) or len(sections) != 3 + or any(type(n) is not int or n < 0 for n in sections) or sum(sections) != half_dim): + raise ValueError("Qwen media requires three MRoPE sections matching partial rotary dimensions") + axes = np.zeros(half_dim, dtype=np.int32) + if rope.get("mrope_interleaved", True): + for axis in (1, 2): + axes[axis:sections[axis] * 3:3] = axis + else: + axes = np.repeat(np.arange(3, dtype=np.int32), sections) + masks = (np.arange(3, dtype=np.int32)[:, None] == axes[None, :]).astype(dtype).reshape(1, 3, half_dim) + mask = graph_ops.add_constant(network, masks.shape, masks, dtype=dtype) + outputs = [] + for table in (cosine, sine): + rows = network.add_gather(table, coordinates, 0).get_output(0) # [S, 3, half] + selected = network.add_elementwise(rows, mask, trt.ElementWiseOperation.PROD).get_output(0) + outputs.append(network.add_reduce(selected, trt.ReduceOperation.SUM, 1 << 1, keep_dims=False).get_output(0)) + return tuple(outputs) diff --git a/website/docs/features/model-families.md b/website/docs/features/model-families.md index 719405579c..d1fd7c58ba 100644 --- a/website/docs/features/model-families.md +++ b/website/docs/features/model-families.md @@ -341,6 +341,10 @@ owns native TensorRT Python graph construction and Model Connect C++ execution, including prepared routed experts and media inputs. Publication errors, cancellation and runtime errors do not trigger this fallback. Native execution needs neither Edge nor ONNX. +A native single-GPU GPTQ bundle without MTP or a draft also ships `prefill.plan` +when two copies of the checkpoint weights fit in 80% of the GPU memory. The +runtime then prefills text and media prompts up to 64 rows per call and decodes +with `engine.plan`; other bundles prefill one token at a time, as before. The existing validation checks seed rejection on Edge and seeded request-local repeatability on native, retaining capacity recovery, the independent checkpoint reference and the unchanged accuracy gate. Native speculative mappings and From dc25d8953d928601f5fcf343859230eeeab86571 Mon Sep 17 00:00:00 2001 From: chaofengw Date: Mon, 23 Nov 2026 13:41:33 +0000 Subject: [PATCH 2/3] fix(qwen3_5_moe): keep the single-engine bundle when the prefill build fails The prefill engine is optional: if TensorRT fails to build it, the bundle keeps engine.plan with decoder_engine_layout "single" instead of failing the whole build. The two-engine memory check now sizes the shards the loader mapped, and the split decision is one tested helper. Signed-off-by: chaofengw --- families/qwen3_5_moe/native_model.py | 34 ++++++++--- .../qwen3_5_moe/tests/test_prefill_rows.py | 57 +++++++++++++++++-- 2 files changed, 80 insertions(+), 11 deletions(-) diff --git a/families/qwen3_5_moe/native_model.py b/families/qwen3_5_moe/native_model.py index 18ae341f27..04aa560db6 100644 --- a/families/qwen3_5_moe/native_model.py +++ b/families/qwen3_5_moe/native_model.py @@ -2399,9 +2399,30 @@ def _two_engines_fit(weight_bytes: int, gpu_bytes: int | None) -> bool: return False -def _checkpoint_bytes(model_dir: Path) -> int: - """Size of the checkpoint's weight files: what each engine carries, packed experts included.""" - return sum(path.stat().st_size for path in Path(model_dir).glob("*.safetensors")) +def _checkpoint_bytes(readers) -> int: + """Size of the shards the loader mapped: what each engine carries, packed experts included.""" + return sum(len(reader.mapping) for reader in readers) + + +def _wants_prefill_engine(weights, readers, *, tensor_parallel_size: int, require_mtp: bool, + has_draft: bool) -> bool: + """Whether the bundle adds the chunked prefill engine: single-GPU GPTQ without MTP or a draft, if it fits.""" + return (not require_mtp and not has_draft and tensor_parallel_size == 1 + and _dense_prefill_experts(weights) + and _two_engines_fit(_checkpoint_bytes(readers), _gpu_memory_bytes())) + + +def _stage_prefill_engine(writer, build) -> bool: + """Stage ``prefill.plan`` from ``build()``. The engine is optional: if its build fails, the bundle keeps + the single-engine layout and prompts run through the decode engine.""" + try: + plan = build() + except (RuntimeError, MemoryError) as error: + print(f"Skipping the prefill engine: its build failed ({error}); prompts run through the decode engine", + file=sys.stderr) + return False + writer.add_bytes("prefill.plan", plan) + return True def _dense_prefill_experts(weights) -> bool: @@ -2506,9 +2527,8 @@ def _build_native(request: "BuildRequest", writer: "BundleWriter", *, require_mt if require_mtp: model._load_mtp_weights(readers, weights, config) # Single-GPU GPTQ bundles add an engine that prefills the prompt (text and media rows) in chunks. - split = (not require_mtp and draft_config is None and int(request.tensor_parallel_size or 1) == 1 - and _dense_prefill_experts(weights) - and _two_engines_fit(_checkpoint_bytes(model_dir), _gpu_memory_bytes())) + split = _wants_prefill_engine(weights, readers, tensor_parallel_size=int(request.tensor_parallel_size or 1), + require_mtp=require_mtp, has_draft=draft_config is not None) plan = model.build_engine( config, weights, @@ -2524,7 +2544,7 @@ def _build_native(request: "BuildRequest", writer: "BundleWriter", *, require_mt writer.add_bytes("engine.plan", plan) del plan # The section is staged; do not retain a full plan during the next build. if split: - writer.add_bytes("prefill.plan", model.build_engine( + split = _stage_prefill_engine(writer, lambda: model.build_engine( config, weights, max_sequence_length, precision=precision, verbose=bool(request.verbose), media_inputs=visual, prefill_rows=PREFILL_MAX_TOKENS, )) diff --git a/families/qwen3_5_moe/tests/test_prefill_rows.py b/families/qwen3_5_moe/tests/test_prefill_rows.py index 3c37afcb5e..d5e069e8e7 100644 --- a/families/qwen3_5_moe/tests/test_prefill_rows.py +++ b/families/qwen3_5_moe/tests/test_prefill_rows.py @@ -5,6 +5,8 @@ from __future__ import annotations +from types import SimpleNamespace + import numpy as np import pytest @@ -135,11 +137,58 @@ def one(network, x): np.testing.assert_array_equal(got[[row, ROWS + row]], want) -def test_the_prefill_engine_is_built_only_when_a_second_weight_copy_fits(tmp_path): +def test_the_prefill_engine_is_built_only_when_a_second_weight_copy_fits(): gib = 1024**3 assert native_model._two_engines_fit(20 * gib, 121 * gib) # 35B-A3B GPTQ on a 128 GB unified-memory GPU assert not native_model._two_engines_fit(67 * gib, 121 * gib) # the BF16 original: decode engine alone assert not native_model._two_engines_fit(2 * gib, None) # no device to ask: keep the single-engine layout - for name, size in (("model-00001.safetensors", 3), ("model-00002.safetensors", 5), ("config.json", 7)): - (tmp_path / name).write_bytes(b"x" * size) - assert native_model._checkpoint_bytes(tmp_path) == 8 + + +@pytest.mark.parametrize( + ("gpu_gib", "options", "wanted"), + [ + (121, {}, True), + (30, {}, False), + (None, {}, False), + (121, {"require_mtp": True}, False), + (121, {"has_draft": True}, False), + (121, {"tensor_parallel_size": 2}, False), + ], +) +def test_the_split_decision_uses_the_mapped_shards_and_the_gpu_memory(monkeypatch, gpu_gib, options, wanted): + gib = 1024**3 + readers = [SimpleNamespace(mapping=_Sized(12 * gib)), SimpleNamespace(mapping=_Sized(8 * gib))] + weights = {"layer.0.moe": _experts(np.random.default_rng(3))} + monkeypatch.setattr(native_model, "_gpu_memory_bytes", lambda: None if gpu_gib is None else gpu_gib * gib) + assert native_model._checkpoint_bytes(readers) == 20 * gib + arguments = {"tensor_parallel_size": 1, "require_mtp": False, "has_draft": False, **options} + assert native_model._wants_prefill_engine(weights, readers, **arguments) is wanted + + +class _Sized: + def __init__(self, size: int): + self.size = size + + def __len__(self) -> int: + return self.size + + +class _RecordingWriter: + def __init__(self): + self.sections: dict[str, object] = {} + + def add_bytes(self, name: str, data) -> None: + self.sections[name] = data + + +def test_a_failed_prefill_build_keeps_the_single_engine_bundle(): + writer = _RecordingWriter() + assert native_model._stage_prefill_engine(writer, lambda: b"plan") + assert writer.sections == {"prefill.plan": b"plan"} + + def failed(): + raise RuntimeError("TensorRT engine build failed") + + writer = _RecordingWriter() + assert not native_model._stage_prefill_engine(writer, failed) + assert writer.sections == {} From b75e6b66425c95c5ddcc2d1d75279381b17faef0 Mon Sep 17 00:00:00 2001 From: chaofengw Date: Mon, 23 Nov 2026 14:22:34 +0000 Subject: [PATCH 3/3] fix(qwen3_5_moe): release the stacked experts after any prefill build outcome A failed prefill graph construction left the stacked expert copies in weights["_prefill_keep"] while the vision engine built. Drop them in a finally around the whole optional build. Signed-off-by: chaofengw --- families/qwen3_5_moe/native_model.py | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/families/qwen3_5_moe/native_model.py b/families/qwen3_5_moe/native_model.py index 04aa560db6..ecce12a158 100644 --- a/families/qwen3_5_moe/native_model.py +++ b/families/qwen3_5_moe/native_model.py @@ -2544,10 +2544,14 @@ def _build_native(request: "BuildRequest", writer: "BundleWriter", *, require_mt writer.add_bytes("engine.plan", plan) del plan # The section is staged; do not retain a full plan during the next build. if split: - split = _stage_prefill_engine(writer, lambda: model.build_engine( - config, weights, max_sequence_length, precision=precision, - verbose=bool(request.verbose), media_inputs=visual, prefill_rows=PREFILL_MAX_TOKENS, - )) + try: + split = _stage_prefill_engine(writer, lambda: model.build_engine( + config, weights, max_sequence_length, precision=precision, + verbose=bool(request.verbose), media_inputs=visual, prefill_rows=PREFILL_MAX_TOKENS, + )) + finally: + # Also after a failed graph construction: the stacked expert copies must not outlive this build. + weights.pop("_prefill_keep", None) if require_mtp: # Preserve the admitted three draft steps plus one target anchor. writer.add_bytes("mtp_engine.plan", model.build_mtp_engine(