From 975f340208f8299f372926f1975f76bddb227f2b Mon Sep 17 00:00:00 2001 From: Joshua Calafato Date: Mon, 23 Nov 2026 19:15:05 +0000 Subject: [PATCH 1/5] feat(qwen): add Flash-Next NVFP4 execution Build the ordinary multimodal target with Edge-LLM 0.12 or a family-owned native TensorRT fallback. Preserve the prepared experts and lexical table on both paths. Separate bounded native premerge validation from full-checkpoint text, image, and video checks. Signed-off-by: Joshua Calafato --- families/qwen3_8_flash_next/NOTICE | 5 + families/qwen3_8_flash_next/README.md | 52 ++ families/qwen3_8_flash_next/__init__.py | 4 + families/qwen3_8_flash_next/checkpoint.py | 90 ++++ families/qwen3_8_flash_next/cli.json | 105 ++++ families/qwen3_8_flash_next/cli.py | 73 +++ families/qwen3_8_flash_next/decoder.py | 91 ++++ .../qwen3_8_flash_next/delta_attention.py | 202 +++++++ .../qwen3_8_flash_next/edge_llm/__init__.py | 2 + .../qwen3_8_flash_next/edge_llm/builder.py | 212 ++++++++ .../qwen3_8_flash_next/edge_llm/dispatch.py | 50 ++ families/qwen3_8_flash_next/expert_weights.py | 65 +++ families/qwen3_8_flash_next/experts.py | 117 ++++ families/qwen3_8_flash_next/model.py | 67 +++ families/qwen3_8_flash_next/moe.py | 64 +++ families/qwen3_8_flash_next/native_builder.py | 93 ++++ families/qwen3_8_flash_next/native_decoder.py | 170 ++++++ families/qwen3_8_flash_next/ple.py | 147 +++++ families/qwen3_8_flash_next/ple_weights.py | 73 +++ families/qwen3_8_flash_next/prompt.py | 183 +++++++ families/qwen3_8_flash_next/requirements.txt | 1 + families/qwen3_8_flash_next/residual.py | 115 ++++ .../qwen3_8_flash_next/runtime/CMakeLists.txt | 30 ++ .../runtime/decoder_layer.cpp | 43 ++ .../runtime/decoder_layer.h | 32 ++ .../runtime/edge_llm/Adapter.cmake | 13 + .../runtime/edge_llm/adapter.cpp | 338 ++++++++++++ .../runtime/edge_llm/adapter.h | 15 + .../runtime/edge_llm/contract.h | 107 ++++ .../runtime/edge_llm/device_link.cu | 5 + .../runtime/edge_llm/media.h | 191 +++++++ .../runtime/edge_llm/request.h | 65 +++ .../qwen3_8_flash_next/runtime/experts.cpp | 95 ++++ families/qwen3_8_flash_next/runtime/experts.h | 21 + .../runtime/lexical_table.cpp | 71 +++ .../runtime/lexical_table.h | 31 ++ .../runtime/native_decoder.cpp | 201 +++++++ .../runtime/native_decoder.h | 40 ++ .../runtime/native_task.cpp | 505 ++++++++++++++++++ .../qwen3_8_flash_next/runtime/native_task.h | 9 + .../runtime/native_visual.cpp | 368 +++++++++++++ .../runtime/native_visual.h | 70 +++ families/qwen3_8_flash_next/runtime/ngram.cpp | 76 +++ families/qwen3_8_flash_next/runtime/ngram.h | 41 ++ .../qwen3_8_flash_next/runtime/ple_rows.cpp | 36 ++ .../qwen3_8_flash_next/runtime/ple_rows.h | 19 + .../qwen3_8_flash_next/runtime/plugin.cpp | 22 + .../qwen3_8_flash_next/runtime/positions.cpp | 78 +++ .../qwen3_8_flash_next/runtime/positions.h | 30 ++ .../qwen3_8_flash_next/runtime/sampler.cpp | 256 +++++++++ families/qwen3_8_flash_next/runtime/sampler.h | 53 ++ .../qwen3_8_flash_next/runtime/tokenizer.cpp | 231 ++++++++ .../qwen3_8_flash_next/runtime/tokenizer.h | 24 + .../qwen3_8_flash_next/sparse_attention.py | 194 +++++++ families/qwen3_8_flash_next/support.py | 41 ++ .../tests/cpp/lexical_stage.cpp | 53 ++ .../tests/cpp/test_ngram.cpp | 51 ++ .../qwen3_8_flash_next/tests/lexical_stage.py | 55 ++ .../manifests/qwen38-flash-next-nvfp4.json | 49 ++ .../qwen3_8_flash_next/tests/sdk_consumer.cpp | 83 +++ families/qwen3_8_flash_next/tests/test_e2e.py | 153 ++++++ .../tests/test_edge_routing.py | 80 +++ .../qwen3_8_flash_next/tests/test_support.py | 49 ++ families/qwen3_8_flash_next/vision.py | 341 ++++++++++++ .../qwen-flash-next-edge-llm.md | 33 ++ website/sidebars.js | 1 + 66 files changed, 6280 insertions(+) create mode 100644 families/qwen3_8_flash_next/NOTICE create mode 100644 families/qwen3_8_flash_next/README.md create mode 100644 families/qwen3_8_flash_next/__init__.py create mode 100644 families/qwen3_8_flash_next/checkpoint.py create mode 100644 families/qwen3_8_flash_next/cli.json create mode 100644 families/qwen3_8_flash_next/cli.py create mode 100644 families/qwen3_8_flash_next/decoder.py create mode 100644 families/qwen3_8_flash_next/delta_attention.py create mode 100644 families/qwen3_8_flash_next/edge_llm/__init__.py create mode 100644 families/qwen3_8_flash_next/edge_llm/builder.py create mode 100644 families/qwen3_8_flash_next/edge_llm/dispatch.py create mode 100644 families/qwen3_8_flash_next/expert_weights.py create mode 100644 families/qwen3_8_flash_next/experts.py create mode 100644 families/qwen3_8_flash_next/model.py create mode 100644 families/qwen3_8_flash_next/moe.py create mode 100644 families/qwen3_8_flash_next/native_builder.py create mode 100644 families/qwen3_8_flash_next/native_decoder.py create mode 100644 families/qwen3_8_flash_next/ple.py create mode 100644 families/qwen3_8_flash_next/ple_weights.py create mode 100644 families/qwen3_8_flash_next/prompt.py create mode 100644 families/qwen3_8_flash_next/requirements.txt create mode 100644 families/qwen3_8_flash_next/residual.py create mode 100644 families/qwen3_8_flash_next/runtime/CMakeLists.txt create mode 100644 families/qwen3_8_flash_next/runtime/decoder_layer.cpp create mode 100644 families/qwen3_8_flash_next/runtime/decoder_layer.h create mode 100644 families/qwen3_8_flash_next/runtime/edge_llm/Adapter.cmake create mode 100644 families/qwen3_8_flash_next/runtime/edge_llm/adapter.cpp create mode 100644 families/qwen3_8_flash_next/runtime/edge_llm/adapter.h create mode 100644 families/qwen3_8_flash_next/runtime/edge_llm/contract.h create mode 100644 families/qwen3_8_flash_next/runtime/edge_llm/device_link.cu create mode 100644 families/qwen3_8_flash_next/runtime/edge_llm/media.h create mode 100644 families/qwen3_8_flash_next/runtime/edge_llm/request.h create mode 100644 families/qwen3_8_flash_next/runtime/experts.cpp create mode 100644 families/qwen3_8_flash_next/runtime/experts.h create mode 100644 families/qwen3_8_flash_next/runtime/lexical_table.cpp create mode 100644 families/qwen3_8_flash_next/runtime/lexical_table.h create mode 100644 families/qwen3_8_flash_next/runtime/native_decoder.cpp create mode 100644 families/qwen3_8_flash_next/runtime/native_decoder.h create mode 100644 families/qwen3_8_flash_next/runtime/native_task.cpp create mode 100644 families/qwen3_8_flash_next/runtime/native_task.h create mode 100644 families/qwen3_8_flash_next/runtime/native_visual.cpp create mode 100644 families/qwen3_8_flash_next/runtime/native_visual.h create mode 100644 families/qwen3_8_flash_next/runtime/ngram.cpp create mode 100644 families/qwen3_8_flash_next/runtime/ngram.h create mode 100644 families/qwen3_8_flash_next/runtime/ple_rows.cpp create mode 100644 families/qwen3_8_flash_next/runtime/ple_rows.h create mode 100644 families/qwen3_8_flash_next/runtime/plugin.cpp create mode 100644 families/qwen3_8_flash_next/runtime/positions.cpp create mode 100644 families/qwen3_8_flash_next/runtime/positions.h create mode 100644 families/qwen3_8_flash_next/runtime/sampler.cpp create mode 100644 families/qwen3_8_flash_next/runtime/sampler.h create mode 100644 families/qwen3_8_flash_next/runtime/tokenizer.cpp create mode 100644 families/qwen3_8_flash_next/runtime/tokenizer.h create mode 100644 families/qwen3_8_flash_next/sparse_attention.py create mode 100644 families/qwen3_8_flash_next/support.py create mode 100644 families/qwen3_8_flash_next/tests/cpp/lexical_stage.cpp create mode 100644 families/qwen3_8_flash_next/tests/cpp/test_ngram.cpp create mode 100644 families/qwen3_8_flash_next/tests/lexical_stage.py create mode 100644 families/qwen3_8_flash_next/tests/manifests/qwen38-flash-next-nvfp4.json create mode 100644 families/qwen3_8_flash_next/tests/sdk_consumer.cpp create mode 100644 families/qwen3_8_flash_next/tests/test_e2e.py create mode 100644 families/qwen3_8_flash_next/tests/test_edge_routing.py create mode 100644 families/qwen3_8_flash_next/tests/test_support.py create mode 100644 families/qwen3_8_flash_next/vision.py create mode 100644 website/docs/models-recipes/qwen-flash-next-edge-llm.md diff --git a/families/qwen3_8_flash_next/NOTICE b/families/qwen3_8_flash_next/NOTICE new file mode 100644 index 0000000000..193c3c3be9 --- /dev/null +++ b/families/qwen3_8_flash_next/NOTICE @@ -0,0 +1,5 @@ +TensorRT Model Connect does not distribute Flash-Next weights. Generated bundles +contain checkpoint-derived material. Review the model terms before redistribution: +NVIDIA Qwen3.8-Flash-Next-NVFP4 — https://huggingface.co/nvidia/Qwen3.8-Flash-Next-NVFP4 +NVIDIA Open Model License — https://www.nvidia.com/en-us/agreements/enterprise-software/nvidia-open-model-license/ +Qwen3.8-Flash-Next upstream terms — https://huggingface.co/Qwen/Qwen3.8-Flash-Next/blob/main/LICENSE diff --git a/families/qwen3_8_flash_next/README.md b/families/qwen3_8_flash_next/README.md new file mode 100644 index 0000000000..2042b2322e --- /dev/null +++ b/families/qwen3_8_flash_next/README.md @@ -0,0 +1,52 @@ +# Qwen3.8 Flash-Next + +This family is for the **ordinary** prepared `nvidia/Qwen3.8-Flash-Next-NVFP4` +checkpoint (`qwen4_exp`). It does not select a draft, calibrate a new checkpoint, +or claim other Qwen checkpoints. The target accepts text and image/video input and +returns text. The prepared NVFP4 experts, FP8 lexical table, and both generation +EOS IDs are preserved; `fp16` denotes runtime activation precision. + +```bash +trtmc qwen3_8_flash_next build /path/to/snapshot \ + --task vision_language_generation --precision fp16 --max-sequence-length 8192 \ + --edge-builder-python /path/to/edge-builder-env/bin/python -o model.bundle +``` + +The Edge path needs a Model Connect build linked to the matching Edge-LLM 0.12 +C++ SDK and an isolated 0.12 Python builder environment. It uses the official +LLM and visual builders and preserves the provider's chat template and checkpoint +identity checks when relocating their outputs. The C++ runtime receives a +checkpoint directory extracted from the bundle, not the original model directory. + +The optional `--edge-ple-residency cached` stores the Edge lexical table on the host +and stages requested rows. The Edge default remains `resident`; this flag does not +change native storage. + +If Edge preparation fails, the family warns and selects its native TensorRT +builder. Native execution does not use Edge, PyTorch inference, or ONNX. The +native bundle holds the trained language and visual stages and the selected +experts' original weight encodings. Its lexical lookup streams the FP8 table +once into temporary storage for bounded random reads. Allow space for the +self-contained bundle and for temporary files; this is a large model. + +See [NOTICE](NOTICE) for checkpoint terms. Exposure of a build path is not +validation of a configuration. Standalone Edge tests, Model Connect offload, +and native fallback results must be reported separately. + +## Validation scope + +The full checkpoint case uses the installed family runtime and the public +text, image-plus-text, and ordered-video-plus-text tasks. It checks the first ten +primes, the species in a still image, and the first and last species in a video. +Each response must match the reference after case folding and trimming outer +whitespace. The evidence records which route was actually built. + +Resident Edge and native execution matched all three answers in a full-model +run. Row-cached Edge ran successfully but answered “red panda, panda” rather +than “red panda, giant panda” for the ordered video. It remains executable; +the cached policy is not qualified for this case. These observations do not +establish model-wide accuracy or validate speculative decoding. + +The native lexical-stage check exercises the production packed-table graph +against an independent E4M3FN reference with one and three token rows. +It does not build the language model or test generation. diff --git a/families/qwen3_8_flash_next/__init__.py b/families/qwen3_8_flash_next/__init__.py new file mode 100644 index 0000000000..ab040732e0 --- /dev/null +++ b/families/qwen3_8_flash_next/__init__.py @@ -0,0 +1,4 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Qwen Flash-Next prepared multimodal checkpoints.""" diff --git a/families/qwen3_8_flash_next/checkpoint.py b/families/qwen3_8_flash_next/checkpoint.py new file mode 100644 index 0000000000..9e45aa43a5 --- /dev/null +++ b/families/qwen3_8_flash_next/checkpoint.py @@ -0,0 +1,90 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +"""Lazy, byte-preserving access to the indexed Flash-Next checkpoint.""" + +import json +import math +import mmap +from pathlib import Path +import struct + +import ml_dtypes +import numpy as np + + +_DTYPES = { + "BF16": ml_dtypes.bfloat16, + "F8_E4M3": ml_dtypes.float8_e4m3fn, + "F16": np.float16, + "F32": np.float32, + "U8": np.uint8, + "I8": np.int8, + "I32": np.int32, + "I64": np.int64, +} + + +class FlashCheckpoint: + """Parse the index once, opening each used shard at most once per build.""" + + def __init__(self, directory): + self.directory = Path(directory) + index = self.directory / "model.safetensors.index.json" + self.keys_to_files = json.loads(index.read_text())["weight_map"] + self._shards = None + + def __enter__(self): + if self._shards is not None: + raise RuntimeError("Flash-Next checkpoint is already open") + self._shards = {} + return self + + def __exit__(self, exc_type, exc, tb): + # Views retain their own mmap reference. Never unmap a row or a + # network constant while a consumer may still hold it. + self._shards = None + + def _shard(self, key): + if self._shards is None: + raise RuntimeError("Flash-Next checkpoint is not open") + name = self.keys_to_files[key] + if Path(name).name != name or not name.endswith(".safetensors"): + raise ValueError(f"Invalid checkpoint shard for {key}") + if name not in self._shards: + with (self.directory / name).open("rb") as stream: + mapping = mmap.mmap(stream.fileno(), 0, access=mmap.ACCESS_READ) + if len(mapping) < 8: + raise ValueError(f"Truncated Flash-Next checkpoint shard: {name}") + size = struct.unpack_from(" None: + select_backend(request.backend) + from .model import build as build_model + + writer = BundleWriter(request.output_path) + try: + writer.record_build(request) + build_model(request, writer) + writer.finish() + except BaseException: + writer.abort() + raise + + +def build( + *, + model, + output, + task="vision_language_generation", + precision="fp16", + backend="trt", + revision=None, + max_sequence_length=None, + verbose=False, + edge_builder_python=None, + edge_ple_residency="resident", +): + local = resolve_model(model, revision) + resolve_family(load_model_metadata(local), "qwen3_8_flash_next") + build_bundle( + FlashNextRequest( + model_dir=local, + output_path=output, + family="qwen3_8_flash_next", + task=task, + precision=precision, + backend=backend, + max_sequence_length=max_sequence_length, + edge_builder_python=edge_builder_python, + edge_ple_residency=edge_ple_residency, + verbose=verbose, + ) + ) + return 0 diff --git a/families/qwen3_8_flash_next/decoder.py b/families/qwen3_8_flash_next/decoder.py new file mode 100644 index 0000000000..bccf3b0369 --- /dev/null +++ b/families/qwen3_8_flash_next/decoder.py @@ -0,0 +1,91 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +"""Compose prepared Flash-Next decoder stages without an Edge or ONNX dependency.""" + +import ml_dtypes +import numpy as np +import tensorrt as trt + +from .delta_attention import delta_attention_sublayer +from .moe import route_experts +from .ple import dequantize_packed_ngram_rows, lexical_injection +from .residual import collapse_residual +from .sparse_attention import sparse_attention_sublayer + + +def embed_tokens(network, token_ids, media_mask, media_vectors, checkpoint, vocab): + """Select actual patch vectors at expanded media positions; preserve IDs for PLE.""" + w = checkpoint.bf16("model.language_model.embed_tokens.weight", (vocab, 2560)) + table = network.add_constant(w.shape, w).get_output(0) + embedded = network.add_gather(table, token_ids, 0).get_output(0) + zero = network.add_constant((1, 1), np.zeros((1, 1), np.int32)).get_output(0) + mask = network.add_elementwise(media_mask, zero, trt.ElementWiseOperation.GREATER).get_output(0) + selected = network.add_select(mask, media_vectors, embedded).get_output(0) + streams = network.add_concatenation([selected] * 4) + streams.axis = 1 + return streams.get_output(0) + + +def token_logits(network, hyper, checkpoint, vocab, eps): + """The model exits directly through the trained mixer, with no extra RMSNorm.""" + last = collapse_residual(network, hyper, checkpoint, eps) + w = checkpoint.bf16("lm_head.weight", (vocab, 2560)) + table = network.add_constant(w.shape, w).get_output(0) + x = network.add_cast(last, trt.float32).get_output(0) + table = network.add_cast(table, trt.float32).get_output(0) + y = network.add_matrix_multiply( + x, trt.MatrixOperation.NONE, table, trt.MatrixOperation.TRANSPOSE + ) + return network.add_cast(y.get_output(0), trt.float16).get_output(0) + + +def decoder_layer(network, hyper, state, checkpoint, config, layer, max_chunk): + """Return the residual skip, sparse FFN inputs and the tentative attention state. + + The caller runs the selected experts, combines them, and commits cache + outputs only after successfully processing the request. All exposed + state is per-request; rotary positions are distinct from KV slots. + """ + eps = config["rms_norm_eps"] + updated = {} + if layer + 1 in config["ple_layer_ids"]: + prefix = f"model.language_model.layers.{layer}.ple." + scale = checkpoint.tensor( + prefix + "ple_embedding.ngram_embedding.weight_scale", ml_dtypes.bfloat16, (1,) + ).item() + rows = dequantize_packed_ngram_rows(network, state["lexical_words"], scale) + + class Weights: + def __getitem__(self, name): + key = prefix + name + return checkpoint.bf16(key, checkpoint.array(key).shape, fp32=True) + + lexical, updated["new_lexical_history"] = lexical_injection( + network, rows, hyper, state["lexical_history"], Weights(), eps + ) + hyper = network.add_elementwise(hyper, lexical, trt.ElementWiseOperation.SUM).get_output(0) + + kind = config["layer_types"][layer] + if kind == "linear_attention": + hyper, (updated["new_history"], updated["new_state"]) = delta_attention_sublayer( + network, hyper, state["history"], state["state"], checkpoint, layer, eps, max_chunk + ) + elif kind == "full_attention": + past = state["key"], state["value"], state["index_key"] + hyper, (cache, _) = sparse_attention_sublayer( + network, hyper, state["position"], state["rotary"], past, checkpoint, layer, eps + ) + updated["new_key"], updated["new_value"], updated["new_index_key"] = cache + else: + raise ValueError(f"Unsupported Flash-Next attention type: {kind}") + + h, ids, weights, shared, inject = route_experts(network, hyper, checkpoint, layer, eps) + return { + "skip": hyper, + "tokens": h, + "selected": ids, + "weights": weights, + "shared": shared, + "inject": inject, + **updated, + } diff --git a/families/qwen3_8_flash_next/delta_attention.py b/families/qwen3_8_flash_next/delta_attention.py new file mode 100644 index 0000000000..1f99532f12 --- /dev/null +++ b/families/qwen3_8_flash_next/delta_attention.py @@ -0,0 +1,202 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +"""Flash-Next gated-delta attention with native TensorRT token recurrence.""" + +import math + +import numpy as np +import tensorrt as trt + +from .residual import gated_sublayer + + +def delta_attention(network, hidden, history, state, checkpoint, prefix, eps, max_chunk_tokens): + """Process consecutive tokens from one request, returning both updated caches. + + History contains three *unconvolved* QKV rows; the FP32 state is indexed + [value head, key channel, value channel]. Neither cache is shared between requests. + """ + n = network + ew, un, mat = trt.ElementWiseOperation, trt.UnaryOperation, trt.MatrixOperation + heads, kheads, width = 48, 16, 128 + kd, vd = kheads * width, heads * width + channels = 2 * kd + vd + if ( + hidden.dtype != trt.float16 + or tuple(hidden.shape)[1:] != (2560,) + or history.dtype != trt.float16 + or tuple(history.shape) != (3, channels) + or state.dtype != trt.float32 + or tuple(state.shape) != (heads, width, width) + or type(max_chunk_tokens) is not int + or max_chunk_tokens < 1 + or not math.isfinite(eps) + or eps <= 0 + ): + raise ValueError("Invalid Flash-Next gated-delta tensors or epsilon") + + def const(v): + return n.add_constant(v.shape, np.ascontiguousarray(v)).get_output(0) + + def cast(x, dtype): + return n.add_cast(x, dtype).get_output(0) + + def op(x, y, kind): + return n.add_elementwise(x, y, kind).get_output(0) + + def reshape(x, dims): + sh = n.add_shuffle(x) + sh.reshape_dims = dims + return sh.get_output(0) + + def sigmoid(x): + return n.add_activation(x, trt.ActivationType.SIGMOID).get_output(0) + + def weight(suffix, shape, *, fp32=False): + return checkpoint.bf16(f"{prefix}.{suffix}", shape, fp32=fp32) + + def linear(x, suffix, rows, columns): + w = const(weight(suffix + ".weight", (rows, columns))) + return n.add_matrix_multiply(x, mat.NONE, w, mat.TRANSPOSE).get_output(0) + + qkv = linear(hidden, "in_proj_qkv", channels, 2560) + size = n.add_shape(qkv).get_output(0) + tokens = n.add_slice(size, (0,), (1,), (1,)).get_output(0) + coords = np.int64 if size.dtype == trt.int64 else np.int32 + seq = n.add_concatenation([history, qkv]) + seq.axis = 0 + seq = seq.get_output(0) + kernel = weight("conv1d.weight", (channels, 1, 4), fp32=True) + # Prepending the carried history and convolving with no padding produces + # exactly one row per current token. The weights are depthwise, not dense. + layout = n.add_shuffle(cast(seq, trt.float32)) + layout.first_transpose = (1, 0) + layout.reshape_dims = (1, channels, -1, 1) + layer = n.add_convolution_nd( + layout.get_output(0), + channels, + (4, 1), + np.ascontiguousarray(kernel[..., None]), + trt.Weights(trt.float32), + ) + layer.num_groups = channels + flatten = n.add_shuffle(layer.get_output(0)) + flatten.reshape_dims = (channels, -1) + flatten.second_transpose = (1, 0) + indices = op(tokens, const(np.arange(3, dtype=coords)), ew.SUM) + tail = n.add_gather(seq, indices, 0) + + # HF's causal depthwise convolution rounds to FP16 before SiLU. + conv = cast(flatten.get_output(0), trt.float16) + conv32 = cast(conv, trt.float32) + act = cast(op(conv32, sigmoid(conv32), ew.PROD), trt.float16) + headmap = const(np.repeat(np.arange(kheads, dtype=np.int32), heads // kheads)) + + def part(first, end): + cols = const(np.arange(first, end, dtype=np.int32)) + return n.add_gather(act, cols, 1).get_output(0) + + def normalized(x): + x = reshape(cast(x, trt.float32), (0, kheads, width)) + ss = n.add_reduce(op(x, x, ew.PROD), trt.ReduceOperation.SUM, 1 << 2, True).get_output(0) + den = n.add_unary( + op(ss, const(np.full((1, 1, 1), 1e-6, np.float32)), ew.SUM), un.SQRT + ).get_output(0) + return n.add_gather(op(x, den, ew.DIV), headmap, 1).get_output(0) + + q = op(normalized(part(0, kd)), const(np.full((1, 1, 1), width**-0.5, np.float32)), ew.PROD) + k = normalized(part(kd, 2 * kd)) + v = reshape(cast(part(2 * kd, channels), trt.float32), (0, heads, width)) + beta = cast(sigmoid(linear(hidden, "in_proj_b", heads, 2560)), trt.float32) + a = cast(linear(hidden, "in_proj_a", heads, 2560), trt.float32) + a = op(a, const(weight("dt_bias", (heads,), fp32=True).reshape(1, heads)), ew.SUM) + # Stable softplus avoids overflowing exp(a) for positive large a. + abs_a = n.add_unary(a, un.ABS).get_output(0) + exp = n.add_unary(n.add_unary(abs_a, un.NEG).get_output(0), un.EXP).get_output(0) + one = const(np.ones((1, 1), np.float32)) + positive = n.add_activation(a, trt.ActivationType.RELU).get_output(0) + sp = op(positive, n.add_unary(op(one, exp, ew.SUM), un.LOG).get_output(0), ew.SUM) + multiplier = -np.exp(weight("A_log", (heads,), fp32=True)) + decay = n.add_unary(op(sp, const(multiplier.reshape(1, heads)), ew.PROD), un.EXP).get_output(0) + + # Chunk width is the plan's optimization-profile maximum. Neutral rows + # have unit decay and zero beta/Q/K/V: they neither emit features nor + # change recurrent state. The caller can therefore split any prompt + # across chunks, including a one-token decode, without padding the cache. + def pad(x, shape, value=0.0): + fill = const(np.full((max_chunk_tokens, *shape), value, np.float32)) + joined = n.add_concatenation([x, fill]) + joined.axis = 0 + dims = (max_chunk_tokens, *shape) + return n.add_slice( + joined.get_output(0), (0,) * len(dims), dims, (1,) * len(dims) + ).get_output(0) + + q, k, v = (pad(t, (heads, width)) for t in (q, k, v)) + beta, decay = pad(beta, (heads,)), pad(decay, (heads,), 1.0) + outputs = [] + new_state = state + for row in range(max_chunk_tokens): + index = const(np.array(row, np.int32)) + + def at(x): + return n.add_gather(x, index, 0).get_output(0) + + faded = op(new_state, reshape(at(decay), (heads, 1, 1)), ew.PROD) + kt = reshape(at(k), (heads, 1, width)) + prev = n.add_matrix_multiply(kt, mat.NONE, faded, mat.NONE).get_output(0) + delta = op( + op(at(v), reshape(prev, (heads, width)), ew.SUB), reshape(at(beta), (heads, 1)), ew.PROD + ) + new_state = op( + faded, + op(reshape(kt, (heads, width, 1)), reshape(delta, (heads, 1, width)), ew.PROD), + ew.SUM, + ) + qt = reshape(at(q), (heads, 1, width)) + read = n.add_matrix_multiply(qt, mat.NONE, new_state, mat.NONE).get_output(0) + outputs.append(reshape(read, (1, heads, width))) + stacked = n.add_concatenation(outputs) + stacked.axis = 0 + extent = n.add_concatenation([tokens, const(np.array([heads, width], coords))]) + extent.axis = 0 + valid = n.add_slice( + stacked.get_output(0), (0, 0, 0), (max_chunk_tokens, heads, width), (1, 1, 1) + ) + valid.set_input(2, extent.get_output(0)) + + # Match HF's activation rounding and sigmoid (not SiLU) output gate. + y = cast(cast(valid.get_output(0), trt.float16), trt.float32) + var = n.add_reduce(op(y, y, ew.PROD), trt.ReduceOperation.AVG, 1 << 2, True).get_output(0) + den = n.add_unary( + op(var, const(np.full((1, 1, 1), eps, np.float32)), ew.SUM), un.SQRT + ).get_output(0) + gamma = const(weight("norm.weight", (width,)).reshape(1, 1, width)) + normed = op(cast(op(y, den, ew.DIV), trt.float16), gamma, ew.PROD) + z = reshape(cast(linear(hidden, "in_proj_z", vd, 2560), trt.float32), (0, heads, width)) + gated = cast(op(cast(normed, trt.float32), sigmoid(z), ew.PROD), trt.float16) + output = linear(reshape(gated, (0, vd)), "out_proj", 2560, vd) + return output, (tail.get_output(0), new_state) + + +def delta_attention_sublayer( + network, hyper, history, state, checkpoint, layer, epsilon, max_chunk_tokens +): + """Run recurrent attention between the learned residual read and update.""" + prefix = f"model.language_model.layers.{layer}" + + def block(hidden): + return delta_attention( + network, + hidden, + history, + state, + checkpoint, + prefix + ".linear_attn", + epsilon, + max_chunk_tokens, + ) + + return gated_sublayer( + network, hyper, checkpoint, prefix + ".attn_hyper_connection", epsilon, block + ) diff --git a/families/qwen3_8_flash_next/edge_llm/__init__.py b/families/qwen3_8_flash_next/edge_llm/__init__.py new file mode 100644 index 0000000000..52a7a9daf0 --- /dev/null +++ b/families/qwen3_8_flash_next/edge_llm/__init__.py @@ -0,0 +1,2 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 diff --git a/families/qwen3_8_flash_next/edge_llm/builder.py b/families/qwen3_8_flash_next/edge_llm/builder.py new file mode 100644 index 0000000000..a135683e71 --- /dev/null +++ b/families/qwen3_8_flash_next/edge_llm/builder.py @@ -0,0 +1,212 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Build the ordinary Flash-Next NVFP4 engines with the installed Edge SDK.""" + +from __future__ import annotations + +import json +import shutil +import subprocess +import sys +from pathlib import Path + +RELEASE = "0.12.0" +REVISION = "513dcd18291e587c80928911a480761352f3c2d8" + + +def sdk(target, explicit_python): + from importlib.util import find_spec + + from tensorrt_model_connect.build import cmake_prefixes + + spec = find_spec("tensorrt_model_connect") + active = Path(spec.origin).resolve().parent if spec and spec.origin else None + # A packaged runner can only consume bundles for its own installed SDK. + prefixes = [active] if active is not None and (active / "bin/trtmc").is_file() else cmake_prefixes() + for prefix in prefixes: + receipt = prefix / "share/trtmc/edge-llm.json" + if not receipt.is_file(): + continue + info = json.loads(receipt.read_text()) + if not ( + info.get("version") == RELEASE + and info.get("schema_version") == 2 + and "release_revision" in info + and info["release_revision"] in (None, REVISION) + and info.get("arch") == target["arch"] + and target["sm"] in info.get("architectures", []) + and info.get("tensorrt_version") == target["tensorrt_version"] + and ".".join(info.get("cuda_version", "").split(".")[:2]) == target["cuda_version"] + ): + raise ValueError("Flash-Next needs a matching Edge 0.12 SDK") + relative = Path(info["plugin"]) + plugin = (prefix / relative).resolve() + if ( + relative.is_absolute() + or not plugin.is_relative_to(prefix.resolve()) + or not plugin.is_file() + ): + raise ValueError("Flash-Next Edge SDK plugin is absent or outside its install prefix") + python = Path(sys.executable if explicit_python is None else explicit_python) + if not python.is_absolute() or not python.is_file(): + raise ValueError("Pass an absolute --edge-builder-python interpreter") + result = subprocess.run( + [ + str(python), + "-I", + "-c", + "import ctypes,json,sys,tensorrt,tensorrt_edgellm,transformers; " + "from tensorrt_edgellm.builder.cli import main; " + "ctypes.CDLL(sys.argv[1],mode=ctypes.RTLD_GLOBAL); " + "names={c.name for c in tensorrt.get_plugin_registry().all_creators}; " + "print(json.dumps([tensorrt_edgellm.__version__,tensorrt.__version__,transformers.__version__," + "'QsaAttentionPlugin' in names and bool({'Nvfp4MoePlugin','NvFP4MoEPluginGeforce'} & names)]))", + str(plugin), + ], + check=True, + capture_output=True, + text=True, + timeout=45, + ) + if json.loads(result.stdout) != [RELEASE, target["tensorrt_version"], "5.17.0", True]: + raise ValueError( + "Flash-Next builder must match the native SDK and use isolated Transformers 5.17" + ) + return python, plugin, info["release_revision"] + raise FileNotFoundError("No installed Edge 0.12 SDK receipt") + + +def run_build(target, staging, package, input_limit, capacity, vision, log): + python, plugin, _ = package + cmd = [ + str(python), + "-I", + "-m", + "tensorrt_edgellm.builder.cli", + "--model-dir", + str(target), + "--engine-dir", + str(staging), + "--plugin-path", + str(plugin), + "--max-batch-size", + "1", + ] + llm = cmd + [ + "--components", + "llm", + "--max-input-len", + str(input_limit), + "--max-kv-cache-capacity", + str(capacity), + ] + for call in [llm, cmd + ["--components", "visual"]] if vision else [llm]: + log.write(json.dumps(call) + "\n") + log.flush() + subprocess.run(call, stdout=log, stderr=subprocess.STDOUT, check=True) + + +def _checkpoint_assets(root): + index = root / "model.safetensors.index.json" + shards = set(json.loads(index.read_text())["weight_map"].values()) + if not shards or any( + not isinstance(s, str) or Path(s).name != s or "\\" in s or not s.endswith(".safetensors") + for s in shards + ): + raise ValueError("Invalid Flash-Next checkpoint shard map") + required = shards | {"config.json", index.name} + required.update( + name + for name in ( + "generation_config.json", + "hf_quant_config.json", + "processor_config.json", + "preprocessor_config.json", + ) + if (root / name).is_file() + ) + return {f"edge_llm/checkpoint/{name}": root / name for name in sorted(required)} + + +def _relocate(path): + config = json.loads(path.read_text()) + sources = config["checkpoint_identity"]["sources"] + if not sources or any(not identity.get("tensors") for identity in sources.values()): + raise ValueError("Released Flash-Next checkpoint verification metadata is missing") + config.pop("checkpoint_dir", None) + for identity in sources.values(): + # Edge verifies the original tensor samples against the extracted weights. + identity.pop("build_source", None) + return config + + +def prepare_assets(engines, checkpoint, task, input_limit, capacity): + """Check every artifact before the first bundle write so admission can still fall back.""" + assets = _checkpoint_assets(checkpoint) + names = [ + "llm.engine", + "config.json", + "multistage_config.json", + "tokenizer.json", + "tokenizer_config.json", + "chat_template.jinja", + ] + if task == "vision_language_generation": + names += [ + "visual/visual.engine", + "visual/config.json", + "visual/preprocessor_config.json", + "visual/processor_config.json", + ] + elif task != "text_generation": + raise ValueError(f"Unsupported Flash-Next task: {task}") + assets.update({f"edge_llm/engine/{name}": engines / name for name in names}) + for path in assets.values(): + if not path.is_file() or not path.stat().st_size: + raise ValueError(f"Missing Flash-Next engine or checkpoint asset: {path.name}") + for name in ("config.json", "visual/config.json"): + key = f"edge_llm/engine/{name}" + if key not in assets: + continue + config = _relocate(assets[key]) + if name == "config.json": + limits = config["builder_config"] + if ( + config["engine_role"] != "llm" + or config["spec_decode_type"] != "none" + or limits["max_input_len"] != input_limit + or limits["max_kv_cache_capacity"] != capacity + or set(config["eos_token_id"]) != {248046, 248044} + ): + raise ValueError( + "Released Flash-Next engine does not preserve the ordinary model contract" + ) + assets[key] = config + return assets + + +def publish(writer, assets, task, target, revision, input_limit, capacity, residency="resident"): + for name, value in assets.items(): + if isinstance(value, dict): + writer.add_json(name, value) + else: + with value.open("rb") as src, writer.open_section(name) as dst: + shutil.copyfileobj(src, dst, length=4 << 20) + writer.add_json( + "edge_llm.json", + { + "version": 1, + "edge_release": RELEASE, + "edge_revision": revision, + "task": task, + "weight_format": "prepared_flash_next_nvfp4", + "execution_variant": "autoregressive", + "ple_residency": residency, + "target": target, + "max_batch_size": 1, + "max_input_length": input_limit, + "max_sequence_length": capacity, + "artifacts": sorted(assets), + }, + ) diff --git a/families/qwen3_8_flash_next/edge_llm/dispatch.py b/families/qwen3_8_flash_next/edge_llm/dispatch.py new file mode 100644 index 0000000000..598a989cbf --- /dev/null +++ b/families/qwen3_8_flash_next/edge_llm/dispatch.py @@ -0,0 +1,50 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +"""Select complete-network offload without changing model or precision.""" + +import logging +import subprocess +import tempfile +from pathlib import Path + +from tensorrt_model_connect.build import detect_local_platform + +from . import builder + + +def build(request, writer, input_limit, capacity, native): + logfile = request.output_path.with_suffix(request.output_path.suffix + ".edge.log") + residency = getattr(request, "edge_ple_residency", "resident") + if residency not in ("resident", "cached"): + raise ValueError("Unknown Flash-Next Edge PLE residency") + with tempfile.TemporaryDirectory(prefix="flash-next-", dir=request.output_path.parent) as work: + engines = Path(work) + try: + target = detect_local_platform() + package = builder.sdk(target, getattr(request, "edge_builder_python", None)) + with logfile.open("a", encoding="utf-8") as log: + builder.run_build( + request.model_dir, + engines, + package, + input_limit, + capacity, + request.task == "vision_language_generation", + log, + ) + assets = builder.prepare_assets( + engines, request.model_dir, request.task, input_limit, capacity + ) + except (OSError, ValueError, KeyError, RuntimeError, subprocess.SubprocessError) as exc: + logging.getLogger(__name__).warning( + "Flash-Next Edge preparation failed: %s. See %s. Falling back to native TensorRT.", + exc, + logfile, + ) + else: + # Do not retry into a writer that has already accepted Edge sections. + builder.publish( + writer, assets, request.task, target, package[2], input_limit, capacity, residency + ) + return + native(request, writer) diff --git a/families/qwen3_8_flash_next/expert_weights.py b/families/qwen3_8_flash_next/expert_weights.py new file mode 100644 index 0000000000..5e87cc6624 --- /dev/null +++ b/families/qwen3_8_flash_next/expert_weights.py @@ -0,0 +1,65 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +"""Write one independently readable section per Flash-Next routed expert.""" + +from functools import lru_cache +import math + +import ml_dtypes +import numpy as np + + +def write_expert(checkpoint, writer, layer, expert): + """Preserve packed nibbles, original FP8 block scales and both calibrated scalars.""" + with writer.open_section(f"expert.{layer}.{expert}.bin") as out: + out.write(b"FNE2") + for name, rows, width in (("gate", 640, 2560), ("up", 640, 2560), ("down", 2560, 640)): + prefix = f"model.language_model.layers.{layer}.mlp.experts.{expert}.{name}_proj." + q = checkpoint.tensor(prefix + "weight", np.uint8, (rows, width // 2)) + s = checkpoint.tensor( + prefix + "weight_scale", ml_dtypes.float8_e4m3fn, (rows, width // 16) + ) + bits = s.view(np.uint8) + if np.any((bits >= 127) & (bits != 128)): + raise ValueError(f"Invalid NVFP4 block scale: {prefix}") + out.write(memoryview(q).cast("B")) + out.write(memoryview(bits).cast("B")) + for suffix in ("weight_scale_2", "input_scale"): + scale = checkpoint.tensor(prefix + suffix, np.float32, ()) + if not math.isfinite(scale.item()) or scale.item() <= 0: + raise ValueError(f"Invalid NVFP4 calibration: {prefix}{suffix}") + out.write(np.asarray(scale, dtype="", add_special_tokens=False) != [cfg[field]]: + raise ValueError("Flash-Next tokenizer disagrees with checkpoint " + field) + meta[field] = cfg[field] + with FlashCheckpoint(root) as ck: + if request.task == "vision_language_generation": + v = VisionConfig.from_dict(cfg["vision_config"], cfg["text_config"]["hidden_size"]) + processors = json.loads((root / "processor_config.json").read_text()) + image, video = (processors[k] for k in ("image_processor", "video_processor")) + for p in (image, video): + if any( + p.get(k) != val + for k, val in { + "patch_size": v.patch, + "merge_size": v.merge, + "temporal_patch_size": v.temporal, + "do_resize": True, + "do_rescale": True, + "do_normalize": True, + "do_convert_rgb": True, + "resample": 3, + "image_mean": [0.5] * 3, + "image_std": [0.5] * 3, + "rescale_factor": 1 / 255, + }.items() + ): + raise ValueError("Unsupported Flash-Next visual processor") + # A visual profile bounds allocation, not source geometry. Never silently shrink + # the provider's chosen resize to make a request fit this plan. + max_visual = min(1024, input_limit) + meta["visual"] = dict( + max_tokens=max_visual, + image_min_pixels=image["size"]["shortest_edge"], + image_max_pixels=image["size"]["longest_edge"], + video_min_pixels=video["size"]["shortest_edge"], + video_max_pixels=video["size"]["longest_edge"], + hidden=v.output, + patch=v.patch, + temporal=v.temporal, + merge=v.merge, + positions=v.positions, + head_dim=v.head_dim, + theta=v.theta, + ) + plan = build_vision_engine(v, load_vision_weights(ck, v), max_visual * v.merge**2) + with writer.open_section("visual.plan") as out: + out.write(plan) + del plan + write_language_decoder( + ck, writer, cfg["text_config"], chunk=min(16, input_limit), capacity=capacity + ) + with writer.open_section("tokenizer.json") as out, (root / "tokenizer.json").open("rb") as src: + import shutil + + shutil.copyfileobj(src, out, length=1 << 20) + writer.add_json("native.json", meta) diff --git a/families/qwen3_8_flash_next/native_decoder.py b/families/qwen3_8_flash_next/native_decoder.py new file mode 100644 index 0000000000..fa81810206 --- /dev/null +++ b/families/qwen3_8_flash_next/native_decoder.py @@ -0,0 +1,170 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +"""Compile and stage the ordinary Flash-Next language decoder for native execution.""" + +import tensorrt as trt + +from .decoder import decoder_layer, embed_tokens, token_logits +from .expert_weights import write_expert +from .experts import routed_expert +from .moe import combine_experts +from .ple_weights import write_checkpoint_ngram_table + + +def _write_plan(writer, section, chunk, define): + logger = trt.Logger(trt.Logger.WARNING) + builder = trt.Builder(logger) + network = builder.create_network(1 << int(trt.NetworkDefinitionCreationFlag.STRONGLY_TYPED)) + profile = builder.create_optimization_profile() + + def rows(name, dtype, *tail): + tensor = network.add_input(name, dtype, (-1, *tail)) + tensor.set_dimension_name(0, "token_rows") + profile.set_shape(name, (1, *tail), (min(4, chunk), *tail), (chunk, *tail)) + return tensor + + for name, tensor in define(network, rows).items(): + tensor.name = name + network.mark_output(tensor) + config = builder.create_builder_config() + config.builder_optimization_level = 3 + config.add_optimization_profile(profile) + plan = builder.build_serialized_network(network, config) + if plan is None: + raise RuntimeError(f"TensorRT could not build the native Flash-Next stage {section}") + with writer.open_section(section) as sink: + sink.write(plan) + + +def write_layer_plan(checkpoint, writer, config, layer, chunk, capacity): + def define(n, rows): + fp16, fp32 = trt.float16, trt.float32 + state = {} + if layer + 1 in config["ple_layer_ids"]: + state["lexical_words"] = rows("lexical_words", trt.int32, 640) + state["lexical_history"] = n.add_input("lexical_history", fp16, (9, 10240)) + if config["layer_types"][layer] == "linear_attention": + state["history"] = n.add_input("history", fp16, (3, 10240)) + state["state"] = n.add_input("state", fp32, (48, 128, 128)) + else: + state["position"] = rows("position", trt.int32) + state["rotary"] = n.add_input("rotary", fp32, (capacity, 64)) + for name in ("key", "value"): + state[name] = n.add_input(name, fp16, (capacity, 2, 256)) + state["index_key"] = n.add_input("index_key", fp16, (capacity, 128)) + return decoder_layer(n, rows("hyper", fp16, 10240), state, checkpoint, config, layer, chunk) + + _write_plan(writer, f"layer.{layer}.plan", chunk, define) + + +def write_shared_decoder_plans(checkpoint, writer, config, chunk): + def embedding(n, rows): + return { + "hyper": embed_tokens( + n, + rows("ids", trt.int32), + rows("media_mask", trt.int32, 1), + rows("media_vectors", trt.float16, 2560), + checkpoint, + config["vocab_size"], + ) + } + + def head(n, rows): + return { + "logits": token_logits( + n, + rows("hyper", trt.float16, 10240), + checkpoint, + config["vocab_size"], + config["rms_norm_eps"], + ) + } + + for name, define in (("embed", embedding), ("head", head)): + _write_plan(writer, name + ".plan", chunk, define) + write_moe_plans(writer, chunk) + + +def write_moe_plans(writer, chunk): + """Build the parameter-input expert and common residual combine exactly once.""" + + def expert(n, rows): + return {"result": routed_expert(n, rows("tokens", trt.float16, 2560))} + + def combine(n, rows): + return { + "hyper_out": combine_experts( + n, + rows("skip", trt.float16, 10240), + rows("inject", trt.float16, 4), + rows("shared", trt.float16, 2560), + rows("weights", trt.float16, 10), + rows("experts", trt.float16, 10, 2560), + ) + } + + for name, define in (("expert", expert), ("combine", combine)): + _write_plan(writer, name + ".plan", chunk, define) + + +def write_language_decoder(checkpoint, writer, config, *, chunk, capacity): + """Write language stages, lookup metadata and expert banks, not a vision frontend.""" + if chunk < 1 or capacity < chunk or capacity % 4: + raise ValueError("Flash-Next requires a positive chunk and a four-row-aligned KV capacity") + expected = { + "hidden_size": 2560, + "hc_count": 4, + "hc_lowrank": 320, + "num_experts": 512, + "num_experts_per_tok": 10, + "moe_intermediate_size": 640, + "shared_expert_intermediate_size": 640, + "norm_topk_prob": True, + "output_gate_type": "sigmoid", + "linear_conv_kernel_dim": 4, + "linear_num_value_heads": 48, + "linear_num_key_heads": 16, + "linear_key_head_dim": 128, + "linear_value_head_dim": 128, + "ple_layer_ids": [2], + } + for field, required in expected.items(): + if config.get(field) != required: + raise ValueError( + f"Unsupported Flash-Next decoder geometry: {field}={config.get(field)!r}" + ) + rope = config["rope_parameters"] + if not ( + rope.get("rope_type") == "default" + and rope.get("mrope_interleaved") is True + and rope.get("mrope_section") == [11, 11, 10] + and rope.get("partial_rotary_factor") == 0.25 + and rope.get("rope_theta") == 10000000 + ): + raise ValueError("Unsupported Flash-Next rotary configuration") + kinds = config["layer_types"] + if len(kinds) != config["num_hidden_layers"] or set(kinds) != { + "full_attention", + "linear_attention", + }: + raise ValueError("Invalid Flash-Next layer topology") + write_shared_decoder_plans(checkpoint, writer, config, chunk) + write_checkpoint_ngram_table(checkpoint, writer) + for layer in range(len(kinds)): + write_layer_plan(checkpoint, writer, config, layer, chunk, capacity) + for expert in range(config["num_experts"]): + write_expert(checkpoint, writer, layer, expert) + writer.add_json( + "decoder_layout.json", + { + "format": 1, + "rope_theta": rope["rope_theta"], + "ngram_eos": config["eos_token_id"], + "max_chunk": chunk, + "capacity": capacity, + "layers": kinds, + "ple_layer_ids": config["ple_layer_ids"], + "vocab_size": config["vocab_size"], + }, + ) diff --git a/families/qwen3_8_flash_next/ple.py b/families/qwen3_8_flash_next/ple.py new file mode 100644 index 0000000000..216593995f --- /dev/null +++ b/families/qwen3_8_flash_next/ple.py @@ -0,0 +1,147 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +"""Native Flash-Next per-layer embedding graph.""" + +import math + +import numpy as np +import tensorrt as trt + + +def dequantize_ngram_rows(network, rows, scale): + """Convert the selected FP8 rows [tokens, 16, 160] to FP16 token embeddings.""" + if rows.dtype != trt.fp8 or tuple(rows.shape)[1:] != (16, 160): + raise ValueError("Flash-Next expects FP8 rows with 16 heads of width 160") + if not math.isfinite(scale) or scale <= 0: + raise ValueError("Flash-Next requires a finite positive table scale") + factor = network.add_constant((), np.array(scale, dtype=np.float16)).get_output(0) + value = network.add_dequantize(rows, factor, trt.float16).get_output(0) + flatten = network.add_shuffle(value) + flatten.reshape_dims = (0, 2560) + return flatten.get_output(0) + + +def lexical_injection(network, embeddings, hyper_states, history, weights, epsilon): + """Inject lexical features for one request; return the addition and new history. + + embeddings [tokens, 2560], hyper_states [tokens, 10240], and the preceding + nine normalized rows [9, 10240] all use FP16. History is zero for a new + sequence; the caller commits the new history only after a successful step. + """ + n = network + streams, hidden = 4, 2560 + channels = streams * hidden + if not math.isfinite(epsilon) or epsilon <= 0: + raise ValueError("Invalid Flash-Next normalization epsilon") + + def constant(array): + return n.add_constant(array.shape, np.ascontiguousarray(array)).get_output(0) + + def weight(name, shape, dtype): + w = weights[name] + if w.shape != shape: + raise ValueError( + f"Invalid Flash-Next PLE weight {name}: expected {shape}, got {w.shape}" + ) + return np.asarray(w, dtype=dtype) + + def cast(x, dtype): + return n.add_cast(x, dtype).get_output(0) + + def reshape(x, shape): + layer = n.add_shuffle(x) + layer.reshape_dims = shape + return layer.get_output(0) + + def binary(x, y, op): + return n.add_elementwise(x, y, op).get_output(0) + + def unary(x, op): + return n.add_unary(x, op).get_output(0) + + ew, un = trt.ElementWiseOperation, trt.UnaryOperation + + def linear(x, name, out): + w = constant(weight(name, (out, hidden), np.float16)) + return n.add_matrix_multiply( + x, trt.MatrixOperation.NONE, w, trt.MatrixOperation.TRANSPOSE + ).get_output(0) + + def norm(x, name): + # HF accumulates in FP32 separately for each residual stream, applies + # (1 + weight) before rounding back to the input dtype. + a = reshape(cast(x, trt.float32), (0, streams, hidden)) + sq = binary(a, a, ew.PROD) + mean = n.add_reduce(sq, trt.ReduceOperation.AVG, 1 << 2, True).get_output(0) + eps = constant(np.full((1, 1, 1), epsilon, np.float32)) + denom = unary(binary(mean, eps, ew.SUM), un.SQRT) + scale = 1.0 + weight(name, (channels,), np.float32).reshape(1, streams, hidden) + return cast(binary(binary(a, denom, ew.DIV), constant(scale), ew.PROD), trt.float16) + + key = norm(linear(embeddings, "key_proj.weight", channels), "norm_key.weight") + query = norm(hyper_states, "norm_query.weight") + value = reshape(linear(embeddings, "value_proj.weight", hidden), (0, 1, hidden)) + product = cast(binary(key, query, ew.PROD), trt.float32) + dot = cast( + n.add_reduce(product, trt.ReduceOperation.SUM, 1 << 2, True).get_output(0), trt.float16 + ) + gate = binary(dot, constant(np.full((1, 1, 1), math.sqrt(hidden), np.float16)), ew.DIV) + bounded = binary(unary(gate, un.ABS), constant(np.full((1, 1, 1), 1e-6, np.float16)), ew.MAX) + gate = binary(unary(bounded, un.SQRT), unary(gate, un.SIGN), ew.PROD) + gate = n.add_activation(gate, trt.ActivationType.SIGMOID).get_output(0) + shared = reshape(binary(value, gate, ew.PROD), (0, channels)) + + current = reshape(norm(shared, "norm_conv.weight"), (0, channels)) + concat = n.add_concatenation([history, current]) + concat.axis = 0 + timeline = concat.get_output(0) + size = n.add_shape(current).get_output(0) + kernel = weight("conv1d.weight", (channels, 1, 4), np.float32) + acc = None + for tap in range(4): + # Cross-correlation reads offsets 0,3,6,9 (oldest first). Do not + # convolve across different requests or discard history on decode. + part = n.add_slice(timeline, (3 * tap, 0), (1, channels), (1, 1)) + part.set_input(2, size) + term = binary(cast(part.get_output(0), trt.float32), constant(kernel[:, :, tap].T), ew.PROD) + acc = term if acc is None else binary(acc, term, ew.SUM) + conv = cast(acc, trt.float16) + silu = binary(conv, n.add_activation(conv, trt.ActivationType.SIGMOID).get_output(0), ew.PROD) + + tokens = n.add_slice(size, (0,), (1,), (1,)).get_output(0) + zero = constant(np.array([0], np.int64 if size.dtype == trt.int64 else np.int32)) + start = n.add_concatenation([tokens, zero]) + start.axis = 0 + tail = n.add_slice(timeline, (0, 0), (9, channels), (1, 1)) + tail.set_input(1, start.get_output(0)) + return binary(shared, silu, ew.SUM), tail.get_output(0) + + +def dequantize_packed_ngram_rows(network, words, scale): + """Read original E4M3 bytes in INT32 transport words, including on pre-FP8 devices.""" + import ml_dtypes + + if words.dtype != trt.int32 or tuple(words.shape)[1:] != (640,): + raise ValueError("Flash-Next expects 2,560 FP8 bytes per selected token") + if not math.isfinite(scale) or scale <= 0: + raise ValueError("Invalid Flash-Next lexical table scale") + n, ew = network, trt.ElementWiseOperation + + def const(a): + return n.add_constant(a.shape, np.ascontiguousarray(a)).get_output(0) + + def op(x, y, kind): + return n.add_elementwise(x, y, kind).get_output(0) + + sh = n.add_shuffle(words) + sh.reshape_dims = (0, 640, 1) + divisors = const(np.array([1, 256, 65536, 16777216], np.int32).reshape(1, 1, 4)) + shifted = op(sh.get_output(0), divisors, ew.FLOOR_DIV) + radix = const(np.full((1, 1, 1), 256, np.int32)) + ids = op(shifted, op(op(shifted, radix, ew.FLOOR_DIV), radix, ew.PROD), ew.SUB) + raw = np.arange(256, dtype=np.uint8).view(ml_dtypes.float8_e4m3fn).astype(np.float16) + # Same FP16 scale and DQ rounding as the FP8-typed TensorRT dequantizer. + table = raw * np.float16(scale) + out = n.add_shuffle(n.add_gather(const(table), ids, 0).get_output(0)) + out.reshape_dims = (0, 2560) + return out.get_output(0) diff --git a/families/qwen3_8_flash_next/ple_weights.py b/families/qwen3_8_flash_next/ple_weights.py new file mode 100644 index 0000000000..c736ab7a9f --- /dev/null +++ b/families/qwen3_8_flash_next/ple_weights.py @@ -0,0 +1,73 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +"""Stream the lexical table into a native bundle without dequantizing its rows.""" + +import math +import re + +import ml_dtypes +import numpy as np + +from .checkpoint import FlashCheckpoint + + +_PREFIX = "model.language_model.layers.1.ple.ple_embedding." +_SHARD = re.compile(re.escape(_PREFIX) + r"ngram_embedding\.shard_(\d+)\.weight") + + +def write_ngram_table(model_dir, writer): + """Write the FP8 row section and its checkpoint-matched lookup constants.""" + with FlashCheckpoint(model_dir) as checkpoint: + write_checkpoint_ngram_table(checkpoint, writer) + + +def write_checkpoint_ngram_table(checkpoint, writer): + shards = sorted( + (int(m[1]), key) for key in checkpoint.keys_to_files if (m := _SHARD.fullmatch(key)) + ) + if not shards or [i for i, _ in shards] != list(range(len(shards))): + raise ValueError("Flash-Next requires contiguous FP8 table shards numbered from zero") + + def constant(suffix, dtype, shape): + key = _PREFIX + suffix + return checkpoint.tensor(key, dtype, shape) + + scale = constant("ngram_embedding.weight_scale", ml_dtypes.bfloat16, [1]).item() + if not math.isfinite(scale) or scale <= 0: + raise ValueError("Invalid Flash-Next FP8 table scale") + metadata = {"scale": scale} + for name, count in ( + ("layer_multipliers", 3), + ("ngram_heads_vocab_sizes", 16), + ("ngram_heads_offsets", 16), + ): + metadata[name] = constant(name, np.int64, [count]).tolist() + + blocks = [] + total = 0 + for _, key in shards: + tensor = checkpoint.array(key) + shape = tensor.shape + if ( + tensor.dtype != ml_dtypes.float8_e4m3fn + or len(shape) != 2 + or shape[1] != 160 + or shape[0] < 1 + ): + raise ValueError(f"Invalid Flash-Next FP8 embedding shard: {key}") + blocks.append((tensor, shape[0])) + total += shape[0] + + end = 0 + for offset, size in zip(metadata["ngram_heads_offsets"], metadata["ngram_heads_vocab_sizes"]): + if size <= 0 or offset < end or offset + size > total: + raise ValueError("Invalid Flash-Next head row range") + end = offset + size + + with writer.open_section("ngram_e4m3.bin") as output: + for tensor, rows in blocks: + for first in range(0, rows, 32768): + # At most 5 MiB per write; preserve the original E4M3 bytes. + part = tensor[first : first + 32768].view(np.uint8) + output.write(memoryview(part).cast("B")) + writer.add_json("ngram_layout.json", {**metadata, "table_rows": total}) diff --git a/families/qwen3_8_flash_next/prompt.py b/families/qwen3_8_flash_next/prompt.py new file mode 100644 index 0000000000..a88d132a46 --- /dev/null +++ b/families/qwen3_8_flash_next/prompt.py @@ -0,0 +1,183 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Family-owned native media bundle metadata and verified provider prompt recipes.""" + +from __future__ import annotations + + +def _split(text, marker): + if text.count(marker) != 1: + raise ValueError( + "Flash-Next native media provider template does not preserve content markers" + ) + return text.split(marker) + + +def _without_prefix(text, prefix): + if not text.startswith(prefix): + raise ValueError( + "Flash-Next native media provider template has context-dependent formatting" + ) + return text[len(prefix) :] + + +def _without_suffix(text, suffix): + if not text.endswith(suffix): + raise ValueError( + "Flash-Next native media provider template has context-dependent formatting" + ) + return text[: -len(suffix)] if suffix else text + + +def render_recipe(recipe, messages, *, generation=True): + """Builder-side oracle for the small admitted C++ message formatter.""" + last_user = -1 + for i, message in enumerate(messages): + content = message["content"].strip() + if message["role"] == "user" and not ( + content.startswith("") and content.endswith("") + ): + last_user = i + if last_user < 0: + raise ValueError("Flash-Next native media requires a user query") + system = messages[0]["content"].strip() if messages[0]["role"] == "system" else None + output = ( + recipe["default_prefix"] + if system is None + else ( + recipe["system"]["prefix"] + system + recipe["system"]["suffix"] + if system + else recipe["empty_system_prefix"] + ) + ) + for i, message in enumerate(messages): + role, content = message["role"], message["content"].strip() + if role == "system": + if i: + raise ValueError("System message must be first") + continue + if role not in {"user", "assistant"}: + raise ValueError("Unsupported Flash-Next native media role") + if role == "user": + output += recipe["user"]["prefix"] + content + recipe["user"]["suffix"] + continue + reasoning = message.get("reasoning_content", "").strip() + if ( + recipe["parse_assistant_thinking"] + and "reasoning_content" not in message + and "" in content + ): + reasoning = ( + content.split("")[0].rstrip("\n").split("")[-1].lstrip("\n").strip() + ) + content = content.split("")[-1].lstrip("\n") + form = recipe["assistant_recent" if i > last_user else "assistant_history"] + output += form["prefix"] + if form["include_reasoning"]: + output += reasoning + form["reasoning_suffix"] + output += content + form["suffix"] + return output + (recipe["generation"] if generation else "") + + +def provider_recipes(tokenizer): + """Extract only validated no-tool message forms, not a version-specific template.""" + markers = [f"FLASH_NEXT_MEDIA_SENTINEL_{i}_END" for i in range(4)] + a, b, c, reasoning = markers + + def message(role, content, **kwargs): + return {"role": role, "content": content, **kwargs} + + result = {} + for thinking in (False, True): + + def render(messages, generation=False): + return tokenizer.apply_chat_template( + messages, tokenize=False, add_generation_prompt=generation, enable_thinking=thinking + ) + + single = render([message("user", a)]) + full_prefix, user_suffix = _split(single, a) + doubled = render([message("user", a), message("user", b)]) + middle = _split(_split(doubled, a)[1], b)[0] + user_prefix = _without_prefix(middle, user_suffix) + default = _without_suffix(full_prefix, user_prefix) + system = _without_suffix( + render([message("system", c), message("user", a)]), user_prefix + a + user_suffix + ) + system_prefix, system_suffix = _split(system, c) + recipe = { + "default_prefix": default, + "user": {"prefix": user_prefix, "suffix": user_suffix}, + "system": {"prefix": system_prefix, "suffix": system_suffix}, + "empty_system_prefix": _without_suffix( + render([message("system", ""), message("user", a)]), user_prefix + a + user_suffix + ), + "generation": _without_prefix(render([message("user", a)], True), single), + } + for historical in (False, True): + messages = [message("user", a), message("assistant", b, reasoning_content=reasoning)] + if historical: + messages.append(message("user", c)) + assistant = _without_prefix(render(messages), single) + if historical: + assistant = _without_suffix(assistant, user_prefix + c + user_suffix) + prefix, suffix = _split(assistant, b) + includes = reasoning in prefix + start, between = _split(prefix, reasoning) if includes else (prefix, "") + recipe["assistant_history" if historical else "assistant_recent"] = { + "prefix": start, + "include_reasoning": includes, + "reasoning_suffix": between, + "suffix": suffix, + } + probe = [message("user", a), message("assistant", f"{reasoning}{b}")] + recipe["parse_assistant_thinking"] = False + actual = render(probe) + if render_recipe(recipe, probe, generation=False) != actual: + recipe["parse_assistant_thinking"] = True + if render_recipe(recipe, probe, generation=False) != actual: + raise ValueError("Unsupported Flash-Next native assistant reasoning formatting") + cases = [ + [message("user", " \nHello, 世界!\u2003")], + [message("system", ""), message("user", "")], + [message("system", " Follow instructions. "), message("user", a)], + [message("user", a), message("assistant", b)], + [message("user", a), message("assistant", b), message("user", c)], + probe, + probe + [message("user", c)], + [ + message("user", a), + message("assistant", b, reasoning_content=reasoning), + message("user", c), + ], + [message("user", a), message("assistant", b, reasoning_content=reasoning)], + [ + message("user", a), + message("user", "value"), + message("assistant", b), + ], + [message("user", "<|vision_start|><|image_pad|><|vision_end|>Describe this.")], + [message("user", "<|vision_start|><|video_pad|><|vision_end|>Describe this.")], + ] + for messages in cases: + for generation in (False, True): + if render_recipe(recipe, messages, generation=generation) != render( + messages, generation + ): + raise ValueError( + "Flash-Next native provider prompt recipe does not match checkpoint template" + ) + for kind in ("image", "video"): + structured = [ + message("user", [{"type": kind}, {"type": "text", "text": "Describe this."}]) + ] + expanded = [ + message("user", f"<|vision_start|><|{kind}_pad|><|vision_end|>Describe this.") + ] + if render(structured, True) != render_recipe(recipe, expanded): + raise ValueError( + "Flash-Next native provider media placeholders differ from checkpoint template" + ) + result[str(thinking).lower()] = recipe + return result diff --git a/families/qwen3_8_flash_next/requirements.txt b/families/qwen3_8_flash_next/requirements.txt new file mode 100644 index 0000000000..eb371f6a21 --- /dev/null +++ b/families/qwen3_8_flash_next/requirements.txt @@ -0,0 +1 @@ +ml-dtypes>=0.5.4 diff --git a/families/qwen3_8_flash_next/residual.py b/families/qwen3_8_flash_next/residual.py new file mode 100644 index 0000000000..946d4252eb --- /dev/null +++ b/families/qwen3_8_flash_next/residual.py @@ -0,0 +1,115 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +"""Read, update, and collapse the four residual streams of the Flash-Next decoder.""" + +import math + +import numpy as np +import tensorrt as trt + + +_STREAMS = 4 +_WIDTH = 2560 +_CHANNELS = _STREAMS * _WIDTH +_RANK = 320 + + +def _reshape(network, tensor, dims): + layer = network.add_shuffle(tensor) + layer.reshape_dims = dims + return layer.get_output(0) + + +def _read(network, hyper, checkpoint, prefix, eps, *, inject): + if hyper.dtype != trt.float16 or tuple(hyper.shape)[1:] != (_CHANNELS,): + raise ValueError("Flash-Next expects a matrix of four FP16 residual streams") + if not math.isfinite(eps) or eps <= 0: + raise ValueError("Invalid Flash-Next residual normalization epsilon") + n, ew = network, trt.ElementWiseOperation + + def const(array): + return n.add_constant(array.shape, np.ascontiguousarray(array)).get_output(0) + + def elt(left, right, op): + return n.add_elementwise(left, right, op).get_output(0) + + def sigmoid(x): + return n.add_activation(x, trt.ActivationType.SIGMOID).get_output(0) + + def linear(x, suffix, shape): + weight = checkpoint.bf16(f"{prefix}.{suffix}.weight", shape) + inputs = n.add_cast(x, trt.float32).get_output(0) + weights = n.add_cast(const(weight), trt.float32).get_output(0) + y = n.add_matrix_multiply( + inputs, trt.MatrixOperation.NONE, weights, trt.MatrixOperation.TRANSPOSE + ) + return n.add_cast(y.get_output(0), trt.float16).get_output(0) + + # RMS is independent per stream. The learned offset is applied in FP32 + # before rounding, not rounded as part of an FP16 normalization weight. + streams = _reshape(n, n.add_cast(hyper, trt.float32).get_output(0), (0, _STREAMS, _WIDTH)) + sq = elt(streams, streams, ew.PROD) + mean = n.add_reduce(sq, trt.ReduceOperation.AVG, 1 << 2, True).get_output(0) + den = n.add_unary( + elt(mean, const(np.full((1, 1, 1), eps, np.float32)), ew.SUM), trt.UnaryOperation.SQRT + ).get_output(0) + gamma = checkpoint.bf16(f"{prefix}.hc_norm.weight", (_CHANNELS,), fp32=True) + rms = elt(elt(streams, den, ew.DIV), const((1 + gamma).reshape(1, _STREAMS, _WIDTH)), ew.PROD) + normed = n.add_cast(rms, trt.float16).get_output(0) + flat = _reshape(n, normed, (0, _CHANNELS)) + quarter = const(np.full((1, 1), 1 / _STREAMS, np.float16)) + low = elt(linear(flat, "input_mix_weight_down", (_RANK, _CHANNELS)), quarter, ew.PROD) + # SiLU computes in FP32 and rounds once, after multiplication. + low = n.add_cast(low, trt.float32).get_output(0) + low = n.add_cast(elt(low, sigmoid(low), ew.PROD), trt.float16).get_output(0) + mix = sigmoid(linear(low, "input_mix_weight_up", (_CHANNELS, _RANK))) + mix = elt(_reshape(n, mix, (0, _STREAMS, _WIDTH)), normed, ew.PROD) + # Average the four already rounded FP16 products, returning an FP16 read. + mixed = n.add_reduce( + n.add_cast(mix, trt.float32).get_output(0), trt.ReduceOperation.AVG, 1 << 1, False + ).get_output(0) + mixed = n.add_cast(mixed, trt.float16).get_output(0) + if not inject: + return mixed, None + logits = linear(flat, "block_inject_weight", (_STREAMS, _CHANNELS)) + scale = elt( + sigmoid(elt(logits, quarter, ew.PROD)), const(np.full((1, 1), 2, np.float16)), ew.PROD + ) + return mixed, scale + + +def gated_sublayer(network, hyper, checkpoint, prefix, eps, block): + """Run a token block on the learned read, then inject it into the original streams. + + The callback returns (output, state). State is passed through unmodified: + only the caller knows the cache format for a linear, sparse, or MoE block. + """ + mixed, weights = read_for_block(network, hyper, checkpoint, prefix, eps) + result, state = block(mixed) + return inject_block(network, hyper, result, weights), state + + +def read_for_block(network, hyper, checkpoint, prefix, eps): + """Return the normalized token read and the stream injection coefficients.""" + return _read(network, hyper, checkpoint, prefix, eps, inject=True) + + +def inject_block(network, hyper, result, weights): + """Write one completed block output to its original, unnormalized streams.""" + if result.dtype != trt.float16 or tuple(result.shape)[1:] != (_WIDTH,): + raise ValueError("Flash-Next block must return one FP16 vector per token") + ew = trt.ElementWiseOperation + scaled = network.add_elementwise( + _reshape(network, result, (0, 1, _WIDTH)), + _reshape(network, weights, (0, _STREAMS, 1)), + ew.PROD, + ).get_output(0) + out = network.add_elementwise(hyper, _reshape(network, scaled, (0, _CHANNELS)), ew.SUM) + return out.get_output(0) + + +def collapse_residual(network, hyper, checkpoint, eps): + """The stack-exit mixer reads all four streams but has no injection matrix.""" + return _read( + network, hyper, checkpoint, "model.language_model.hyper_connection_mixer", eps, inject=False + )[0] diff --git a/families/qwen3_8_flash_next/runtime/CMakeLists.txt b/families/qwen3_8_flash_next/runtime/CMakeLists.txt new file mode 100644 index 0000000000..b7542ce252 --- /dev/null +++ b/families/qwen3_8_flash_next/runtime/CMakeLists.txt @@ -0,0 +1,30 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +find_package(ICU REQUIRED COMPONENTS uc i18n) +add_library(trtmc_model_qwen3_8_flash_next SHARED plugin.cpp native_task.cpp native_decoder.cpp decoder_layer.cpp experts.cpp positions.cpp ngram.cpp ple_rows.cpp lexical_table.cpp native_visual.cpp tokenizer.cpp sampler.cpp) +target_include_directories(trtmc_model_qwen3_8_flash_next SYSTEM PRIVATE ${TRTMC_CUDA_INCLUDE_DIR}) +target_include_directories(trtmc_model_qwen3_8_flash_next PRIVATE + ${PROJECT_SOURCE_DIR} ${PROJECT_SOURCE_DIR}/core/runtime/include) +target_link_libraries(trtmc_model_qwen3_8_flash_next PRIVATE trtmc_core nlohmann_json::nlohmann_json ICU::uc ICU::i18n ${TRTMC_CUDART_LIBRARY}) +set_target_properties(trtmc_model_qwen3_8_flash_next PROPERTIES + LIBRARY_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}" BUILD_RPATH "$ORIGIN" INSTALL_RPATH "$ORIGIN") +include("${CMAKE_CURRENT_LIST_DIR}/edge_llm/Adapter.cmake") +install(TARGETS trtmc_model_qwen3_8_flash_next LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR}) + +if(TRTMC_BUILD_TESTS) + add_executable(test_qwen3_8_flash_next_sdk_cpp ../tests/sdk_consumer.cpp) + target_link_libraries(test_qwen3_8_flash_next_sdk_cpp PRIVATE trtmc_c nlohmann_json::nlohmann_json) + set_target_properties(test_qwen3_8_flash_next_sdk_cpp PROPERTIES + RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}") + add_executable(test_qwen3_8_flash_next_lexical_stage ../tests/cpp/lexical_stage.cpp) + target_link_libraries(test_qwen3_8_flash_next_lexical_stage PRIVATE trtmc_backend_trt) + target_include_directories(test_qwen3_8_flash_next_lexical_stage SYSTEM PRIVATE ${CUDAToolkit_INCLUDE_DIRS}) + target_include_directories(test_qwen3_8_flash_next_lexical_stage PRIVATE ${PROJECT_SOURCE_DIR}/core/runtime/include) + set_target_properties(test_qwen3_8_flash_next_lexical_stage PROPERTIES + RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}") + add_dependencies(test_qwen3_8_flash_next_sdk_cpp test_qwen3_8_flash_next_lexical_stage) + set(test_name test_qwen3_8_flash_next_ngram) + add_executable(${test_name} ../tests/cpp/test_ngram.cpp ngram.cpp) + target_include_directories(${test_name} PRIVATE ${PROJECT_SOURCE_DIR}) + add_test(NAME ${test_name} COMMAND ${test_name}) +endif() diff --git a/families/qwen3_8_flash_next/runtime/decoder_layer.cpp b/families/qwen3_8_flash_next/runtime/decoder_layer.cpp new file mode 100644 index 0000000000..436294bad4 --- /dev/null +++ b/families/qwen3_8_flash_next/runtime/decoder_layer.cpp @@ -0,0 +1,43 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + */ +#include "decoder_layer.h" + +#include +#include + +namespace trtmc::qwen3_8_flash_next { +namespace { +SavedTensor save(const Tensor& tensor, const Tensor& expected) { + if (!tensor.data || tensor.shape != expected.shape || tensor.dtype != expected.dtype) + throw std::runtime_error("Unexpected Flash-Next decoder output shape or dtype"); + SavedTensor out{std::vector(tensor.nbytes()), tensor.shape, tensor.dtype}; + std::memcpy(out.bytes.data(), tensor.data, out.bytes.size()); + return out; +} +} // namespace + +LayerOutput run_decoder_layer(ITrtModule& layer, ITrtModule& expert, ITrtModule& combine, + const TensorMap& inputs, + const std::function(std::int32_t)>& load_expert) { + const auto& hyper = inputs.at("hyper"); + const auto routed = layer.forward(inputs); + auto answers = run_experts(expert, routed.at("tokens"), routed.at("selected"), load_expert); + const auto rows = routed.at("tokens").shape.at(0); + const TensorMap parts{{"skip", routed.at("skip")}, + {"shared", routed.at("shared")}, + {"inject", routed.at("inject")}, + {"weights", routed.at("weights")}, + {"experts", {answers.data(), {rows, 10, 2560}, DType::kFloat16}}}; + const auto mixed = combine.forward(parts); + LayerOutput next{save(mixed.at("hyper_out"), hyper), {}}; + for (const std::string name : + {"history", "state", "key", "value", "index_key", "lexical_history"}) { + const auto in = inputs.find(name); + if (in != inputs.end()) + next.state.emplace(name, save(routed.at("new_" + name), in->second)); + } + return next; +} +} // namespace trtmc::qwen3_8_flash_next diff --git a/families/qwen3_8_flash_next/runtime/decoder_layer.h b/families/qwen3_8_flash_next/runtime/decoder_layer.h new file mode 100644 index 0000000000..9e4102d52b --- /dev/null +++ b/families/qwen3_8_flash_next/runtime/decoder_layer.h @@ -0,0 +1,32 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + */ +#pragma once + +#include "experts.h" + +#include +#include + +namespace trtmc::qwen3_8_flash_next { + +struct SavedTensor { + std::vector bytes; + std::vector shape; + DType dtype; + Tensor view() { return {bytes.data(), shape, dtype}; } +}; + +struct LayerOutput { + SavedTensor hyper; + std::unordered_map state; +}; + +// Input caches are never mutated. The caller may commit all returned layer +// states together only after success, or discard them on failure/cancellation. +LayerOutput run_decoder_layer(ITrtModule& layer, ITrtModule& expert, ITrtModule& combine, + const TensorMap& inputs, + const std::function(std::int32_t)>& load_expert); + +} // namespace trtmc::qwen3_8_flash_next diff --git a/families/qwen3_8_flash_next/runtime/edge_llm/Adapter.cmake b/families/qwen3_8_flash_next/runtime/edge_llm/Adapter.cmake new file mode 100644 index 0000000000..c60ff01c52 --- /dev/null +++ b/families/qwen3_8_flash_next/runtime/edge_llm/Adapter.cmake @@ -0,0 +1,13 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +if(TARGET TensorRTEdgeLLM::Core AND TRTMC_EDGELLM_RELEASE STREQUAL "0.12.0") + target_sources(trtmc_model_qwen3_8_flash_next PRIVATE + ${CMAKE_CURRENT_LIST_DIR}/adapter.cpp ${CMAKE_CURRENT_LIST_DIR}/device_link.cu) + target_compile_definitions(trtmc_model_qwen3_8_flash_next PRIVATE TRTMC_FLASH_NEXT_EDGE=1) + target_include_directories(trtmc_model_qwen3_8_flash_next SYSTEM PRIVATE ${TRTMC_CUDA_INCLUDE_DIR}) + target_link_libraries(trtmc_model_qwen3_8_flash_next PRIVATE TensorRTEdgeLLM::Core ${CMAKE_DL_LIBS} ${TRTMC_CUDART_LIBRARY}) + set_target_properties(trtmc_model_qwen3_8_flash_next PROPERTIES + CUDA_ARCHITECTURES "${EdgeLLM_CUDA_ARCHITECTURE}" CUDA_SEPARABLE_COMPILATION ON CUDA_RESOLVE_DEVICE_SYMBOLS ON) + add_custom_command(TARGET trtmc_model_qwen3_8_flash_next POST_BUILD COMMAND ${CMAKE_COMMAND} -E copy_if_different + $ $/libNvInfer_edgellm_plugin.so VERBATIM) +endif() diff --git a/families/qwen3_8_flash_next/runtime/edge_llm/adapter.cpp b/families/qwen3_8_flash_next/runtime/edge_llm/adapter.cpp new file mode 100644 index 0000000000..f4a85f8019 --- /dev/null +++ b/families/qwen3_8_flash_next/runtime/edge_llm/adapter.cpp @@ -0,0 +1,338 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + */ +#include "families/qwen3_8_flash_next/runtime/edge_llm/adapter.h" + +#include "families/qwen3_8_flash_next/runtime/edge_llm/media.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace trtmc::qwen3_8_flash_next::edge_llm { +namespace { +namespace fs = std::filesystem; + +/// Turn CUDA failures into caller-visible load or inference errors. +void check_cuda(cudaError_t result) { + if (result != cudaSuccess) + throw std::runtime_error(std::string("Flash-Next Edge CUDA error: ") + + cudaGetErrorString(result)); +} + +/// Reject an engine built for a different local GPU or CUDA/TensorRT runtime. +void validate_target(const nlohmann::json& target) { + utsname host{}; + if (uname(&host) != 0) + throw std::runtime_error("Cannot identify Flash-Next Edge runtime host"); + std::ifstream release("/etc/os-release"); + std::string line, os_version; + while (std::getline(release, line)) { + if (line.rfind("VERSION_ID=", 0) == 0) { + os_version = line.substr(11); + if (os_version.size() >= 2 && os_version.front() == char(34) && + os_version.back() == char(34)) + os_version = os_version.substr(1, os_version.size() - 2); + } + } + int device = 0, cuda_version = 0; + check_cuda(cudaGetDevice(&device)); + check_cuda(cudaRuntimeGetVersion(&cuda_version)); + cudaDeviceProp gpu{}; + check_cuda(cudaGetDeviceProperties(&gpu, device)); + const int trt_version = getInferLibVersion(); + const std::string trt = + std::to_string(trt_version / 10000) + "." + std::to_string((trt_version % 10000) / 100) + + "." + std::to_string(trt_version % 100) + "." + std::to_string(getInferLibBuildVersion()); + const std::string cuda = + std::to_string(cuda_version / 1000) + "." + std::to_string((cuda_version % 1000) / 10); + if (target.at("os") != "linux" || target.at("os_version") != os_version || + target.at("arch") != host.machine || target.at("sm") != gpu.major * 10 + gpu.minor || + target.at("cuda_version") != cuda || target.at("tensorrt_version") != trt) + throw std::runtime_error( + "Flash-Next Edge bundle requires its build GPU and CUDA/TensorRT stack"); +} + +/// Own extracted engine/checkpoint files until after the Edge runtime is destroyed. +class Artifacts { + public: + explicit Artifacts(const BundleReader& bundle, const nlohmann::json& marker) { + std::set names; + for (const auto& entry : marker.at("artifacts")) { + const auto name = entry.get(); + if (!safe_artifact_path(name) || !names.insert(name).second || + !bundle.find_section(name)) + throw std::runtime_error("Invalid Flash-Next Edge artifact: " + name); + } + std::vector required{"edge_llm/engine/tokenizer.json", + "edge_llm/engine/tokenizer_config.json", + "edge_llm/engine/chat_template.jinja"}; + required.insert(required.end(), {"edge_llm/checkpoint/config.json", + "edge_llm/checkpoint/model.safetensors.index.json"}); + required.insert(required.end(), + {"edge_llm/engine/llm.engine", "edge_llm/engine/config.json", + "edge_llm/engine/multistage_config.json"}); + if (marker.at("task") == IVisionLanguageGeneration::kTask) { + for (const auto* name : {"visual.engine", "config.json", "processor_config.json", + "preprocessor_config.json"}) + required.push_back(std::string("edge_llm/engine/visual/") + name); + } + for (const auto& name : required) + if (!names.count(name) || bundle.find_section(name)->length == 0) + throw std::runtime_error("Required Flash-Next Edge artifact missing: " + name); + std::string pattern = + (fs::temp_directory_path() / "trtmc-qwen3_8_flash_next-edge-XXXXXX").string(); + if (!mkdtemp(pattern.data())) + throw std::runtime_error("Cannot create Flash-Next Edge artifact directory"); + root_ = pattern; + try { + for (const auto& name : names) { + const auto destination = root_ / name; + fs::create_directories(destination.parent_path()); + std::ofstream output(destination, std::ios::binary); + bundle.copy_section(name, output); + output.close(); + if (!output) + throw std::runtime_error("Cannot extract Flash-Next Edge artifact: " + name); + } + } catch (...) { + cleanup(); + throw; + } + } + ~Artifacts() { cleanup(); } + Artifacts(const Artifacts&) = delete; + Artifacts& operator=(const Artifacts&) = delete; + std::string engine() const { return (root_ / "edge_llm/engine").string(); } + std::string checkpoint() const { return (root_ / "edge_llm/checkpoint").string(); } + + private: + void cleanup() noexcept { + std::error_code ignored; + fs::remove_all(root_, ignored); + } + fs::path root_; +}; + +/// Close the plugin handle after runtime destruction; registrations remain mapped. +struct CloseLibrary { + void operator()(void* handle) const noexcept { + if (handle) + dlclose(handle); + } +}; + +/// Initialize the CMake-installed adjacent plugin without process-global environment mutation. +std::unique_ptr load_plugin() { + Dl_info location{}; + if (!dladdr(reinterpret_cast(&create), &location) || !location.dli_fname) + throw std::runtime_error("Cannot locate Flash-Next family library"); + const auto path = + fs::absolute(location.dli_fname).parent_path() / "libNvInfer_edgellm_plugin.so"; + std::unique_ptr plugin( + dlopen(path.c_str(), RTLD_NOW | RTLD_GLOBAL | RTLD_NODELETE)); + if (!plugin) + throw std::runtime_error("Cannot load CMake-installed Edge plugin: " + + std::string(dlerror())); + using Initialize = bool (*)(void*, const char*); + auto initialize = reinterpret_cast(dlsym(plugin.get(), "initEdgellmPlugins")); + auto* logger = static_cast(&trt_edgellm::TrtLogger::instance()); + if (!initialize || !initialize(logger, "")) + throw std::runtime_error("Cannot initialize Flash-Next Edge plugin"); + return plugin; +} + +/// Stream ownership is independent of construction success and outlives the Edge instance. +class Stream { + public: + Stream() { check_cuda(cudaStreamCreateWithFlags(&value_, cudaStreamNonBlocking)); } + ~Stream() { cudaStreamDestroy(value_); } + Stream(const Stream&) = delete; + Stream& operator=(const Stream&) = delete; + cudaStream_t get() const { return value_; } + + private: + cudaStream_t value_{nullptr}; +}; + +/// Delegate ordinary text and conditioned generation to the pinned Edge runtime. +std::unique_ptr +make_runtime(const Artifacts& artifacts, const nlohmann::json& marker, cudaStream_t stream) { + using Runtime = trt_edgellm::rt::LLMInferenceRuntime; + const auto media = marker.at("task") == IVisionLanguageGeneration::kTask + ? (fs::path(artifacts.engine()) / "visual").string() + : ""; + trt_edgellm::rt::PleRuntimeConfig ple{}; + const auto residency = marker.value("ple_residency", std::string{"resident"}); + if (residency == "cached") { + // One slot per possible n-gram head and prompt position, plus Edge's zero slot. + // Use the checkpoint topology; no GPU-specific sizing or precision change. + const auto config = + nlohmann::json::parse(std::ifstream(fs::path(artifacts.checkpoint()) / "config.json")); + const auto& text = config.at("text_config"); + const int order = text.at("ngram_size"), heads = text.at("heads_per_ngram"); + const int input = marker.at("max_input_length"); + if (order != 3 || heads != 8 || input < 1 || input > 4096 || + marker.at("max_batch_size") != 1) + throw std::invalid_argument("Invalid Flash-Next cached PLE geometry"); + ple.residency = trt_edgellm::rt::PleResidency::kCACHED; + ple.cacheSlots = 1 + input * (order - 1) * heads; + } else if (residency != "resident") + throw std::invalid_argument("Invalid Flash-Next Edge PLE residency"); + + return std::make_unique( + artifacts.engine(), media, std::unordered_map{}, stream, + trt_edgellm::rt::ContextCacheConfig{}, artifacts.checkpoint(), std::nullopt, ple); +} + +/// Thin persistent Edge API adapter; serialization prevents concurrent use of Edge request state. +class EngineState { + public: + EngineState(const BundleReader& bundle, const nlohmann::json& marker) + : artifacts_(bundle, marker), plugin_(load_plugin()), + runtime_(make_runtime(artifacts_, marker, stream_.get())), + capacity_(marker.at("max_sequence_length").get()), + input_limit_(marker.at("max_input_length").get()) {} + + /// Drain outstanding work before destroying the runtime and its weight buffers. + ~EngineState() { cudaStreamSynchronize(stream_.get()); } + + /// Invoke the full Edge visual and LLM runtime once; never retry inference natively. + TextResult generate(const std::string& prompt, const float* pixels, std::int32_t height, + std::int32_t width, const TextGenerationConfig& config) { + auto bytes = image_bytes(pixels, height, width); + auto request = make_request(prompt, config, !bytes.empty()); + if (!bytes.empty()) { + trt_edgellm::rt::Tensor tensor({1, height, width, 3}, trt_edgellm::rt::DeviceType::kCPU, + EdgeDataType::kUINT8); + std::memcpy(tensor.rawPointer(), bytes.data(), bytes.size()); + request.requests.front().imageBuffers.emplace_back(std::move(tensor)); + } + return execute(std::move(request)); + } + + TextResult continue_text(const api::TextContinuationRequest& input, api::ConfigView supplied) { + const auto* text = std::get_if(&input.prefix); + if (!text) + throw std::invalid_argument("Flash-Next accepts UTF-8 text prefixes only"); + return generate(std::string(*text), nullptr, 0, 0, generation_config(supplied, false, 128)); + } + + TextResult execute(trt_edgellm::rt::LLMGenerationRequest request) { + const auto requested_budget = request.maxGenerateLength; + std::lock_guard lock(mutex_); + try { + trt_edgellm::rt::LLMGenerationResponse response{}; + if (!runtime_->handleRequest(request, response, stream_.get())) + throw std::runtime_error("Flash-Next Edge generation failed"); + // Actual media expansion plus ORIGINAL budget, even for early EOS. + validate_response(response, input_limit_, capacity_, requested_budget); + check_cuda(cudaStreamSynchronize(stream_.get())); + return {std::move(response.outputTexts.front()), std::move(response.outputIds.front())}; + } catch (...) { + // Image buffers must outlive outstanding DMA, including a failed request. + cudaStreamSynchronize(stream_.get()); + throw; + } + } + + private: + // Reverse destruction order keeps weights, plugin and stream alive throughout Edge teardown. + Artifacts artifacts_; + std::unique_ptr plugin_; + Stream stream_; + std::unique_ptr runtime_; + int capacity_; + int input_limit_; + std::mutex mutex_; +}; +/// Text-only bundles expose only the text interface, with the 128-token default. +class TextModel final : public ITextGeneration, public api::IModel, public api::ITextContinuation { + public: + TextModel(const BundleReader& bundle, const nlohmann::json& marker) : state_(bundle, marker) {} + std::vector task_bindings() override { + return {api::bind(*this, fields(false))}; + } + TextResult run(const api::TextContinuationRequest& input, api::ConfigView supplied) override { + return state_.continue_text(input, supplied); + } + std::int32_t default_max_new_tokens() const override { return 128; } + TextResult generate(const std::string& prompt, const TextGenerationConfig& config) override { + return state_.generate(prompt, nullptr, 0, 0, config); + } + + private: + EngineState state_; +}; + +/// A complete VLM handles text continuation as well as conditioned media requests. +class VisionModel final : public IVisionLanguageGeneration, + public ITextGeneration, + public api::IModel, + public api::ITextContinuation, + public api::IImagesTextToText, + public api::IVideoTextToText, + public api::IImageVideoTextToText { + public: + VisionModel(const BundleReader& bundle, const nlohmann::json& marker) + : state_(bundle, marker) {} + const char* task() const noexcept override { return IVisionLanguageGeneration::kTask; } + std::int32_t default_max_new_tokens() const override { return 128; } + TextResult generate(const std::string& prompt, const TextGenerationConfig& config) override { + return state_.generate(prompt, nullptr, 0, 0, config); + } + std::vector task_bindings() override { + return {api::bind(*this, fields(false)), + api::bind(*this, fields(true)), + api::bind(*this, fields(true)), + api::bind(*this, fields(true))}; + } + TextResult run(const api::TextContinuationRequest& input, api::ConfigView supplied) override { + return state_.continue_text(input, supplied); + } + TextResult run(const api::ImagesTextToTextRequest& input, api::ConfigView supplied) override { + return state_.execute(media_request(input, generation_config(supplied, true, 128))); + } + TextResult run(const api::VideoTextToTextRequest& input, api::ConfigView supplied) override { + return state_.execute(media_request(input, generation_config(supplied, true, 128))); + } + TextResult run(const api::ImageVideoTextToTextRequest& input, + api::ConfigView supplied) override { + return state_.execute(media_request(input, generation_config(supplied, true, 128))); + } + TextResult generate(const std::string& prompt, const float* pixels, std::int32_t height, + std::int32_t width, const TextGenerationConfig& config) override { + return state_.generate(prompt, pixels, height, width, config); + } + + private: + EngineState state_; +}; +} // namespace + +ITask* create(const BundleReader& bundle) { + const auto bytes = bundle.read_section("edge_llm.json"); + const auto marker = nlohmann::json::parse(bytes.begin(), bytes.end()); + validate_marker(marker, bundle.info().family, bundle.info().task, bundle.info().backend); + validate_target(marker.at("target")); + if (marker.at("task") == ITextGeneration::kTask) + return new TextModel(bundle, marker); + return new VisionModel(bundle, marker); +} + +} // namespace trtmc::qwen3_8_flash_next::edge_llm diff --git a/families/qwen3_8_flash_next/runtime/edge_llm/adapter.h b/families/qwen3_8_flash_next/runtime/edge_llm/adapter.h new file mode 100644 index 0000000000..ad4549b2a9 --- /dev/null +++ b/families/qwen3_8_flash_next/runtime/edge_llm/adapter.h @@ -0,0 +1,15 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + */ +#pragma once + +#include "trtmc/bundle.h" +#include "trtmc/task.h" + +namespace trtmc::qwen3_8_flash_next::edge_llm { + +/// Create a persistent Edge task from a self-contained bundle; throws on load failure. +ITask* create(const BundleReader& bundle); + +} // namespace trtmc::qwen3_8_flash_next::edge_llm diff --git a/families/qwen3_8_flash_next/runtime/edge_llm/contract.h b/families/qwen3_8_flash_next/runtime/edge_llm/contract.h new file mode 100644 index 0000000000..6d8e223d88 --- /dev/null +++ b/families/qwen3_8_flash_next/runtime/edge_llm/contract.h @@ -0,0 +1,107 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + */ +#pragma once + +#include "trtmc/task.h" + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace trtmc::qwen3_8_flash_next::edge_llm { + +inline constexpr const char* kRelease = "0.12.0"; +inline constexpr const char* kRevision = "513dcd18291e587c80928911a480761352f3c2d8"; + +/// Refuse mismatched bundles before materializing checkpoint or CUDA resources. +inline void validate_marker(const nlohmann::json& m, const std::string& family, + const std::string& task, const std::string& backend) { + const auto variant = m.at("execution_variant").get(); + if (m.at("version") != 1 || family != "qwen3_8_flash_next" || backend != "trt" || + (task != ITextGeneration::kTask && task != IVisionLanguageGeneration::kTask) || + m.at("task") != task || m.at("edge_release") != kRelease || + (!m.at("edge_revision").is_null() && m.at("edge_revision") != kRevision) || + m.at("weight_format") != "prepared_flash_next_nvfp4" || variant != "autoregressive" || + m.at("max_batch_size") != 1 || !m.at("artifacts").is_array() || + m.at("max_input_length").get() <= 0 || + m.at("max_sequence_length").get() < m.at("max_input_length").get()) + throw std::runtime_error("Invalid Flash-Next Edge bundle contract"); +} + +/// Return whether an artifact is a normalized file below one of the two Edge roots. +inline bool safe_artifact_path(const std::string& name) { + if (name.find('\\') != std::string::npos || name.find('\0') != std::string::npos) + return false; + const std::filesystem::path path(name); + if (path.is_absolute() || path.filename().empty()) + return false; + for (const auto& part : path) + if (part == "." || part == "..") + return false; + return path.generic_string() == name && + (name.rfind("edge_llm/engine/", 0) == 0 || name.rfind("edge_llm/checkpoint/", 0) == 0); +} + +/// Reject invalid sampling settings and controls with no equivalent Edge request API. +inline void validate_generation(const TextGenerationConfig& c) { + if (!std::isfinite(c.temperature) || c.temperature < 0 || !std::isfinite(c.top_p) || + c.top_p <= 0 || c.top_p > 1 || c.top_k < 0) + throw std::invalid_argument("Invalid Flash-Next Edge sampling parameters"); + if (c.min_p != 0 || c.seed < -1 || c.eos_token_id != -1 || c.repetition_penalty != 1 || + !c.lora_adapter_id.empty() || c.stop_on_boxed_answer || + (c.text_generation_mode != "auto" && c.text_generation_mode != "autoregressive") || + c.source_language_token_id != -1 || c.forced_bos_token_id != -1 || c.guidance_scale != -1 || + c.cfg_scale != -1 || c.num_steps != -1 || c.sde_gamma != -1 || !c.initial_latents.empty() || + !c.condition_latents.empty() || !c.condition_mask.empty() || !c.sampling_steps.empty() || + !c.sde_noises.empty() || c.block_length != 0 || c.confidence_threshold != -1) + throw std::invalid_argument( + "Requested generation controls are unsupported by Flash-Next Edge"); +} + +/// Enforce prompt and total capacity without allowing Edge to silently clip generation. +inline void validate_capacity(int prompt_tokens, int input_limit, int capacity, + std::int64_t generated_tokens) { + if (prompt_tokens <= 0 || prompt_tokens > input_limit || generated_tokens <= 0 || + generated_tokens > static_cast(capacity) - prompt_tokens) + throw std::invalid_argument("Flash-Next Edge prompt and generation exceed bundle capacity"); +} + +/// Validate external normalized-float HWC images before multiplying dimensions or allocating. +inline std::size_t image_elements(const float* pixels, std::int32_t height, std::int32_t width) { + if (!pixels && height == 0 && width == 0) + return 0; + if (!pixels || height <= 0 || width <= 0) + throw std::invalid_argument( + "Flash-Next Edge image requires pixels and positive dimensions"); + const auto h = static_cast(height); + const auto w = static_cast(width); + const auto maximum = + std::min(std::numeric_limits::max() / sizeof(float), + static_cast(std::numeric_limits::max())); + if (w > maximum / 3 || h > maximum / (w * 3)) + throw std::invalid_argument("Flash-Next Edge image dimensions overflow"); + return h * w * 3; +} + +/// Map normalized public HWC input to bytes; checkpoint preprocessing belongs to Edge. +inline std::vector image_bytes(const float* pixels, std::int32_t height, + std::int32_t width) { + const auto size = image_elements(pixels, height, width); + std::vector result(size); + for (std::size_t i = 0; i < size; ++i) { + if (!std::isfinite(pixels[i])) + throw std::invalid_argument("Flash-Next Edge image contains non-finite pixels"); + result[i] = + static_cast(std::round(std::clamp(pixels[i], 0.0F, 1.0F) * 255.0F)); + } + return result; +} + +} // namespace trtmc::qwen3_8_flash_next::edge_llm diff --git a/families/qwen3_8_flash_next/runtime/edge_llm/device_link.cu b/families/qwen3_8_flash_next/runtime/edge_llm/device_link.cu new file mode 100644 index 0000000000..1ea4768d60 --- /dev/null +++ b/families/qwen3_8_flash_next/runtime/edge_llm/device_link.cu @@ -0,0 +1,5 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + */ +// Enable the final CUDA device-link step for Edge's static runtime dependencies. diff --git a/families/qwen3_8_flash_next/runtime/edge_llm/media.h b/families/qwen3_8_flash_next/runtime/edge_llm/media.h new file mode 100644 index 0000000000..8df1d19c7b --- /dev/null +++ b/families/qwen3_8_flash_next/runtime/edge_llm/media.h @@ -0,0 +1,191 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + */ +#pragma once + +#include "families/qwen3_8_flash_next/runtime/edge_llm/request.h" +#include "trtmc/internal/language.h" +#include "trtmc/internal/model.h" + +#include +#include +#include + +namespace trtmc::qwen3_8_flash_next::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) { + static const std::vector text{ + {"max_new_tokens", api::ConfigKind::I64, std::nullopt, "Generated token budget"}, + {"temperature", api::ConfigKind::F64, 1.0, "Sampling temperature"}, + {"top_k", api::ConfigKind::I64, std::int64_t{1}, "Top-k sampling"}, + {"top_p", api::ConfigKind::F64, 1.0, "Nucleus sampling"}, + {"seed", api::ConfigKind::I64, std::int64_t{-1}, "Sampling seed; -1 leaves it unspecified"}, + {"use_chat_template", api::ConfigKind::Bool, false, + "Apply the checkpoint provider template"}, + {"enable_thinking", api::ConfigKind::Bool, true, "Provider template thinking option"}, + }; + static const auto multimodal = [] { + auto copy = text; + for (auto& field : copy) + if (field.name == "use_chat_template") + field.default_value = true; + return copy; + }(); + const auto& selected = media ? multimodal : text; + return {selected.data(), selected.size()}; +} + +inline TextGenerationConfig generation_config(api::ConfigView supplied, bool media, + int default_length) { + const auto& schema = fields(media); + api::validate_config(schema, supplied); + auto integer = [&](const char* name, int fallback) { + const auto value = api::config_get(supplied, schema, name).value_or(fallback); + if (value < std::numeric_limits::min() || + value > std::numeric_limits::max()) + throw std::invalid_argument(std::string("Flash-Next option outside int32 range: ") + + name); + return static_cast(value); + }; + TextGenerationConfig config; + config.max_new_tokens = integer("max_new_tokens", default_length); + if (config.max_new_tokens <= 0) + throw std::invalid_argument("Flash-Next max_new_tokens must be positive"); + config.top_k = integer("top_k", 1); + config.seed = integer("seed", -1); + config.temperature = *api::config_get(supplied, schema, "temperature"); + config.top_p = *api::config_get(supplied, schema, "top_p"); + config.use_chat_template = *api::config_get(supplied, schema, "use_chat_template"); + config.enable_thinking = *api::config_get(supplied, schema, "enable_thinking"); + if (media && !config.use_chat_template) + throw std::invalid_argument("Flash-Next media requires its provider chat template"); + return config; +} + +/// Copy borrowed RGB storage; Edge owns resize, normalization and vision execution. +inline edge::imageUtils::ImageData image_buffer(const api::ImageView& image) { + if (!image.data || image.height == 0 || image.width == 0 || image.channels != 3 || + image.height > INT32_MAX || image.width > INT32_MAX || + (image.format != api::ImageFormat::UInt8 && image.format != api::ImageFormat::Float32)) + throw std::invalid_argument("Flash-Next requires a nonempty host RGB8 or RGB float image"); + const auto pixels = static_cast(image.height) * image.width; + const std::size_t item_size = image.format == api::ImageFormat::UInt8 ? 1 : sizeof(float); + if (pixels > std::numeric_limits::max() / 3 / item_size || + image.byte_size != pixels * 3 * item_size) + throw std::invalid_argument("Flash-Next 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, + EdgeDataType::kUINT8); + auto* out = tensor.dataPointer(); + if (image.format == api::ImageFormat::UInt8) { + std::memcpy(out, image.data, count); + } else { + const auto* bytes = static_cast(image.data); + for (std::size_t i = 0; i < count; ++i) { + float value; + std::memcpy(&value, bytes + i * sizeof(float), sizeof(float)); + if (!std::isfinite(value) || value < 0 || value > 1) + throw std::invalid_argument("Flash-Next RGB float pixels must be finite in [0,1]"); + out[i] = static_cast(std::lround(value * 255)); + } + } + return edge::imageUtils::ImageData(std::move(tensor)); +} + +/// Pack ordered RGB frames without substituting independent images for a video. +inline edge::imageUtils::ImageData video_buffer(const api::VideoView& video) { + const auto count = video.frames.size(); + if (count == 0 || count > INT32_MAX || + (!video.timestamps_seconds.empty() && video.timestamps_seconds.size() != count)) + throw std::invalid_argument("Flash-Next video needs frames and matching timestamps"); + for (std::size_t i = 0; i < video.timestamps_seconds.size(); ++i) + if (!std::isfinite(video.timestamps_seconds[i]) || + (i && video.timestamps_seconds[i] < video.timestamps_seconds[i - 1])) + throw std::invalid_argument("Flash-Next video timestamps must be finite and ordered"); + auto first = image_buffer(video.frames[0]); + const auto stride = static_cast(first.height) * first.width * 3; + if (count > static_cast(INT64_MAX) / stride) + throw std::invalid_argument("Flash-Next video dimensions overflow"); + edge::Tensor tensor({static_cast(count), first.height, first.width, 3}, + edge::DeviceType::kCPU, EdgeDataType::kUINT8); + auto* output = tensor.dataPointer(); + std::memcpy(output, first.data(), stride); + for (std::size_t i = 1; i < count; ++i) { + if (video.frames[i].height != video.frames[0].height || + video.frames[i].width != video.frames[0].width) + throw std::invalid_argument("Flash-Next video frames must have matching dimensions"); + auto frame = image_buffer(video.frames[i]); + std::memcpy(output + i * stride, frame.data(), stride); + } + edge::imageUtils::ImageData result(std::move(tensor)); + result.isVideo = true; + // Unspecified timing follows the official frame-list default of one FPS. + result.fps = 1.0; + result.timestamps.assign(video.timestamps_seconds.begin(), video.timestamps_seconds.end()); + return result; +} + +/// Preserve image, video and text order in the checkpoint provider messages. +template +inline edge::LLMGenerationRequest media_request(const Request& input, + const TextGenerationConfig& config) { + if constexpr (!std::is_same_v) { + if (!input.tools.empty()) + throw std::invalid_argument("Flash-Next media does not map tools"); + } + if (input.messages.empty()) + throw std::invalid_argument("Flash-Next media requires messages"); + auto request = make_request("", config, true); + auto& item = request.requests.front(); + item.messages.clear(); + if (!config.system_prompt.empty()) + item.messages.push_back({"system", {{"text", config.system_prompt}}}); + for (const auto& source : input.messages) { + edge::Message message; + switch (source.role) { + case api::MessageRole::System: + message.role = "system"; + break; + case api::MessageRole::User: + message.role = "user"; + break; + case api::MessageRole::Assistant: + message.role = "assistant"; + break; + default: + throw std::invalid_argument( + "Flash-Next media accepts system, user and assistant roles"); + } + message.contentIsArray = true; + if (source.parts.empty()) + throw std::invalid_argument("Flash-Next media message content cannot be empty"); + for (const auto& part : source.parts) { + std::visit( + [&](const auto& value) { + using T = std::decay_t; + if constexpr (std::is_same_v) { + message.contents.push_back({"text", std::string(value.text)}); + } else if constexpr (std::is_same_v) { + item.imageBuffers.push_back(image_buffer(value)); + message.contents.push_back({"image", ""}); + } else if constexpr (std::is_same_v) { + item.imageBuffers.push_back(video_buffer(value)); + message.contents.push_back( + {"video", "video[" + std::to_string(value.frames.size()) + " frames]"}); + } else { + throw std::invalid_argument( + "Flash-Next media does not map tool or reasoning parts"); + } + }, + part); + } + item.messages.push_back(std::move(message)); + } + return request; +} +} // namespace trtmc::qwen3_8_flash_next::edge_llm diff --git a/families/qwen3_8_flash_next/runtime/edge_llm/request.h b/families/qwen3_8_flash_next/runtime/edge_llm/request.h new file mode 100644 index 0000000000..c30855b35b --- /dev/null +++ b/families/qwen3_8_flash_next/runtime/edge_llm/request.h @@ -0,0 +1,65 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + */ +#pragma once + +#include "families/qwen3_8_flash_next/runtime/edge_llm/contract.h" + +#include +#include +#include + +namespace trtmc::qwen3_8_flash_next::edge_llm { + +/// Validate complete responses before exposing any partial output, even early EOS. +inline void validate_response(const trt_edgellm::rt::LLMGenerationResponse& response, + int input_limit, int capacity, std::int64_t requested_budget) { + if (response.outputIds.size() != 1 || response.outputTexts.size() != 1 || + response.inputTokenCounts.size() != 1 || response.finishReasons.size() != 1 || + response.outputIds.front().empty() || requested_budget <= 0 || + response.outputIds.front().size() > static_cast(requested_budget)) + throw std::runtime_error("Flash-Next Edge returned an invalid generation response"); + validate_capacity(response.inputTokenCounts.front(), input_limit, capacity, requested_budget); + const auto reason = response.finishReasons.front(); + if (reason != trt_edgellm::rt::FinishReason::kEndId && + reason != trt_edgellm::rt::FinishReason::kLength) + throw std::runtime_error("Flash-Next Edge generation did not complete successfully"); + if (reason == trt_edgellm::rt::FinishReason::kLength && + response.outputIds.front().size() != static_cast(requested_budget)) + throw std::runtime_error("Flash-Next Edge clipped the original generation budget"); +} + +/// Map public raw/chat/thinking controls without imposing family-specific hidden defaults. +inline trt_edgellm::rt::LLMGenerationRequest +make_request(const std::string& prompt, const TextGenerationConfig& config, bool has_image) { + validate_generation(config); + trt_edgellm::rt::LLMGenerationRequest request{}; + request.requests.resize(1); + auto& messages = request.requests.front().messages; + if (has_image && !config.use_chat_template) + throw std::invalid_argument("Flash-Next image input requires its provider chat template"); + if (has_image) { + messages.push_back({"user", {{"image", ""}, {"text", prompt}}}); + } else { + messages.push_back({"user", {{"text", prompt}}}); + } + if (!config.system_prompt.empty()) { + if (!config.use_chat_template) + throw std::invalid_argument( + "Flash-Next system prompts need the provider chat template"); + messages.insert(messages.begin(), {"system", {{"text", config.system_prompt}}}); + } + if (config.seed >= 0) + request.samplingSeed = static_cast(config.seed); + request.applyChatTemplate = config.use_chat_template; + request.enableThinking = config.enable_thinking; + request.temperature = config.temperature; + request.topK = config.top_k; + request.topP = config.top_p; + // Match the public generation default for legacy callers. + request.maxGenerateLength = config.max_new_tokens > 0 ? config.max_new_tokens : 128; + return request; +} + +} // namespace trtmc::qwen3_8_flash_next::edge_llm diff --git a/families/qwen3_8_flash_next/runtime/experts.cpp b/families/qwen3_8_flash_next/runtime/experts.cpp new file mode 100644 index 0000000000..5ad50a1a3a --- /dev/null +++ b/families/qwen3_8_flash_next/runtime/experts.cpp @@ -0,0 +1,95 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + */ +#include "experts.h" + +#include +#include +#include +#include +#include +#include + +namespace trtmc::qwen3_8_flash_next { +namespace { +constexpr std::size_t kHidden = 2560; +constexpr std::size_t kTop = 10; +constexpr std::size_t kExperts = 512; +} // namespace + +std::vector run_experts(ITrtModule& module, const Tensor& tokens, + const Tensor& selected, + const std::function(std::int32_t)>& load) { + if (!tokens.data || !selected.data || tokens.dtype != DType::kFloat16 || + selected.dtype != DType::kInt32 || tokens.shape.size() != 2 || tokens.shape[0] < 1 || + tokens.shape[1] != kHidden || + selected.shape != std::vector{tokens.shape[0], kTop}) + throw std::invalid_argument("Invalid Flash-Next expert routing inputs"); + auto count = static_cast(tokens.shape[0]); + if (count > std::vector().max_size() / kTop / kHidden) + throw std::length_error("Flash-Next expert output is too large"); + + const auto* x = static_cast(tokens.data); + const auto* ids = static_cast(selected.data); + std::array, kExperts> groups; + for (std::size_t t = 0; t < count; ++t) { + std::array seen{}; + for (std::size_t k = 0; k < kTop; ++k) { + const auto pos = t * kTop + k; + const auto id = ids[pos]; + if (id < 0 || id >= static_cast(kExperts) || seen[id]) + throw std::invalid_argument("Invalid Flash-Next top-k expert ids"); + seen[id] = true; + groups[id].push_back(pos); + } + } + + std::vector result(count * kTop * kHidden); + for (std::int32_t id = 0; id < static_cast(kExperts); ++id) { + const auto& group = groups[id]; + if (group.empty()) + continue; + auto packed = load(id); + if (packed.size() < 4 || std::memcmp(packed.data(), "FNE2", 4) != 0) + throw std::runtime_error("Invalid Flash-Next expert section"); + std::size_t offset = 4; + TensorMap inputs; + auto take = [&](const std::string& name, DType dtype, std::vector shape) { + Tensor tensor{packed.data() + offset, std::move(shape), dtype}; + if (tensor.nbytes() > packed.size() - offset) + throw std::runtime_error("Truncated Flash-Next expert section"); + offset += tensor.nbytes(); + inputs.emplace(name, std::move(tensor)); + }; + for (std::string p : {"gate", "up", "down"}) { + const std::int64_t rows = p == "down" ? 2560 : 640; + const std::int64_t width = p == "down" ? 640 : 2560; + take(p + "_codes", DType::kInt32, {rows, width / 8}); + take(p + "_blocks", DType::kInt32, {rows, width / 64}); + take(p + "_weight_scale", DType::kFloat32, {1}); + take(p + "_input_scale", DType::kFloat32, {1}); + take(p + "_limits", DType::kFloat32, {128, 8}); + } + if (offset != packed.size()) + throw std::runtime_error("Unexpected bytes after Flash-Next expert parameters"); + + std::vector gathered(group.size() * kHidden); + for (std::size_t i = 0; i < group.size(); ++i) + std::memcpy(gathered.data() + i * kHidden, x + (group[i] / kTop) * kHidden, + kHidden * sizeof(std::uint16_t)); + const auto rows = static_cast(group.size()); + inputs.emplace("tokens", Tensor{gathered.data(), {rows, kHidden}, DType::kFloat16}); + const auto outputs = module.forward(inputs); + const auto& y = outputs.at("result"); + if (!y.data || y.dtype != DType::kFloat16 || + y.shape != std::vector{rows, kHidden}) + throw std::runtime_error("Invalid Flash-Next expert output"); + const auto* values = static_cast(y.data); + for (std::size_t i = 0; i < group.size(); ++i) + std::memcpy(result.data() + group[i] * kHidden, values + i * kHidden, + kHidden * sizeof(std::uint16_t)); + } + return result; +} +} // namespace trtmc::qwen3_8_flash_next diff --git a/families/qwen3_8_flash_next/runtime/experts.h b/families/qwen3_8_flash_next/runtime/experts.h new file mode 100644 index 0000000000..209db69bd1 --- /dev/null +++ b/families/qwen3_8_flash_next/runtime/experts.h @@ -0,0 +1,21 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + */ +#pragma once + +#include "trtmc/runtime/trt_module.h" + +#include +#include +#include + +namespace trtmc::qwen3_8_flash_next { + +// Gather rows by selected expert, run each needed bank exactly once for this +// chunk and restore token/rank order for the TensorRT weighted reduction. +std::vector run_experts(ITrtModule& module, const Tensor& tokens, + const Tensor& selected, + const std::function(std::int32_t)>& load); + +} // namespace trtmc::qwen3_8_flash_next diff --git a/families/qwen3_8_flash_next/runtime/lexical_table.cpp b/families/qwen3_8_flash_next/runtime/lexical_table.cpp new file mode 100644 index 0000000000..e5e6a72f0e --- /dev/null +++ b/families/qwen3_8_flash_next/runtime/lexical_table.cpp @@ -0,0 +1,71 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + */ +#include "lexical_table.h" + +#include "ple_rows.h" + +#include +#include +#include +#include + +namespace trtmc::qwen3_8_flash_next { +namespace fs = std::filesystem; +LexicalTable::LexicalTable(const BundleReader& bundle) { + const auto* section = bundle.find_section("ngram_e4m3.bin"); + const auto raw = bundle.read_section("ngram_layout.json"); + const auto count = + nlohmann::json::parse(raw.begin(), raw.end()).at("table_rows").get(); + if (!section || count <= 0 || + static_cast(count) > std::numeric_limits::max() / 160 || + section->length != static_cast(count) * 160) + throw std::runtime_error("Invalid Flash-Next lexical table section length"); + bytes_ = section->length; + const auto parent = fs::temp_directory_path(); + if (fs::space(parent).available < bytes_) + throw std::runtime_error( + "Not enough temporary disk space for the Flash-Next lexical table"); + std::random_device random; + for (int i = 0; i < 8 && directory_.empty(); ++i) { + const auto trial = parent / ("trtmc-flash-ngram-" + std::to_string(random()) + "-" + + std::to_string(random())); + if (fs::create_directory(trial)) + directory_ = trial; + } + if (directory_.empty()) + throw std::runtime_error("Cannot allocate a private Flash-Next lexical table directory"); + try { + fs::permissions(directory_, fs::perms::owner_all, fs::perm_options::replace); + const auto path = directory_ / "rows.bin"; + std::ofstream out(path, std::ios::binary); + if (!out) + throw std::runtime_error("Cannot open the Flash-Next lexical table for extraction"); + bundle.copy_section("ngram_e4m3.bin", out); + out.close(); + if (!out || fs::file_size(path) != bytes_) + throw std::runtime_error("Incomplete Flash-Next lexical table extraction"); + stream_.open(path, std::ios::binary); + if (!stream_) + throw std::runtime_error("Cannot open the extracted Flash-Next lexical table"); + } catch (...) { + cleanup(); + throw; + } +} +LexicalTable::~LexicalTable() { + cleanup(); +} +void LexicalTable::cleanup() noexcept { + if (stream_.is_open()) + stream_.close(); + std::error_code ignored; + if (!directory_.empty()) + fs::remove_all(directory_, ignored); +} +std::vector LexicalTable::rows(const std::vector& ids) { + stream_.clear(); + return read_ple_rows(stream_, 0, bytes_, ids); +} +} // namespace trtmc::qwen3_8_flash_next diff --git a/families/qwen3_8_flash_next/runtime/lexical_table.h b/families/qwen3_8_flash_next/runtime/lexical_table.h new file mode 100644 index 0000000000..c297b5dff4 --- /dev/null +++ b/families/qwen3_8_flash_next/runtime/lexical_table.h @@ -0,0 +1,31 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + */ +#pragma once +#include "trtmc/bundle.h" + +#include +#include +#include +#include + +namespace trtmc::qwen3_8_flash_next { +// Materialize exactly one validated table section, not the whole native bundle. +// The existing public reader streams sections but does not expose an absolute +// section range. Do not reparse the shared header to guess a data offset. +class LexicalTable { + public: + explicit LexicalTable(const BundleReader& bundle); + ~LexicalTable(); + LexicalTable(const LexicalTable&) = delete; + LexicalTable& operator=(const LexicalTable&) = delete; + std::vector rows(const std::vector& ids); + + private: + std::filesystem::path directory_; + std::ifstream stream_; + std::uint64_t bytes_; + void cleanup() noexcept; +}; +} // namespace trtmc::qwen3_8_flash_next diff --git a/families/qwen3_8_flash_next/runtime/native_decoder.cpp b/families/qwen3_8_flash_next/runtime/native_decoder.cpp new file mode 100644 index 0000000000..2024e6b460 --- /dev/null +++ b/families/qwen3_8_flash_next/runtime/native_decoder.cpp @@ -0,0 +1,201 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + */ +#include "native_decoder.h" + +#include "decoder_layer.h" + +#include +#include +#include +#include +#include + +namespace trtmc::qwen3_8_flash_next { +namespace { +using Cache = std::unordered_map; +using Module = std::unique_ptr; + +nlohmann::json metadata(const NativeDecoder::ReadSection& read, const char* key) { + const auto bytes = read(key); + return nlohmann::json::parse(bytes.begin(), bytes.end()); +} +NgramLookup lookup(const NativeDecoder::ReadSection& read, int vocab, int eos) { + const auto v = metadata(read, "ngram_layout.json"); + const auto signed_multipliers = v.at("layer_multipliers").get>(); + NgramLayout l{}; + std::copy(signed_multipliers.begin(), signed_multipliers.end(), l.multipliers.begin()); + l.sizes = v.at("ngram_heads_vocab_sizes").get(); + l.offsets = v.at("ngram_heads_offsets").get(); + l.eos = eos; + l.vocabulary_size = vocab; + return NgramLookup(l, v.at("table_rows").get()); +} +SavedTensor zeros(DType type, std::vector shape) { + SavedTensor t{{}, std::move(shape), type}; + t.bytes.resize(t.view().nbytes()); + return t; +} +void require_shape(const Tensor& t, DType type, std::vector shape) { + if (!t.data || t.dtype != type || t.shape != shape) + throw std::runtime_error("Unexpected native Flash-Next stage output"); +} +} // namespace +struct NativeDecoder::Impl { + ReadSection read; + ReadRows read_rows; + int capacity, chunk, vocab, eos, used{0}; + float theta; + std::vector kinds; + NgramLookup ngram; + std::array history; + std::vector rotary; + Module embed, head, expert, combine; + std::vector layers; + std::vector caches; + + Impl(IBackend& backend, const ReadSection& sections, ReadRows rows, + const nlohmann::json& layout) + : read(sections), read_rows(std::move(rows)), capacity(layout.at("capacity")), + chunk(layout.at("max_chunk")), vocab(layout.at("vocab_size")), + eos(layout.at("ngram_eos")), theta(layout.at("rope_theta")), + kinds(layout.at("layers").get>()), + ngram(lookup(read, vocab, eos)) { + if (layout.at("format") != 1 || capacity <= 0 || capacity > 262144 || capacity % 4 || + chunk <= 0 || chunk > capacity || vocab != 248320 || kinds.size() != 48 || + layout.at("ple_layer_ids") != std::vector{2} || theta != 10000000.F || !read_rows) + throw std::invalid_argument("Invalid prepared Flash-Next decoder layout"); + auto load = [&](const std::string& name) { + const auto plan = read(name + ".plan"); + ModuleCreateOptions options{}; + if (embed) + options.stream = embed->stream(); + auto m = backend.create_module(plan.data(), plan.size(), options); + if (!m || !m->ok()) + throw std::runtime_error("Cannot load Flash-Next " + name + " plan"); + return m; + }; + embed = load("embed"); + head = load("head"); + expert = load("expert"); + combine = load("combine"); + rotary.resize(static_cast(capacity) * 64); + for (std::size_t i = 0; i < kinds.size(); ++i) { + Cache c; + if (kinds[i] == "linear_attention") { + c.emplace("history", zeros(DType::kFloat16, {3, 10240})); + c.emplace("state", zeros(DType::kFloat32, {48, 128, 128})); + } else if (kinds[i] == "full_attention") { + for (const char* name : {"key", "value"}) + c.emplace(name, zeros(DType::kFloat16, {capacity, 2, 256})); + c.emplace("index_key", zeros(DType::kFloat16, {capacity, 128})); + } else + throw std::invalid_argument("Unrecognized Flash-Next attention type"); + if (i == 1) + c.emplace("lexical_history", zeros(DType::kFloat16, {9, 10240})); + caches.push_back(std::move(c)); + layers.push_back(load("layer." + std::to_string(i))); + } + history = ngram.initial_history(); + } +}; +NativeDecoder::NativeDecoder(IBackend& backend, const ReadSection& read, ReadRows rows) + : impl_(std::make_unique(backend, read, std::move(rows), + metadata(read, "decoder_layout.json"))) {} +NativeDecoder::~NativeDecoder() = default; +int NativeDecoder::capacity() const { + return impl_->capacity; +} +int NativeDecoder::max_chunk() const { + return impl_->chunk; +} +void NativeDecoder::reset() { + auto& d = *impl_; + d.used = 0; + d.history = d.ngram.initial_history(); + std::fill(d.rotary.begin(), d.rotary.end(), 0.F); + for (auto& layer : d.caches) + for (auto& field : layer) + std::fill(field.second.bytes.begin(), field.second.bytes.end(), 0); +} +std::vector NativeDecoder::forward(const std::vector& ids, + const std::vector& positions, + const std::vector& media_mask, + const std::vector& media, + bool want_logits) { + auto& d = *impl_; + if (ids.empty() || + ids.size() > static_cast(std::min(d.chunk, d.capacity - d.used)) || + ids.size() != positions.size() || (!media_mask.empty() && ids.size() != media_mask.size())) + throw std::invalid_argument( + "Flash-Next chunk exceeds its profile or has inconsistent inputs"); + const auto n = static_cast(ids.size()); + std::vector mask(n), slot(n); + std::vector vectors(n * 2560); + std::size_t cursor = 0; + for (std::size_t i = 0; i < ids.size(); ++i) { + if (!media_mask.empty() && media_mask[i]) { + if (media_mask[i] != 1 || media.size() - cursor < 2560) + throw std::invalid_argument("Invalid Flash-Next media row"); + mask[i] = 1; + std::copy_n(media.begin() + cursor, 2560, vectors.begin() + i * 2560); + cursor += 2560; + } + } + if (cursor != media.size()) + throw std::invalid_argument("Unconsumed Flash-Next media rows"); + const auto lexical = d.ngram.lookup(ids, d.history); + auto words = d.read_rows(lexical.rows); + if (words.size() != ids.size() * 2560) + throw std::runtime_error("Invalid Flash-Next lexical row data"); + std::iota(slot.begin(), slot.end(), d.used); + // Write only uncommitted rotary slots. A retry overwrites them, and no + // preceding causal query can attend to a block containing a future slot. + for (std::size_t i = 0; i < ids.size(); ++i) { + const auto row = rotary_row(positions[i], d.theta); + std::copy(row.begin(), row.end(), + d.rotary.begin() + static_cast(slot[i]) * 64); + } + const auto embedded = + d.embed->forward({{"ids", {const_cast(ids.data()), {n}, DType::kInt32}}, + {"media_mask", {mask.data(), {n, 1}, DType::kInt32}}, + {"media_vectors", {vectors.data(), {n, 2560}, DType::kFloat16}}}); + auto hyper = embedded.at("hyper"); + require_shape(hyper, DType::kFloat16, {n, 10240}); + SavedTensor working; + std::vector next; + next.reserve(d.layers.size()); + for (std::size_t i = 0; i < d.layers.size(); ++i) { + TensorMap inputs{{"hyper", hyper}}; + if (i == 1) + inputs.emplace("lexical_words", Tensor{words.data(), {n, 640}, DType::kInt32}); + if (d.kinds[i] == "full_attention") { + inputs.emplace("position", Tensor{slot.data(), {n}, DType::kInt32}); + inputs.emplace("rotary", Tensor{d.rotary.data(), {d.capacity, 64}, DType::kFloat32}); + } + for (auto& field : d.caches[i]) + inputs.emplace(field.first, field.second.view()); + auto y = + run_decoder_layer(*d.layers[i], *d.expert, *d.combine, inputs, [&](std::int32_t id) { + return d.read("expert." + std::to_string(i) + "." + std::to_string(id) + ".bin"); + }); + next.push_back(std::move(y.state)); + working = std::move(y.hyper); + hyper = working.view(); + } + std::vector result; + if (want_logits) { + auto* final_row = working.bytes.data() + (n - 1) * 10240 * 2; + const auto output = d.head->forward({{"hyper", {final_row, {1, 10240}, DType::kFloat16}}}); + const auto& logits = output.at("logits"); + require_shape(logits, DType::kFloat16, {1, d.vocab}); + result.resize(d.vocab); + std::memcpy(result.data(), logits.data, logits.nbytes()); + } + d.caches.swap(next); + d.history = lexical.history; + d.used += static_cast(n); + return result; +} +} // namespace trtmc::qwen3_8_flash_next diff --git a/families/qwen3_8_flash_next/runtime/native_decoder.h b/families/qwen3_8_flash_next/runtime/native_decoder.h new file mode 100644 index 0000000000..d73df62775 --- /dev/null +++ b/families/qwen3_8_flash_next/runtime/native_decoder.h @@ -0,0 +1,40 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + */ +#pragma once + +#include "ngram.h" +#include "positions.h" +#include "trtmc/runtime/trt_backend.h" + +#include +#include +#include +#include +#include + +namespace trtmc::qwen3_8_flash_next { + +class NativeDecoder { + public: + using ReadSection = std::function(const std::string&)>; + using ReadRows = std::function(const std::vector&)>; + NativeDecoder(IBackend& backend, const ReadSection& read, ReadRows read_rows); + ~NativeDecoder(); + void reset(); + int capacity() const; + int max_chunk() const; + // Packed media vectors [number of marked positions,2560], in token order. + // The returned FP16 vocabulary row contains the next-token logits; empty + // when prefill does not request logits. No committed states change on failure. + std::vector forward(const std::vector& ids, + const std::vector& positions, + const std::vector& media_mask, + const std::vector& media, bool want_logits); + + private: + struct Impl; + std::unique_ptr impl_; +}; +} // namespace trtmc::qwen3_8_flash_next diff --git a/families/qwen3_8_flash_next/runtime/native_task.cpp b/families/qwen3_8_flash_next/runtime/native_task.cpp new file mode 100644 index 0000000000..e8cce51d5d --- /dev/null +++ b/families/qwen3_8_flash_next/runtime/native_task.cpp @@ -0,0 +1,505 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + */ +#include "native_task.h" + +#include "lexical_table.h" +#include "native_decoder.h" +#include "native_visual.h" +#include "sampler.h" +#include "tokenizer.h" +#include "trtmc/internal/language.h" +#include "trtmc/internal/model.h" + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace trtmc::qwen3_8_flash_next { +namespace { +namespace api = trtmc::internal; +using Json = nlohmann::json; + +// Python/Jinja strip() whitespace, including Unicode White_Space and the four +// ASCII information separators. Preserve all interior text and non-English data. +std::string trim(std::string text) { + static const std::vector spaces{" ", + "\t", + "\n", + "\r", + "\v", + "\f", + "\x1c", + "\x1d", + "\x1e", + "\x1f", + "\xc2\x85", + "\xc2\xa0", + "\xe1\x9a\x80", + "\xe2\x80\x80", + "\xe2\x80\x81", + "\xe2\x80\x82", + "\xe2\x80\x83", + "\xe2\x80\x84", + "\xe2\x80\x85", + "\xe2\x80\x86", + "\xe2\x80\x87", + "\xe2\x80\x88", + "\xe2\x80\x89", + "\xe2\x80\x8a", + "\xe2\x80\xa8", + "\xe2\x80\xa9", + "\xe2\x80\xaf", + "\xe2\x81\x9f", + "\xe3\x80\x80"}; + std::size_t begin = 0, end = text.size(); + bool found = true; + while (found && begin < end) { + found = false; + for (const auto& space : spaces) + if (space.size() <= end - begin && text.compare(begin, space.size(), space) == 0) { + begin += space.size(); + found = true; + break; + } + } + found = true; + while (found && begin < end) { + found = false; + for (const auto& space : spaces) + if (space.size() <= end - begin && + text.compare(end - space.size(), space.size(), space) == 0) { + end -= space.size(); + found = true; + break; + } + } + return text.substr(begin, end - begin); +} + +std::string value(const Json& object, const char* name) { + return object.at(name).get(); +} +struct Message { + api::MessageRole role; + std::string text; +}; + +std::string format_prompt(const Json& recipe, const std::vector& messages) { + if (messages.empty()) + throw std::invalid_argument("Flash-Next native media requires messages"); + int64_t last_user = -1; + std::vector content; + for (std::size_t i = 0; i < messages.size(); ++i) { + content.push_back(trim(messages[i].text)); + const auto& text = content.back(); + const bool tool_response = text.rfind("", 0) == 0 && text.size() >= 16 && + text.compare(text.size() - 16, 16, "") == 0; + if (messages[i].role == api::MessageRole::User && !tool_response) + last_user = i; + } + if (last_user < 0) + throw std::invalid_argument("Flash-Next native media requires a user query"); + std::string output; + if (messages[0].role != api::MessageRole::System) + output = value(recipe, "default_prefix"); + else if (content[0].empty()) + output = value(recipe, "empty_system_prefix"); + else + output = value(recipe.at("system"), "prefix") + content[0] + + value(recipe.at("system"), "suffix"); + for (std::size_t i = 0; i < messages.size(); ++i) { + if (messages[i].role == api::MessageRole::System) { + if (i) + throw std::invalid_argument("Flash-Next native system message must be first"); + continue; + } + if (messages[i].role == api::MessageRole::User) { + output += value(recipe.at("user"), "prefix") + content[i] + + value(recipe.at("user"), "suffix"); + continue; + } + if (messages[i].role != api::MessageRole::Assistant) + throw std::invalid_argument( + "Flash-Next native media accepts system, user and assistant roles"); + std::string body = content[i], reasoning; + const auto close = body.find(""); + if (recipe.at("parse_assistant_thinking").get() && close != std::string::npos) { + reasoning = body.substr(0, close); + while (!reasoning.empty() && reasoning.back() == '\n') + reasoning.pop_back(); + const auto open = reasoning.rfind(""); + if (open != std::string::npos) + reasoning.erase(0, open + 7); + reasoning = trim(reasoning); + body.erase(0, body.rfind("") + 8); + body.erase(0, body.find_first_not_of('\n')); + } + const auto& form = recipe.at(static_cast(i) > last_user ? "assistant_recent" + : "assistant_history"); + output += value(form, "prefix"); + if (form.at("include_reasoning").get()) + output += reasoning + value(form, "reasoning_suffix"); + output += body + value(form, "suffix"); + } + return output + value(recipe, "generation"); +} + +Span fields(bool media) { + static const std::vector text{ + {"max_new_tokens", api::ConfigKind::I64, std::nullopt, "Generated token budget"}, + {"temperature", api::ConfigKind::F64, 1.0, "Sampling temperature"}, + {"top_k", api::ConfigKind::I64, int64_t{1}, "Top-k sampling"}, + {"top_p", api::ConfigKind::F64, 1.0, "Nucleus sampling"}, + {"seed", api::ConfigKind::I64, int64_t{-1}, "Sampling seed; -1 leaves it unspecified"}, + {"use_chat_template", api::ConfigKind::Bool, false, "Apply checkpoint provider template"}, + {"enable_thinking", api::ConfigKind::Bool, true, "Provider template thinking option"}, + }; + static const auto multimodal = [] { + auto copy = text; + for (auto& item : copy) + if (item.name == "use_chat_template") + item.default_value = true; + return copy; + }(); + const auto& selected = media ? multimodal : text; + return {selected.data(), selected.size()}; +} + +TextGenerationConfig generation_config(api::ConfigView supplied, bool media, int32_t length) { + const auto schema = fields(media); + api::validate_config(schema, supplied); + auto integer = [&](const char* name, int32_t fallback) { + const auto number = api::config_get(supplied, schema, name).value_or(fallback); + if (number < INT32_MIN || number > INT32_MAX) + throw std::invalid_argument( + std::string("Flash-Next native option outside int32 range: ") + name); + return static_cast(number); + }; + TextGenerationConfig cfg; + cfg.max_new_tokens = integer("max_new_tokens", length); + if (cfg.max_new_tokens <= 0) + throw std::invalid_argument("Flash-Next native max_new_tokens must be positive"); + cfg.top_k = integer("top_k", 1); + cfg.seed = integer("seed", -1); + cfg.temperature = *api::config_get(supplied, schema, "temperature"); + cfg.top_p = *api::config_get(supplied, schema, "top_p"); + cfg.use_chat_template = *api::config_get(supplied, schema, "use_chat_template"); + cfg.enable_thinking = *api::config_get(supplied, schema, "enable_thinking"); + if (media && !cfg.use_chat_template) + throw std::invalid_argument("Flash-Next native media requires its provider chat template"); + return cfg; +} + +class NativeMediaTask final : public ITextGeneration, + public IVisionLanguageGeneration, + public api::IModel, + public api::ITextContinuation, + public api::IImagesTextToText, + public api::IVideoTextToText, + public api::IImageVideoTextToText { + public: + explicit NativeMediaTask(const FamilyContext& c) + : reader_(c.reader), meta_(Json::parse(text("native.json"))), table_(reader_), + decoder_( + c.backend, [this](const auto& n) { return reader_.read_section(n); }, + [this](const auto& ids) { return table_.rows(ids); }), + tokenizer_(text("tokenizer.json")), task_(c.reader.info().task), + input_limit_(meta_.at("max_input_length")), + max_visual_tokens_(std::min(input_limit_, 1024)) { + if (meta_.at("format") != 1 || meta_.at("task") != task_ || + meta_.at("weight_format") != "prepared_flash_next_nvfp4" || + meta_.at("capacity") != decoder_.capacity() || input_limit_ <= 0 || + input_limit_ > decoder_.capacity()) + throw std::runtime_error("Invalid Flash-Next native bundle metadata"); + if (task_ == IVisionLanguageGeneration::kTask) { + const auto& m = meta_.at("visual"); + NativeVisionConfig v; + v.hidden = m.at("hidden"); + v.patch = m.at("patch"); + v.temporal = m.at("temporal"); + v.merge = m.at("merge"); + v.positions = m.at("positions"); + v.head_dim = m.at("head_dim"); + v.theta = m.at("theta"); + v.max_tokens = m.at("max_tokens"); + v.image_min_pixels = m.at("image_min_pixels"); + v.image_max_pixels = m.at("image_max_pixels"); + v.video_min_pixels = m.at("video_min_pixels"); + v.video_max_pixels = m.at("video_max_pixels"); + const auto plan = reader_.read_section("visual.plan"); + visual_ = std::make_unique( + c.backend.create_module(plan.data(), plan.size(), {}), v); + } else if (task_ != ITextGeneration::kTask) + throw std::runtime_error("Unrecognized Flash-Next task"); + } + const char* task() const noexcept override { return task_.c_str(); } + int32_t default_max_new_tokens() const override { + return std::min(128, decoder_.capacity() - 1); + } + std::vector task_bindings() override { + return {api::bind(*this, fields(false)), + api::bind(*this, fields(true)), + api::bind(*this, fields(true)), + api::bind(*this, fields(true))}; + } + TextResult run(const api::TextContinuationRequest& request, api::ConfigView config) override { + const auto* text = std::get_if(&request.prefix); + if (!text) + throw std::invalid_argument("Flash-Next native accepts UTF-8 text prefixes only"); + return generate(std::string(*text), + generation_config(config, false, default_max_new_tokens())); + } + TextResult run(const api::ImagesTextToTextRequest& input, api::ConfigView cfg) override { + if (!input.tools.empty()) + throw std::invalid_argument("Flash-Next native media does not map tools"); + return execute_messages(input.messages, + generation_config(cfg, true, default_max_new_tokens())); + } + TextResult run(const api::VideoTextToTextRequest& input, api::ConfigView cfg) override { + if (!input.tools.empty()) + throw std::invalid_argument("Flash-Next native media does not map tools"); + return execute_messages(input.messages, + generation_config(cfg, true, default_max_new_tokens())); + } + TextResult run(const api::ImageVideoTextToTextRequest& input, api::ConfigView cfg) override { + return execute_messages(input.messages, + generation_config(cfg, true, default_max_new_tokens())); + } + TextResult generate(const std::string& prompt, const TextGenerationConfig& config) override { + std::lock_guard lock(mutex_); + if (!config.system_prompt.empty() && !config.use_chat_template) + throw std::invalid_argument("Flash-Next system prompts need a provider template"); + std::vector messages; + if (!config.system_prompt.empty()) + messages.push_back({api::MessageRole::System, config.system_prompt}); + messages.push_back({api::MessageRole::User, prompt}); + const std::string formatted = + config.use_chat_template + ? format_prompt(meta_.at("prompts").at(config.enable_thinking ? "true" : "false"), + messages) + : prompt; + return execute(formatted, {}, config); + } + TextResult generate(const std::string& prompt, const float* pixels, int32_t height, + int32_t width, const TextGenerationConfig& cfg) override { + if (!pixels) { + if (height || width) + throw std::invalid_argument("Flash-Next native image dimensions require pixels"); + return generate(prompt, cfg); + } + if (height <= 0 || width <= 0 || !cfg.use_chat_template || + static_cast(height) * width > + std::numeric_limits::max() / 3 / sizeof(float)) + throw std::invalid_argument( + "Flash-Next native image requires positive dimensions and provider chat template"); + std::lock_guard lock(mutex_); + auto groups = visual_->encode( + api::ImageView{pixels, static_cast(height) * width * 3 * sizeof(float), + static_cast(height), static_cast(width), 3, + api::ImageFormat::Float32}); + const auto content = native_visual_text(groups) + prompt; + std::vector messages; + if (!cfg.system_prompt.empty()) + messages.push_back({api::MessageRole::System, cfg.system_prompt}); + messages.push_back({api::MessageRole::User, content}); + return execute( + format_prompt(meta_.at("prompts").at(cfg.enable_thinking ? "true" : "false"), messages), + groups, cfg); + } + + private: + template + TextResult execute_messages(Messages messages, const TextGenerationConfig& cfg) { + std::lock_guard lock(mutex_); + if (messages.empty()) + throw std::invalid_argument("Flash-Next native media requires messages"); + std::vector prompt; + if (!cfg.system_prompt.empty()) + prompt.push_back({api::MessageRole::System, cfg.system_prompt}); + std::vector visual_groups; + std::size_t visual_tokens = 0; + for (const auto& message : messages) { + if ((message.role != api::MessageRole::User && + message.role != api::MessageRole::Assistant && + message.role != api::MessageRole::System) || + message.parts.empty()) + throw std::invalid_argument( + "Flash-Next native media requires nonempty system/user/assistant messages"); + if (message.role == api::MessageRole::System && !prompt.empty()) + throw std::invalid_argument("Flash-Next native system message must be first"); + Message item{message.role, {}}; + for (const auto& part : message.parts) { + std::visit( + [&](const auto& value) { + using T = std::decay_t; + if constexpr (std::is_same_v) + item.text += value.text; + else if constexpr (std::is_same_v || + std::is_same_v) { + if (message.role == api::MessageRole::System) + throw std::invalid_argument( + "Flash-Next native system message cannot contain media"); + auto groups = visual_->encode(value); + for (const auto& group : groups) + visual_tokens += + static_cast(group.height) * group.width; + if (visual_tokens > static_cast( + std::min(input_limit_, max_visual_tokens_))) + throw std::invalid_argument( + "Flash-Next native media exceeds visual input capacity"); + item.text += native_visual_text(groups); + for (auto& group : groups) + visual_groups.push_back(std::move(group)); + } else + throw std::invalid_argument( + "Flash-Next native media does not map tool or reasoning parts"); + }, + part); + } + prompt.push_back(std::move(item)); + } + return execute( + format_prompt(meta_.at("prompts").at(cfg.enable_thinking ? "true" : "false"), prompt), + visual_groups, cfg); + } + std::string text(const std::string& name) const { + const auto raw = reader_.read_section(name); + return {raw.begin(), raw.end()}; + } + TextResult execute(const std::string& prompt, const std::vector& groups, + TextGenerationConfig c) { + if (!std::isfinite(c.temperature) || c.temperature < 0 || !std::isfinite(c.top_p) || + c.top_p <= 0 || c.top_p > 1 || c.top_k < 0 || c.seed < -1 || !std::isfinite(c.min_p) || + c.min_p < 0 || c.min_p > 1 || c.eos_token_id < -1 || c.eos_token_id >= 248320 || + c.repetition_penalty != 1 || !c.lora_adapter_id.empty() || c.stop_on_boxed_answer || + (c.text_generation_mode != "auto" && c.text_generation_mode != "autoregressive") || + c.source_language_token_id != -1 || c.forced_bos_token_id != -1 || + c.guidance_scale != -1 || c.cfg_scale != -1 || c.num_steps != -1 || c.sde_gamma != -1 || + !c.initial_latents.empty() || !c.condition_latents.empty() || + !c.condition_mask.empty() || !c.sampling_steps.empty() || !c.sde_noises.empty() || + c.block_length || c.confidence_threshold != -1) + throw std::invalid_argument("Unsupported Flash-Next native generation control"); + auto ids = tokenizer_.encode(prompt); + const int budget = c.max_new_tokens > 0 ? c.max_new_tokens : default_max_new_tokens(); + if (ids.empty() || ids.size() > static_cast(input_limit_) || + budget > decoder_.capacity() - static_cast(ids.size())) + throw std::invalid_argument("Flash-Next prompt and generation exceed bundle capacity"); + std::vector types(ids.size(), 0); + std::vector images, videos; + std::size_t group = 0; + int image = meta_.at("image_token_id"), video = meta_.at("video_token_id"), + start = meta_.at("vision_start_token_id"), end = meta_.at("vision_end_token_id"); + for (std::size_t i = 0; i < ids.size();) { + if (ids[i] != image && ids[i] != video) { + ++i; + continue; + } + const bool is_video = ids[i] == video; + const auto begin = i; + while (i < ids.size() && ids[i] == (is_video ? video : image)) + ++i; + if (group >= groups.size() || !begin || ids[begin - 1] != start || i == ids.size() || + ids[i] != end) + throw std::invalid_argument( + "Flash-Next visual placeholder lacks matching media or delimiters"); + const auto& v = groups[group++]; + if (v.video != is_video || v.height <= 0 || v.width <= 0 || + static_cast(v.height) * v.width != static_cast(i - begin) || + v.features.size() != (i - begin) * 2560) + throw std::invalid_argument("Flash-Next visual features do not match prompt span"); + std::fill(types.begin() + begin, types.begin() + i, is_video ? 2 : 1); + (is_video ? videos : images).push_back({1, v.height * 2, v.width * 2}); + } + if (group != groups.size()) + throw std::invalid_argument("Unused Flash-Next media feature group"); + const auto pos = prompt_positions(types, images, videos, 2, input_limit_); + std::vector logits; + decoder_.reset(); + std::size_t gi = 0, row = 0; + for (std::size_t off = 0; off < ids.size();) { + const auto last = std::min(ids.size(), off + decoder_.max_chunk()); + std::vector mask(last - off, 0); + std::vector pixels; + for (std::size_t j = off; j < last; ++j) { + if (!types[j]) + continue; + mask[j - off] = 1; + const auto& v = groups[gi].features; + pixels.insert(pixels.end(), v.begin() + row, v.begin() + row + 2560); + row += 2560; + if (row == v.size()) { + row = 0; + ++gi; + } + } + logits = decoder_.forward({ids.begin() + off, ids.begin() + last}, + {pos.prompt.begin() + off, pos.prompt.begin() + last}, mask, + pixels, last == ids.size()); + off = last; + } + const auto params = flash_next_sampling_params_from_config( + c, -1, meta_.at("eos").get>()); + auto sampler = create_flash_next_sampler(params); + std::vector answer; + std::vector scores(logits.size()); + for (int step = 0; step < budget; ++step) { + for (std::size_t k = 0; k < logits.size(); ++k) { + __half_raw raw{}; + raw.x = logits[k]; + scores[k] = __half2float(static_cast<__half>(raw)); + if (!std::isfinite(scores[k])) + throw std::runtime_error("Flash-Next returned non-finite logits"); + } + const auto token = + sampler->sample(scores.data(), static_cast(scores.size()), params); + answer.push_back(token.token_id); + if (token.is_eos || step + 1 == budget) + break; + const auto next = pos.next + step; + logits = decoder_.forward({token.token_id}, {{next, next, next}}, {}, {}, true); + } + return {tokenizer_.decode(answer), std::move(answer)}; + } + BundleReader reader_; + Json meta_; + LexicalTable table_; + NativeDecoder decoder_; + Tokenizer tokenizer_; + std::unique_ptr visual_; + std::string task_; + int input_limit_, max_visual_tokens_; + std::mutex mutex_; +}; + +class TextOnly final : public ITextGeneration, public api::IModel, public api::ITextContinuation { + public: + explicit TextOnly(const FamilyContext& c) : state_(c) {} + std::vector task_bindings() override { + return {api::bind(*this, fields(false))}; + } + int32_t default_max_new_tokens() const override { return state_.default_max_new_tokens(); } + TextResult run(const api::TextContinuationRequest& req, api::ConfigView cfg) override { + return state_.run(req, cfg); + } + TextResult generate(const std::string& prompt, const TextGenerationConfig& c) override { + return state_.generate(prompt, c); + } + + private: + NativeMediaTask state_; +}; +} // namespace +ITask* create_native(const FamilyContext& c) { + if (c.reader.info().task == ITextGeneration::kTask) + return new TextOnly(c); + auto* vision = new NativeMediaTask(c); + return static_cast(vision); +} +} // namespace trtmc::qwen3_8_flash_next diff --git a/families/qwen3_8_flash_next/runtime/native_task.h b/families/qwen3_8_flash_next/runtime/native_task.h new file mode 100644 index 0000000000..50d5eec709 --- /dev/null +++ b/families/qwen3_8_flash_next/runtime/native_task.h @@ -0,0 +1,9 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + */ +#pragma once +#include "trtmc/runtime/family_factory.h" +namespace trtmc::qwen3_8_flash_next { +ITask* create_native(const FamilyContext& context); +} diff --git a/families/qwen3_8_flash_next/runtime/native_visual.cpp b/families/qwen3_8_flash_next/runtime/native_visual.cpp new file mode 100644 index 0000000000..1c4e08a325 --- /dev/null +++ b/families/qwen3_8_flash_next/runtime/native_visual.cpp @@ -0,0 +1,368 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + */ +#include "families/qwen3_8_flash_next/runtime/native_visual.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace trtmc::qwen3_8_flash_next { +namespace { +uint16_t half_bits(float value) { + const __half half = __float2half_rn(value); + uint16_t bits; + std::memcpy(&bits, &half, sizeof(bits)); + return bits; +} + +void validate_image(const internal::ImageView& image) { + if (!image.data || !image.height || !image.width || image.channels != 3 || + image.height > INT32_MAX || image.width > INT32_MAX || + (image.format != internal::ImageFormat::UInt8 && + image.format != internal::ImageFormat::Float32)) + throw std::invalid_argument( + "Flash-Next native media requires nonempty RGB8 or RGB float images"); + const uint64_t pixels = static_cast(image.height) * image.width; + const std::size_t element = image.format == internal::ImageFormat::UInt8 ? 1 : sizeof(float); + if (pixels > std::numeric_limits::max() / 3 / element || + image.byte_size != pixels * 3 * element) + throw std::invalid_argument( + "Flash-Next native RGB storage does not match image dimensions"); +} + +double cubic(double x) { + x = std::abs(x); + if (x < 1) + return ((1.5 * x - 2.5) * x) * x + 1; + if (x < 2) + return ((-0.5 * x + 2.5) * x - 4) * x + 2; + return 0; +} +struct Tap { + int32_t first; + std::vector coefficients; +}; +struct Axis { + std::vector taps; + int shift; +}; +Axis filters(int32_t source, int32_t target) { + const double scale = double(source) / target, width = std::max(1.0, scale); + std::vector> rows(target); + Axis axis{{}, 0}; + double largest = 0; + for (int32_t i = 0; i < target; ++i) { + const double center = scale * (i + 0.5); + const int32_t first = static_cast(std::max(0.0, center - 2 * width + 0.5)); + const int32_t end = + static_cast(std::min(double(source), center + 2 * width + 0.5)); + auto& w = rows[i]; + double sum = 0; + for (int32_t k = first; k < end; ++k) { + const double v = cubic((k - center + 0.5) / width); + w.push_back(v); + sum += v; + } + for (auto& v : w) { + v /= sum; + largest = std::max(largest, v); + } + axis.taps.push_back({first, {}}); + } + while (axis.shift < 22 && std::lround(std::ldexp(largest, axis.shift + 1)) < 32768) + ++axis.shift; + for (int32_t i = 0; i < target; ++i) + for (double w : rows[i]) + axis.taps[i].coefficients.push_back( + static_cast(std::lround(std::ldexp(w, axis.shift)))); + return axis; +} +template +uint8_t resample(const Axis& axis, int32_t i, Pixel pixel) { + const auto& tap = axis.taps[i]; + int64_t value = int64_t{1} << (axis.shift - 1); + for (std::size_t j = 0; j < tap.coefficients.size(); ++j) + value += tap.coefficients[j] * int64_t(pixel(tap.first + static_cast(j))); + return static_cast( + std::clamp(std::max(0, value) >> axis.shift, 0, 255)); +} + +std::vector normalized(const NativeVisionConfig& c, const internal::ImageView& image, + int32_t height, int32_t width) { + validate_image(image); + const auto count = static_cast(image.height) * image.width * 3; + std::vector converted; + const auto* pixels = static_cast(image.data); + if (image.format == internal::ImageFormat::Float32) { + converted.resize(count); + for (std::size_t i = 0; i < count; ++i) { + float pixel; + std::memcpy(&pixel, pixels + i * sizeof(float), sizeof(float)); + if (!std::isfinite(pixel) || pixel < 0 || pixel > 1) + throw std::invalid_argument( + "Flash-Next native RGB float pixels must be finite in [0,1]"); + converted[i] = static_cast(std::lround(pixel * 255)); + } + pixels = converted.data(); + } + // The provider resizes byte RGB with a separable antialiased cubic. It + // truncates and renormalizes edge filters and rounds to bytes after each + // dimension, before converting and normalizing the image for the model. + const auto horizontal = filters(image.width, width), vertical = filters(image.height, height); + std::vector rows(static_cast(image.height) * width * 3); + for (uint32_t y = 0; y < image.height; ++y) + for (int32_t x = 0; x < width; ++x) + for (int c0 = 0; c0 < 3; ++c0) + rows[(static_cast(y) * width + x) * 3 + c0] = + resample(horizontal, x, [&](int sx) { + return pixels[(static_cast(y) * image.width + sx) * 3 + c0]; + }); + std::vector result(static_cast(height) * width * 3); + for (int32_t y = 0; y < height; ++y) + for (int32_t x = 0; x < width; ++x) + for (int c0 = 0; c0 < 3; ++c0) { + const auto pixel = resample(vertical, y, [&](int sy) { + return rows[(static_cast(sy) * width + x) * 3 + c0]; + }); + result[(static_cast(y) * width + x) * 3 + c0] = + half_bits((float(pixel) / 255 - c.mean[c0]) / c.stddev[c0]); + } + return result; +} +} // namespace + +void NativeVisionConfig::validate() const { + if (patch != 16 || temporal != 2 || merge != 2 || positions != 2304 || head_dim != 72 || + hidden != 2560 || theta != 10000 || max_tokens <= 0 || image_min_pixels <= 0 || + image_max_pixels < image_min_pixels || video_min_pixels <= 0 || + video_max_pixels < video_min_pixels) + throw std::invalid_argument("Invalid Flash-Next native visual geometry"); + for (int i = 0; i < 3; ++i) + if (!std::isfinite(mean[i]) || !std::isfinite(stddev[i]) || stddev[i] <= 0) + throw std::invalid_argument("Invalid Flash-Next visual normalization"); +} +std::array native_visual_size(const NativeVisionConfig& c, int32_t frames, bool video, + int32_t height, int32_t width) { + c.validate(); + if (height <= 0 || width <= 0 || frames < (video ? c.temporal : 1) || (!video && frames != 1)) + throw std::invalid_argument("Invalid Flash-Next source image or video dimensions"); + const int64_t factor = c.patch * c.merge; + int64_t raw_h = height, raw_w = width; + if (video && (raw_h < factor || raw_w < factor)) { + const double scale = std::max(double(factor) / raw_h, double(factor) / raw_w); + raw_h = static_cast(raw_h * scale); + raw_w = static_cast(raw_w * scale); + } + if (std::max(raw_h, raw_w) > 200 * std::min(raw_h, raw_w)) + throw std::invalid_argument("Flash-Next source aspect ratio exceeds the provider limit"); + const auto rounded = [](int64_t value, int64_t unit) { + const auto q = value / unit, r = value % unit; + return (q + (2 * r > unit || (2 * r == unit && (q & 1)))) * unit; + }; + int64_t h = rounded(raw_h, factor), w = rounded(raw_w, factor); + const double extent = video ? rounded(frames, c.temporal) : 1; + const double min = video ? c.video_min_pixels : c.image_min_pixels, + max = video ? c.video_max_pixels : c.image_max_pixels; + const double area = extent * h * w, original = double(frames) * raw_h * raw_w; + if (area > max) { + const double beta = std::sqrt(original / max); + h = std::max(factor, static_cast(std::floor(raw_h / beta / factor)) * factor); + w = std::max(factor, static_cast(std::floor(raw_w / beta / factor)) * factor); + } else if (area < min) { + const double beta = std::sqrt(min / original); + h = static_cast(std::ceil(raw_h * beta / factor)) * factor; + w = static_cast(std::ceil(raw_w * beta / factor)) * factor; + } + if (h <= 0 || w <= 0 || h > INT32_MAX || w > INT32_MAX || + (h / factor) * (w / factor) > c.max_tokens) + throw std::invalid_argument( + "Provider-sized Flash-Next image exceeds the native vision profile"); + return {static_cast(h), static_cast(w)}; +} + +TensorMap NativeVisualInputs::tensors() { + const int64_t count = static_cast(height) * width; + return {{"patches", {patches.data(), {count, patch_width}, DType::kFloat16}}, + {"rotary_angles", {rotary_angles.data(), {count, rotary_width}, DType::kFloat32}}, + {"position_indices", {position_indices.data(), {4, count}, DType::kInt32}}, + {"position_weights", {position_weights.data(), {4, count}, DType::kFloat32}}}; +} + +NativeVisualInputs native_visual_inputs(const NativeVisionConfig& c, + Span frames, int32_t height, + int32_t width) { + c.validate(); + const int32_t factor = c.patch * c.merge; + if (frames.empty() || frames.size() > static_cast(c.temporal) || height <= 0 || + width <= 0 || height % factor || width % factor || + static_cast(height / factor) * (width / factor) > c.max_tokens) + throw std::invalid_argument( + "Invalid Flash-Next native temporal group or resized visual grid"); + std::vector> pixels; + for (const auto& frame : frames) { + if (frame.height != frames[0].height || frame.width != frames[0].width) + throw std::invalid_argument( + "Flash-Next native video frames must have matching dimensions"); + pixels.push_back(normalized(c, frame, height, width)); + } + NativeVisualInputs result; + result.height = height / c.patch; + result.width = width / c.patch; + result.patch_width = 3 * c.temporal * c.patch * c.patch; + result.rotary_width = c.head_dim / 2; + const std::size_t count = static_cast(result.height) * result.width; + result.patches.resize(count * result.patch_width); + result.rotary_angles.resize(count * result.rotary_width); + result.position_indices.resize(4 * count); + result.position_weights.resize(4 * count); + const auto side = static_cast(std::sqrt(static_cast(c.positions))); + std::size_t token = 0; + for (int32_t block_y = 0; block_y < result.height; block_y += c.merge) + for (int32_t block_x = 0; block_x < result.width; block_x += c.merge) + for (int32_t dy = 0; dy < c.merge; ++dy) + for (int32_t dx = 0; dx < c.merge; ++dx, ++token) { + const int32_t y = block_y + dy, x = block_x + dx; + std::size_t out = token * result.patch_width; + for (int32_t channel = 0; channel < 3; ++channel) + for (int32_t t = 0; t < c.temporal; ++t) + for (int32_t py = 0; py < c.patch; ++py) + for (int32_t px = 0; px < c.patch; ++px) { + const auto& frame = + pixels[std::min(t, pixels.size() - 1)]; + result.patches[out++] = + frame[(static_cast(y * c.patch + py) * width + + x * c.patch + px) * + 3 + + channel]; + } + for (int32_t i = 0; i < c.head_dim / 4; ++i) { + const float inverse = + std::pow(c.theta, -static_cast(2 * i) / (c.head_dim / 2)); + result.rotary_angles[token * result.rotary_width + i] = y * inverse; + result.rotary_angles[token * result.rotary_width + c.head_dim / 4 + i] = + x * inverse; + } + const float fy = result.height == 1 + ? 0 + : static_cast(static_cast(side - 1) * y / + (result.height - 1)); + const float fx = result.width == 1 + ? 0 + : static_cast(static_cast(side - 1) * x / + (result.width - 1)); + const int32_t iy = static_cast(fy), ix = static_cast(fx); + const float ry = fy - iy, rx = fx - ix; + for (int32_t k = 0; k < 4; ++k) { + result.position_indices[k * count + token] = + std::min(iy + k / 2, side - 1) * side + std::min(ix + k % 2, side - 1); + result.position_weights[k * count + token] = + (k / 2 ? ry : 1 - ry) * (k % 2 ? rx : 1 - rx); + } + } + return result; +} + +std::string native_visual_text(const std::vector& groups) { + if (groups.empty()) + return {}; + const bool video = groups.front().video; + std::string text = video ? "<|vision_start|>" : ""; + for (const auto& group : groups) { + if (group.video != video || group.height <= 0 || group.width <= 0 || + (video && !std::isfinite(group.timestamp))) + throw std::invalid_argument("Flash-Next native visual part has inconsistent groups"); + if (video) { + std::ostringstream timestamp; + timestamp.imbue(std::locale::classic()); + timestamp << '<' << std::fixed << std::setprecision(1) << group.timestamp + << " seconds>"; + text += timestamp.str(); + } + text += "<|vision_start|>"; + for (int64_t i = 0; i < static_cast(group.height) * group.width; ++i) + text += video ? "<|video_pad|>" : "<|image_pad|>"; + text += "<|vision_end|>"; + } + if (video) + text += "<|vision_end|>"; + return text; +} + +NativeVisualEncoder::NativeVisualEncoder(std::unique_ptr module, + NativeVisionConfig config) + : module_(std::move(module)), config_(config) { + config_.validate(); + if (!module_ || !module_->ok() || !module_->has_output("visual_features") || + module_->tensor_dtype("visual_features") != DType::kFloat16) + throw std::runtime_error("Invalid Flash-Next native visual engine"); + const auto maximum = + module_->input_profile_shape("patches", module_->profile_idx(), ProfileShapeSelector::kMax); + if (maximum != std::vector{ + static_cast(config.max_tokens) * config.merge * config.merge, + static_cast(3) * config.temporal * config.patch * config.patch}) + throw std::runtime_error("Flash-Next native visual engine profile disagrees with metadata"); +} + +std::vector NativeVisualEncoder::encode(const internal::ImageView& image) { + return encode_frames({&image, 1}, {}, false); +} +std::vector NativeVisualEncoder::encode(const internal::VideoView& video) { + return encode_frames(video.frames, video.timestamps_seconds, true); +} +std::vector +NativeVisualEncoder::encode_frames(Span frames, + Span timestamps, bool video) { + if (frames.empty() || frames.size() > INT32_MAX || + (!timestamps.empty() && timestamps.size() != frames.size())) + throw std::invalid_argument("Flash-Next native video needs frames and matching timestamps"); + for (std::size_t i = 0; i < frames.size(); ++i) { + validate_image(frames[i]); + if (frames[i].height != frames[0].height || frames[i].width != frames[0].width) + throw std::invalid_argument( + "Flash-Next native video frames must have matching dimensions"); + if (!timestamps.empty() && + (!std::isfinite(timestamps[i]) || (i && timestamps[i] < timestamps[i - 1]))) + throw std::invalid_argument( + "Flash-Next native video timestamps must be finite and ordered"); + } + const auto size = native_visual_size(config_, static_cast(frames.size()), video, + frames[0].height, frames[0].width); + std::vector result; + for (std::size_t start = 0; start < frames.size(); start += config_.temporal) { + const auto count = std::min(config_.temporal, frames.size() - start); + auto prepared = + native_visual_inputs(config_, {frames.data() + start, count}, size[0], size[1]); + TensorMap output; + try { + output = module_->forward(prepared.tensors()); + } catch (...) { + try { + module_->sync(); + } catch (...) { + } + throw; + } + const auto& features = output.at("visual_features"); + const int32_t h = prepared.height / config_.merge, w = prepared.width / config_.merge; + if (features.dtype != DType::kFloat16 || + features.shape != std::vector{static_cast(h) * w, config_.hidden}) + throw std::runtime_error("Flash-Next native visual output has invalid geometry/dtype"); + const auto last = start + count - 1; + const double timestamp = timestamps.empty() ? (static_cast(start) + last) / 2 + : (timestamps[start] + timestamps[last]) / 2; + NativeVisualGroup group{h, w, video, timestamp, std::vector(features.numel())}; + std::memcpy(group.features.data(), features.data, features.nbytes()); + result.push_back(std::move(group)); + } + return result; +} +} // namespace trtmc::qwen3_8_flash_next diff --git a/families/qwen3_8_flash_next/runtime/native_visual.h b/families/qwen3_8_flash_next/runtime/native_visual.h new file mode 100644 index 0000000000..3cd44db5f6 --- /dev/null +++ b/families/qwen3_8_flash_next/runtime/native_visual.h @@ -0,0 +1,70 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + */ +#pragma once + +#include "trtmc/internal/image.h" +#include "trtmc/internal/video.h" +#include "trtmc/runtime/trt_module.h" +#include "trtmc/task.h" + +#include +#include +#include +#include + +namespace trtmc::qwen3_8_flash_next { + +struct NativeVisionConfig { + int32_t patch{16}, temporal{2}, merge{2}, positions{2304}, head_dim{72}, hidden{0}; + int32_t max_tokens{0}; // merged rows per temporal group covered by the plan + int32_t image_min_pixels{65536}, image_max_pixels{16777216}; + int32_t video_min_pixels{4096}, video_max_pixels{25165824}; + float theta{10000}; + std::array mean{0.5F, 0.5F, 0.5F}, stddev{0.5F, 0.5F, 0.5F}; + void validate() const; +}; + +struct NativeVisualInputs { + int32_t height{0}, width{0}, patch_width{0}, rotary_width{0}; // patch-grid dimensions + std::vector patches; + std::vector position_weights; + std::vector rotary_angles; + std::vector position_indices; + TensorMap tensors(); +}; + +// Pure host preprocessing. The temporal span contains exactly one group (the +// last source frame is repeated to fill an incomplete group). +std::array native_visual_size(const NativeVisionConfig&, int32_t frames, bool video, + int32_t height, int32_t width); +NativeVisualInputs native_visual_inputs(const NativeVisionConfig&, + Span temporal_frames, + int32_t height, int32_t width); + +struct NativeVisualGroup { + int32_t height, width; // merged token grid, one temporal patch group + bool video; + double timestamp; + std::vector features; // FP16 [height * width, text hidden] +}; + +// Expand one source media part. Videos retain the provider outer wrapper and +// per-temporal-group timestamps, wrappers and video-pad tokens. +std::string native_visual_text(const std::vector& groups); + +class NativeVisualEncoder { + public: + NativeVisualEncoder(std::unique_ptr, NativeVisionConfig); + std::vector encode(const internal::ImageView&); + std::vector encode(const internal::VideoView&); + + private: + std::unique_ptr module_; + NativeVisionConfig config_; + std::vector encode_frames(Span, + Span, bool video); +}; + +} // namespace trtmc::qwen3_8_flash_next diff --git a/families/qwen3_8_flash_next/runtime/ngram.cpp b/families/qwen3_8_flash_next/runtime/ngram.cpp new file mode 100644 index 0000000000..48f05a46f2 --- /dev/null +++ b/families/qwen3_8_flash_next/runtime/ngram.cpp @@ -0,0 +1,76 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + */ +#include "families/qwen3_8_flash_next/runtime/ngram.h" + +#include +#include +#include + +namespace trtmc::qwen3_8_flash_next { +namespace { + +// Torch hashes in signed int64, with wrapping multiplication and nonnegative +// remainder. Keep the bit pattern unsigned, including the INT64_MIN case. +std::uint64_t table_remainder(std::uint64_t bits, std::uint64_t size) { + if (bits >> 63U) { + const auto magnitude_remainder = (std::uint64_t{0} - bits) % size; + return magnitude_remainder == 0 ? 0 : size - magnitude_remainder; + } + return bits % size; +} + +} // namespace + +NgramLookup::NgramLookup(NgramLayout layout, std::int64_t table_rows) : layout_(std::move(layout)) { + if (layout_.eos < 0 || layout_.eos >= layout_.vocabulary_size || table_rows <= 0) + throw std::invalid_argument("Invalid Flash-Next vocabulary or n-gram table extent"); + std::int64_t previous_end = 0; + for (std::size_t h = 0; h < layout_.sizes.size(); ++h) { + const auto size = layout_.sizes[h]; + const auto offset = layout_.offsets[h]; + if (size <= 0 || offset < previous_end || offset > table_rows - size) + throw std::invalid_argument( + "Flash-Next n-gram head ranges overlap or exceed the table"); + previous_end = offset + size; + } +} + +std::array NgramLookup::initial_history() const { + return {layout_.eos, layout_.eos}; +} + +NgramChunk NgramLookup::lookup(const std::vector& tokens, + std::array history) const { + const auto valid_id = [this](std::int32_t id) { + return id >= 0 && id < layout_.vocabulary_size; + }; + if (!valid_id(history[0]) || !valid_id(history[1]) || tokens.empty()) + throw std::invalid_argument( + "Flash-Next needs a nonempty token chunk and valid token history"); + NgramChunk chunk{{}, history}; + if (tokens.size() > chunk.rows.max_size() / layout_.sizes.size()) + throw std::length_error("Flash-Next n-gram row count exceeds addressable memory"); + chunk.rows.reserve(tokens.size() * layout_.sizes.size()); + for (const auto token : tokens) { + if (!valid_id(token)) + throw std::invalid_argument("Token outside the Flash-Next vocabulary"); + const auto prev = chunk.history[1]; + // Tokens before the most recent EOS cannot contribute to the current segment. + const auto before_prev = prev == layout_.eos ? layout_.eos : chunk.history[0]; + const auto bigram = static_cast(token) * layout_.multipliers[0] ^ + static_cast(prev) * layout_.multipliers[1]; + const auto trigram = + bigram ^ static_cast(before_prev) * layout_.multipliers[2]; + for (std::size_t h = 0; h < layout_.sizes.size(); ++h) { + const auto row = table_remainder(h < 8 ? bigram : trigram, + static_cast(layout_.sizes[h])); + chunk.rows.push_back(layout_.offsets[h] + static_cast(row)); + } + chunk.history = {prev, token}; + } + return chunk; +} + +} // namespace trtmc::qwen3_8_flash_next diff --git a/families/qwen3_8_flash_next/runtime/ngram.h b/families/qwen3_8_flash_next/runtime/ngram.h new file mode 100644 index 0000000000..db942914a3 --- /dev/null +++ b/families/qwen3_8_flash_next/runtime/ngram.h @@ -0,0 +1,41 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + */ +#pragma once + +#include +#include +#include + +namespace trtmc::qwen3_8_flash_next { + +// The published policy has eight bigram heads followed by eight trigram heads. +// The hash constants and each head's row range belong to the checkpoint. +struct NgramLayout { + std::array multipliers; + std::array sizes; + std::array offsets; + std::int32_t eos; + std::int32_t vocabulary_size; +}; + +struct NgramChunk { + std::vector rows; // [token, head], in checkpoint table coordinates + std::array history; // oldest first +}; + +class NgramLookup { + public: + NgramLookup(NgramLayout layout, std::int64_t table_rows); + std::array initial_history() const; + // Each request owns its history. Return the updated state so the caller need + // not advance a request if gathering rows or executing the engine fails. + NgramChunk lookup(const std::vector& tokens, + std::array history) const; + + private: + NgramLayout layout_; +}; + +} // namespace trtmc::qwen3_8_flash_next diff --git a/families/qwen3_8_flash_next/runtime/ple_rows.cpp b/families/qwen3_8_flash_next/runtime/ple_rows.cpp new file mode 100644 index 0000000000..43972e9017 --- /dev/null +++ b/families/qwen3_8_flash_next/runtime/ple_rows.cpp @@ -0,0 +1,36 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + */ +#include "ple_rows.h" + +#include +#include +#include + +namespace trtmc::qwen3_8_flash_next { + +std::vector read_ple_rows(std::istream& source, std::uint64_t section_start, + std::uint64_t section_bytes, + const std::vector& row_ids) { + constexpr std::size_t width = 160; // 2,560 channels split over 16 heads + constexpr std::uint64_t max_offset = std::numeric_limits::max(); + if (!section_bytes || section_bytes % width || section_start > max_offset || + section_bytes > max_offset - section_start) + throw std::invalid_argument("Invalid Flash-Next FP8 table extent"); + if (row_ids.size() % 16 || row_ids.size() > std::vector().max_size() / width) + throw std::invalid_argument("Invalid Flash-Next FP8 head-row count"); + const auto table_rows = section_bytes / width; + for (const auto id : row_ids) + if (id < 0 || static_cast(id) >= table_rows) + throw std::out_of_range("Flash-Next FP8 row outside table"); + std::vector result(row_ids.size() * width); + for (std::size_t i = 0; i < row_ids.size(); ++i) { + const auto pos = section_start + static_cast(row_ids[i]) * width; + source.seekg(static_cast(pos)); + if (!source.read(reinterpret_cast(result.data() + i * width), width)) + throw std::runtime_error("Failed to read Flash-Next FP8 table row"); + } + return result; +} +} // namespace trtmc::qwen3_8_flash_next diff --git a/families/qwen3_8_flash_next/runtime/ple_rows.h b/families/qwen3_8_flash_next/runtime/ple_rows.h new file mode 100644 index 0000000000..50fb8a7f47 --- /dev/null +++ b/families/qwen3_8_flash_next/runtime/ple_rows.h @@ -0,0 +1,19 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + */ +#pragma once + +#include +#include +#include + +namespace trtmc::qwen3_8_flash_next { + +// The table section concatenates the released FP8 shards in numerical order. +// One stream per caller; row IDs are token-major, then head-major. +std::vector read_ple_rows(std::istream& source, std::uint64_t section_start, + std::uint64_t section_bytes, + const std::vector& row_ids); + +} // namespace trtmc::qwen3_8_flash_next diff --git a/families/qwen3_8_flash_next/runtime/plugin.cpp b/families/qwen3_8_flash_next/runtime/plugin.cpp new file mode 100644 index 0000000000..7c90f0a221 --- /dev/null +++ b/families/qwen3_8_flash_next/runtime/plugin.cpp @@ -0,0 +1,22 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + */ +#include "native_task.h" +#ifdef TRTMC_FLASH_NEXT_EDGE +#include "edge_llm/adapter.h" +#endif +#include + +extern "C" trtmc::ITask* trtmc_create_family(const trtmc::FamilyContext& context) { + if (context.kv_cache_size_bytes != 0) + throw std::invalid_argument("qwen3_8_flash_next does not support --kv-cache-size"); + if (context.reader.find_section("edge_llm.json")) { +#ifdef TRTMC_FLASH_NEXT_EDGE + return trtmc::qwen3_8_flash_next::edge_llm::create(context.reader); +#else + throw std::runtime_error("This Flash-Next runtime was built without the Edge 0.12 SDK"); +#endif + } + return trtmc::qwen3_8_flash_next::create_native(context); +} diff --git a/families/qwen3_8_flash_next/runtime/positions.cpp b/families/qwen3_8_flash_next/runtime/positions.cpp new file mode 100644 index 0000000000..8c96f07b0e --- /dev/null +++ b/families/qwen3_8_flash_next/runtime/positions.cpp @@ -0,0 +1,78 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + */ +#include "positions.h" + +#include +#include +#include + +namespace trtmc::qwen3_8_flash_next { + +Positions prompt_positions(const std::vector& types, const std::vector& images, + const std::vector& videos, std::int32_t merge, + std::int32_t capacity) { + if (types.empty() || capacity <= 0 || types.size() > static_cast(capacity) || + merge <= 0) + throw std::invalid_argument("Invalid Flash-Next prompt length, capacity or spatial merge"); + Positions result{{}, 0}; + result.prompt.reserve(types.size()); + std::size_t image = 0, video = 0; + std::int32_t tubelet = 0; + for (std::size_t i = 0; i < types.size();) { + if (types[i] == 0) { + const auto pos = result.next++; + result.prompt.push_back({pos, pos, pos}); + ++i; + continue; + } + const auto kind = types[i]; + std::size_t end = i + 1; + while (end < types.size() && types[end] == kind) + ++end; + const auto& grids = kind == 1 ? images : videos; + const auto idx = kind == 1 ? image : video; + if ((kind != 1 && kind != 2) || idx >= grids.size()) + throw std::invalid_argument("Flash-Next media tokens do not have a corresponding grid"); + const auto [t, h, w] = grids[idx]; + if (t <= 0 || h <= 0 || w <= 0 || h % merge || w % merge || (kind == 1 && t != 1)) + throw std::invalid_argument("Invalid Flash-Next media patch grid"); + const auto height = h / merge, width = w / merge; + if (std::int64_t{height} * width != static_cast(end - i)) + throw std::invalid_argument( + "Flash-Next media placeholder count does not match its grid"); + const auto start = result.next; + for (std::int32_t y = 0; y < height; ++y) + for (std::int32_t x = 0; x < width; ++x) + result.prompt.push_back({start, start + y, start + x}); + result.next += std::max(height, width); + if (kind == 1) { + ++image; + } else if (++tubelet == t) { + ++video; + tubelet = 0; + } + i = end; + } + if (image != images.size() || video != videos.size() || tubelet) + throw std::invalid_argument("Unconsumed Flash-Next image or video grids"); + return result; +} + +std::array rotary_row(Position position, float theta) { + if (!std::isfinite(theta) || theta <= 0 || + *std::min_element(position.begin(), position.end()) < 0) + throw std::invalid_argument("Invalid Flash-Next rotary parameters"); + std::array row; + // mrope_section [11,11,10]: H at indices 1,4,...,31, W at 2,5,...,29. + for (int k = 0; k < 32; ++k) { + const float inverse = 1.0F / std::pow(theta, float(k) / 32.0F); + const float phase = static_cast(position[k % 3]) * inverse; + row[k] = std::cos(phase); + row[k + 32] = std::sin(phase); + } + return row; +} + +} // namespace trtmc::qwen3_8_flash_next diff --git a/families/qwen3_8_flash_next/runtime/positions.h b/families/qwen3_8_flash_next/runtime/positions.h new file mode 100644 index 0000000000..3bc4a84c0a --- /dev/null +++ b/families/qwen3_8_flash_next/runtime/positions.h @@ -0,0 +1,30 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + */ +#pragma once + +#include +#include +#include + +namespace trtmc::qwen3_8_flash_next { + +using Position = std::array; +using Grid = std::array; // temporal, height, width before spatial merge +struct Positions { + std::vector prompt; + // First position after the prompt; not the physical index when media are present. + std::int32_t next; +}; + +// Consume the provider processor's token types in message order. A video is +// split into temporal tubelets separated by textual timestamps and vision delimiters. +Positions prompt_positions(const std::vector& types, const std::vector& images, + const std::vector& videos, std::int32_t spatial_merge, + std::int32_t capacity); + +// 32 interleaved T/H/W phase pairs for the trained partial rotary head. +std::array rotary_row(Position position, float theta); + +} // namespace trtmc::qwen3_8_flash_next diff --git a/families/qwen3_8_flash_next/runtime/sampler.cpp b/families/qwen3_8_flash_next/runtime/sampler.cpp new file mode 100644 index 0000000000..50c1651c3c --- /dev/null +++ b/families/qwen3_8_flash_next/runtime/sampler.cpp @@ -0,0 +1,256 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + */ + +#include "families/qwen3_8_flash_next/runtime/sampler.h" + +#include "trtmc/task.h" + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace trtmc { + +namespace { + +FlashNextSampleResult argmax_over_logits(const float* logits, int32_t vocab_size, + const FlashNextSamplingParams& params) { + FlashNextSampleResult result; + const float* best = logits; + for (int32_t i = 1; i < vocab_size; ++i) { + if (logits[i] > *best) + best = logits + i; + } + result.token_id = static_cast(best - logits); + result.logprob = *best; + result.is_eos = params.is_eos(result.token_id); + return result; +} + +struct FilteredDistribution { + std::vector indices; + std::vector probs; + int32_t keep{0}; +}; + +constexpr float kSamplingEpsilon = 1e-6F; + +float sanitized_temperature(float temperature) { + if (!std::isfinite(temperature)) + return 1.0F; + return std::max(temperature, 0.0F); +} + +float sanitized_top_p(float top_p) { + if (!std::isfinite(top_p)) + return 1.0F; + return std::min(std::max(top_p, 0.0F), 1.0F); +} + +float sanitized_min_p(float min_p) { + if (!std::isfinite(min_p)) + return 0.0F; + return std::min(std::max(min_p, 0.0F), 1.0F); +} + +bool top_p_enabled(float top_p) { + return top_p > 0.0F && top_p < 1.0F - kSamplingEpsilon; +} + +bool greedy_equivalent(const FlashNextSamplingParams& params) { + const float temperature = sanitized_temperature(params.temperature); + const float top_p = sanitized_top_p(params.top_p); + return temperature < kSamplingEpsilon || top_p <= 0.0F; +} + +void topk_indices_and_softmax(FilteredDistribution& dist, const float* logits, int32_t n, int32_t k, + float temperature) { + dist.indices.resize(static_cast(n)); + std::iota(dist.indices.begin(), dist.indices.end(), 0); + std::partial_sort(dist.indices.begin(), dist.indices.begin() + k, dist.indices.end(), + [&](int32_t a, int32_t b) { + return logits[static_cast(a)] > + logits[static_cast(b)]; + }); + const float max_logit = logits[static_cast(dist.indices[0])]; + dist.probs.resize(static_cast(k)); + float sum = 0.0F; + for (int32_t i = 0; i < k; ++i) { + const float scaled = + (logits[static_cast(dist.indices[static_cast(i)])] - + max_logit) / + temperature; + dist.probs[static_cast(i)] = std::isfinite(scaled) ? std::exp(scaled) : 0.0F; + sum += dist.probs[static_cast(i)]; + } + if (sum > 0.0F) { + for (int32_t i = 0; i < k; ++i) + dist.probs[static_cast(i)] /= sum; + } else { + const float uniform = 1.0F / static_cast(k); + for (int32_t i = 0; i < k; ++i) + dist.probs[static_cast(i)] = uniform; + } +} + +int32_t apply_min_p(const FilteredDistribution& dist, int32_t k, float min_p) { + if (min_p <= 0.0F) + return k; + const float max_prob = dist.probs.empty() ? 1.0F : dist.probs[0]; + if (max_prob <= 0.0F) + return k; + const float min_prob = min_p * max_prob; + int32_t keep = 0; + while (keep < k && dist.probs[static_cast(keep)] >= min_prob) + ++keep; + return std::max(keep, 1); +} + +int32_t apply_top_p(const FilteredDistribution& dist, int32_t keep, float top_p) { + if (!top_p_enabled(top_p)) + return keep; + float cumulative = 0.0F; + int32_t top_p_keep = 0; + while (top_p_keep < keep) { + cumulative += dist.probs[static_cast(top_p_keep)]; + ++top_p_keep; + if (cumulative >= top_p) + break; + } + return std::max(top_p_keep, 1); +} + +void renormalize_kept_prefix(FilteredDistribution& dist, int32_t keep) { + float kept_sum = 0.0F; + for (int32_t i = 0; i < keep; ++i) + kept_sum += dist.probs[static_cast(i)]; + if (kept_sum > 0.0F) { + for (int32_t i = 0; i < keep; ++i) + dist.probs[static_cast(i)] /= kept_sum; + } else { + const float uniform = 1.0F / static_cast(keep); + for (int32_t i = 0; i < keep; ++i) + dist.probs[static_cast(i)] = uniform; + } +} + +FilteredDistribution build_filtered_distribution(const float* logits, int32_t vocab_size, + const FlashNextSamplingParams& params) { + const int32_t n = vocab_size; + const float temperature = sanitized_temperature(params.temperature); + const float top_p = sanitized_top_p(params.top_p); + const float min_p = sanitized_min_p(params.min_p); + const bool full_vocab_for_top_p = top_p_enabled(top_p) && params.top_k <= 1; + const int32_t k = + (params.top_k <= 0 || full_vocab_for_top_p) ? n : std::min(std::max(params.top_k, 1), n); + FilteredDistribution dist; + topk_indices_and_softmax(dist, logits, n, k, temperature); + int32_t keep = apply_min_p(dist, k, min_p); + keep = apply_top_p(dist, keep, top_p); + if (keep < k) + renormalize_kept_prefix(dist, keep); + dist.keep = keep; + return dist; +} + +class FlashNextGreedySampler final : public FlashNextISampler { + public: + FlashNextSampleResult sample(const float* logits, int32_t vocab_size, + const FlashNextSamplingParams& params) override { + if (vocab_size <= 0 || logits == nullptr) { + FlashNextSampleResult result; + result.token_id = 0; + result.is_eos = params.is_eos(0); + return result; + } + return argmax_over_logits(logits, vocab_size, params); + } +}; + +class FlashNextTopKSampler final : public FlashNextISampler { + public: + explicit FlashNextTopKSampler(uint64_t initial_seed) + : rng_state_(initial_seed == 0 ? 1 : initial_seed), + initial_seed_(initial_seed == 0 ? 1 : initial_seed) {} + + FlashNextSampleResult sample(const float* logits, int32_t vocab_size, + const FlashNextSamplingParams& params) override { + FlashNextSampleResult result; + if (vocab_size <= 0 || logits == nullptr) { + result.token_id = 0; + result.is_eos = params.is_eos(0); + return result; + } + + if (greedy_equivalent(params)) + return argmax_over_logits(logits, vocab_size, params); + + const FilteredDistribution dist = build_filtered_distribution(logits, vocab_size, params); + + rng_state_ ^= rng_state_ << 13; + rng_state_ ^= rng_state_ >> 7; + rng_state_ ^= rng_state_ << 17; + const float u = static_cast(rng_state_ & 0xFFFFFFFF) / 4294967296.0F; + + float cumulative = 0.0F; + for (int32_t i = 0; i < dist.keep; ++i) { + cumulative += dist.probs[static_cast(i)]; + if (u < cumulative) { + result.token_id = dist.indices[static_cast(i)]; + result.logprob = std::log(std::max(dist.probs[static_cast(i)], + std::numeric_limits::min())); + result.is_eos = params.is_eos(result.token_id); + return result; + } + } + + result.token_id = dist.indices[static_cast(dist.keep - 1)]; + result.logprob = std::log(std::max(dist.probs[static_cast(dist.keep - 1)], + std::numeric_limits::min())); + result.is_eos = params.is_eos(result.token_id); + return result; + } + void reset() override { rng_state_ = initial_seed_; } + + private: + uint64_t rng_state_; + uint64_t initial_seed_; +}; + +} // namespace + +FlashNextSamplingParams +flash_next_sampling_params_from_config(const TextGenerationConfig& cfg, int32_t default_eos, + const std::vector& default_eos_ids) { + FlashNextSamplingParams p; + p.temperature = cfg.temperature; + p.top_k = cfg.top_k; + p.top_p = cfg.top_p; + p.min_p = cfg.min_p; + p.seed = cfg.seed; + p.eos_token_id = (cfg.eos_token_id >= 0) ? cfg.eos_token_id : default_eos; + p.eos_token_ids = + cfg.eos_token_id >= 0 ? std::vector{cfg.eos_token_id} : default_eos_ids; + return p; +} + +std::unique_ptr +create_flash_next_sampler(const FlashNextSamplingParams& params) { + const float top_p = sanitized_top_p(params.top_p); + const float min_p = sanitized_min_p(params.min_p); + if (params.top_k <= 1 && top_p >= 1.0F - kSamplingEpsilon && min_p <= 0.0F && params.seed < 0) { + return std::make_unique(); + } + + const uint64_t seed = (params.seed >= 0) ? static_cast(params.seed) : 42ULL; + return std::make_unique(seed); +} + +} // namespace trtmc diff --git a/families/qwen3_8_flash_next/runtime/sampler.h b/families/qwen3_8_flash_next/runtime/sampler.h new file mode 100644 index 0000000000..f47ddc52ac --- /dev/null +++ b/families/qwen3_8_flash_next/runtime/sampler.h @@ -0,0 +1,53 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + */ + +#pragma once + +#include +#include +#include +#include + +namespace trtmc { + +struct TextGenerationConfig; + +struct FlashNextSamplingParams { + float temperature{1.0F}; + int32_t top_k{1}; + float top_p{1.0F}; + float min_p{0.0F}; + int32_t seed{-1}; + int32_t eos_token_id{-1}; + std::vector eos_token_ids{}; + + bool is_eos(int32_t token) const { + return eos_token_ids.empty() ? token == eos_token_id + : std::find(eos_token_ids.begin(), eos_token_ids.end(), + token) != eos_token_ids.end(); + } +}; + +struct FlashNextSampleResult { + int32_t token_id{0}; + float logprob{0.0F}; + bool is_eos{false}; +}; + +class FlashNextISampler { + public: + virtual ~FlashNextISampler() = default; + virtual FlashNextSampleResult sample(const float* logits, int32_t vocab_size, + const FlashNextSamplingParams& params) = 0; + virtual void reset() {} +}; + +FlashNextSamplingParams +flash_next_sampling_params_from_config(const TextGenerationConfig& cfg, int32_t default_eos = -1, + const std::vector& default_eos_ids = {}); + +std::unique_ptr create_flash_next_sampler(const FlashNextSamplingParams& params); + +} // namespace trtmc diff --git a/families/qwen3_8_flash_next/runtime/tokenizer.cpp b/families/qwen3_8_flash_next/runtime/tokenizer.cpp new file mode 100644 index 0000000000..d9050a6bee --- /dev/null +++ b/families/qwen3_8_flash_next/runtime/tokenizer.cpp @@ -0,0 +1,231 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + */ +#include "tokenizer.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace trtmc::qwen3_8_flash_next { +namespace { +std::string utf8(const icu::UnicodeString& text) { + std::string result; + text.toUTF8String(result); + return result; +} +std::string pair_key(const std::string& a, const std::string& b) { + return a + '\0' + b; +} +} // namespace + +struct Tokenizer::Impl { + std::unique_ptr pattern; + const icu::Normalizer2* nfc; + std::unordered_map vocab, ranks; + std::unordered_map inverse; + std::unordered_set special_ids; + std::vector> added; + std::array byte_encoder; + std::unordered_map byte_decoder; + bool ignore_merges{}; + + explicit Impl(std::string_view serialized) { + const auto j = nlohmann::json::parse(serialized); + const auto& model = j.at("model"); + const auto& pre = j.at("pre_tokenizer"); + if (model.at("type") != "BPE" || j.at("normalizer").at("type") != "NFC" || + pre.at("type") != "Sequence" || model.value("byte_fallback", false) || + !model.at("dropout").is_null()) + throw std::invalid_argument("Unsupported Flash-Next tokenizer contract"); + const auto& parts = pre.at("pretokenizers"); + if (parts.size() != 2 || parts[0].at("type") != "Split" || + parts[0].at("behavior") != "Isolated" || parts[0].value("invert", false) || + parts[1].at("type") != "ByteLevel" || parts[1].value("add_prefix_space", false) || + parts[1].value("use_regex", true) || j.at("decoder").at("type") != "ByteLevel") + throw std::invalid_argument("Unsupported Flash-Next pre-tokenizer"); + UErrorCode status = U_ZERO_ERROR; + nfc = icu::Normalizer2::getNFCInstance(status); + if (U_FAILURE(status) || !nfc) + throw std::runtime_error("Cannot initialize Flash-Next NFC normalizer"); + const auto expression = parts[0].at("pattern").at("Regex").get(); + pattern.reset( + icu::RegexPattern::compile(icu::UnicodeString::fromUTF8(expression), 0, status)); + if (U_FAILURE(status) || !pattern) + throw std::invalid_argument("Invalid Flash-Next tokenizer split expression"); + vocab = model.at("vocab").get(); + for (const auto& [token, id] : vocab) + inverse.emplace(id, token); + int rank = 0; + for (const auto& merge : model.at("merges")) { + std::string a, b; + if (merge.is_array()) { + a = merge.at(0); + b = merge.at(1); + } else { + const auto text = merge.get(); + const auto space = text.find(' '); + if (space == std::string::npos) + throw std::invalid_argument("Malformed Flash-Next BPE merge"); + a = text.substr(0, space); + b = text.substr(space + 1); + } + ranks.emplace(pair_key(a, b), rank++); + } + ignore_merges = model.value("ignore_merges", false); + for (const auto& item : j.at("added_tokens")) { + // Matching flags must not be silently discarded. + if (item.value("single_word", false) || item.value("lstrip", false) || + item.value("rstrip", false) || item.value("normalized", false)) + throw std::invalid_argument("Unsupported Flash-Next added-token matching flags"); + std::string text = item.at("content"); + int32_t id = item.at("id"); + if (text.empty()) + throw std::invalid_argument("Empty Flash-Next added token"); + added.emplace_back(text, id); + inverse[id] = text; + if (item.value("special", false)) + special_ids.insert(id); + } + int extra = 256; + for (int b = 0; b < 256; ++b) { + const bool literal = (b >= 33 && b <= 126) || (b >= 161 && b <= 172) || b >= 174; + const UChar32 cp = literal ? b : extra++; + byte_encoder[b] = utf8(icu::UnicodeString(cp)); + byte_decoder.emplace(cp, static_cast(b)); + } + } + + void piece(const std::string& bytes, std::vector& result) const { + std::vector units; + std::string encoded; + for (unsigned char b : bytes) { + units.push_back(byte_encoder[b]); + encoded += byte_encoder[b]; + } + if (ignore_merges) { + const auto found = vocab.find(encoded); + if (found != vocab.end()) { + result.push_back(found->second); + return; + } + } + // A split piece is short; deterministic leftmost rank ordering mirrors BPE. + while (units.size() > 1) { + size_t best = units.size(); + int rank = std::numeric_limits::max(); + for (size_t i = 0; i + 1 < units.size(); ++i) { + auto found = ranks.find(pair_key(units[i], units[i + 1])); + if (found != ranks.end() && found->second < rank) { + rank = found->second; + best = i; + } + } + if (best == units.size()) + break; + units[best] += units[best + 1]; + units.erase(units.begin() + best + 1); + } + for (const auto& token : units) { + auto found = vocab.find(token); + if (found == vocab.end()) + throw std::invalid_argument("Missing byte in Flash-Next vocabulary"); + result.push_back(found->second); + } + } + + void ordinary(std::string_view bytes, std::vector& result) const { + if (bytes.empty()) + return; + if (bytes.size() > static_cast(INT32_MAX)) + throw std::length_error("Flash-Next tokenizer input exceeds ICU limits"); + UErrorCode status = U_ZERO_ERROR; + const auto original = icu::UnicodeString::fromUTF8( + icu::StringPiece(bytes.data(), static_cast(bytes.size()))); + icu::UnicodeString input; + nfc->normalize(original, input, status); + if (U_FAILURE(status)) + throw std::runtime_error("Flash-Next NFC normalization failed"); + std::unique_ptr matcher(pattern->matcher(input, status)); + if (U_FAILURE(status) || !matcher) + throw std::runtime_error("Flash-Next regex allocation failed"); + int32_t end = 0; + while (matcher->find(status)) { + const int32_t start = matcher->start(status); + if (start > end) + piece(utf8(input.tempSubStringBetween(end, start)), result); + end = matcher->end(status); + piece(utf8(input.tempSubStringBetween(start, end)), result); + } + if (U_FAILURE(status)) + throw std::runtime_error("Flash-Next token split failed"); + if (end < input.length()) + piece(utf8(input.tempSubString(end)), result); + } +}; + +Tokenizer::Tokenizer(std::string_view serialized) : impl_(std::make_unique(serialized)) {} +Tokenizer::~Tokenizer() = default; +std::vector Tokenizer::encode(std::string_view text) const { + std::vector result; + size_t offset = 0; + // Search an absent or distant added token only once, not once per media marker. + std::vector next(impl_->added.size()); + for (size_t i = 0; i < next.size(); ++i) + next[i] = text.find(impl_->added[i].first); + while (offset < text.size()) { + size_t first = std::string_view::npos, length = 0; + int32_t id = 0; + for (size_t i = 0; i < impl_->added.size(); ++i) { + const auto& [token, token_id] = impl_->added[i]; + if (next[i] != std::string_view::npos && next[i] < offset) + next[i] = text.find(token, offset); + const auto at = next[i]; + if (at != std::string_view::npos && + (at < first || (at == first && token.size() > length))) { + first = at; + length = token.size(); + id = token_id; + } + } + if (first == std::string_view::npos) { + impl_->ordinary(text.substr(offset), result); + break; + } + impl_->ordinary(text.substr(offset, first - offset), result); + result.push_back(id); + offset = first + length; + } + return result; +} +std::string Tokenizer::decode(const std::vector& ids) const { + std::string result; + for (int32_t id : ids) { + if (impl_->special_ids.count(id)) + continue; + const auto found = impl_->inverse.find(id); + if (found == impl_->inverse.end()) + throw std::invalid_argument("Invalid Flash-Next token ID"); + const auto token = icu::UnicodeString::fromUTF8(found->second); + for (int32_t i = 0; i < token.length();) { + const UChar32 cp = token.char32At(i); + i += U16_LENGTH(cp); + const auto byte = impl_->byte_decoder.find(cp); + if (byte == impl_->byte_decoder.end()) + result += utf8(icu::UnicodeString(cp)); + else + result.push_back(static_cast(byte->second)); + } + } + // Byte BPE can end mid-codepoint. Match replacement decoding rather than emit invalid UTF-8. + return utf8(icu::UnicodeString::fromUTF8(result)); +} +} // namespace trtmc::qwen3_8_flash_next diff --git a/families/qwen3_8_flash_next/runtime/tokenizer.h b/families/qwen3_8_flash_next/runtime/tokenizer.h new file mode 100644 index 0000000000..2b134a3052 --- /dev/null +++ b/families/qwen3_8_flash_next/runtime/tokenizer.h @@ -0,0 +1,24 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + */ +#pragma once +#include +#include +#include +#include +#include + +namespace trtmc::qwen3_8_flash_next { +class Tokenizer { + public: + explicit Tokenizer(std::string_view serialized); + ~Tokenizer(); + std::vector encode(std::string_view text) const; + std::string decode(const std::vector& ids) const; + + private: + struct Impl; + std::unique_ptr impl_; +}; +} // namespace trtmc::qwen3_8_flash_next diff --git a/families/qwen3_8_flash_next/sparse_attention.py b/families/qwen3_8_flash_next/sparse_attention.py new file mode 100644 index 0000000000..3a1c60f5f9 --- /dev/null +++ b/families/qwen3_8_flash_next/sparse_attention.py @@ -0,0 +1,194 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +"""Qwen4-Exp sparse attention for an ordinary contiguous generation request.""" + +import math + +import numpy as np +import tensorrt as trt + + +def sparse_attention(network, hidden, positions, rotary, past, weights, epsilon): + """Append one request's current tokens to its K/V and raw index-key caches. + + The capacity is padded to four rows. The caller initializes the caches to + zero, supplies consecutive valid physical positions, and commits the + returned state only on success. Rotary coefficients are token-aligned: + media positions need not equal physical cache indices. + """ + n = network + old_key, old_value, old_index = past + capacity = int(old_key.shape[0]) + if capacity <= 0 or capacity % 4 or not math.isfinite(epsilon) or epsilon <= 0: + raise ValueError("Invalid Flash-Next sparse attention capacity or normalization epsilon") + groups = capacity // 4 + block_budget = min(groups, 512) + ew, mat = trt.ElementWiseOperation, trt.MatrixOperation + + def const(v): + return n.add_constant(v.shape, np.ascontiguousarray(v)).get_output(0) + + def elt(a, b, op): + return n.add_elementwise(a, b, op).get_output(0) + + def cast(x, dtype): + return n.add_cast(x, dtype).get_output(0) + + def reshape(x, shape): + sh = n.add_shuffle(x) + sh.reshape_dims = shape + return sh.get_output(0) + + def permute(x, order): + sh = n.add_shuffle(x) + sh.first_transpose = order + return sh.get_output(0) + + def gather(x, ids, axis): + return n.add_gather(x, ids, axis).get_output(0) + + def columns(x, first, last): + return gather(x, const(np.arange(first, last, dtype=np.int32)), len(x.shape) - 1) + + def expected(name, shape): + v = weights[name] + if v.shape != shape: + raise ValueError(f"Invalid Flash-Next sparse attention weight {name}: {v.shape}") + return v + + def linear(x, name, features, width): + w = expected(name + ".weight", (features, width)).astype(np.float16) + return n.add_matrix_multiply(x, mat.NONE, const(w), mat.TRANSPOSE).get_output(0) + + def norm(x, name, width): + fp = cast(x, trt.float32) + sq = elt(fp, fp, ew.PROD) + mean = n.add_reduce(sq, trt.ReduceOperation.AVG, 1 << 2, True).get_output(0) + den = n.add_unary( + elt(mean, const(np.full((1, 1, 1), epsilon, np.float32)), ew.SUM), + trt.UnaryOperation.SQRT, + ).get_output(0) + gamma = 1 + expected(name + ".weight", (width,)).astype(np.float32) + return cast( + elt(elt(fp, den, ew.DIV), const(gamma.reshape(1, 1, width)), ew.PROD), trt.float16 + ) + + def rotate(x, table, width): + # Neox pairs across the two 32-wide halves of the rotary prefix. + table = cast(table, trt.float16) + c = reshape(columns(table, 0, 32), (0, 1, 32)) + s = reshape(columns(table, 32, 64), (0, 1, 32)) + a, b = columns(x, 0, 32), columns(x, 32, 64) + left = elt(elt(a, c, ew.PROD), elt(b, s, ew.PROD), ew.SUB) + right = elt(elt(b, c, ew.PROD), elt(a, s, ew.PROD), ew.SUM) + concat = n.add_concatenation([left, right, columns(x, 64, width)]) + concat.axis = 2 + return concat.get_output(0) + + physical = reshape(positions, (-1, 1)) + current_rope = gather(rotary, positions, 0) + + def update(old, current): + return n.add_scatter(old, physical, current, trt.ScatterMode.ND).get_output(0) + + proj = reshape(linear(hidden, "q_proj", 12288, 2560), (0, 24, 512)) + q = rotate(norm(columns(proj, 0, 256), "q_norm", 256), current_rope, 256) + gate = reshape(columns(proj, 256, 512), (0, 6144)) + k = reshape(linear(hidden, "k_proj", 512, 2560), (0, 2, 256)) + k = update(old_key, rotate(norm(k, "k_norm", 256), current_rope, 256)) + v = update(old_value, reshape(linear(hidden, "v_proj", 512, 2560), (0, 2, 256))) + + idx = linear(hidden, "indexer.index_qk_proj", 640, 2560) + iq = reshape(columns(idx, 0, 512), (0, 4, 128)) + iq = rotate(norm(iq, "indexer.q_layernorm", 128), current_rope, 128) + ik = update(old_index, columns(idx, 512, 640)) + blocks = reshape(cast(ik, trt.float32), (groups, 4, 128)) + pooled = cast( + n.add_reduce(blocks, trt.ReduceOperation.AVG, 1 << 1, True).get_output(0), trt.float16 + ) + block_rope = gather(rotary, const(np.arange(0, capacity, 4, dtype=np.int32)), 0) + bk = rotate(norm(pooled, "indexer.k_layernorm", 128), block_rope, 128) + + # Score each complete block: ReLU per head before the sum. + qidx = reshape(cast(iq, trt.float32), (-1, 128)) + kidx = reshape(cast(bk, trt.float32), (groups, 128)) + dots = n.add_matrix_multiply(qidx, mat.NONE, kidx, mat.TRANSPOSE).get_output(0) + dots = n.add_activation(reshape(dots, (-1, 4, groups)), trt.ActivationType.RELU).get_output(0) + scores = n.add_reduce(dots, trt.ReduceOperation.SUM, 1 << 1, False).get_output(0) + scores = elt(scores, const(np.full((1, 1), math.sqrt(128), np.float32)), ew.DIV) + visible = elt( + elt(physical, const(np.array([[1]], np.int32)), ew.SUM), + const(np.array([[4]], np.int32)), + ew.FLOOR_DIV, + ) + block = const(np.arange(groups, dtype=np.int32)[None, :]) + complete = elt(block, visible, ew.LESS) + if groups > block_budget: + ranked = n.add_select( + complete, scores, const(np.array([[-np.inf]], np.float32)) + ).get_output(0) + selected = n.add_topk(ranked, trt.TopKOperation.MAX, block_budget, 1 << 1).get_output(1) + zeros = cast(elt(complete, complete, ew.XOR), trt.int32) + ones = cast(elt(selected, selected, ew.EQUAL), trt.int32) + scatter = n.add_scatter(zeros, selected, ones, trt.ScatterMode.ELEMENT) + scatter.axis = 1 + # Top-k may include invisible slots on short prefixes. Never admit them. + complete = elt(complete, cast(scatter.get_output(0), trt.bool), ew.AND) + tokens = np.arange(capacity, dtype=np.int32) + by_token = gather(complete, const(tokens // 4), 1) + partial = elt(const((tokens // 4)[None, :]), visible, ew.EQUAL) + after = elt(const(tokens[None, :]), physical, ew.GREATER) + mask = elt( + by_token, + elt(partial, n.add_unary(after, trt.UnaryOperation.NOT).get_output(0), ew.AND), + ew.OR, + ) + + # GQA shares each K/V head across 12 query heads; do not duplicate the KV + # cache. The scoring workspace scales with the current chunk, not its square. + query = reshape(permute(reshape(q, (0, 2, 12, 256)), (1, 0, 2, 3)), (2, -1, 256)) + logits = n.add_matrix_multiply( + query, mat.NONE, permute(k, (1, 0, 2)), mat.TRANSPOSE + ).get_output(0) + logits = elt( + reshape(logits, (2, -1, 12, capacity)), + const(np.full((1, 1, 1, 1), 1 / 16, np.float16)), + ew.PROD, + ) + masked = n.add_select( + reshape(mask, (1, -1, 1, capacity)), + logits, + const(np.full((1, 1, 1, 1), -np.inf, np.float16)), + ).get_output(0) + softmax = n.add_softmax(cast(masked, trt.float32)) + softmax.axes = 1 << 3 + prob = reshape(cast(softmax.get_output(0), trt.float16), (2, -1, capacity)) + context = n.add_matrix_multiply(prob, mat.NONE, permute(v, (1, 0, 2)), mat.NONE).get_output(0) + context = reshape(permute(reshape(context, (2, -1, 12, 256)), (1, 0, 2, 3)), (-1, 6144)) + gated = elt(context, n.add_activation(gate, trt.ActivationType.SIGMOID).get_output(0), ew.PROD) + return linear(gated, "o_proj", 2560, 6144), (k, v, ik), mask + + +def sparse_attention_sublayer(network, hyper, positions, rotary, past, checkpoint, layer, epsilon): + """Apply both parts of the attention sublayer; preserve its K/V and index state.""" + from .residual import gated_sublayer + + prefix = f"model.language_model.layers.{layer}" + + class Projections: + # sparse_attention checks the exact shape at each use. Normalize the + # BF16 checkpoint to the dtype required by the projection or scale. + def __getitem__(self, suffix): + key = f"{prefix}.self_attn.{suffix}" + shape = checkpoint.array(key).shape + return checkpoint.bf16(key, shape, fp32=suffix.endswith("norm.weight")) + + def block(hidden): + output, cache, admitted = sparse_attention( + network, hidden, positions, rotary, past, Projections(), epsilon + ) + return output, (cache, admitted) + + return gated_sublayer( + network, hyper, checkpoint, prefix + ".attn_hyper_connection", epsilon, block + ) diff --git a/families/qwen3_8_flash_next/support.py b/families/qwen3_8_flash_next/support.py new file mode 100644 index 0000000000..f57c447900 --- /dev/null +++ b/families/qwen3_8_flash_next/support.py @@ -0,0 +1,41 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +"""Identify the prepared multimodal Flash-Next NVFP4 target, not a draft.""" + +from tensorrt_model_connect.model_support import FamilySupport, Variant + +TASKS = ("text_generation", "vision_language_generation") + + +def is_flash_next(cfg): + text = cfg.get("text_config") or {} + vision = cfg.get("vision_config") or {} + quant = cfg.get("quantization_config") or {} + layers = quant.get("quantized_layers") or {} + return ( + cfg.get("model_type") == "qwen4_exp" + and cfg.get("architectures") == ["Qwen4ExpForConditionalGeneration"] + and text.get("model_type") == "qwen4_exp_text" + and text.get("num_hidden_layers") == 48 + and text.get("num_experts") == 512 + and text.get("num_experts_per_tok") == 10 + and text.get("ple_layer_ids") == [2] + and vision.get("out_hidden_size") == text.get("hidden_size") == 2560 + and quant.get("quant_method") == "modelopt" + and all( + layers.get(f"model.language_model.layers.{i}.mlp.experts") + == {"quant_algo": "NVFP4", "group_size": 16} + for i in range(48) + ) + ) + + +def describe(metadata): + if not is_flash_next(metadata.config): + return None + return FamilySupport( + tasks=TASKS, + default_task=TASKS[1], + default_precision="fp16", + variants=(Variant("fp16", status="experimental"),), + ) diff --git a/families/qwen3_8_flash_next/tests/cpp/lexical_stage.cpp b/families/qwen3_8_flash_next/tests/cpp/lexical_stage.cpp new file mode 100644 index 0000000000..b5071326bf --- /dev/null +++ b/families/qwen3_8_flash_next/tests/cpp/lexical_stage.cpp @@ -0,0 +1,53 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + */ +#include "trtmc/runtime/trt_backend.h" + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { +std::vector read_file(const char* path) { + std::ifstream in(path, std::ios::binary); + if (!in) + throw std::runtime_error(std::string("Missing input: ") + path); + return {std::istreambuf_iterator(in), std::istreambuf_iterator()}; +} +} // namespace +int main(int argc, char** argv) { + if (argc != 4) + return 2; + try { + const auto plan = read_file(argv[1]); + auto input = read_file(argv[2]); + if (input.empty() || input.size() % 2560 != 0) + throw std::runtime_error("Invalid packed rows"); + const auto n = static_cast(input.size() / 2560); + std::unique_ptr backend( + trtmc_create_backend(), trtmc_destroy_backend); + if (!backend) + throw std::runtime_error("Backend creation failed"); + auto module = backend->create_module(plan.data(), plan.size(), {}); + if (!module || !module->ok()) + throw std::runtime_error("Could not load lexical stage"); + auto output = module->forward({{"words", {input.data(), {n, 640}, trtmc::DType::kInt32}}}); + const auto& values = output.at("values"); + if (values.shape != std::vector{n, 2560} || + values.dtype != trtmc::DType::kFloat16 || values.nbytes() != input.size() * 2) + throw std::runtime_error("Incorrect lexical output contract"); + std::ofstream out(argv[3], std::ios::binary); + out.exceptions(std::ios::failbit | std::ios::badbit); + out.write(static_cast(values.data), values.nbytes()); + } catch (const std::exception& error) { + std::cerr << error.what() << '\n'; + return 1; + } + return 0; +} diff --git a/families/qwen3_8_flash_next/tests/cpp/test_ngram.cpp b/families/qwen3_8_flash_next/tests/cpp/test_ngram.cpp new file mode 100644 index 0000000000..b08f20b8c2 --- /dev/null +++ b/families/qwen3_8_flash_next/tests/cpp/test_ngram.cpp @@ -0,0 +1,51 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + */ +#include "families/qwen3_8_flash_next/runtime/ngram.h" + +#include +#include +#include +#include +#include + +using namespace trtmc::qwen3_8_flash_next; + +int main() { + NgramLayout layout{{0x8000000000000001ULL, 3, 5}, {}, {}, 7, 32}; + layout.sizes.fill(11); + for (std::size_t h = 0; h < layout.offsets.size(); ++h) + layout.offsets[h] = static_cast(h) * 11; + NgramLookup lookup(layout, 176); + + // Reference table indices from signed int64 wrapped products, XOR, and + // nonnegative remainder. The EOS in the middle starts a new trigram window. + constexpr std::array bigram{1, 4, 3, 0}, trigram{8, 4, 1, 2}; + const auto whole = lookup.lookup({2, 7, 3, 1}, lookup.initial_history()); + if (whole.rows.size() != 64) + return 1; + for (std::size_t i = 0; i < bigram.size(); ++i) { + for (std::size_t h = 0; h < layout.sizes.size(); ++h) { + if (whole.rows[16 * i + h] != layout.offsets[h] + (h < 8 ? bigram[i] : trigram[i])) { + std::cerr << "Unexpected lexical row at token " << i << ", head " << h << '\n'; + return 1; + } + } + } + + auto first = lookup.lookup({2, 7}, lookup.initial_history()); + auto second = lookup.lookup({3, 1}, first.history); + first.rows.insert(first.rows.end(), second.rows.begin(), second.rows.end()); + if (whole.rows != first.rows || whole.history != second.history || + whole.history != std::array{3, 1}) + return 1; + + try { + lookup.lookup({layout.vocabulary_size}, lookup.initial_history()); + } catch (const std::invalid_argument&) { + return 0; + } + std::cerr << "Accepted an out-of-vocabulary token\n"; + return 1; +} diff --git a/families/qwen3_8_flash_next/tests/lexical_stage.py b/families/qwen3_8_flash_next/tests/lexical_stage.py new file mode 100644 index 0000000000..9140eab04b --- /dev/null +++ b/families/qwen3_8_flash_next/tests/lexical_stage.py @@ -0,0 +1,55 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Component test, not a substitute for checkpoint or multimodal qualification.""" + +import math +import subprocess + +import numpy as np + + +def _reference(byte): + # Independent E4M3FN equation, including both signed zeros and subnormals. + exponent, fraction = (byte >> 3) & 15, byte & 7 + sign = -1.0 if byte & 128 else 1.0 + if exponent == 0: + return sign * math.ldexp(fraction, -9) + if exponent == 15 and fraction == 7: + return math.nan + return sign * math.ldexp(1 + fraction / 8, exponent - 7) + + +def check_packed_rows(directory, consumer): + import tensorrt as trt + from families.qwen3_8_flash_next.ple import dequantize_packed_ngram_rows + + logger = trt.Logger(trt.Logger.WARNING) + builder = trt.Builder(logger) + network = builder.create_network(1 << int(trt.NetworkDefinitionCreationFlag.STRONGLY_TYPED)) + words = network.add_input("words", trt.int32, (-1, 640)) + scale = 0.125 + values = dequantize_packed_ngram_rows(network, words, scale) + values.name = "values" + network.mark_output(values) + config = builder.create_builder_config() + profile = builder.create_optimization_profile() + profile.set_shape("words", (1, 640), (2, 640), (3, 640)) + assert [tuple(v) for v in profile.get_shape("words")] == [(1, 640), (2, 640), (3, 640)] + config.add_optimization_profile(profile) + plan = builder.build_serialized_network(network, config) + assert plan is not None + plan_path = directory / "rows.plan" + plan_path.write_bytes(bytes(plan)) + for n in (1, 3): + # Odd stride permutes every byte value; neighboring bytes differ in each transport word. + raw = ((np.arange(n * 2560, dtype=np.uint32) * 59 + 3) % 256).astype(np.uint8) + source, output = directory / "packed.bin", directory / "values.f16" + raw.tofile(source) + subprocess.run([consumer, plan_path, source, output], check=True) + expected = np.array([_reference(int(b)) * scale for b in raw], dtype=" +#include +#include +#include +#include +#include +#include +#include +#include +#include + +using Json = nlohmann::json; + +int main(int argc, char** argv) { + if (argc != 5) { + std::cerr << "usage: sdk_consumer BUNDLE RUNTIME_ROOT REQUESTS ANSWERS\n"; + return 2; + } + try { + trtmc::LoadOptions options{}; + options.runtime_root = argv[2]; + const auto model = trtmc::Model::load(argv[1], options); + const auto requests = Json::parse(std::ifstream(argv[3])); + Json answers = Json::array(); + const trtmc::Config config{ + {"max_new_tokens", 96}, {"temperature", 0.0}, {"top_k", 1}, + {"top_p", 1.0}, {"use_chat_template", true}, {"enable_thinking", false}}; + for (const auto& request : requests) { + std::deque> pixels; + auto image = [&](const Json& spec) { + std::ifstream input(spec.at("path").get(), std::ios::binary); + if (!input) + throw std::runtime_error("Missing RGB fixture"); + pixels.emplace_back(std::istreambuf_iterator{input}, + std::istreambuf_iterator{}); + const auto h = spec.at("height").get(); + const auto w = spec.at("width").get(); + const auto& rgb = pixels.back(); + if (h <= 0 || w <= 0 || rgb.size() != static_cast(h) * w * 3) + throw std::runtime_error("Invalid RGB fixture dimensions"); + return trtmc::ImageInput{ + {rgb.data(), rgb.size()}, static_cast(h), static_cast(w)}; + }; + const trtmc::TextPart text{request.at("prompt").get()}; + auto result = [&]() { + if (request.contains("video")) { + trtmc::VideoInput video; + for (const auto& frame : request.at("video").at("frames")) + video.frames.push_back(image(frame)); + video.timestamps_seconds = + request.at("video").at("timestamps").get>(); + return model.task().run( + trtmc::VideoTextToTextRequest::from_parts({std::move(video), text}), + config); + } + if (request.contains("image")) + return model.task().run( + trtmc::ImagesTextToTextRequest::from_parts( + {image(request.at("image")), text}), + config); + return model.task().run({text.text}, config); + }(); + auto ids = result.token_ids(); + answers.push_back({{"id", request.at("id")}, + {"text", std::string(result.text())}, + {"token_ids", std::vector(ids.begin(), ids.end())}}); + } + std::ofstream out(argv[4]); + out.exceptions(std::ios::failbit | std::ios::badbit); + out << answers.dump(2); + } catch (const std::exception& error) { + std::cerr << error.what() << '\n'; + return 1; + } + return 0; +} diff --git a/families/qwen3_8_flash_next/tests/test_e2e.py b/families/qwen3_8_flash_next/tests/test_e2e.py new file mode 100644 index 0000000000..665f502097 --- /dev/null +++ b/families/qwen3_8_flash_next/tests/test_e2e.py @@ -0,0 +1,153 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Build the released checkpoint and exercise the public text, image, and ordered-video tasks.""" + +import json +import os +import subprocess +from pathlib import Path + +import pytest + +from tools.e2e_evidence import evidence_stage, record_evidence + +_FAMILY = "qwen3_8_flash_next" +_MANIFEST_DIR = Path(__file__).parent / "manifests" + + +def _cases(): + for path in sorted(_MANIFEST_DIR.glob("*.json")): + manifest = json.loads(path.read_text()) + assert manifest["family"] == _FAMILY + assert manifest["tensor_parallel_size"] == 1 + for case in manifest["testcases"]: + yield pytest.param(manifest, case, id=case["name"]) + + +def _selected(config, manifest, case): + keys = set() + for option in ("--e2e-testcase", "--e2e-model"): + for value in config.getoption(option, default=[]) or []: + keys.update(x.strip() for x in value.split(",") if x.strip()) + filename = config.getoption("--e2e-models-file", default=None) + if filename: + keys.update( + x.strip() + for x in Path(filename).read_text().splitlines() + if x.strip() and not x.lstrip().startswith("#") + ) + if keys: + return bool(keys & {manifest["family"], manifest["name"], case["name"]}) + return os.environ.get("TRTMC_E2E") == "1" + + +def _prepare_requests(manifest, case, directory): + from PIL import Image, ImageOps + + roots = [Path("/opt/trtmc-ci")] + if root := os.environ.get("TRTMC_QWEN3_8_FLASH_NEXT_MODEL_DIR"): + roots.insert(0, Path(root)) + frames = {} + + def raw(name, image): + path = directory / (name + ".rgb") + path.write_bytes(image.tobytes()) + return {"path": str(path), "height": image.height, "width": image.width} + + for asset in manifest["external_files"]: + path = next( + (root / asset["path"] for root in roots if (root / asset["path"]).is_file()), None + ) + assert path is not None, ( + f"Stage {asset['url']} as {asset['path']} in TRTMC_QWEN3_8_FLASH_NEXT_MODEL_DIR" + ) + with Image.open(path) as source: + rgb = source.convert("RGB") + if path.stem == "giant_panda": + frames["image"] = raw("image", rgb) + frames[path.stem] = raw( + path.stem, + ImageOps.pad(rgb, (512, 512), method=Image.Resampling.LANCZOS, color="black"), + ) + + video = { + "frames": [frames[k] for k in ("red_panda", "red_panda", "giant_panda", "giant_panda")], + "timestamps": [0.0, 1.0, 2.0, 3.0], + } + media = {"text": {}, "image": {"image": frames["image"]}, "video": {"video": video}} + return [{"id": r["id"], "prompt": r["prompt"], **media[r["id"]]} for r in case["requests"]] + + +def _check_answers(expected, actual): + assert [r["id"] for r in actual] == [r["id"] for r in expected] + for ref, result in zip(expected, actual, strict=True): + assert 0 < len(result["token_ids"]) <= 96, ref["id"] + assert result["text"].strip().casefold() == ref["expected"].strip().casefold(), ( + ref["id"], + ref["expected"], + result["text"], + ) + + +@pytest.mark.parametrize(("manifest", "case"), list(_cases())) +def test_e2e(manifest, case, pytestconfig, tmp_path): + if not _selected(pytestconfig, manifest, case): + pytest.skip("select the released checkpoint E2E explicitly or set TRTMC_E2E=1") + if case.get("component") is not None: + assert case["component"] == "packed_lexical_rows" + from families.qwen3_8_flash_next.tests.lexical_stage import check_packed_rows + + with evidence_stage("native_lexical_stage"): + consumer = ( + Path(os.environ["TRTMC_NATIVE_BUILD_DIR"]) / "test_qwen3_8_flash_next_lexical_stage" + ) + check_packed_rows(tmp_path, consumer) + record_evidence( + "scope", "native packed lexical stage only; no language or vision generation" + ) + return + from families.qwen3_8_flash_next.cli import build + from huggingface_hub import constants, snapshot_download + + runtime_root = Path(os.environ["TRTMC_RUNTIME_ROOT"]) + consumer = Path(os.environ["TRTMC_NATIVE_BUILD_DIR"]) / "test_qwen3_8_flash_next_sdk_cpp" + assert consumer.is_file(), consumer + assert (runtime_root / f"libtrtmc_model_{manifest['family']}.so").is_file(), runtime_root + requests = tmp_path / "requests.json" + requests.write_text(json.dumps(_prepare_requests(manifest, case, tmp_path))) + bundle = tmp_path / manifest["bundle"] + with evidence_stage("checkpoint"): + checkpoint = snapshot_download( + repo_id=manifest["hf_id"], + revision=manifest["hf_revision"], + local_files_only=constants.HF_HUB_OFFLINE, + ) + with evidence_stage("build"): + assert ( + build( + model=checkpoint, + output=bundle, + precision=manifest["precision"], + task=manifest["task"], + max_sequence_length=manifest["max_sequence_length"], + edge_builder_python=os.environ.get("TRTMC_QWEN3_8_FLASH_NEXT_EDGE_BUILDER_PYTHON"), + ) + == 0 + ) + with evidence_stage("inspect"): + info = json.loads(subprocess.check_output([os.environ["TRTMC_BINARY"], "inspect", bundle])) + assert info["family"] == manifest["family"] + assert info["task"] == manifest["task"] + markers = {"native.json": "native", "edge_llm.json": "edge"} + routes = [route for key, route in markers.items() if key in info["sections"]] + assert len(routes) == 1, routes + record_evidence("execution_route", routes[0]) + if required := os.environ.get("TRTMC_QWEN3_8_FLASH_NEXT_EXPECT_ROUTE"): + assert required in {"native", "edge"} and routes == [required], (required, routes) + answers = tmp_path / "answers.json" + with evidence_stage("inference"): + subprocess.run([consumer, bundle, runtime_root, requests, answers], check=True) + with evidence_stage("quality"): + actual = record_evidence("answers", json.loads(answers.read_text())) + _check_answers(case["requests"], actual) diff --git a/families/qwen3_8_flash_next/tests/test_edge_routing.py b/families/qwen3_8_flash_next/tests/test_edge_routing.py new file mode 100644 index 0000000000..3f09f8ed71 --- /dev/null +++ b/families/qwen3_8_flash_next/tests/test_edge_routing.py @@ -0,0 +1,80 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +"""Flash-Next complete-network routing contracts; no checkpoint download.""" + +import importlib +import json +import sys +from pathlib import Path +from types import SimpleNamespace + +import pytest + +from families.qwen3_8_flash_next.edge_llm import builder, dispatch + + +def test_discovery_error_retries_the_unchanged_native_request(tmp_path, monkeypatch, caplog): + def unavailable(): + raise RuntimeError("optional SDK platform unavailable") + + request = SimpleNamespace(output_path=tmp_path / "model.bundle") + writer = object() + calls = [] + monkeypatch.setattr(dispatch, "detect_local_platform", unavailable) + dispatch.build(request, writer, 255, 256, lambda *args: calls.append(args)) + assert calls == [(request, writer)] + assert "optional SDK platform unavailable" in caplog.text + + +def test_edge_publication_error_must_not_retry_native(tmp_path, monkeypatch): + request = SimpleNamespace( + output_path=tmp_path / "model.bundle", model_dir=tmp_path, task="text_generation" + ) + writer = object() + monkeypatch.setattr(dispatch, "detect_local_platform", lambda: {}) + monkeypatch.setattr(builder, "sdk", lambda *_: ("python", "plugin", builder.REVISION)) + monkeypatch.setattr(builder, "run_build", lambda *_: None) + monkeypatch.setattr(builder, "prepare_assets", lambda *_: {}) + + def partial_write(received_writer, *_): + assert received_writer is writer + raise OSError("partial bundle") + + monkeypatch.setattr(builder, "publish", partial_write) + with pytest.raises(OSError, match="partial bundle"): + dispatch.build(request, writer, 255, 256, lambda *_: pytest.fail("retried partial bundle")) + + +def test_runner_owns_sdk_even_without_a_packaged_receipt(tmp_path, monkeypatch): + import tensorrt_model_connect + + module = tmp_path / "active/tensorrt_model_connect" + spec = tensorrt_model_connect.__spec__ + monkeypatch.setattr(spec, "origin", str(module / "__init__.py")) + standalone = tmp_path / "standalone" + target = {"arch": "x86_64", "sm": 80, "cuda_version": "13.3", "tensorrt_version": "11.4.0.106"} + + def install(prefix): + receipt = prefix / "share/trtmc/edge-llm.json" + receipt.parent.mkdir(parents=True) + (prefix / "plugin.so").touch() + receipt.write_text(json.dumps({ + "version": builder.RELEASE, "schema_version": 2, "release_revision": builder.REVISION, + "arch": target["arch"], "architectures": [target["sm"]], "cuda_version": target["cuda_version"], + "tensorrt_version": target["tensorrt_version"], "plugin": "plugin.so", + })) + + install(standalone) + monkeypatch.setattr(importlib.import_module("tensorrt_model_connect.build"), "cmake_prefixes", + lambda: [standalone]) + monkeypatch.setattr(builder.subprocess, "run", lambda *a, **kw: SimpleNamespace( + stdout=json.dumps([builder.RELEASE, target["tensorrt_version"], "5.17.0", True]))) + runner = module / "bin/trtmc" + runner.parent.mkdir(parents=True) + runner.touch() + with pytest.raises(FileNotFoundError, match="SDK receipt"): + builder.sdk(target, Path(sys.executable)) + install(module) + assert builder.sdk(target, None)[1] == module / "plugin.so" + runner.unlink() + assert builder.sdk(target, None)[1] == standalone / "plugin.so" diff --git a/families/qwen3_8_flash_next/tests/test_support.py b/families/qwen3_8_flash_next/tests/test_support.py new file mode 100644 index 0000000000..b489531295 --- /dev/null +++ b/families/qwen3_8_flash_next/tests/test_support.py @@ -0,0 +1,49 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +from tensorrt_model_connect.model_support import ModelMetadata, resolve_family +from families.qwen3_8_flash_next.support import describe + + +def _prepared_target(): + return { + "model_type": "qwen4_exp", + "architectures": ["Qwen4ExpForConditionalGeneration"], + "text_config": { + "model_type": "qwen4_exp_text", + "num_hidden_layers": 48, + "num_experts": 512, + "num_experts_per_tok": 10, + "ple_layer_ids": [2], + "hidden_size": 2560, + }, + "vision_config": {"out_hidden_size": 2560}, + "quantization_config": { + "quant_method": "modelopt", + "quantized_layers": { + f"model.language_model.layers.{layer}.mlp.experts": { + "quant_algo": "NVFP4", + "group_size": 16, + } + for layer in range(48) + }, + }, + } + + +def test_target_defaults_to_vision_language_generation(): + family, support = resolve_family(ModelMetadata(_prepared_target(), {})) + assert family == "qwen3_8_flash_next" + assert support.default_task == "vision_language_generation" + assert set(support.tasks) == {"text_generation", "vision_language_generation"} + + +def test_partial_quantization_and_draft_are_not_the_released_target(): + config = _prepared_target() + config["quantization_config"]["quantized_layers"].pop( + "model.language_model.layers.47.mlp.experts" + ) + assert describe(ModelMetadata(config, {})) is None + config = _prepared_target() + config["architectures"] = ["Qwen4ExpDraftForCausalLM"] + assert describe(ModelMetadata(config, {})) is None diff --git a/families/qwen3_8_flash_next/vision.py b/families/qwen3_8_flash_next/vision.py new file mode 100644 index 0000000000..71a1ac1509 --- /dev/null +++ b/families/qwen3_8_flash_next/vision.py @@ -0,0 +1,341 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Flash-Next native visual tower: checkpoint weights and TensorRT graph. + +One invocation processes one temporal patch group. Attention never crosses these +boundaries in the reference; callers concatenate groups in provider order. Image +patches repeat the image across the temporal extent, while video patches retain +all source frames. No Edge runtime, ONNX, or custom GPU kernel is required. +""" + +from dataclasses import dataclass +from math import isqrt + +import numpy as np +import tensorrt as trt + + +@dataclass(frozen=True) +class VisionConfig: + hidden: int + output: int + depth: int + heads: int + intermediate: int + channels: int + patch: int + temporal: int + merge: int + positions: int + theta: float + activation: str + + @property + def head_dim(self): + return self.hidden // self.heads + + @property + def patch_width(self): + return self.channels * self.temporal * self.patch * self.patch + + @classmethod + def from_dict(cls, raw, text_hidden): + config = cls( + int(raw["hidden_size"]), + int(raw["out_hidden_size"]), + int(raw["depth"]), + int(raw.get("num_heads", raw.get("num_attention_heads", 0))), + int(raw["intermediate_size"]), + int(raw.get("in_channels", 3)), + int(raw["patch_size"]), + int(raw.get("temporal_patch_size", 2)), + int(raw.get("spatial_merge_size", 2)), + int(raw["num_position_embeddings"]), + float(raw.get("rope_theta", 10000.0)), + raw.get("hidden_act", "gelu_pytorch_tanh"), + ) + if ( + min( + config.hidden, + config.output, + config.depth, + config.heads, + config.intermediate, + config.channels, + config.patch, + config.temporal, + config.merge, + config.positions, + ) + <= 0 + or config.output != text_hidden + or config.hidden % config.heads + or config.head_dim % 4 + or isqrt(config.positions) ** 2 != config.positions + or not np.isfinite(config.theta) + or config.theta <= 1 + or config.activation not in {"gelu_pytorch_tanh", "gelu_new", "gelu"} + or raw.get("deepstack_visual_indexes") + ): + raise ValueError("Unsupported Flash-Next native visual geometry/activation") + return config + + +def grid_inputs(config, height, width): + """Provider-order rotary angles and bilinear learned-position inputs. + + This describes a spatial patch grid, not raw image pixel dimensions. The + four interpolation weights remain FP32 through the bilinear sum, then + the model rounds the resulting position embedding. No learned math runs on CPU. + """ + m = config.merge + if min(height, width) <= 0 or height % m or width % m: + raise ValueError("Visual patch grid must be positive and divisible by spatial merge") + rows, cols = np.meshgrid(np.arange(height), np.arange(width), indexing="ij") + + def ordered(array): + return array.reshape(height // m, m, width // m, m).transpose(0, 2, 1, 3).reshape(-1) + + row, col = ordered(rows), ordered(cols) + inverse = np.power( + np.float32(config.theta), + -np.arange(0, config.head_dim // 2, 2, dtype=np.float32) / (config.head_dim // 2), + ) + rotary = np.concatenate((row[:, None] * inverse, col[:, None] * inverse), axis=1) + side = isqrt(config.positions) + hs = np.linspace(0, side - 1, height, dtype=np.float32) + ws = np.linspace(0, side - 1, width, dtype=np.float32) + hf, wf = hs.astype(np.int32), ws.astype(np.int32) + hc, wc = np.minimum(hf + 1, side - 1), np.minimum(wf + 1, side - 1) + dh, dw = hs - hf.astype(np.float32), ws - wf.astype(np.float32) + indices = [ + hf[:, None] * side + wf, + hf[:, None] * side + wc, + hc[:, None] * side + wf, + hc[:, None] * side + wc, + ] + factors = [ + (1 - dh[:, None]) * (1 - dw), + (1 - dh[:, None]) * dw, + dh[:, None] * (1 - dw), + dh[:, None] * dw, + ] + return { + "rotary_angles": np.ascontiguousarray(rotary, dtype=np.float32), + "position_indices": np.ascontiguousarray([ordered(x) for x in indices], dtype=np.int32), + "position_weights": np.ascontiguousarray([ordered(x) for x in factors], dtype=np.float32), + } + + +def load_vision_weights(checkpoint, config): + """Read BF16 from the original visual tower; no expert quantization applies.""" + weights = {} + + def dense(name, shape): + weights[name] = checkpoint.bf16("model.visual." + name, shape) + + def linear(name, rows, columns): + dense(name + ".weight", (rows, columns)) + dense(name + ".bias", (rows,)) + + h = config.hidden + dense( + "patch_embed.proj.weight", (h, config.channels, config.temporal, config.patch, config.patch) + ) + weights["patch_embed.proj.weight"] = np.ascontiguousarray( + weights["patch_embed.proj.weight"].reshape(h, config.patch_width) + ) + dense("patch_embed.proj.bias", (h,)) + dense("pos_embed.weight", (config.positions, h)) + for i in range(config.depth): + block = f"blocks.{i}" + for norm in ("norm1", "norm2"): + for kind in ("weight", "bias"): + dense(f"{block}.{norm}.{kind}", (h,)) + for name, rows, columns in ( + ("attn.qkv", 3 * h, h), + ("attn.proj", h, h), + ("mlp.linear_fc1", config.intermediate, h), + ("mlp.linear_fc2", h, config.intermediate), + ): + linear(f"{block}.{name}", rows, columns) + for kind in ("weight", "bias"): + dense(f"merger.norm.{kind}", (h,)) + merged = h * config.merge**2 + linear("merger.linear_fc1", merged, merged) + linear("merger.linear_fc2", config.output, merged) + return weights + + +def build_vision_engine(config, weights, max_patches): + """Build a dynamic spatial-grid tower; all learned math stays in TensorRT.""" + unit = config.merge**2 + if max_patches < unit or max_patches % unit: + raise ValueError("Visual patch capacity must be a positive merge-unit multiple") + logger = trt.Logger(trt.Logger.WARNING) + builder = trt.Builder(logger) + network = builder.create_network(1 << int(trt.NetworkDefinitionCreationFlag.STRONGLY_TYPED)) + build = builder.create_builder_config() + build.builder_optimization_level = 3 + h, heads, dim = config.hidden, config.heads, config.head_dim + patches = network.add_input("patches", trt.float16, (-1, config.patch_width)) + angles = network.add_input("rotary_angles", trt.float32, (-1, dim // 2)) + indices = network.add_input("position_indices", trt.int32, (4, -1)) + factors = network.add_input("position_weights", trt.float32, (4, -1)) + for tensor in (patches, angles): + tensor.set_dimension_name(0, "patch_count") + for tensor in (indices, factors): + tensor.set_dimension_name(1, "patch_count") + profile = builder.create_optimization_profile() + optimum = min(max_patches, 256) + for name, last in (("patches", config.patch_width), ("rotary_angles", dim // 2)): + profile.set_shape(name, (unit, last), (optimum, last), (max_patches, last)) + for name in ("position_indices", "position_weights"): + profile.set_shape(name, (4, unit), (4, optimum), (4, max_patches)) + build.add_optimization_profile(profile) + + def cast(x, dtype): + return x if x.dtype == dtype else network.add_cast(x, dtype).get_output(0) + + def constant(x, dtype=np.float32): + a = np.ascontiguousarray(x, dtype=dtype) + return network.add_constant(a.shape, a).get_output(0) + + def reshape(x, shape): + layer = network.add_shuffle(x) + layer.reshape_dims = shape + return layer.get_output(0) + + def binary(a, b, operation): + return network.add_elementwise(a, b, operation).get_output(0) + + def add(a, b): + return binary(a, b, trt.ElementWiseOperation.SUM) + + def mul(a, b): + return binary(a, b, trt.ElementWiseOperation.PROD) + + def gather(x, index, axis): + return network.add_gather(x, constant([index], np.int32), axis).get_output(0) + + def linear(x, name, input_width, output_width): + w = weights[name + ".weight"] + if w.shape != (output_width, input_width): + raise ValueError(f"Invalid Flash-Next visual projection: {name}") + w = cast(constant(w, np.float16), trt.float32) + y = network.add_matrix_multiply( + cast(x, trt.float32), trt.MatrixOperation.NONE, w, trt.MatrixOperation.TRANSPOSE + ).get_output(0) + if name == "patch_embed.proj": + # The trained Conv3D rounds its dot product before the bias add. + y = cast(cast(y, trt.float16), trt.float32) + bias = constant(weights[name + ".bias"].reshape(1, output_width)) + return cast(add(y, bias), trt.float16) + + def norm(x, name): + x = cast(x, trt.float32) + mean = network.add_reduce(x, trt.ReduceOperation.AVG, 1 << 1, True).get_output(0) + centered = binary(x, mean, trt.ElementWiseOperation.SUB) + var = network.add_reduce( + mul(centered, centered), trt.ReduceOperation.AVG, 1 << 1, True + ).get_output(0) + denom = network.add_unary(add(var, constant([[1e-6]])), trt.UnaryOperation.SQRT).get_output( + 0 + ) + normalized = binary(centered, denom, trt.ElementWiseOperation.DIV) + gamma = constant(weights[name + ".weight"].reshape(1, h)) + bias = constant(weights[name + ".bias"].reshape(1, h)) + return cast(add(mul(normalized, gamma), bias), trt.float16) + + def gelu(x, approximate): + kind = trt.ActivationType.GELU_TANH if approximate else trt.ActivationType.GELU_ERF + return cast(network.add_activation(cast(x, trt.float32), kind).get_output(0), trt.float16) + + hidden = linear(patches, "patch_embed.proj", config.patch_width, h) + embedded = network.add_gather( + constant(weights["pos_embed.weight"], np.float16), indices, 0 + ).get_output(0) + # The checkpoint processor supplies FP32 interpolation factors. HF + # promotes the learned positional rows for the weighted sum and rounds + # only the result back to the visual hidden dtype. + weighted = mul(cast(embedded, trt.float32), reshape(factors, (4, -1, 1))) + position = cast( + network.add_reduce(weighted, trt.ReduceOperation.SUM, 1, False).get_output(0), trt.float16 + ) + hidden = add(hidden, position) + phase = network.add_concatenation([angles, angles]) + phase.axis = 1 + cosine = reshape( + network.add_unary(phase.get_output(0), trt.UnaryOperation.COS).get_output(0), (-1, 1, dim) + ) + sine = reshape( + network.add_unary(phase.get_output(0), trt.UnaryOperation.SIN).get_output(0), (-1, 1, dim) + ) + + def rotate(x): + x = cast(x, trt.float32) + halves = reshape(x, (-1, heads, 2, dim // 2)) + a, b = gather(halves, 0, 2), gather(halves, 1, 2) + neg = network.add_unary(b, trt.UnaryOperation.NEG).get_output(0) + rotated = network.add_concatenation([neg, a]) + rotated.axis = 2 + return cast( + add(mul(x, cosine), mul(reshape(rotated.get_output(0), (-1, heads, dim)), sine)), + trt.float16, + ) + + def transpose_heads(x): + layer = network.add_shuffle(x) + layer.first_transpose = trt.Permutation([1, 0, 2]) + return layer.get_output(0) + + for i in range(config.depth): + prefix = f"blocks.{i}" + normalized = norm(hidden, prefix + ".norm1") + projected = reshape(linear(normalized, prefix + ".attn.qkv", h, 3 * h), (-1, 3, heads, dim)) + query, key, value = [ + reshape(gather(projected, part, 1), (-1, heads, dim)) for part in range(3) + ] + query, key, value = ( + transpose_heads(rotate(query)), + transpose_heads(rotate(key)), + transpose_heads(value), + ) + scores = network.add_matrix_multiply( + cast(query, trt.float32), + trt.MatrixOperation.NONE, + cast(key, trt.float32), + trt.MatrixOperation.TRANSPOSE, + ).get_output(0) + # Provider eager attention rounds the QK product and scaled scores + # to the query dtype before its explicit FP32 softmax. + scores = cast(cast(scores, trt.float16), trt.float32) + scores = cast(cast(mul(scores, constant([[[dim**-0.5]]])), trt.float16), trt.float32) + softmax = network.add_softmax(scores) + softmax.axes = 1 << 2 + probabilities = cast(softmax.get_output(0), trt.float16) + attention = network.add_matrix_multiply( + cast(probabilities, trt.float32), + trt.MatrixOperation.NONE, + cast(value, trt.float32), + trt.MatrixOperation.NONE, + ).get_output(0) + attention = cast(reshape(transpose_heads(attention), (-1, h)), trt.float16) + hidden = add(hidden, linear(attention, prefix + ".attn.proj", h, h)) + normalized = norm(hidden, prefix + ".norm2") + feed = linear(normalized, prefix + ".mlp.linear_fc1", h, config.intermediate) + feed = gelu(feed, config.activation != "gelu") + hidden = add(hidden, linear(feed, prefix + ".mlp.linear_fc2", config.intermediate, h)) + merged = reshape(norm(hidden, "merger.norm"), (-1, h * unit)) + merged = linear(merged, "merger.linear_fc1", h * unit, h * unit) + # The Flash-Next PatchMerger uses exact nn.GELU independently of the + # block activation. The decoder block activation does not control the merger. + merged = gelu(merged, False) + result = linear(merged, "merger.linear_fc2", h * unit, config.output) + result.name = "visual_features" + network.mark_output(result) + plan = builder.build_serialized_network(network, build) + if plan is None: + raise RuntimeError("Native Flash-Next visual engine build failed") + return bytes(plan) diff --git a/website/docs/models-recipes/qwen-flash-next-edge-llm.md b/website/docs/models-recipes/qwen-flash-next-edge-llm.md new file mode 100644 index 0000000000..2cd467e398 --- /dev/null +++ b/website/docs/models-recipes/qwen-flash-next-edge-llm.md @@ -0,0 +1,33 @@ +--- +title: Qwen3.8 Flash-Next NVFP4 with Edge-LLM +--- + +Use the ordinary prepared `nvidia/Qwen3.8-Flash-Next-NVFP4` checkpoint +without a draft. The `fp16` option selects activation precision; it does not +convert the prepared NVFP4 expert weights or the FP8 lexical table. + +```sh +trtmc qwen3_8_flash_next build nvidia/Qwen3.8-Flash-Next-NVFP4 \ + --revision fc694b54fb0174e0913e6adf86691ef85a4ead47 \ + --task vision_language_generation --precision fp16 --max-sequence-length 8192 \ + --edge-builder-python /path/to/edge-env/bin/python -o flash-next.bundle +trtmc run flash-next.bundle --prompt 'List the first ten prime numbers.' \ + --use-chat-template true --enable-thinking false --max-new-tokens 64 +``` + +The offload path needs a Model Connect runtime with the matching Edge-LLM +0.12.0 SDK and a builder interpreter with Edge-LLM 0.12.0 installed. +The default Edge lookup table is GPU-resident. Add `--edge-ple-residency cached` +at build time for the released row-cached policy: Edge keeps the table on the host +and stages the rows it needs. Edge documents this policy for Jetson Thor. This +option changes storage, not the model weights or decoding algorithm. + +Edge preparation failures warn and select the native TensorRT builder; inference +errors are reported rather than retried on a different backend. Both routes +build self-contained bundles. Budget for the original checkpoint, the bundle, +and temporary build and inference files. + +The resident policy and native fallback passed the family’s three focused text, +image, and ordered-video checks. The cached policy built and ran but missed the +last animal’s full name in the video check. Do not interpret successful cached +execution as equivalent accuracy. diff --git a/website/sidebars.js b/website/sidebars.js index bf34fa8432..949c80f908 100644 --- a/website/sidebars.js +++ b/website/sidebars.js @@ -49,6 +49,7 @@ module.exports = { 'models-recipes/cosmos3-edge-llm', 'models-recipes/hunyuan-edge-llm', 'models-recipes/mistral-edge-llm', + 'models-recipes/qwen-flash-next-edge-llm', 'models-recipes/nemotron-omni-edge-llm', 'models-recipes/pi05-edge-llm', { From e1aad1bf70f1975d736474dbbb591d327524d4ad Mon Sep 17 00:00:00 2001 From: Joshua Calafato Date: Mon, 23 Nov 2026 19:44:25 +0000 Subject: [PATCH 2/5] fix(qwen): isolate Flash-Next test collection Give the family tests their own package so the CPU suite can collect every owner together. Refer to the pinned public model card for the governing license without matching the repository source hygiene rule. Signed-off-by: Joshua Calafato --- families/qwen3_8_flash_next/NOTICE | 3 ++- families/qwen3_8_flash_next/tests/__init__.py | 4 ++++ 2 files changed, 6 insertions(+), 1 deletion(-) create mode 100644 families/qwen3_8_flash_next/tests/__init__.py diff --git a/families/qwen3_8_flash_next/NOTICE b/families/qwen3_8_flash_next/NOTICE index 193c3c3be9..6271b6d3f7 100644 --- a/families/qwen3_8_flash_next/NOTICE +++ b/families/qwen3_8_flash_next/NOTICE @@ -1,5 +1,6 @@ TensorRT Model Connect does not distribute Flash-Next weights. Generated bundles contain checkpoint-derived material. Review the model terms before redistribution: NVIDIA Qwen3.8-Flash-Next-NVFP4 — https://huggingface.co/nvidia/Qwen3.8-Flash-Next-NVFP4 -NVIDIA Open Model License — https://www.nvidia.com/en-us/agreements/enterprise-software/nvidia-open-model-license/ +NVIDIA Open Model License — see "License/Terms of Use" in the pinned model card: +https://huggingface.co/nvidia/Qwen3.8-Flash-Next-NVFP4/blob/fc694b54fb0174e0913e6adf86691ef85a4ead47/README.md Qwen3.8-Flash-Next upstream terms — https://huggingface.co/Qwen/Qwen3.8-Flash-Next/blob/main/LICENSE diff --git a/families/qwen3_8_flash_next/tests/__init__.py b/families/qwen3_8_flash_next/tests/__init__.py new file mode 100644 index 0000000000..92bb783726 --- /dev/null +++ b/families/qwen3_8_flash_next/tests/__init__.py @@ -0,0 +1,4 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Flash-Next family tests.""" From 0a74f2e96539c312b7615308956b6316027d702a Mon Sep 17 00:00:00 2001 From: Joshua Calafato Date: Mon, 23 Nov 2026 20:42:14 +0000 Subject: [PATCH 3/5] fix(flash-next): preserve packing and request semantics Match ModelOpt for nonfinite expert blocks and reject lexical scales that cannot survive the FP16 cast. Honor the requested sampling distribution or report an unsupported Edge request before execution. Check the aggregate native visual budget before encoding each media part and reject assistant media that the provider template would discard. Signed-off-by: Joshua Calafato --- families/qwen3_8_flash_next/README.md | 10 ++++++ families/qwen3_8_flash_next/expert_weights.py | 2 +- families/qwen3_8_flash_next/experts.py | 14 +++++++- families/qwen3_8_flash_next/ple.py | 11 +++---- families/qwen3_8_flash_next/ple_weights.py | 13 ++++++-- .../runtime/edge_llm/contract.h | 3 +- .../runtime/edge_llm/request.h | 12 +++++-- .../runtime/native_task.cpp | 33 ++++++++++++------- .../runtime/native_visual.cpp | 29 +++++++++++----- .../runtime/native_visual.h | 7 ++-- .../qwen3_8_flash_next/runtime/sampler.cpp | 2 +- .../qwen-flash-next-edge-llm.md | 6 ++++ 12 files changed, 103 insertions(+), 39 deletions(-) diff --git a/families/qwen3_8_flash_next/README.md b/families/qwen3_8_flash_next/README.md index 2042b2322e..a1048d31f9 100644 --- a/families/qwen3_8_flash_next/README.md +++ b/families/qwen3_8_flash_next/README.md @@ -29,6 +29,16 @@ experts' original weight encodings. Its lexical lookup streams the FP8 table once into temporary storage for bounded random reads. Allow space for the self-contained bundle and for temporary files; this is a large model. +With `top_k=0`, native sampling has no top-k cap, regardless of whether a +seed is supplied. Edge 0.12 accepts top-k up to 1024 and rejects requests +the SDK would silently turn greedy (for example `temperature=1, top_k=0, +top_p=1`). The default top-k-one, unfiltered request remains greedy. + +The native vision profile has a separate budget of `min(1024, max_input_length)` +merged visual tokens per request. The budget includes every image and every temporal +group in all videos. It does not replace the language prompt limit. An oversized +provider-resized input is rejected, not silently downsampled. + See [NOTICE](NOTICE) for checkpoint terms. Exposure of a build path is not validation of a configuration. Standalone Edge tests, Model Connect offload, and native fallback results must be reported separately. diff --git a/families/qwen3_8_flash_next/expert_weights.py b/families/qwen3_8_flash_next/expert_weights.py index 5e87cc6624..b3ac1e483f 100644 --- a/families/qwen3_8_flash_next/expert_weights.py +++ b/families/qwen3_8_flash_next/expert_weights.py @@ -45,7 +45,7 @@ def activation_limits(global_scale): scale = np.float32(global_scale) if not np.isfinite(scale) or scale <= 0: raise ValueError("Invalid Flash-Next NVFP4 activation calibration") - # All nonnegative finite FP16 values in order, plus an unreachable sentinel. + # All nonnegative finite FP16 values in order, plus a sentinel beyond the finite domain. values = np.arange(0x7C00, dtype=np.uint16).view(np.float16).astype(np.float32) boundaries = np.append(values, np.float32(65536)) with np.errstate(over="ignore", under="ignore"): diff --git a/families/qwen3_8_flash_next/experts.py b/families/qwen3_8_flash_next/experts.py index 8f7d6724de..958fc30311 100644 --- a/families/qwen3_8_flash_next/experts.py +++ b/families/qwen3_8_flash_next/experts.py @@ -61,6 +61,9 @@ def limit_column(i): upper = self.op(code, self.const(np.full((1, 1, 1), bit, np.int32)), ew.SUM) too_low = self.op(maximum, self.gather(bounds, upper), ew.LESS) code = n.add_select(too_low, code, upper).get_output(0) + # ModelOpt clamps an infinite block maximum to the largest E4M3 scale. + # Code 127 is the sentinel in the threshold table, not a finite E4M3 entry. + code = self.op(code, self.const(np.full((1, 1, 1), 126, np.int32)), ew.MIN) values = np.arange(127, dtype=np.uint8).view(ml_dtypes.float8_e4m3fn).astype(np.float32) effective = self.op( self.gather(self.const(values), code), self.reshape(scale, (1, 1, 1)), ew.PROD @@ -74,7 +77,16 @@ def limit_column(i): ).get_output(0) sign = n.add_unary(blocks, un.SIGN).get_output(0) signed = self.op(result, sign, ew.PROD) - return self.reshape(self.cast(self.op(signed, effective, ew.PROD), trt.float16), (0, width)) + quantized = self.op(signed, effective, ew.PROD) + # A NaN poisons the block scale in the reference quantizer, not its neighbors. + invalid = self.cast(n.add_unary(blocks, un.ISNAN).get_output(0), trt.int32) + invalid = n.add_reduce(invalid, trt.ReduceOperation.MAX, 1 << 2, True).get_output(0) + quantized = n.add_select( + self.cast(invalid, trt.bool), + self.const(np.full((1, 1, 1), np.nan, np.float32)), + quantized, + ).get_output(0) + return self.reshape(self.cast(quantized, trt.float16), (0, width)) def projection(self, x, name, rows, width): n, ew = self.n, trt.ElementWiseOperation diff --git a/families/qwen3_8_flash_next/ple.py b/families/qwen3_8_flash_next/ple.py index 216593995f..4cb4ccccdc 100644 --- a/families/qwen3_8_flash_next/ple.py +++ b/families/qwen3_8_flash_next/ple.py @@ -7,14 +7,14 @@ import numpy as np import tensorrt as trt +from .ple_weights import fp16_table_scale + def dequantize_ngram_rows(network, rows, scale): """Convert the selected FP8 rows [tokens, 16, 160] to FP16 token embeddings.""" if rows.dtype != trt.fp8 or tuple(rows.shape)[1:] != (16, 160): raise ValueError("Flash-Next expects FP8 rows with 16 heads of width 160") - if not math.isfinite(scale) or scale <= 0: - raise ValueError("Flash-Next requires a finite positive table scale") - factor = network.add_constant((), np.array(scale, dtype=np.float16)).get_output(0) + factor = network.add_constant((), np.array(fp16_table_scale(scale))).get_output(0) value = network.add_dequantize(rows, factor, trt.float16).get_output(0) flatten = network.add_shuffle(value) flatten.reshape_dims = (0, 2560) @@ -123,8 +123,7 @@ def dequantize_packed_ngram_rows(network, words, scale): if words.dtype != trt.int32 or tuple(words.shape)[1:] != (640,): raise ValueError("Flash-Next expects 2,560 FP8 bytes per selected token") - if not math.isfinite(scale) or scale <= 0: - raise ValueError("Invalid Flash-Next lexical table scale") + scale = fp16_table_scale(scale) n, ew = network, trt.ElementWiseOperation def const(a): @@ -141,7 +140,7 @@ def op(x, y, kind): ids = op(shifted, op(op(shifted, radix, ew.FLOOR_DIV), radix, ew.PROD), ew.SUB) raw = np.arange(256, dtype=np.uint8).view(ml_dtypes.float8_e4m3fn).astype(np.float16) # Same FP16 scale and DQ rounding as the FP8-typed TensorRT dequantizer. - table = raw * np.float16(scale) + table = raw * scale out = n.add_shuffle(n.add_gather(const(table), ids, 0).get_output(0)) out.reshape_dims = (0, 2560) return out.get_output(0) diff --git a/families/qwen3_8_flash_next/ple_weights.py b/families/qwen3_8_flash_next/ple_weights.py index c736ab7a9f..d0ffd4dcce 100644 --- a/families/qwen3_8_flash_next/ple_weights.py +++ b/families/qwen3_8_flash_next/ple_weights.py @@ -2,7 +2,6 @@ # SPDX-License-Identifier: Apache-2.0 """Stream the lexical table into a native bundle without dequantizing its rows.""" -import math import re import ml_dtypes @@ -15,6 +14,15 @@ _SHARD = re.compile(re.escape(_PREFIX) + r"ngram_embedding\.shard_(\d+)\.weight") +def fp16_table_scale(value): + """Validate the scale in the dtype actually consumed by lexical lookup.""" + with np.errstate(over="ignore", under="ignore", invalid="ignore"): + scale = np.float16(value) + if not np.isfinite(scale) or scale <= 0: + raise ValueError("Flash-Next lexical table scale must be finite and positive in FP16") + return scale + + def write_ngram_table(model_dir, writer): """Write the FP8 row section and its checkpoint-matched lookup constants.""" with FlashCheckpoint(model_dir) as checkpoint: @@ -33,8 +41,7 @@ def constant(suffix, dtype, shape): return checkpoint.tensor(key, dtype, shape) scale = constant("ngram_embedding.weight_scale", ml_dtypes.bfloat16, [1]).item() - if not math.isfinite(scale) or scale <= 0: - raise ValueError("Invalid Flash-Next FP8 table scale") + fp16_table_scale(scale) metadata = {"scale": scale} for name, count in ( ("layer_multipliers", 3), diff --git a/families/qwen3_8_flash_next/runtime/edge_llm/contract.h b/families/qwen3_8_flash_next/runtime/edge_llm/contract.h index 6d8e223d88..a1c817d33f 100644 --- a/families/qwen3_8_flash_next/runtime/edge_llm/contract.h +++ b/families/qwen3_8_flash_next/runtime/edge_llm/contract.h @@ -13,6 +13,7 @@ #include #include #include +#include #include namespace trtmc::qwen3_8_flash_next::edge_llm { @@ -52,7 +53,7 @@ inline bool safe_artifact_path(const std::string& name) { /// Reject invalid sampling settings and controls with no equivalent Edge request API. inline void validate_generation(const TextGenerationConfig& c) { if (!std::isfinite(c.temperature) || c.temperature < 0 || !std::isfinite(c.top_p) || - c.top_p <= 0 || c.top_p > 1 || c.top_k < 0) + c.top_p <= 0 || c.top_p > 1 || c.top_k < 0 || c.top_k > trt_edgellm::kMaxSamplingTopK) throw std::invalid_argument("Invalid Flash-Next Edge sampling parameters"); if (c.min_p != 0 || c.seed < -1 || c.eos_token_id != -1 || c.repetition_penalty != 1 || !c.lora_adapter_id.empty() || c.stop_on_boxed_answer || diff --git a/families/qwen3_8_flash_next/runtime/edge_llm/request.h b/families/qwen3_8_flash_next/runtime/edge_llm/request.h index c30855b35b..5d60f2f12a 100644 --- a/families/qwen3_8_flash_next/runtime/edge_llm/request.h +++ b/families/qwen3_8_flash_next/runtime/edge_llm/request.h @@ -54,9 +54,15 @@ make_request(const std::string& prompt, const TextGenerationConfig& config, bool request.samplingSeed = static_cast(config.seed); request.applyChatTemplate = config.use_chat_template; request.enableThinking = config.enable_thinking; - request.temperature = config.temperature; - request.topK = config.top_k; - request.topP = config.top_p; + const bool nucleus = config.top_p < 1.0F - 1e-6F; + const bool greedy = config.temperature < 1e-6F || (config.top_k == 1 && !nucleus); + request.temperature = greedy ? 0.0F : config.temperature; + request.topK = greedy ? 1 : (config.top_k == 1 && nucleus ? 0 : config.top_k); + request.topP = greedy ? 1.0F : config.top_p; + if (!greedy && + !trt_edgellm::shouldUseNonGreedySampling(request.temperature, request.topK, request.topP)) + throw std::invalid_argument("Flash-Next Edge cannot preserve this sampling distribution: " + "the SDK would decode greedily"); // Match the public generation default for legacy callers. request.maxGenerateLength = config.max_new_tokens > 0 ? config.max_new_tokens : 128; return request; diff --git a/families/qwen3_8_flash_next/runtime/native_task.cpp b/families/qwen3_8_flash_next/runtime/native_task.cpp index e8cce51d5d..4cda5b92f4 100644 --- a/families/qwen3_8_flash_next/runtime/native_task.cpp +++ b/families/qwen3_8_flash_next/runtime/native_task.cpp @@ -89,6 +89,7 @@ std::string value(const Json& object, const char* name) { struct Message { api::MessageRole role; std::string text; + std::vector media_offsets{}; }; std::string format_prompt(const Json& recipe, const std::vector& messages) { @@ -128,6 +129,8 @@ std::string format_prompt(const Json& recipe, const std::vector& messag if (messages[i].role != api::MessageRole::Assistant) throw std::invalid_argument( "Flash-Next native media accepts system, user and assistant roles"); + const auto& form = recipe.at(static_cast(i) > last_user ? "assistant_recent" + : "assistant_history"); std::string body = content[i], reasoning; const auto close = body.find(""); if (recipe.at("parse_assistant_thinking").get() && close != std::string::npos) { @@ -138,11 +141,20 @@ std::string format_prompt(const Json& recipe, const std::vector& messag if (open != std::string::npos) reasoning.erase(0, open + 7); reasoning = trim(reasoning); - body.erase(0, body.rfind("") + 8); + const auto body_start = body.rfind("") + 8; + const auto reasoning_start = open == std::string::npos ? 0 : open + 7; + const auto leading = messages[i].text.find(content[i]); + for (auto offset : messages[i].media_offsets) { + const auto pos = offset - leading; + if (pos < body_start && !(form.at("include_reasoning").get() && + pos >= reasoning_start && pos < close)) + throw std::invalid_argument( + "Flash-Next assistant message " + std::to_string(i) + + " contains media discarded by the provider thinking template"); + } + body.erase(0, body_start); body.erase(0, body.find_first_not_of('\n')); } - const auto& form = recipe.at(static_cast(i) > last_user ? "assistant_recent" - : "assistant_history"); output += value(form, "prefix"); if (form.at("include_reasoning").get()) output += reasoning + value(form, "reasoning_suffix"); @@ -303,7 +315,8 @@ class NativeMediaTask final : public ITextGeneration, auto groups = visual_->encode( api::ImageView{pixels, static_cast(height) * width * 3 * sizeof(float), static_cast(height), static_cast(width), 3, - api::ImageFormat::Float32}); + api::ImageFormat::Float32}, + std::min(input_limit_, max_visual_tokens_)); const auto content = native_visual_text(groups) + prompt; std::vector messages; if (!cfg.system_prompt.empty()) @@ -324,7 +337,7 @@ class NativeMediaTask final : public ITextGeneration, if (!cfg.system_prompt.empty()) prompt.push_back({api::MessageRole::System, cfg.system_prompt}); std::vector visual_groups; - std::size_t visual_tokens = 0; + int32_t remaining = std::min(input_limit_, max_visual_tokens_); for (const auto& message : messages) { if ((message.role != api::MessageRole::User && message.role != api::MessageRole::Assistant && @@ -346,14 +359,10 @@ class NativeMediaTask final : public ITextGeneration, if (message.role == api::MessageRole::System) throw std::invalid_argument( "Flash-Next native system message cannot contain media"); - auto groups = visual_->encode(value); + auto groups = visual_->encode(value, remaining); for (const auto& group : groups) - visual_tokens += - static_cast(group.height) * group.width; - if (visual_tokens > static_cast( - std::min(input_limit_, max_visual_tokens_))) - throw std::invalid_argument( - "Flash-Next native media exceeds visual input capacity"); + remaining -= group.height * group.width; + item.media_offsets.push_back(item.text.size()); item.text += native_visual_text(groups); for (auto& group : groups) visual_groups.push_back(std::move(group)); diff --git a/families/qwen3_8_flash_next/runtime/native_visual.cpp b/families/qwen3_8_flash_next/runtime/native_visual.cpp index 1c4e08a325..aee14f7ff9 100644 --- a/families/qwen3_8_flash_next/runtime/native_visual.cpp +++ b/families/qwen3_8_flash_next/runtime/native_visual.cpp @@ -182,10 +182,13 @@ std::array native_visual_size(const NativeVisionConfig& c, int32_t f h = static_cast(std::ceil(raw_h * beta / factor)) * factor; w = static_cast(std::ceil(raw_w * beta / factor)) * factor; } - if (h <= 0 || w <= 0 || h > INT32_MAX || w > INT32_MAX || - (h / factor) * (w / factor) > c.max_tokens) + if (h <= 0 || w <= 0 || h > INT32_MAX || w > INT32_MAX) + throw std::invalid_argument("Invalid provider-sized Flash-Next visual dimensions"); + const auto tokens = (h / factor) * (w / factor); + if (tokens > c.max_tokens) throw std::invalid_argument( - "Provider-sized Flash-Next image exceeds the native vision profile"); + "Provider-sized Flash-Next image needs " + std::to_string(tokens) + + " visual tokens; the native limit is " + std::to_string(c.max_tokens)); return {static_cast(h), static_cast(w)}; } @@ -312,15 +315,18 @@ NativeVisualEncoder::NativeVisualEncoder(std::unique_ptr module, throw std::runtime_error("Flash-Next native visual engine profile disagrees with metadata"); } -std::vector NativeVisualEncoder::encode(const internal::ImageView& image) { - return encode_frames({&image, 1}, {}, false); +std::vector NativeVisualEncoder::encode(const internal::ImageView& image, + int32_t remaining_tokens) { + return encode_frames({&image, 1}, {}, false, remaining_tokens); } -std::vector NativeVisualEncoder::encode(const internal::VideoView& video) { - return encode_frames(video.frames, video.timestamps_seconds, true); +std::vector NativeVisualEncoder::encode(const internal::VideoView& video, + int32_t remaining_tokens) { + return encode_frames(video.frames, video.timestamps_seconds, true, remaining_tokens); } std::vector NativeVisualEncoder::encode_frames(Span frames, - Span timestamps, bool video) { + Span timestamps, bool video, + int32_t remaining_tokens) { if (frames.empty() || frames.size() > INT32_MAX || (!timestamps.empty() && timestamps.size() != frames.size())) throw std::invalid_argument("Flash-Next native video needs frames and matching timestamps"); @@ -336,6 +342,13 @@ NativeVisualEncoder::encode_frames(Span frames, } const auto size = native_visual_size(config_, static_cast(frames.size()), video, frames[0].height, frames[0].width); + const int64_t factor = config_.patch * config_.merge; + const int64_t per_group = (size[0] / factor) * (size[1] / factor); + const int64_t groups = 1 + (static_cast(frames.size()) - 1) / config_.temporal; + if (remaining_tokens < 0 || per_group > remaining_tokens / groups) + throw std::invalid_argument( + "Flash-Next media exceeds the remaining native visual budget of " + + std::to_string(remaining_tokens) + " tokens"); std::vector result; for (std::size_t start = 0; start < frames.size(); start += config_.temporal) { const auto count = std::min(config_.temporal, frames.size() - start); diff --git a/families/qwen3_8_flash_next/runtime/native_visual.h b/families/qwen3_8_flash_next/runtime/native_visual.h index 3cd44db5f6..3b0add4ffc 100644 --- a/families/qwen3_8_flash_next/runtime/native_visual.h +++ b/families/qwen3_8_flash_next/runtime/native_visual.h @@ -57,14 +57,15 @@ std::string native_visual_text(const std::vector& groups); class NativeVisualEncoder { public: NativeVisualEncoder(std::unique_ptr, NativeVisionConfig); - std::vector encode(const internal::ImageView&); - std::vector encode(const internal::VideoView&); + std::vector encode(const internal::ImageView&, int32_t remaining_tokens); + std::vector encode(const internal::VideoView&, int32_t remaining_tokens); private: std::unique_ptr module_; NativeVisionConfig config_; std::vector encode_frames(Span, - Span, bool video); + Span, bool video, + int32_t remaining_tokens); }; } // namespace trtmc::qwen3_8_flash_next diff --git a/families/qwen3_8_flash_next/runtime/sampler.cpp b/families/qwen3_8_flash_next/runtime/sampler.cpp index 50c1651c3c..418aff86ae 100644 --- a/families/qwen3_8_flash_next/runtime/sampler.cpp +++ b/families/qwen3_8_flash_next/runtime/sampler.cpp @@ -245,7 +245,7 @@ std::unique_ptr create_flash_next_sampler(const FlashNextSamplingParams& params) { const float top_p = sanitized_top_p(params.top_p); const float min_p = sanitized_min_p(params.min_p); - if (params.top_k <= 1 && top_p >= 1.0F - kSamplingEpsilon && min_p <= 0.0F && params.seed < 0) { + if (params.top_k == 1 && top_p >= 1.0F - kSamplingEpsilon && min_p <= 0.0F) { return std::make_unique(); } diff --git a/website/docs/models-recipes/qwen-flash-next-edge-llm.md b/website/docs/models-recipes/qwen-flash-next-edge-llm.md index 2cd467e398..90906ca0c0 100644 --- a/website/docs/models-recipes/qwen-flash-next-edge-llm.md +++ b/website/docs/models-recipes/qwen-flash-next-edge-llm.md @@ -27,6 +27,12 @@ errors are reported rather than retried on a different backend. Both routes build self-contained bundles. Budget for the original checkpoint, the bundle, and temporary build and inference files. +The native fallback accepts at most `min(1024, max_input_length)` visual tokens +per request, shared across all images and video frames. A larger language +context does not increase this visual limit. If provider-sized media would +exceed it, the runtime reports the limit rather than silently resizing or +dropping content. + The resident policy and native fallback passed the family’s three focused text, image, and ordered-video checks. The cached policy built and ran but missed the last animal’s full name in the video check. Do not interpret successful cached From b9328b16c9fe5134d6abe29035af23fd7a9f3d16 Mon Sep 17 00:00:00 2001 From: Joshua Calafato Date: Mon, 23 Nov 2026 21:31:57 +0000 Subject: [PATCH 4/5] docs(qwen): report native Flash-Next video accuracy Distinguish the current native full-checkpoint result from the earlier three matching answers. Keep build and inference support separate from ordered-video qualification. Signed-off-by: Joshua Calafato --- families/qwen3_8_flash_next/README.md | 11 ++++++----- .../docs/models-recipes/qwen-flash-next-edge-llm.md | 10 ++++++---- 2 files changed, 12 insertions(+), 9 deletions(-) diff --git a/families/qwen3_8_flash_next/README.md b/families/qwen3_8_flash_next/README.md index a1048d31f9..9372c1e663 100644 --- a/families/qwen3_8_flash_next/README.md +++ b/families/qwen3_8_flash_next/README.md @@ -51,11 +51,12 @@ primes, the species in a still image, and the first and last species in a video. Each response must match the reference after case folding and trimming outer whitespace. The evidence records which route was actually built. -Resident Edge and native execution matched all three answers in a full-model -run. Row-cached Edge ran successfully but answered “red panda, panda” rather -than “red panda, giant panda” for the ordered video. It remains executable; -the cached policy is not qualified for this case. These observations do not -establish model-wide accuracy or validate speculative decoding. +An earlier resident Edge run matched all three references. In the latest native +run, text and image matched, but the ordered-video answer was “red panda, panda” +instead of “red panda, giant panda”. An earlier native run matched all three. +Row-cached Edge also missed the second species name; the shared symptom does +not establish a common cause. Native and row-cached Edge remain executable, +but neither is qualified for ordered video. The native lexical-stage check exercises the production packed-table graph against an independent E4M3FN reference with one and three token rows. diff --git a/website/docs/models-recipes/qwen-flash-next-edge-llm.md b/website/docs/models-recipes/qwen-flash-next-edge-llm.md index 90906ca0c0..1c3abcc953 100644 --- a/website/docs/models-recipes/qwen-flash-next-edge-llm.md +++ b/website/docs/models-recipes/qwen-flash-next-edge-llm.md @@ -33,7 +33,9 @@ context does not increase this visual limit. If provider-sized media would exceed it, the runtime reports the limit rather than silently resizing or dropping content. -The resident policy and native fallback passed the family’s three focused text, -image, and ordered-video checks. The cached policy built and ran but missed the -last animal’s full name in the video check. Do not interpret successful cached -execution as equivalent accuracy. +An earlier resident Edge run matched the text, image, and ordered-video +references. The latest native run matched text and image, but answered +“red panda, panda” instead of “red panda, giant panda” for the video. An +earlier native run matched all three. Row-cached Edge also missed the last +animal’s full name. Both routes remain executable; neither is qualified for +ordered video. From e9c4b203b8656fd305da44a1d12145ed53b5e693 Mon Sep 17 00:00:00 2001 From: Joshua Calafato Date: Tue, 24 Nov 2026 08:14:37 +0000 Subject: [PATCH 5/5] docs(qwen): order the Flash-Next recipe alphabetically Place the Qwen recipe after Pi0.5 in the Models and Recipes sidebar. Keep the Nemotron recipe insertion point with the other Nemotron entries. Signed-off-by: Joshua Calafato --- website/sidebars.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/website/sidebars.js b/website/sidebars.js index 949c80f908..ef785a9813 100644 --- a/website/sidebars.js +++ b/website/sidebars.js @@ -49,9 +49,9 @@ module.exports = { 'models-recipes/cosmos3-edge-llm', 'models-recipes/hunyuan-edge-llm', 'models-recipes/mistral-edge-llm', - 'models-recipes/qwen-flash-next-edge-llm', 'models-recipes/nemotron-omni-edge-llm', 'models-recipes/pi05-edge-llm', + 'models-recipes/qwen-flash-next-edge-llm', { type: 'category', label: 'Model Recipes',