Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions families/qwen3_8_flash_next/NOTICE
Original file line number Diff line number Diff line change
@@ -0,0 +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 — 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
63 changes: 63 additions & 0 deletions families/qwen3_8_flash_next/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
# 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.

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.

## 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.

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.
It does not build the language model or test generation.
4 changes: 4 additions & 0 deletions families/qwen3_8_flash_next/__init__.py
Original file line number Diff line number Diff line change
@@ -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."""
90 changes: 90 additions & 0 deletions families/qwen3_8_flash_next/checkpoint.py
Original file line number Diff line number Diff line change
@@ -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("<Q", mapping)[0]
if not 0 < size <= min(100_000_000, len(mapping) - 8):
raise ValueError(f"Invalid Flash-Next shard header size: {name}")
header = json.loads(mapping[8 : 8 + size])
self._shards[name] = header, mapping, 8 + size
return self._shards[name]

def array(self, key):
"""Return a read-only NumPy view; no table or expert-bank copy."""
header, mapping, start = self._shard(key)
item = header[key]
dtype = np.dtype(_DTYPES[item["dtype"]]).newbyteorder("<")
shape = tuple(item["shape"])
first, end = item["data_offsets"]
if (
type(first) is not int
or type(end) is not int
or any(type(n) is not int or n < 0 for n in shape)
or not 0 <= first <= end <= len(mapping) - start
or end - first != math.prod(shape) * dtype.itemsize
):
raise ValueError(f"Invalid Flash-Next tensor extent: {key}")
return np.ndarray(shape, dtype=dtype, buffer=mapping, offset=start + first)

def tensor(self, key, dtype, shape):
item = self.array(key)
if item.dtype != dtype or item.shape != tuple(shape):
raise ValueError(f"Invalid Flash-Next checkpoint tensor: {key}")
return item

def bf16(self, key, shape, *, fp32=False):
param = self.tensor(key, ml_dtypes.bfloat16, shape)
return param.astype(np.float32 if fp32 else np.float16)
105 changes: 105 additions & 0 deletions families/qwen3_8_flash_next/cli.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
{
"version": 1,
"commands": [
{
"name": "build",
"help": "Build an ordinary prepared Qwen3.8 Flash-Next NVFP4 bundle",
"executor": "python",
"handler": "cli:build",
"arguments": [
{
"name": "model",
"type": "string",
"help": "Hugging Face model ID or local snapshot"
},
{
"name": "output",
"flags": [
"-o",
"--output"
],
"type": "path",
"required": true
},
{
"name": "revision",
"flags": [
"--revision"
],
"type": "string"
},
{
"name": "task",
"flags": [
"--task"
],
"type": "string",
"choices": [
"text_generation",
"vision_language_generation"
],
"default": "vision_language_generation"
},
{
"name": "precision",
"flags": [
"--precision"
],
"type": "string",
"choices": [
"fp16"
],
"default": "fp16"
},
{
"name": "backend",
"flags": [
"--backend"
],
"type": "string",
"choices": [
"trt"
],
"default": "trt"
},
{
"name": "max_sequence_length",
"flags": [
"--max-sequence-length"
],
"type": "int"
},
{
"name": "verbose",
"flags": [
"--verbose"
],
"type": "bool",
"action": "store_true",
"default": false
},
{
"name": "edge_builder_python",
"flags": [
"--edge-builder-python"
],
"type": "path",
"help": "Absolute Python interpreter for the optional Edge builder"
},
{
"name": "edge_ple_residency",
"flags": [
"--edge-ple-residency"
],
"type": "string",
"choices": [
"resident",
"cached"
],
"default": "resident",
"help": "Edge lookup-table storage policy; cached keeps rows on the host"
}
]
}
]
}
73 changes: 73 additions & 0 deletions families/qwen3_8_flash_next/cli.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0

"""Flash-Next-specific build arguments; no shared command-line switches."""

from dataclasses import dataclass
from pathlib import Path

from tensorrt_model_connect.build import select_backend
from tensorrt_model_connect.bundle_writer import BundleWriter
from tensorrt_model_connect.model_support import load_model_metadata, resolve_family, resolve_model


@dataclass(frozen=True)
class FlashNextRequest:
"""Only the controls exposed by this family-owned command."""

model_dir: Path
output_path: Path
family: str
task: str
precision: str
backend: str
max_sequence_length: int | None
verbose: bool
edge_builder_python: Path | None = None
edge_ple_residency: str = "resident"


def build_bundle(request: FlashNextRequest) -> 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
Loading