From b813889d35c738e7cd9480d3a4c935bb71eb3a3e Mon Sep 17 00:00:00 2001 From: Will Guo Date: Thu, 12 Nov 2026 01:20:38 -0800 Subject: [PATCH 01/10] feat(minimax_m3): add bounded text continuation Add MiniMax M3.1 Flash's 60-layer text model as a self-contained family with staged MXFP8/NVFP4 weights, native BPE tokenization and greedy continuation through the public task API. Bound the initial path to one request and 128 total tokens without a KV cache. Use exact projection reductions and family-owned TVM-FFI kernels to preserve BF16 rounding boundaries and NVFP4 per-token input scaling. Add a model-agnostic section-range reader for staged tensor loading and cover numerical ties, malformed UTF-8 and C/C++ result lifetimes. Signed-off-by: Will Guo --- core/runtime/bundle/bundle_format.cpp | 18 +- core/runtime/include/trtmc/bundle.h | 5 + core/runtime/tests/test_bundle_format_v1.cpp | 27 ++ families/minimax_m3/README.md | 126 ++++++ families/minimax_m3/__init__.py | 4 + families/minimax_m3/graph.py | 203 ++++++++++ families/minimax_m3/model.py | 183 +++++++++ families/minimax_m3/precision.py | 89 ++++ families/minimax_m3/projection.py | 326 +++++++++++++++ families/minimax_m3/runtime/CMakeLists.txt | 43 ++ families/minimax_m3/runtime/bpe_tokenizer.cpp | 217 ++++++++++ families/minimax_m3/runtime/pipeline.cpp | 263 ++++++++++++ families/minimax_m3/runtime/pipeline.h | 36 ++ families/minimax_m3/runtime/plugin.cpp | 11 + families/minimax_m3/runtime/precision.cu | 381 ++++++++++++++++++ families/minimax_m3/runtime/tokenizer.h | 29 ++ families/minimax_m3/runtime/weights.cpp | 138 +++++++ families/minimax_m3/runtime/weights.h | 31 ++ families/minimax_m3/support.py | 14 + families/minimax_m3/tests/__init__.py | 2 + .../minimax_m3/tests/fixtures/config.json | 357 ++++++++++++++++ families/minimax_m3/tests/logits_consumer.cpp | 53 +++ .../manifests/minimax-m3.1-flash-bf16.json | 19 + families/minimax_m3/tests/reference.py | 217 ++++++++++ families/minimax_m3/tests/sdk_consumer.c | 68 ++++ families/minimax_m3/tests/sdk_consumer.cpp | 37 ++ .../tests/test_attention_precision.py | 74 ++++ families/minimax_m3/tests/test_e2e.py | 208 ++++++++++ .../minimax_m3/tests/test_e2e_selection.py | 59 +++ families/minimax_m3/tests/test_model.py | 68 ++++ .../minimax_m3/tests/test_normalization.py | 64 +++ families/minimax_m3/tests/test_nv_input.py | 70 ++++ .../tests/test_projection_precision.py | 82 ++++ .../minimax_m3/tests/test_quantization.py | 72 ++++ .../tests/test_reference_precision.py | 116 ++++++ .../minimax_m3/tests/test_rope_precision.py | 74 ++++ .../tests/test_routing_precision.py | 84 ++++ families/minimax_m3/tests/test_support.py | 30 ++ .../minimax_m3/tests/tokenizer_consumer.cpp | 32 ++ families/minimax_m3/tests/trt_runner.py | 63 +++ website/data/hf-model-metadata.json | 11 + 41 files changed, 4002 insertions(+), 2 deletions(-) create mode 100644 families/minimax_m3/README.md create mode 100644 families/minimax_m3/__init__.py create mode 100644 families/minimax_m3/graph.py create mode 100644 families/minimax_m3/model.py create mode 100644 families/minimax_m3/precision.py create mode 100644 families/minimax_m3/projection.py create mode 100644 families/minimax_m3/runtime/CMakeLists.txt create mode 100644 families/minimax_m3/runtime/bpe_tokenizer.cpp create mode 100644 families/minimax_m3/runtime/pipeline.cpp create mode 100644 families/minimax_m3/runtime/pipeline.h create mode 100644 families/minimax_m3/runtime/plugin.cpp create mode 100644 families/minimax_m3/runtime/precision.cu create mode 100644 families/minimax_m3/runtime/tokenizer.h create mode 100644 families/minimax_m3/runtime/weights.cpp create mode 100644 families/minimax_m3/runtime/weights.h create mode 100644 families/minimax_m3/support.py create mode 100644 families/minimax_m3/tests/__init__.py create mode 100644 families/minimax_m3/tests/fixtures/config.json create mode 100644 families/minimax_m3/tests/logits_consumer.cpp create mode 100644 families/minimax_m3/tests/manifests/minimax-m3.1-flash-bf16.json create mode 100644 families/minimax_m3/tests/reference.py create mode 100644 families/minimax_m3/tests/sdk_consumer.c create mode 100644 families/minimax_m3/tests/sdk_consumer.cpp create mode 100644 families/minimax_m3/tests/test_attention_precision.py create mode 100644 families/minimax_m3/tests/test_e2e.py create mode 100644 families/minimax_m3/tests/test_e2e_selection.py create mode 100644 families/minimax_m3/tests/test_model.py create mode 100644 families/minimax_m3/tests/test_normalization.py create mode 100644 families/minimax_m3/tests/test_nv_input.py create mode 100644 families/minimax_m3/tests/test_projection_precision.py create mode 100644 families/minimax_m3/tests/test_quantization.py create mode 100644 families/minimax_m3/tests/test_reference_precision.py create mode 100644 families/minimax_m3/tests/test_rope_precision.py create mode 100644 families/minimax_m3/tests/test_routing_precision.py create mode 100644 families/minimax_m3/tests/test_support.py create mode 100644 families/minimax_m3/tests/tokenizer_consumer.cpp create mode 100644 families/minimax_m3/tests/trt_runner.py diff --git a/core/runtime/bundle/bundle_format.cpp b/core/runtime/bundle/bundle_format.cpp index 2c1661f088..c524965e88 100644 --- a/core/runtime/bundle/bundle_format.cpp +++ b/core/runtime/bundle/bundle_format.cpp @@ -195,13 +195,27 @@ std::vector BundleReader::read_section(std::string_view name) const { const auto* section = find_section(name); if (section == nullptr) throw std::runtime_error("Bundle section not found: " + std::string(name)); + return read_section_range(name, 0, section->length); +} + +std::vector BundleReader::read_section_range(std::string_view name, std::uint64_t offset, + std::uint64_t length) const { + const auto* section = find_section(name); + if (section == nullptr) + throw std::runtime_error("Bundle section not found: " + std::string(name)); + if (offset > section->length || length > section->length - offset) + throw std::runtime_error("Bundle section range out of bounds: " + std::string(name)); const std::uint64_t file_offset = - checked_section_file_offset(*section, data_offset_, file_size_, path_); + checked_section_file_offset(*section, data_offset_, file_size_, path_) + offset; if (file_offset > static_cast(std::numeric_limits::max())) throw std::runtime_error("Bundle section '" + section->name + "' has an unsupported file offset: " + path_); - std::vector data(static_cast(section->length)); + if (length > std::vector().max_size() || + length > static_cast(std::numeric_limits::max())) + throw std::runtime_error("Bundle section range cannot be represented: " + + std::string(name)); + std::vector data(static_cast(length)); if (data.empty()) return data; std::ifstream in(path_, std::ios::binary); diff --git a/core/runtime/include/trtmc/bundle.h b/core/runtime/include/trtmc/bundle.h index 2b32776d2e..ff6f3161bd 100644 --- a/core/runtime/include/trtmc/bundle.h +++ b/core/runtime/include/trtmc/bundle.h @@ -45,6 +45,11 @@ class BundleReader { const BundleSectionInfo* find_section(std::string_view name) const noexcept; std::vector read_section(std::string_view name) const; + // Read a bounded range relative to one validated section. The range cannot + // cross into another section, including when offset + length overflows. + std::vector read_section_range(std::string_view name, std::uint64_t offset, + std::uint64_t length) const; + /// Copy a named section to an output stream using bounded working memory. /// @param name Validated bundle section name. /// @param output Caller-owned stream; may contain partial data on failure. diff --git a/core/runtime/tests/test_bundle_format_v1.cpp b/core/runtime/tests/test_bundle_format_v1.cpp index 6c5faa420f..a360da958a 100644 --- a/core/runtime/tests/test_bundle_format_v1.cpp +++ b/core/runtime/tests/test_bundle_format_v1.cpp @@ -101,6 +101,33 @@ int main() { check(valid_reader.info().sections.size() == 1, "one section descriptor"); check(valid_reader.info().sections.front().length == 4, "section length parsed"); check(valid_reader.read_section("engine.plan").size() == 4, "section payload read"); + const auto range = valid_reader.read_section_range("engine.plan", 1, 2); + check(std::string(range.begin(), range.end()) == "LA", "bounded section range read"); + check(valid_reader.read_section_range("engine.plan", 4, 0).empty(), + "empty range at section endpoint is valid"); + const auto adjacent = directory / "adjacent.bundle"; + write_bundle( + adjacent, + R"({"format":1,"family":"fake","task":"time_series_forecast","backend":"fake","sections":{"first":{"offset":0,"length":4},"next":{"offset":4,"length":4}}})", + "PLANnext"); + const trtmc::BundleReader adjacent_reader(adjacent.string()); + bool crossed = false; + try { + (void)adjacent_reader.read_section_range("first", 3, 2); + } catch (const std::runtime_error&) { + crossed = true; + } + check(crossed, "range cannot expose a valid neighboring section"); + for (const auto& bounds : std::vector>{ + {5, 0}, {3, 2}, {1, UINT64_MAX}, {UINT64_MAX, 1}}) { + bool rejected = false; + try { + (void)valid_reader.read_section_range("engine.plan", bounds.first, bounds.second); + } catch (const std::runtime_error&) { + rejected = true; + } + check(rejected, "range cannot cross section boundary or wrap around"); + } const auto original_directory = std::filesystem::current_path(); std::filesystem::current_path(directory); diff --git a/families/minimax_m3/README.md b/families/minimax_m3/README.md new file mode 100644 index 0000000000..4f9c838d4b --- /dev/null +++ b/families/minimax_m3/README.md @@ -0,0 +1,126 @@ +# MiniMax M3.1 Flash + +The `minimax_m3` family implements a bounded text continuation path for +`MiniMaxAI/MiniMax-M3.1-Flash`, revision +`ce7f4df87d2e05262f5775f373dac4772f134041`. It owns the checkpoint mapping, +TensorRT graphs, staged weight loading, NFC byte-level BPE tokenizer, greedy +generation, and validation. + +The initial Task is `text_continuation`, with raw UTF-8 text or token IDs as +the decoder prefix. Chat templating, images, video, DSpark, sampling, batching, +parallelism, streaming, and KV caching are not implemented by this path. + +## Build and run + +Use the repository development environment with TensorRT 11.1 or newer and +ICU development libraries (`libicu-dev` on Ubuntu), and the public TVM-FFI +BYOK bridge (`apache-tvm-ffi==0.1.12`, CMake `TRTMC_ENABLE_BYOK=ON`). Python +dependencies are provided by the repository's base environment. No +family-specific Python package installation is required. + +```bash +cmake -S . -B build -DTRTMC_ENABLE_BYOK=ON -DTRTMC_BUILD_TESTS=ON +cmake --build build --parallel 12 --target \ + trtmc trtmc_backend_trt trtmc_model_minimax_m3 \ + test_minimax_m3_sdk_c test_minimax_m3_sdk_cpp +export PYTHONPATH=core/builder:apps/benchmark:. +export LD_LIBRARY_PATH="$PWD/build${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}" +python -m tensorrt_model_connect build MiniMaxAI/MiniMax-M3.1-Flash \ + --revision ce7f4df87d2e05262f5775f373dac4772f134041 \ + --precision bf16 --max-sequence-length 128 --output minimax-m3.bundle + +build/trtmc run minimax-m3.bundle --runtime-root "$PWD/build" \ + --task text_continuation --prompt 'The capital of France is' \ + --set max_new_tokens=1 +``` + +The builder preserves BF16 activation boundaries and disables TF32. Projection +reductions use format-aware integer arithmetic when lossless encoding and range +checks establish that the sum fits; otherwise they use FP32 GEMM. The original +MXFP8 projection codes/scales and NVFP4 expert codes/scales remain unchanged. +This is not a new quantization or calibration pass. The native runtime expands +only projections needed for the current stage and passes their values through +the ordinary backend Tensor API. + +Family-owned TVM-FFI BYOK bindings evaluate Gemma normalization, the small router, +rotary products, causal attention reductions, and the weighted expert merge in +FP64 before the specified FP32/BF16 rounding boundaries. Attention scores and probabilities +retain FP32 boundaries; final vocabulary logits use FP32 GEMM. These precision +reductions limit summation noise before quantization. +The family DSO loads its adjacent `libtrtmc_minimax_m3_precision.so` through the +public BYOK bridge. Build that module before constructing the Python graphs; +the builder resolves native libraries through the standard dynamic loader. +Rotary tables are calculated in FP64 before FP32 storage; rotation products +are reduced before the FP32/BF16 boundaries. All model topology, kernels, and +orchestration remain inside this family. The runtime validates each bundle +against the required precision and input-scaling contract. + +NVFP4 activation rounding compares values against scaled FP4 midpoints in the +graph, including round-to-even ties. This avoids reciprocal-scale rounding +moving an exact midpoint to the wrong FP4 level. The regression sweep checks +all BF16 mantissas across 17 exponents, including subnormal FP8 scales. + +The first routed-expert GEMM uses the pinned per-token NVFP4 input recipe: +`outer = max(row_absmax, 1e-4) / 2688`, FP8 scales per 16 values, and FP4 +round-to-even codes. The outer multiplier is applied in the projection epilogue +before BF16 conversion. The second expert GEMM retains the published unit +static activation global scale. Dyadic regression cases cover multiple token +amplitudes, including inputs that a missing outer multiplier collapses to zero. +This follows the pre-dispatch contract in SGLang's pinned `sgl-deep-gemm==0.2.7`. + +All 60 decoder layers, 128 routed experts per MoE layer, the four-expert router, +shared experts, Gemma RMS norms, partial RoPE, and the checkpoint's clipped +SwiGLU-OAI activation are retained. For prefixes within one 128-token block, +the mandatory local sparse block covers all causal keys. All checkpoint index +value paths are disabled. The initial graph therefore implements that exact +bounded case without an indexer that cannot change the selected key set. +Requests beyond the configured total prefix/output capacity are rejected. + +Build capacity is between 2 and 128 tokens, default 128 when unspecified. +`max_new_tokens` is the only Task Config field and defaults to 2. Decoding +recomputes the full prefix for each output token. Native inference requires +neither Python nor the original checkpoint directory. The large bundle keeps +its packed source weights on disk and uses bounded section ranges to read the +current tensors; callers must keep the bundle available during inference. + +The checkpoint is approximately 250 GB. Building uses additional temporary +space for staged bundle sections and the final bundle. The staged execution +path bounds resident weight memory at the cost of host decoding and transfers. +It is an initial correctness path, not a latency or throughput qualification. + +## Validate + +The family oracle independently evaluates the complete 60-layer text model in +PyTorch with BF16 activation boundaries and explicit FP32 rounding points, using +the published checkpoint and equations from SGLang commit +`b2568f706b5caa2daf800355b015b042d8dbb535`. It preserves dynamic MXFP8/NVFP4 +activation rounding and original packed weight values. It does not import the +TensorRT graph or runtime implementation. Reductions use FP64 to establish the +value before FP32/BF16 rounding. Independent rational cancellation, BF16 tie, +weighted-sum, Decimal normalization, sigmoid, rotary, and attention fixtures +verify the rounding behavior. This oracle checks the declared precision profile; it does +not reproduce the accumulation order of an upstream fused serving kernel. + +The direct E2E compares six intermediate layer outputs and final full-vocabulary +logits (relative L2 below `1e-2`, cosine above `0.9999`), then requires an exact +greedy token and text match through the CLI and public C/C++ SDKs. The C++ +consumer repeats a request through one loaded Task. Both SDK consumers inspect +owned results after releasing the model wrapper. Native tokenizer IDs and +decoded text are compared against the checkpoint tokenizer on English, Arabic, +Chinese, normalization, whitespace, number, contraction, and special-token cases. + +```bash +export TRTMC_BINARY="$PWD/build/trtmc" +export TRTMC_RUNTIME_ROOT="$PWD/build" +export TRTMC_NATIVE_BUILD_DIR="$PWD/build" +export TRTMC_MINIMAX_M3_MODEL_DIR=/path/to/pinned/checkpoint +PYTHONPATH=core/builder:apps/benchmark:. python -m pytest \ + families/minimax_m3/tests --e2e-model minimax_m3 -q -s +ctest --test-dir build -R '^bundle_format_v1$' --output-on-failure +``` + +Set `TRTMC_MINIMAX_M3_BUNDLE` only to reuse an already-built bundle. Tests still +execute the independent reference and real native inference. The manifest pins +the checkpoint and declares the prompt and build profile. This small exact +case does not establish corpus-level accuracy, chat/vision/video support, +long-context behavior, performance, or other hardware/TensorRT cohorts. diff --git a/families/minimax_m3/__init__.py b/families/minimax_m3/__init__.py new file mode 100644 index 0000000000..ad40ca7ab5 --- /dev/null +++ b/families/minimax_m3/__init__.py @@ -0,0 +1,4 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""MiniMax M3 sparse mixture-of-experts text continuation.""" diff --git a/families/minimax_m3/graph.py b/families/minimax_m3/graph.py new file mode 100644 index 0000000000..6e09c4206d --- /dev/null +++ b/families/minimax_m3/graph.py @@ -0,0 +1,203 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Bounded short-context M3 graphs; TensorRT graphs with family-owned BYOK precision reductions.""" + +import numpy as np +import tensorrt as trt +from .precision import add_normalization, add_merge, add_precision_kernel, add_nv_input +from .projection import ProjectionMath + + +class Graph(ProjectionMath): + def __init__(self, network, profile, capacity): + self.net = network + self.profile = profile + self.capacity = capacity + self.storage = [] + + def round(self, x): + """Preserve BF16 activation boundaries with explicit FP32 arithmetic islands.""" + value = self.net.add_cast(x, trt.bfloat16).get_output(0) + return self.net.add_cast(value, trt.float32).get_output(0) + + def constant(self, value, dtype=np.float32): + value = np.ascontiguousarray(value, dtype=dtype) + self.storage.append(value) + return self.net.add_constant(value.shape, value).get_output(0) + + def input(self, name, shape, dtype=trt.float32): + tensor = self.net.add_input(name, dtype, shape) + if -1 in shape: + minimum = tuple(1 if x == -1 else x for x in shape) + optimum = tuple(min(16, self.capacity) if x == -1 else x for x in shape) + maximum = tuple(self.capacity if x == -1 else x for x in shape) + self.profile.set_shape(name, minimum, optimum, maximum) + return tensor + + def shape(self, *values): + values = [self.constant([x], np.int64) if isinstance(x, int) else x for x in values] + return self.net.add_concatenation(values).get_output(0) + + def length(self, x): + shape = self.net.add_shape(x).get_output(0) + return self.net.add_slice(shape, (0,), (1,), (1,)).get_output(0) + + def reshape(self, x, shape, transpose=None): + layer = self.net.add_shuffle(x) + if transpose is not None: + layer.first_transpose = trt.Permutation(transpose) + layer.reshape_dims = shape + return layer.get_output(0) + + def op(self, x, y, kind=trt.ElementWiseOperation.SUM): + return self.net.add_elementwise(x, y, kind).get_output(0) + + def product(self, x, y): + return self.op(x, y, trt.ElementWiseOperation.PROD) + + def scale(self, x, value): + return self.product(x, self.constant(np.full((1,) * len(x.shape), value))) + + def norm(self, x, weight, width): + return add_normalization(self.net, x, weight) + + def quantize(self, x, kind): + if kind == "mx": + quant = self.net.add_dynamic_quantize(x, 1, 32, trt.fp8, trt.DataType.E8M0) + scale = quant.get_output(1) + else: + one = self.constant([1.0]) + # Compare in the original domain: reciprocal-scale multiplication + # can move an exact FP4 midpoint across its round-to-even boundary. + # FP8 scales times these dyadic midpoints are exact in FP32. + width = x.shape[1] + grouped = self.reshape(x, (-1, width // 16, 16)) + absolute = self.net.add_unary(grouped, trt.UnaryOperation.ABS).get_output(0) + maximum = self.net.add_reduce( + absolute, trt.ReduceOperation.MAX, 1 << 2, True + ).get_output(0) + unscaled = self.op(maximum, self.constant([[[6.0]]]), trt.ElementWiseOperation.DIV) + encoded_scale = self.net.add_quantize(unscaled, one, trt.fp8).get_output(0) + scale = self.net.add_dequantize(encoded_scale, one, trt.float32).get_output(0) + levels = [0, 0.5, 1, 1.5, 2, 3, 4, 6] + rounded = self.constant([[[0.0]]]) + for index, midpoint in enumerate([0.25, 0.75, 1.25, 1.75, 2.5, 3.5, 5.0]): + boundary = self.scale(scale, midpoint) + above = self.op(absolute, boundary, trt.ElementWiseOperation.GREATER) + if index % 2: + equal = self.op(absolute, boundary, trt.ElementWiseOperation.EQUAL) + above = self.op(above, equal, trt.ElementWiseOperation.OR) + rounded = self.net.add_select( + above, self.constant([[[levels[index + 1]]]]), rounded + ).get_output(0) + decoded = self.product(rounded, scale) + negative = self.op(grouped, self.constant([[[0.0]]]), trt.ElementWiseOperation.LESS) + signed = self.net.add_select(negative, self.scale(decoded, -1), decoded).get_output(0) + return self.reshape(signed, (-1, width)) + dq = self.net.add_dequantize(quant.get_output(0), scale, trt.float32) + dq.axis = 1 + return dq.get_output(0) + + def mm(self, x, y, transpose=True): + return self.net.add_matrix_multiply( + x, + trt.MatrixOperation.NONE, + y, + trt.MatrixOperation.TRANSPOSE if transpose else trt.MatrixOperation.NONE, + ).get_output(0) + + def projection(self, x, name, n, k, kind="mx", output_scale=None): + return self.exact_projection(x, name, n, k, kind, output_scale) + + def feed_forward(self, x, intermediate, kind): + outer = None + if kind == "nv": + quant, broadcast_outer = add_nv_input(self.net, x) + outer = self.net.add_reduce( + broadcast_outer, trt.ReduceOperation.MAX, 1 << 1, True + ).get_output(0) + else: + quant = self.quantize(x, kind) + gate = self.projection(quant, "gate", intermediate, 6144, kind, outer) + up = self.projection(quant, "up", intermediate, 6144, kind, outer) + gate = self.op(gate, self.constant([[7.0]]), trt.ElementWiseOperation.MIN) + clip = self.net.add_activation(up, trt.ActivationType.CLIP) + clip.alpha, clip.beta = -7.0, 7.0 + up = self.op(clip.get_output(0), self.constant([[1.0]])) + sigmoid = self.net.add_activation( + self.scale(gate, 1.702), trt.ActivationType.SIGMOID + ).get_output(0) + hidden = self.round(self.product(self.product(gate, sigmoid), up)) + return self.projection(self.quantize(hidden, kind), "down", 6144, intermediate, kind) + + def rope(self, x, heads): + x = self.reshape(x, (-1, heads, 128)) + positions = np.arange(self.capacity, dtype=np.float64)[:, None] + inverse = 1.0 / np.power(1e7, np.arange(0, 64, 2, dtype=np.float64) / 64) + angles = positions * inverse + return add_precision_kernel( + self.net, "rope", [x, self.constant(np.cos(angles)), self.constant(np.sin(angles))] + ) + + def attention(self): + residual = self.input("hidden", (-1, 6144)) + norm = self.norm(residual, self.input("norm", (6144,)), 6144) + quant = self.quantize(norm, "mx") + query = self.projection(quant, "query", 8192, 6144) + key = self.projection(quant, "key", 512, 6144) + value = self.projection(quant, "value", 512, 6144) + query = self.norm(self.reshape(query, (-1, 64, 128)), self.input("qnorm", (128,)), 128) + key = self.norm(self.reshape(key, (-1, 4, 128)), self.input("knorm", (128,)), 128) + query = self.rope(self.reshape(query, (-1, 8192)), 64) + key = self.rope(self.reshape(key, (-1, 512)), 4) + output = add_precision_kernel( + self.net, "causal_attention", [query, key, self.reshape(value, (-1, 4, 128))] + ) + output = self.reshape(output, (-1, 8192)) + projected = self.projection(self.quantize(self.round(output), "mx"), "output", 6144, 8192) + return {"result": self.round(self.op(residual, projected))} + + def dense(self): + hidden = self.input("hidden", (-1, 6144)) + normalized = self.norm(hidden, self.input("norm", (6144,)), 6144) + return {"result": self.round(self.op(hidden, self.feed_forward(normalized, 12288, "mx")))} + + def route(self): + hidden = self.input("hidden", (-1, 6144)) + normalized = self.norm(hidden, self.input("norm", (6144,)), 6144) + router = self.input("router", (128, 6144)) + logits = self.mm(normalized, router) + scores = add_precision_kernel(self.net, "router_scores", [logits, normalized, router]) + biased = self.op(scores, self.reshape(self.input("bias", (128,)), (1, 128))) + topk = self.net.add_topk(biased, trt.TopKOperation.MAX, 4, 1 << 1) + ids = topk.get_output(1) + gather = self.net.add_gather_v2(scores, ids, trt.GatherMode.ELEMENT) + gather.axis = 1 + selected = gather.get_output(0) + weights = add_precision_kernel(self.net, "router_weights", [selected]) + base = self.feed_forward(normalized, 3072, "mx") + return {"normalized": normalized, "ids": ids, "weights": weights, "base": base} + + def expert(self): + return {"result": self.feed_forward(self.input("hidden", (-1, 6144)), 3072, "nv")} + + def merge(self): + base = self.input("base", (-1, 6144)) + residual = self.input("residual", (-1, 6144)) + values = self.input("values", (-1, 4, 6144)) + weights = self.input("weights", (-1, 4)) + return {"result": add_merge(self.net, residual, base, values, weights)} + + def head(self): + hidden = self.input("hidden", (-1, 6144)) + last = self.net.add_slice(hidden, (0, 0), (1, 6144), (1, 1)) + start = self.op(self.length(hidden), self.constant([-1], np.int64)) + last.set_input(1, self.shape(start, 0)) + normalized = self.norm(last.get_output(0), self.input("norm", (6144,)), 6144) + return {"logits": self.mm(normalized, self.input("weight", (200064, 6144)))} + + def embedding(self): + weight = self.input("weight", (200064, 6144)) + ids = self.input("ids", (-1,), trt.int32) + return {"result": self.net.add_gather(weight, ids, 0).get_output(0)} diff --git a/families/minimax_m3/model.py b/families/minimax_m3/model.py new file mode 100644 index 0000000000..bb01c8a510 --- /dev/null +++ b/families/minimax_m3/model.py @@ -0,0 +1,183 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Build staged, input-weight TensorRT engines and retain source quantized tensors.""" + +import json +from pathlib import Path +import tensorrt as trt +from safetensors import safe_open +import torch +from .graph import Graph + + +def _validate_config(config): + text = config.get("text_config", {}) + expected = dict( + hidden_size=6144, + num_hidden_layers=60, + num_attention_heads=64, + num_key_value_heads=4, + head_dim=128, + vocab_size=200064, + rms_norm_eps=1e-6, + use_gemma_norm=True, + use_qk_norm=True, + qk_norm_type="per_head", + rope_theta=10000000, + rotary_dim=64, + hidden_act="swigluoai", + dense_intermediate_size=12288, + intermediate_size=3072, + num_local_experts=128, + num_experts_per_tok=4, + n_shared_experts=1, + scoring_func="sigmoid", + use_routing_bias=True, + swiglu_alpha=1.702, + swiglu_limit=7.0, + routed_scaling_factor=2.0, + attention_output_gate=False, + moe_layer_freq=[0] * 3 + [1] * 57, + ) + if ( + config.get("model_type") != "minimax_m3_vl" + or config.get("architectures") != ["MiniMaxM3SparseForConditionalGeneration"] + or any(text.get(k) != v for k, v in expected.items()) + ): + raise ValueError("minimax_m3 requires the published M3.1 Flash text topology") + sparse = text.get("sparse_attention_config", {}) + if any( + sparse.get(k) != v + for k, v in dict( + use_sparse_attention=True, + sparse_block_size=128, + sparse_topk_blocks=16, + sparse_local_block=1, + sparse_attention_freq=[1] * 60, + sparse_disable_index_value=[1] * 60, + ).items() + ): + raise ValueError("minimax_m3 requires local-block coverage with index values disabled") + quant = config.get("quantization_config", {}) + if any( + quant.get(k) != v + for k, v in dict( + quant_method="mxfp8", + activation_scheme="dynamic", + weight_block_size=[1, 32], + group_size=16, + moe_quant_algo="NVFP4", + moe_quant_format="nvfp4-pack-quantized", + ).items() + ): + raise ValueError("minimax_m3 requires source MXFP8/NVFP4 quantization") + + +def _engine(kind, capacity, verbose): + logger = trt.Logger(trt.Logger.VERBOSE if verbose else trt.Logger.WARNING) + builder = trt.Builder(logger) + network = builder.create_network(1 << int(trt.NetworkDefinitionCreationFlag.STRONGLY_TYPED)) + settings = builder.create_builder_config() + settings.builder_optimization_level = 1 + settings.clear_flag(trt.BuilderFlag.TF32) + settings.max_aux_streams = 0 + settings.set_memory_pool_limit(trt.MemoryPoolType.WORKSPACE, 8 << 30) + profile = builder.create_optimization_profile() + graph = Graph(network, profile, capacity) + for name, tensor in getattr(graph, kind)().items(): + tensor.name = name + network.mark_output(tensor) + settings.add_optimization_profile(profile) + plan = builder.build_serialized_network(network, settings) + if plan is None: + raise RuntimeError(f"minimax_m3 {kind} engine build failed") + return bytes(plan) + + +def build(request, writer): + if request.task != "text_continuation" or request.backend != "trt": + raise ValueError("minimax_m3 supports TensorRT text_continuation only") + if request.precision != "bf16": + raise ValueError("minimax_m3 requires precision=bf16 with source quantization preserved") + if ( + request.max_batch_size != 1 + or request.tensor_parallel_size != 1 + or request.context_parallel_size != 1 + ): + raise ValueError("minimax_m3 supports one request on one GPU") + if request.dynamic_kv_cache: + raise NotImplementedError("minimax_m3 does not support dynamic_kv_cache") + if ( + request.fp32_layers + or request.mtp_seq_len is not None + or request.quantization not in (None, "none") + ): + raise ValueError( + "minimax_m3 does not support KV, mixed-precision, MTP or requantization options" + ) + if any( + x is not None for x in [request.image_height, request.image_width, request.video_num_frames] + ): + raise ValueError("minimax_m3 initial path has text input only") + capacity = request.max_sequence_length or 128 + if not 2 <= capacity <= 128: + raise ValueError("minimax_m3 total prefix/output capacity must be between 2 and 128") + directory = Path(request.model_dir) + config = json.loads((directory / "config.json").read_text()) + _validate_config(config) + writer.set_header(family="minimax_m3", task=request.task, backend=request.backend) + for kind in ["embedding", "attention", "dense", "route", "expert", "merge", "head"]: + writer.add_bytes(kind + ".plan", _engine(kind, capacity, request.verbose)) + writer.add_bytes("tokenizer.json", (directory / "tokenizer.json").read_bytes()) + index = json.loads((directory / "model.safetensors.index.json").read_text())["weight_map"] + selected = { + name: shard + for name, shard in index.items() + if name.startswith("language_model.") and ".self_attn.index_" not in name + } + inventory = {} + for shard_index, shard in enumerate(sorted(set(selected.values()))): + with ( + safe_open(str(directory / shard), framework="pt", device="cpu") as reader, + writer.open_section("s" + str(shard_index)) as stream, + ): + for name in sorted(n for n, s in selected.items() if s == shard): + value = reader.get_tensor(name) + dtype = str(value.dtype).removeprefix("torch.") + if dtype not in {"float32", "bfloat16", "float8_e4m3fn", "uint8"}: + raise ValueError(f"minimax_m3 unsupported checkpoint tensor {name}: {dtype}") + if name.endswith(".input_global_scale") and value.item() != 1.0: + raise ValueError( + "minimax_m3 requires the published unit NVFP4 input global scale" + ) + entry = dict(shape=list(value.shape), dtype=dtype) + inventory[name] = entry + if dtype in {"float32", "bfloat16"} and value.numel() <= 8192: + entry["values"] = value.float().reshape(-1).tolist() + continue + entry.update( + section="s" + str(shard_index), + offset=stream.tell(), + bytes=value.numel() * value.element_size(), + ) + # Keep the original packed source. The native family expands only + # the current projection and feeds it through the backend contract. + stream.write(value.reshape(-1).view(torch.uint8).numpy().data) + writer.add_json("weights.json", inventory) + generation = json.loads((directory / "generation_config.json").read_text()) + eos = generation["eos_token_id"] + writer.add_json( + "runtime.json", + dict( + precision=request.precision, + normalization="fp64_byok", + nvfp4_input_scale="per_token", + rotary_precision="fp64", + max_sequence_length=capacity, + num_layers=60, + hidden_size=6144, + vocab_size=200064, + eos_token_ids=eos if isinstance(eos, list) else [eos], + ), + ) diff --git a/families/minimax_m3/precision.py b/families/minimax_m3/precision.py new file mode 100644 index 0000000000..eeccfad831 --- /dev/null +++ b/families/minimax_m3/precision.py @@ -0,0 +1,89 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +"""Bind the family's reduction precision islands through the public BYOK API.""" + +import ctypes +from functools import lru_cache +from pathlib import Path + +from tensorrt_model_connect.byok import add_kernel + + +@lru_cache(maxsize=None) +def _load(root=None): + if root is None: + # Resolve through the standard native loader, exactly as other native + # dependencies. Model policy does not read environment/profile switches. + library = ctypes.CDLL("libtrtmc_byok_tvm_ffi.so", mode=ctypes.RTLD_GLOBAL) + + class Location(ctypes.Structure): + _fields_ = [ + ("filename", ctypes.c_char_p), + ("base", ctypes.c_void_p), + ("symbol", ctypes.c_char_p), + ("address", ctypes.c_void_p), + ] + + location = Location() + dladdr = ctypes.CDLL(None).dladdr + dladdr.argtypes = [ctypes.c_void_p, ctypes.POINTER(Location)] + dladdr.restype = ctypes.c_int + if not dladdr( + ctypes.cast(library.trtmc_load_byok_kernel, ctypes.c_void_p), ctypes.byref(location) + ): + raise RuntimeError("Cannot locate the MiniMax native BYOK bridge") + root = Path(location.filename.decode()).resolve().parent + bridge = root / "libtrtmc_byok_tvm_ffi.so" + kernel = root / "libtrtmc_minimax_m3_precision.so" + for path in (bridge, kernel): + if not path.is_file(): + raise FileNotFoundError(f"minimax_m3 native BYOK dependency is missing: {path}") + library = ctypes.CDLL(str(bridge), mode=ctypes.RTLD_GLOBAL) + library.trtmc_load_byok_kernel.argtypes = [ctypes.c_char_p] * 3 + library.trtmc_load_byok_kernel.restype = ctypes.c_char_p + for exported, name in ( + ("run", "gemma_norm"), + ("merge", "moe_merge"), + ("scores", "router_scores"), + ("attention", "causal_attention"), + ("nv_input", "nv_input"), + ("rope", "rope"), + ("routing_weights", "router_weights"), + ): + error = library.trtmc_load_byok_kernel( + str(kernel).encode(), exported.encode(), ("minimax_m3." + name).encode() + ) + if error: + raise RuntimeError(error.decode()) + return bridge, library + + +def add_precision_kernel(network, name, inputs): + bridge, _owner = _load() + (result,) = add_kernel( + network, + plugin_library=bridge, + kernel_name="minimax_m3." + name, + inputs=inputs, + output_specs=[{"dims": "same_as_input_0", "dtype": "float32"}], + ) + return result + + +def add_normalization(network, hidden, weight): + return add_precision_kernel(network, "gemma_norm", [hidden, weight]) + + +def add_merge(network, residual, shared, values, weights): + return add_precision_kernel(network, "moe_merge", [residual, shared, values, weights]) + + +def add_nv_input(network, hidden): + bridge, _owner = _load() + return add_kernel( + network, + plugin_library=bridge, + kernel_name="minimax_m3.nv_input", + inputs=[hidden], + output_specs=[{"dims": "same_as_input_0", "dtype": "float32"}] * 2, + ) diff --git a/families/minimax_m3/projection.py b/families/minimax_m3/projection.py new file mode 100644 index 0000000000..00223bcba2 --- /dev/null +++ b/families/minimax_m3/projection.py @@ -0,0 +1,326 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +"""Format-aware exact projection reductions with an FP32 fallback. + +Integer reductions retain the quantized operand values and make the final +FP32-to-BF16 rounding independent of floating-point GEMM summation order. +Bounds and lossless encoding checks select ordinary FP32 multiplication when +the exact representation cannot safely cover a wider input range. +""" + +import math +import numpy as np +import tensorrt as trt + + +class ProjectionMath: + def exact_projection(self, x, name, n, k, kind, output_scale=None): + return ( + self.nv_projection(x, name, n, k, output_scale) + if kind == "nv" + else self.mx_projection(x, name, n, k) + ) + + def integer(self, value): + return self.constant(value, np.int64) + + def divide(self, a, b): + return self.op(a, b, trt.ElementWiseOperation.FLOOR_DIV) + + def cast(self, value, dtype): + return self.net.add_cast(value, dtype).get_output(0) + + def choose(self, condition, yes, no): + return self.net.add_select(condition, yes, no).get_output(0) + + def either(self, a, b): + return self.op(a, b, trt.ElementWiseOperation.OR) + + def both(self, a, b): + return self.op(a, b, trt.ElementWiseOperation.AND) + + def floor_power(self, value): + # Correct a logarithm estimate with exact integer comparisons, including + # integer values rounded up to a power of two by their FP32 conversion. + estimate = self.net.add_unary( + self.scale( + self.net.add_unary( + self.cast(value, trt.float32), trt.UnaryOperation.LOG + ).get_output(0), + 1 / math.log(2), + ), + trt.UnaryOperation.FLOOR, + ).get_output(0) + power = self.op(self.constant([[2.0]]), estimate, trt.ElementWiseOperation.POW) + power = self.op(power, self.constant([[2.0**62]]), trt.ElementWiseOperation.MIN) + for _ in range(2): + below = self.op(value, self.cast(power, trt.int64), trt.ElementWiseOperation.LESS) + power = self.choose(below, self.scale(power, 0.5), power) + divisor = self.op( + self.cast(power, trt.int64), self.integer([[1]]), trt.ElementWiseOperation.MAX + ) + above = self.op( + self.divide(value, divisor), self.integer([[1]]), trt.ElementWiseOperation.GREATER + ) + power = self.choose(above, self.scale(power, 2), power) + return power + + def rounded_pair(self, high, low, low_bits=32): + # Exact signed value is high + low / 2**low_bits, with nonnegative low. + zero = self.integer([[0]]) + base = self.integer([[1 << low_bits]]) + negative = self.op(high, zero, trt.ElementWiseOperation.LESS) + nonzero = self.op(low, zero, trt.ElementWiseOperation.GREATER) + correction = self.cast(nonzero, trt.int64) + absolute_high = self.choose( + negative, + self.op( + self.product(high, self.integer([[-1]])), correction, trt.ElementWiseOperation.SUB + ), + high, + ) + absolute_low = self.choose( + self.both(negative, nonzero), self.op(base, low, trt.ElementWiseOperation.SUB), low + ) + safe_high = self.op(absolute_high, self.integer([[1]]), trt.ElementWiseOperation.MAX) + power = self.floor_power(safe_high) + divisor = self.op( + self.cast(self.scale(power, 2.0**-23), trt.int64), + self.integer([[2]]), + trt.ElementWiseOperation.MAX, + ) + quotient = self.divide(absolute_high, divisor) + remainder = self.op( + absolute_high, self.product(quotient, divisor), trt.ElementWiseOperation.SUB + ) + half = self.divide(divisor, self.integer([[2]])) + odd = self.op( + quotient, + self.product(self.divide(quotient, self.integer([[2]])), self.integer([[2]])), + trt.ElementWiseOperation.SUB, + ) + sticky = self.either( + self.op(absolute_low, zero, trt.ElementWiseOperation.GREATER), + self.op(odd, zero, trt.ElementWiseOperation.GREATER), + ) + increment = self.either( + self.op(remainder, half, trt.ElementWiseOperation.GREATER), + self.both(self.op(remainder, half, trt.ElementWiseOperation.EQUAL), sticky), + ) + large = self.product( + self.cast(self.op(quotient, self.cast(increment, trt.int64)), trt.float32), + self.cast(divisor, trt.float32), + ) + small_high = self.op( + absolute_high, self.integer([[(1 << 24) - 1]]), trt.ElementWiseOperation.MIN + ) + small = self.scale( + self.cast(self.op(self.product(small_high, base), absolute_low), trt.float32), + 2.0**-low_bits, + ) + magnitude = self.choose( + self.op(absolute_high, self.integer([[1 << 24]]), trt.ElementWiseOperation.LESS), + small, + large, + ) + return self.choose(negative, self.scale(magnitude, -1), magnitude) + + def encoding(self, value, bits, low_bits=16): + maximum = self.net.add_reduce( + self.net.add_unary(value, trt.UnaryOperation.ABS).get_output(0), + trt.ReduceOperation.MAX, + 1 << 1, + True, + ).get_output(0) + maximum = self.op(maximum, self.constant([[2.0**-60]]), trt.ElementWiseOperation.MAX) + exponent = self.net.add_unary( + self.scale( + self.net.add_unary(maximum, trt.UnaryOperation.LOG).get_output(0), 1 / math.log(2) + ), + trt.UnaryOperation.FLOOR, + ).get_output(0) + power = self.op(self.constant([[2.0]]), exponent, trt.ElementWiseOperation.POW) + for _ in range(2): + power = self.choose( + self.op(maximum, power, trt.ElementWiseOperation.GREATER), + self.scale(power, 2), + power, + ) + power = self.choose( + self.either( + self.op(maximum, self.scale(power, 0.5), trt.ElementWiseOperation.LESS), + self.op(maximum, self.scale(power, 0.5), trt.ElementWiseOperation.EQUAL), + ), + self.scale(power, 0.5), + power, + ) + scale = self.scale(power, 2.0**-bits) + high = self.cast(self.op(value, scale, trt.ElementWiseOperation.DIV), trt.int64) + residual = self.op( + value, self.product(self.cast(high, trt.float32), scale), trt.ElementWiseOperation.SUB + ) + low_scale = self.scale(scale, 2.0**-low_bits) + low = self.cast(self.op(residual, low_scale, trt.ElementWiseOperation.DIV), trt.int64) + exact = self.op( + residual, + self.product(self.cast(low, trt.float32), low_scale), + trt.ElementWiseOperation.EQUAL, + ) + exact = self.net.add_reduce( + self.cast(exact, trt.int32), trt.ReduceOperation.MIN, 1 << 1, True + ).get_output(0) + return ( + high, + low, + scale, + self.op(exact, self.constant([[1]], np.int32), trt.ElementWiseOperation.EQUAL), + ) + + def check(self, valid): + if not hasattr(self, "precision_checks"): + self.precision_checks = [] + self.precision_checks.append( + self.net.add_reduce( + self.cast(valid, trt.int32), trt.ReduceOperation.MIN, 3, False + ).get_output(0) + ) + + def finish(self, valid, exact, x, w, output_scale=None): + selected = self.choose(valid, exact, self.mm(x, w)) + if output_scale is not None: + selected = self.product(selected, output_scale) + return self.round(selected) + + def mx_codes(self, value, rows, k): + grouped = self.reshape(value, (rows, k // 32, 32)) + absolute = self.net.add_unary(grouped, trt.UnaryOperation.ABS).get_output(0) + maximum = self.net.add_reduce(absolute, trt.ReduceOperation.MAX, 1 << 2, True).get_output(0) + maximum = self.op(maximum, self.constant([[[2.0**-60]]]), trt.ElementWiseOperation.MAX) + normalized = self.op(maximum, self.constant([[[448.0]]]), trt.ElementWiseOperation.DIV) + exponent = self.net.add_unary( + self.scale( + self.net.add_unary(normalized, trt.UnaryOperation.LOG).get_output(0), 1 / np.log(2) + ), + trt.UnaryOperation.FLOOR, + ).get_output(0) + power = self.op(self.constant([[[2.0]]]), exponent, trt.ElementWiseOperation.POW) + for _ in range(2): + power = self.choose( + self.op(normalized, power, trt.ElementWiseOperation.GREATER), + self.scale(power, 2), + power, + ) + half = self.scale(power, 0.5) + power = self.choose( + self.either( + self.op(normalized, half, trt.ElementWiseOperation.LESS), + self.op(normalized, half, trt.ElementWiseOperation.EQUAL), + ), + half, + power, + ) + quantum = self.scale(power, 2.0**-9) + codes = self.cast(self.op(grouped, quantum, trt.ElementWiseOperation.DIV), trt.int64) + valid = self.op( + grouped, + self.product(self.cast(codes, trt.float32), quantum), + trt.ElementWiseOperation.EQUAL, + ) + valid = self.net.add_reduce( + self.cast(valid, trt.int32), trt.ReduceOperation.MIN, 1 << 2, False + ).get_output(0) + return ( + codes, + self.reshape(quantum, (rows, k // 32)), + self.op(valid, self.constant([[1]], np.int32), trt.ElementWiseOperation.EQUAL), + ) + + def mx_projection(self, x, name, n, k): + w = self.input(name, (n, k)) + xi, xs, xv = self.mx_codes(x, -1, k) + wi, ws, wv = self.mx_codes(w, n, k) + # Source MXFP8 codes have magnitude <= 448 * 512. For k <= 12288, + # summing blocks of 32 with scale ratios <= 8192 stays below 2**63: + # 12288 * (448 * 512)**2 * 8192 < 2**63. + product = self.product( + self.reshape(xi, (-1, 1, k // 32, 32)), self.reshape(wi, (1, n, k // 32, 32)) + ) + sums = self.net.add_reduce(product, trt.ReduceOperation.SUM, 1 << 3, False).get_output(0) + scale = self.product(self.reshape(xs, (-1, 1, k // 32)), self.reshape(ws, (1, n, k // 32))) + zero = self.constant([[[0]]], np.int64) + nonzero = self.either( + self.op(sums, zero, trt.ElementWiseOperation.GREATER), + self.op(sums, zero, trt.ElementWiseOperation.LESS), + ) + active = self.net.add_reduce( + self.cast(nonzero, trt.int32), trt.ReduceOperation.MAX, 1 << 2, True + ).get_output(0) + active = self.op(active, self.constant([[[0]]], np.int32), trt.ElementWiseOperation.GREATER) + chosen = self.choose(nonzero, scale, self.constant([[[2.0**120]]])) + quantum = self.net.add_reduce(chosen, trt.ReduceOperation.MIN, 1 << 2, True).get_output(0) + quantum = self.choose(active, quantum, self.constant([[[1.0]]])) + quantum = self.op(quantum, self.constant([[[2.0**-120]]]), trt.ElementWiseOperation.MAX) + ratios = self.op(scale, quantum, trt.ElementWiseOperation.DIV) + bound = self.op(ratios, self.constant([[[8192.0]]]), trt.ElementWiseOperation.GREATER) + bad_scale = self.either( + self.op(scale, self.constant([[[2.0**-120]]]), trt.ElementWiseOperation.LESS), + self.op(scale, self.constant([[[2.0**120]]]), trt.ElementWiseOperation.GREATER), + ) + unsafe = self.both(nonzero, self.either(bound, bad_scale)) + unsafe = self.net.add_reduce( + self.cast(unsafe, trt.int32), trt.ReduceOperation.MAX, 1 << 2, False + ).get_output(0) + ratios = self.op(ratios, self.constant([[[8192.0]]]), trt.ElementWiseOperation.MIN) + integers = self.cast(ratios, trt.int64) + total = self.net.add_reduce( + self.product(sums, integers), trt.ReduceOperation.SUM, 1 << 2, False + ).get_output(0) + exact = self.product(self.cast(total, trt.float32), self.reshape(quantum, (-1, n))) + pair = self.both(self.reshape(xv, (-1, 1, k // 32)), self.reshape(wv, (1, n, k // 32))) + pair = self.net.add_reduce( + self.cast(pair, trt.int32), trt.ReduceOperation.MIN, 1 << 2, False + ).get_output(0) + valid = self.both( + self.op(pair, self.constant([[1]], np.int32), trt.ElementWiseOperation.EQUAL), + self.op(unsafe, self.constant([[0]], np.int32), trt.ElementWiseOperation.EQUAL), + ) + self.check(valid) + return self.finish(valid, exact, x, w) + + def nv_projection(self, x, name, n, k, output_scale=None): + w = self.input(name, (n, k)) + xi = self.cast(self.scale(x, 1024), trt.int64) + xv = self.op( + x, self.scale(self.cast(xi, trt.float32), 2.0**-10), trt.ElementWiseOperation.EQUAL + ) + in_range = self.op( + self.net.add_unary(xi, trt.UnaryOperation.ABS).get_output(0), + self.integer([[1 << 22]]), + trt.ElementWiseOperation.LESS, + ) + xv = self.both(xv, in_range) + xv = self.net.add_reduce( + self.cast(xv, trt.int32), trt.ReduceOperation.MIN, 1 << 1, True + ).get_output(0) + # xi < 2**22, |wh| <= 2**28, k <= 6144: each integer dot fits + # signed INT64. The smaller 18-bit residual dot also fits. + wh, wl, ws, wv = self.encoding(w, 28, 18) + + def dot(weight): + values = self.product(self.reshape(xi, (-1, 1, k)), self.reshape(weight, (1, n, k))) + return self.net.add_reduce(values, trt.ReduceOperation.SUM, 1 << 2, False).get_output(0) + + high, low = dot(wh), dot(wl) + base = self.integer([[1 << 18]]) + carry = self.divide(low, base) + low = self.op(low, self.product(carry, base), trt.ElementWiseOperation.SUB) + high = self.op(high, carry) + exact = self.product( + self.scale(self.rounded_pair(high, low, 18), 2.0**-10), self.reshape(ws, (1, n)) + ) + valid = self.both( + self.op(xv, self.constant([[1]], np.int32), trt.ElementWiseOperation.EQUAL), + self.reshape(wv, (1, n)), + ) + self.check(valid) + return self.finish(valid, exact, x, w, output_scale) diff --git a/families/minimax_m3/runtime/CMakeLists.txt b/families/minimax_m3/runtime/CMakeLists.txt new file mode 100644 index 0000000000..674dd1aa04 --- /dev/null +++ b/families/minimax_m3/runtime/CMakeLists.txt @@ -0,0 +1,43 @@ +# 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_minimax_m3 SHARED bpe_tokenizer.cpp weights.cpp pipeline.cpp plugin.cpp) +target_include_directories(trtmc_model_minimax_m3 PRIVATE ${PROJECT_SOURCE_DIR} ${PROJECT_SOURCE_DIR}/core/runtime/include) +target_include_directories(trtmc_model_minimax_m3 SYSTEM PRIVATE ${TRTMC_CUDA_INCLUDE_DIR}) +target_link_libraries(trtmc_model_minimax_m3 PRIVATE trtmc_core nlohmann_json::nlohmann_json ${TRTMC_CUDART_LIBRARY} ICU::uc ICU::i18n) +target_compile_options(trtmc_model_minimax_m3 PRIVATE -Wall -Wextra -Wpedantic) +set_target_properties(trtmc_model_minimax_m3 PROPERTIES LIBRARY_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}" BUILD_RPATH "\$ORIGIN" INSTALL_RPATH "\$ORIGIN") +install(TARGETS trtmc_model_minimax_m3 LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR}) +if(TARGET trtmc_byok_tvm_ffi) + add_library(trtmc_minimax_m3_precision SHARED precision.cu) + target_include_directories(trtmc_minimax_m3_precision SYSTEM PRIVATE ${TRTMC_TVM_FFI_INCLUDE_DIR}) + target_link_libraries(trtmc_minimax_m3_precision PRIVATE CUDA::cudart ${TRTMC_TVM_FFI_LIBRARY}) + set_target_properties(trtmc_minimax_m3_precision PROPERTIES + CUDA_STANDARD 17 CUDA_STANDARD_REQUIRED ON + LIBRARY_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}" + BUILD_RPATH "\$ORIGIN;${TRTMC_TVM_FFI_LIBRARY_DIR}" + INSTALL_RPATH "\$ORIGIN;${TRTMC_TVM_FFI_LIBRARY_DIR}") + target_compile_definitions(trtmc_model_minimax_m3 PRIVATE TRTMC_MINIMAX_M3_HAS_PRECISION=1) + target_link_libraries(trtmc_model_minimax_m3 PRIVATE trtmc_byok_tvm_ffi ${CMAKE_DL_LIBS}) + add_dependencies(trtmc_model_minimax_m3 trtmc_minimax_m3_precision) + install(TARGETS trtmc_minimax_m3_precision LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR}) +endif() +if(TRTMC_BUILD_TESTS) + add_executable(test_minimax_m3_tokenizer ${PROJECT_SOURCE_DIR}/families/minimax_m3/tests/tokenizer_consumer.cpp) + target_include_directories(test_minimax_m3_tokenizer PRIVATE ${PROJECT_SOURCE_DIR}) + target_link_libraries(test_minimax_m3_tokenizer PRIVATE trtmc_model_minimax_m3 nlohmann_json::nlohmann_json) + set_target_properties(test_minimax_m3_tokenizer PROPERTIES RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}") + add_executable(test_minimax_m3_logits ${PROJECT_SOURCE_DIR}/families/minimax_m3/tests/logits_consumer.cpp) + target_include_directories(test_minimax_m3_logits PRIVATE ${PROJECT_SOURCE_DIR} ${PROJECT_SOURCE_DIR}/core/runtime/include) + target_include_directories(test_minimax_m3_logits SYSTEM PRIVATE ${TRTMC_CUDA_INCLUDE_DIR}) + target_link_libraries(test_minimax_m3_logits PRIVATE trtmc_model_minimax_m3 trtmc_core ${CMAKE_DL_LIBS}) + set_target_properties(test_minimax_m3_logits PROPERTIES RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}") + foreach(_language IN ITEMS c cpp) + add_executable(test_minimax_m3_sdk_${_language} ${PROJECT_SOURCE_DIR}/families/minimax_m3/tests/sdk_consumer.${_language}) + target_link_libraries(test_minimax_m3_sdk_${_language} PRIVATE trtmc_c) + target_compile_options(test_minimax_m3_sdk_${_language} PRIVATE -Wall -Wextra -Wpedantic -Werror) + add_dependencies(test_minimax_m3_sdk_${_language} test_minimax_m3_logits) + add_dependencies(test_minimax_m3_sdk_${_language} test_minimax_m3_tokenizer) + set_target_properties(test_minimax_m3_sdk_${_language} PROPERTIES RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}") + endforeach() +endif() diff --git a/families/minimax_m3/runtime/bpe_tokenizer.cpp b/families/minimax_m3/runtime/bpe_tokenizer.cpp new file mode 100644 index 0000000000..361e82b8a1 --- /dev/null +++ b/families/minimax_m3/runtime/bpe_tokenizer.cpp @@ -0,0 +1,217 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + */ +#include "families/minimax_m3/runtime/tokenizer.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace trtmc { +namespace { +std::string utf8(UChar32 point) { + char buffer[4]; + int32_t size = 0; + U8_APPEND_UNSAFE(buffer, size, point); + return {buffer, static_cast(size)}; +} +class Tokenizer final : public ITokenizer { + public: + explicit Tokenizer(const nlohmann::json& config) { + if (config.at("normalizer").at("type") != "NFC" || config.at("model").at("type") != "BPE") + throw std::runtime_error( + "minimax_m3 requires its checkpoint NFC byte-level BPE tokenizer"); + std::array direct{}; + for (int i = 33; i <= 126; ++i) + direct[i] = true; + for (int i = 161; i <= 172; ++i) + direct[i] = true; + for (int i = 174; i <= 255; ++i) + direct[i] = true; + int extra = 256; + for (int i = 0; i < 256; ++i) { + const auto point = direct[i] ? i : extra++; + bytes_[i] = utf8(point); + inverse_[point] = i; + } + for (const auto& item : config.at("model").at("vocab").items()) { + const int id = item.value(); + vocabulary_[item.key()] = id; + pieces_[id] = item.key(); + } + int rank = 0; + for (const auto& merge : config.at("model").at("merges")) { + std::string left, right; + if (merge.is_array()) { + left = merge.at(0); + right = merge.at(1); + } else { + const auto text = merge.get(); + const auto at = text.find(' '); + if (at == std::string::npos) + throw std::runtime_error("invalid MiniMax BPE merge"); + left = text.substr(0, at); + right = text.substr(at + 1); + } + ranks_[left + std::string(1, '\0') + right] = rank++; + } + for (const auto& token : config.at("added_tokens")) { + if (token.at("single_word").get() || token.at("lstrip").get() || + token.at("rstrip").get() || token.at("normalized").get()) + throw std::runtime_error("unsupported MiniMax added-token matching contract"); + const auto text = token.at("content").get(); + const int id = token.at("id"); + added_.emplace_back(text, id); + pieces_[id] = text; + vocabulary_[text] = id; + if (token.at("special").get()) + special_.insert(id); + } + const auto& pre = config.at("pre_tokenizer").at("pretokenizers"); + if (pre.size() != 2 || pre.at(0).at("type") != "Split" || + pre.at(0).at("behavior") != "Removed" || !pre.at(0).at("invert").get() || + pre.at(1).at("type") != "ByteLevel" || pre.at(1).at("add_prefix_space").get() || + pre.at(1).at("use_regex").get()) + throw std::runtime_error("unsupported MiniMax pre-tokenizer contract"); + std::string pattern = pre.at(0).at("pattern").at("Regex"); + // The published converter serializes this O200K pattern with doubled + // escapes. tokenizers treats these as the underlying regex escapes. + if (pattern.find("\\\\p") != std::string::npos) { + std::string decoded; + for (std::size_t i = 0; i < pattern.size(); ++i) { + if (pattern[i] == '\\' && i + 1 < pattern.size() && pattern[i + 1] == '\\') + ++i; + decoded.push_back(pattern[i]); + } + pattern = std::move(decoded); + } + UErrorCode status = U_ZERO_ERROR; + pattern_.reset( + icu::RegexPattern::compile(icu::UnicodeString::fromUTF8(pattern), 0, status)); + if (U_FAILURE(status) || !pattern_) + throw std::runtime_error("invalid MiniMax tokenizer regex"); + } + std::vector encode(const std::string& text) const override { + if (text.size() > INT_MAX) + throw std::invalid_argument("MiniMax tokenizer input is too large"); + std::vector result; + std::size_t position = 0; + while (position < text.size()) { + std::size_t found = std::string::npos; + const std::pair* token = nullptr; + for (const auto& item : added_) { + auto at = text.find(item.first, position); + if (at != std::string::npos && + (at < found || + (at == found && token && item.first.size() > token->first.size()))) { + found = at; + token = &item; + } + } + const auto end = found == std::string::npos ? text.size() : found; + if (end > position) + encode_plain(text.substr(position, end - position), result); + if (!token) + break; + result.push_back(token->second); + position = found + token->first.size(); + } + return result; + } + std::string decode(const std::vector& ids) const override { + std::string result; + for (auto id : ids) { + if (special_.count(id)) + continue; + const auto& piece = pieces_.at(id); + const auto* data = reinterpret_cast(piece.data()); + int32_t at = 0; + while (at < static_cast(piece.size())) { + UChar32 point; + U8_NEXT(data, at, static_cast(piece.size()), point); + const auto found = inverse_.find(point); + if (found == inverse_.end()) + throw std::runtime_error("invalid MiniMax byte-level vocabulary piece"); + result.push_back(static_cast(found->second)); + } + } + // Byte-level tokens can end partway through a UTF-8 character. Match + // the checkpoint decoder's replacement of malformed byte sequences. + std::string decoded; + icu::UnicodeString::fromUTF8(result).toUTF8String(decoded); + return decoded; + } + int32_t id_for_token(std::string_view token) const override { + auto it = vocabulary_.find(std::string(token)); + return it == vocabulary_.end() ? -1 : it->second; + } + std::string token_for_id(int32_t id) const override { return pieces_.at(id); } + + private: + void encode_plain(const std::string& text, std::vector& result) const { + UErrorCode status = U_ZERO_ERROR; + const auto* nfc = icu::Normalizer2::getNFCInstance(status); + icu::UnicodeString normalized; + nfc->normalize(icu::UnicodeString::fromUTF8(text), normalized, status); + std::unique_ptr matcher(pattern_->matcher(normalized, status)); + if (U_FAILURE(status) || !matcher) + throw std::runtime_error("MiniMax tokenizer normalization failed"); + int32_t consumed = 0; + while (matcher->find(status)) { + const auto start = matcher->start(status), end = matcher->end(status); + if (start != consumed) + throw std::runtime_error("MiniMax tokenizer regex did not cover input"); + consumed = end; + std::string bytes; + normalized.tempSubStringBetween(start, end).toUTF8String(bytes); + std::vector parts; + for (unsigned char byte : bytes) + parts.push_back(bytes_[byte]); + while (parts.size() > 1) { + std::size_t selected = parts.size(); + int best = std::numeric_limits::max(); + for (std::size_t i = 0; i + 1 < parts.size(); ++i) { + auto it = ranks_.find(parts[i] + std::string(1, '\0') + parts[i + 1]); + if (it != ranks_.end() && it->second < best) { + best = it->second; + selected = i; + } + } + if (selected == parts.size()) + break; + parts[selected] += parts[selected + 1]; + parts.erase(parts.begin() + selected + 1); + } + for (const auto& part : parts) + result.push_back(vocabulary_.at(part)); + } + if (U_FAILURE(status) || consumed != normalized.length()) + throw std::runtime_error("MiniMax tokenizer regex failed"); + } + std::array bytes_; + std::unordered_map inverse_; + std::unordered_map vocabulary_, ranks_; + std::unordered_map pieces_; + std::unordered_set special_; + std::vector> added_; + std::unique_ptr pattern_; +}; +} // namespace +std::unique_ptr CreateBpeTokenizer(const char* data, std::size_t size, + bool add_special_tokens) { + if (add_special_tokens) + throw std::invalid_argument( + "MiniMax initial path uses raw continuation without an implicit prompt"); + return std::make_unique(nlohmann::json::parse(data, data + size)); +} +} // namespace trtmc diff --git a/families/minimax_m3/runtime/pipeline.cpp b/families/minimax_m3/runtime/pipeline.cpp new file mode 100644 index 0000000000..754074d5ae --- /dev/null +++ b/families/minimax_m3/runtime/pipeline.cpp @@ -0,0 +1,263 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + */ +#include "families/minimax_m3/runtime/pipeline.h" + +#include +#include +#include +#include +#include +#if TRTMC_MINIMAX_M3_HAS_PRECISION +#include "trtmc/byok.h" + +#include +#include +#include +#endif + +namespace trtmc::minimax_m3 { +namespace { +void load_precision() { +#if TRTMC_MINIMAX_M3_HAS_PRECISION + static std::once_flag once; + std::call_once(once, [] { + static const int location_anchor = 0; + Dl_info location{}; + if (!dladdr(&location_anchor, &location) || !location.dli_fname) + throw std::runtime_error("minimax_m3 cannot locate its precision module"); + const auto library = std::filesystem::canonical(location.dli_fname).parent_path() / + "libtrtmc_minimax_m3_precision.so"; + trtmc::load_byok_kernel(library.string(), "run", "minimax_m3.gemma_norm"); + trtmc::load_byok_kernel(library.string(), "merge", "minimax_m3.moe_merge"); + trtmc::load_byok_kernel(library.string(), "scores", "minimax_m3.router_scores"); + trtmc::load_byok_kernel(library.string(), "attention", "minimax_m3.causal_attention"); + trtmc::load_byok_kernel(library.string(), "nv_input", "minimax_m3.nv_input"); + trtmc::load_byok_kernel(library.string(), "rope", "minimax_m3.rope"); + trtmc::load_byok_kernel(library.string(), "routing_weights", "minimax_m3.router_weights"); + }); +#else + throw std::runtime_error( + "minimax_m3 precision module requires a native build with BYOK enabled"); +#endif +} +const internal::ConfigField fields[] = { + {"max_new_tokens", internal::ConfigKind::I64, internal::ConfigValue{int64_t{2}}, + "Maximum greedy continuation tokens; prefix and output must fit the bundle capacity."}}; +Tensor tensor(const std::vector& value, std::vector shape) { + std::size_t count = 1; + for (auto dimension : shape) { + if (dimension < 0 || (dimension != 0 && count > value.size() / dimension)) + throw std::runtime_error("minimax_m3 input tensor shape mismatch"); + count *= dimension; + } + if (count != value.size()) + throw std::runtime_error("minimax_m3 input tensor size mismatch"); + return {const_cast(value.data()), std::move(shape), DType::kFloat32}; +} +std::vector output(const TensorMap& values, const std::string& name, std::size_t size) { + const auto& value = values.at(name); + if (value.dtype != DType::kFloat32 || value.numel() != size || !value.data) + throw std::runtime_error("minimax_m3 invalid TensorRT output: " + name); + const auto* begin = static_cast(value.data); + std::vector result(begin, begin + size); + if (!std::all_of(result.begin(), result.end(), [](float x) { return std::isfinite(x); })) + throw std::runtime_error("minimax_m3 non-finite TensorRT output: " + name); + return result; +} +} // namespace +Pipeline::Pipeline(BundleReader reader, IBackend& backend) : weights_(reader) { + auto raw = reader.read_section("runtime.json"); + const auto config = nlohmann::json::parse(raw.begin(), raw.end()); + capacity_ = config.at("max_sequence_length"); + eos_ = config.at("eos_token_ids").get>(); + if (capacity_ < 2 || capacity_ > 128 || config.at("num_layers") != 60 || + config.at("precision") != "bf16" || config.at("hidden_size") != 6144 || + config.at("vocab_size") != 200064 || eos_.empty() || + config.value("nvfp4_input_scale", std::string{}) != "per_token" || + config.value("normalization", std::string{}) != "fp64_byok" || + config.value("rotary_precision", std::string{}) != "fp64") + throw std::runtime_error("minimax_m3 bundle contract mismatch"); + load_precision(); + raw = reader.read_section("tokenizer.json"); + tokenizer_ = CreateBpeTokenizer(raw.data(), raw.size(), false); + for (const std::string kind : + {"embedding", "attention", "dense", "route", "expert", "merge", "head"}) { + auto plan = reader.read_section(kind + ".plan"); + auto module = backend.create_module(plan.data(), plan.size(), {}); + if (!module || !module->ok()) + throw std::runtime_error("minimax_m3 invalid " + kind + " engine"); + modules_.emplace(kind, std::move(module)); + } +} +std::vector Pipeline::task_bindings() { + return {internal::bind(*this, {fields, 1})}; +} +std::vector Pipeline::step(const std::string& engine, const std::vector& hidden, + const std::string& prefix, int n, int intermediate) { + auto gate = weights_.projection(prefix + (engine == "expert" ? ".w1" : ".gate_proj"), + intermediate, 6144); + auto up = + weights_.projection(prefix + (engine == "expert" ? ".w3" : ".up_proj"), intermediate, 6144); + auto down = weights_.projection(prefix + (engine == "expert" ? ".w2" : ".down_proj"), 6144, + intermediate); + TensorMap inputs{{"hidden", tensor(hidden, {n, 6144})}, + {"gate", tensor(gate, {intermediate, 6144})}, + {"up", tensor(up, {intermediate, 6144})}, + {"down", tensor(down, {6144, intermediate})}}; + std::vector norm; + if (engine == "dense") { + norm = weights_.values(prefix.substr(0, prefix.size() - 4) + + ".post_attention_layernorm.weight"); + inputs.emplace("norm", tensor(norm, {6144})); + } + return output(modules_.at(engine)->forward(inputs), "result", + static_cast(n) * 6144); +} +std::vector +Pipeline::logits(const std::vector& ids, + const std::function&)>& observer) { + if (ids.empty() || ids.size() > static_cast(capacity_)) + throw std::invalid_argument("minimax_m3 invalid prefix length"); + for (auto id : ids) + if (id < 0 || id >= 200064) + throw std::invalid_argument("minimax_m3 input token outside vocabulary"); + const int n = static_cast(ids.size()); + auto embedding = weights_.projection("language_model.model.embed_tokens", 200064, 6144); + Tensor token_input{const_cast(ids.data()), {n}, DType::kInt32}; + auto hidden = + output(modules_.at("embedding") + ->forward({{"ids", token_input}, {"weight", tensor(embedding, {200064, 6144})}}), + "result", static_cast(n) * 6144); + embedding.clear(); + embedding.shrink_to_fit(); + for (int layer = 0; layer < 60; ++layer) { + const auto prefix = "language_model.model.layers." + std::to_string(layer); + { + auto norm = weights_.values(prefix + ".input_layernorm.weight"); + auto qnorm = weights_.values(prefix + ".self_attn.q_norm.weight"); + auto knorm = weights_.values(prefix + ".self_attn.k_norm.weight"); + auto query = weights_.projection(prefix + ".self_attn.q_proj", 8192, 6144); + auto key = weights_.projection(prefix + ".self_attn.k_proj", 512, 6144); + auto value = weights_.projection(prefix + ".self_attn.v_proj", 512, 6144); + auto projected = weights_.projection(prefix + ".self_attn.o_proj", 6144, 8192); + hidden = output(modules_.at("attention") + ->forward({{"hidden", tensor(hidden, {n, 6144})}, + {"norm", tensor(norm, {6144})}, + {"qnorm", tensor(qnorm, {128})}, + {"knorm", tensor(knorm, {128})}, + {"query", tensor(query, {8192, 6144})}, + {"key", tensor(key, {512, 6144})}, + {"value", tensor(value, {512, 6144})}, + {"output", tensor(projected, {6144, 8192})}}), + "result", static_cast(n) * 6144); + } + if (layer < 3) { + hidden = step("dense", hidden, prefix + ".mlp", n, 12288); + if (observer) + observer(layer, hidden); + continue; + } + const auto moe = prefix + ".block_sparse_moe"; + TensorMap routed; + { + auto norm = weights_.values(prefix + ".post_attention_layernorm.weight"); + auto router = weights_.projection(moe + ".gate", 128, 6144); + auto bias = weights_.values(moe + ".e_score_correction_bias"); + auto gate = weights_.projection(moe + ".shared_experts.gate_proj", 3072, 6144); + auto up = weights_.projection(moe + ".shared_experts.up_proj", 3072, 6144); + auto down = weights_.projection(moe + ".shared_experts.down_proj", 6144, 3072); + routed = modules_.at("route")->forward({{"hidden", tensor(hidden, {n, 6144})}, + {"norm", tensor(norm, {6144})}, + {"router", tensor(router, {128, 6144})}, + {"bias", tensor(bias, {128})}, + {"gate", tensor(gate, {3072, 6144})}, + {"up", tensor(up, {3072, 6144})}, + {"down", tensor(down, {6144, 3072})}}); + } + auto normalized = output(routed, "normalized", static_cast(n) * 6144); + auto base = output(routed, "base", static_cast(n) * 6144); + auto routing_weights = output(routed, "weights", static_cast(n) * 4); + const auto& id_tensor = routed.at("ids"); + if (id_tensor.dtype != DType::kInt32 || + id_tensor.numel() != static_cast(n) * 4 || !id_tensor.data) + throw std::runtime_error("minimax_m3 invalid expert routing output"); + const auto* expert_ids = static_cast(id_tensor.data); + std::vector> groups(128); + for (int row = 0; row < n * 4; ++row) { + if (expert_ids[row] < 0 || expert_ids[row] >= 128) + throw std::runtime_error("minimax_m3 invalid expert ID"); + groups[expert_ids[row]].push_back(row); + } + std::vector contributions(static_cast(n) * 4 * 6144); + for (int expert = 0; expert < 128; ++expert) { + const auto& rows = groups[expert]; + if (rows.empty()) + continue; + std::vector gathered(rows.size() * 6144); + for (std::size_t r = 0; r < rows.size(); ++r) + std::memcpy(gathered.data() + r * 6144, normalized.data() + (rows[r] / 4) * 6144, + 6144 * sizeof(float)); + auto values = step("expert", gathered, moe + ".experts." + std::to_string(expert), + static_cast(rows.size()), 3072); + for (std::size_t r = 0; r < rows.size(); ++r) + std::memcpy(contributions.data() + rows[r] * 6144, values.data() + r * 6144, + 6144 * sizeof(float)); + } + hidden = + output(modules_.at("merge")->forward({{"base", tensor(base, {n, 6144})}, + {"residual", tensor(hidden, {n, 6144})}, + {"weights", tensor(routing_weights, {n, 4})}, + {"values", tensor(contributions, {n, 4, 6144})}}), + "result", static_cast(n) * 6144); + if (observer) + observer(layer, hidden); + } + auto norm = weights_.values("language_model.model.norm.weight"); + auto head = weights_.projection("language_model.lm_head", 200064, 6144); + return output(modules_.at("head")->forward({{"hidden", tensor(hidden, {n, 6144})}, + {"norm", tensor(norm, {6144})}, + {"weight", tensor(head, {200064, 6144})}}), + "logits", 200064); +} +TextResult Pipeline::generate_ids(std::vector ids, int count) { + if (ids.empty() || count < 1 || ids.size() > static_cast(capacity_) || + static_cast(count) > static_cast(capacity_) - ids.size()) + throw std::invalid_argument( + "minimax_m3 prefix and requested output must fit 2..128 bundle capacity"); + for (auto id : ids) + if (id < 0 || id >= 200064) + throw std::invalid_argument("minimax_m3 input token outside vocabulary"); + const auto begin = std::chrono::steady_clock::now(); + TextResult result; + for (int step = 0; step < count; ++step) { + auto values = logits(ids); + const auto next = + static_cast(std::max_element(values.begin(), values.end()) - values.begin()); + if (std::find(eos_.begin(), eos_.end(), next) != eos_.end()) + break; + result.token_ids.push_back(next); + ids.push_back(next); + } + result.text = tokenizer_->decode(result.token_ids); + result.decode_ms = + std::chrono::duration(std::chrono::steady_clock::now() - begin).count(); + return result; +} +TextResult Pipeline::run(const internal::TextContinuationRequest& request, + internal::ConfigView config) { + internal::validate_config({fields, 1}, config); + const auto count = *internal::config_get(config, {fields, 1}, "max_new_tokens"); + if (count < 1 || count > capacity_) + throw internal::ConfigError("minimax_m3 invalid max_new_tokens"); + std::vector ids; + if (const auto* text = std::get_if(&request.prefix)) + ids = tokenizer_->encode(std::string(*text)); + else { + auto span = std::get>(request.prefix); + ids.assign(span.begin(), span.end()); + } + return generate_ids(std::move(ids), static_cast(count)); +} +} // namespace trtmc::minimax_m3 diff --git a/families/minimax_m3/runtime/pipeline.h b/families/minimax_m3/runtime/pipeline.h new file mode 100644 index 0000000000..9e5a1f5ae2 --- /dev/null +++ b/families/minimax_m3/runtime/pipeline.h @@ -0,0 +1,36 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + */ +#pragma once +#include "families/minimax_m3/runtime/tokenizer.h" +#include "families/minimax_m3/runtime/weights.h" +#include "trtmc/internal/model.h" +#include "trtmc/internal/text.h" +#include "trtmc/runtime/trt_backend.h" + +#include +#include + +namespace trtmc::minimax_m3 { +class Pipeline final : public internal::IModel, public internal::ITextContinuation { + public: + Pipeline(BundleReader reader, IBackend& backend); + const char* task() const noexcept override { return "text_continuation"; } + std::vector task_bindings() override; + TextResult run(const internal::TextContinuationRequest&, internal::ConfigView) override; + std::vector + logits(const std::vector& ids, + const std::function&)>& observer = {}); + + private: + std::vector step(const std::string&, const std::vector&, const std::string&, + int n, int intermediate); + TextResult generate_ids(std::vector, int count); + Weights weights_; + std::unique_ptr tokenizer_; + std::map> modules_; + int capacity_; + std::vector eos_; +}; +} // namespace trtmc::minimax_m3 diff --git a/families/minimax_m3/runtime/plugin.cpp b/families/minimax_m3/runtime/plugin.cpp new file mode 100644 index 0000000000..d510be519f --- /dev/null +++ b/families/minimax_m3/runtime/plugin.cpp @@ -0,0 +1,11 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + */ +#include "families/minimax_m3/runtime/pipeline.h" +#include "trtmc/runtime/family_factory.h" +extern "C" trtmc::ITask* trtmc_create_family(const trtmc::FamilyContext& context) { + if (context.kv_cache_size_bytes) + throw std::invalid_argument("minimax_m3 does not support --kv-cache-size"); + return new trtmc::minimax_m3::Pipeline(context.reader, context.backend); +} diff --git a/families/minimax_m3/runtime/precision.cu b/families/minimax_m3/runtime/precision.cu new file mode 100644 index 0000000000..902468a0e2 --- /dev/null +++ b/families/minimax_m3/runtime/precision.cu @@ -0,0 +1,381 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + */ +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { +__global__ void gemma_norm(const float* input, const float* weight, float* output, int width) { + __shared__ double sums[256]; + const auto row = static_cast(blockIdx.x) * width; + double sum = 0.0; + for (int column = threadIdx.x; column < width; column += blockDim.x) { + const double value = input[row + column]; + sum = __dadd_rn(sum, __dmul_rn(value, value)); + } + sums[threadIdx.x] = sum; + __syncthreads(); + for (int stride = blockDim.x / 2; stride; stride /= 2) { + if (threadIdx.x < stride) + sums[threadIdx.x] = __dadd_rn(sums[threadIdx.x], sums[threadIdx.x + stride]); + __syncthreads(); + } + const double variance = __ddiv_rn(sums[0], static_cast(width)); + const double inverse = __ddiv_rn(1.0, __dsqrt_rn(__dadd_rn(variance, 1e-6))); + for (int column = threadIdx.x; column < width; column += blockDim.x) { + const double normalized = __dmul_rn(static_cast(input[row + column]), inverse); + const double scaled = + __dmul_rn(normalized, __dadd_rn(1.0, static_cast(weight[column]))); + output[row + column] = __bfloat162float(__float2bfloat16_rn(__double2float_rn(scaled))); + } +} + +void run(tvm::ffi::TensorView input, tvm::ffi::TensorView weight, tvm::ffi::TensorView output) { + for (const auto& tensor : {input, weight, output}) { + const auto dtype = tensor.dtype(); + if (!tensor.IsContiguous() || tensor.device().device_type != kDLCUDA || + tensor.device().device_id != input.device().device_id || dtype.code != kDLFloat || + dtype.bits != 32 || dtype.lanes != 1) + TVM_FFI_THROW(ValueError) + << "minimax_m3 normalization requires contiguous CUDA FP32 tensors"; + } + if ((input.ndim() != 2 && input.ndim() != 3) || weight.ndim() != 1 || + output.ndim() != input.ndim() || input.size(input.ndim() - 1) != weight.size(0) || + (weight.size(0) != 128 && weight.size(0) != 6144) || input.numel() < 1 || + input.numel() / weight.size(0) > std::numeric_limits::max()) + TVM_FFI_THROW(ValueError) << "minimax_m3 normalization tensor shape mismatch"; + for (int dimension = 0; dimension < input.ndim(); ++dimension) + if (input.size(dimension) != output.size(dimension)) + TVM_FFI_THROW(ValueError) << "minimax_m3 normalization output shape mismatch"; + const auto stream = + reinterpret_cast(TVMFFIEnvGetStream(kDLCUDA, input.device().device_id)); + const auto* source = reinterpret_cast(static_cast(input.data_ptr()) + + input.byte_offset()); + const auto* scale = reinterpret_cast(static_cast(weight.data_ptr()) + + weight.byte_offset()); + auto* destination = + reinterpret_cast(static_cast(output.data_ptr()) + output.byte_offset()); + gemma_norm<<(input.numel() / weight.size(0)), 256, 0, stream>>>( + source, scale, destination, static_cast(weight.size(0))); + const auto error = cudaGetLastError(); + if (error != cudaSuccess) + TVM_FFI_THROW(RuntimeError) + << "minimax_m3 normalization launch failed: " << cudaGetErrorString(error); +} + +__global__ void merge_experts(const float* residual, const float* shared, const float* values, + const float* weights, float* output, std::size_t count) { + const std::size_t index = static_cast(blockIdx.x) * blockDim.x + threadIdx.x; + if (index >= count) + return; + const auto row = index / 6144; + const auto column = index % 6144; + double sum = 0.0; + for (int slot = 0; slot < 4; ++slot) + sum = + __dadd_rn(sum, __dmul_rn(static_cast(values[(row * 4 + slot) * 6144 + column]), + static_cast(weights[row * 4 + slot]))); + const float routed = __bfloat162float(__float2bfloat16_rn(__double2float_rn(sum))); + const float mixture = __bfloat162float(__float2bfloat16_rn(__fadd_rn(shared[index], routed))); + output[index] = __bfloat162float(__float2bfloat16_rn(__fadd_rn(residual[index], mixture))); +} + +void merge(tvm::ffi::TensorView residual, tvm::ffi::TensorView shared, tvm::ffi::TensorView values, + tvm::ffi::TensorView weights, tvm::ffi::TensorView output) { + for (const auto& tensor : {residual, shared, values, weights, output}) { + const auto dtype = tensor.dtype(); + if (!tensor.IsContiguous() || tensor.device().device_type != kDLCUDA || + tensor.device().device_id != residual.device().device_id || dtype.code != kDLFloat || + dtype.bits != 32 || dtype.lanes != 1) + TVM_FFI_THROW(ValueError) + << "minimax_m3 expert merge requires contiguous CUDA FP32 tensors"; + } + if (residual.ndim() != 2 || shared.ndim() != 2 || values.ndim() != 3 || weights.ndim() != 2 || + output.ndim() != 2 || residual.size(0) < 1 || residual.size(0) > 128 || + residual.size(1) != 6144 || shared.size(0) != residual.size(0) || shared.size(1) != 6144 || + output.size(0) != residual.size(0) || output.size(1) != 6144 || + values.size(0) != residual.size(0) || values.size(1) != 4 || values.size(2) != 6144 || + weights.size(0) != residual.size(0) || weights.size(1) != 4) + TVM_FFI_THROW(ValueError) << "minimax_m3 expert merge tensor shape mismatch"; + const auto pointer = [](tvm::ffi::TensorView tensor) { + return reinterpret_cast(static_cast(tensor.data_ptr()) + + tensor.byte_offset()); + }; + const auto stream = + reinterpret_cast(TVMFFIEnvGetStream(kDLCUDA, residual.device().device_id)); + const auto count = static_cast(residual.numel()); + merge_experts<<((count + 255) / 256), 256, 0, stream>>>( + pointer(residual), pointer(shared), pointer(values), pointer(weights), pointer(output), + count); + const auto error = cudaGetLastError(); + if (error != cudaSuccess) + TVM_FFI_THROW(RuntimeError) + << "minimax_m3 expert merge launch failed: " << cudaGetErrorString(error); +} +// Re-evaluate the small router in FP64. Its FP32 GEMM tensor supplies the +// output shape; the independently reduced logits define the numeric result. +__global__ void router_scores(const float* hidden, const float* weight, float* output) { + __shared__ double sums[256]; + const int row = blockIdx.x; + const int expert = blockIdx.y; + double sum = 0.0; + for (int column = threadIdx.x; column < 6144; column += blockDim.x) + sum = __dadd_rn(sum, __dmul_rn(static_cast(hidden[row * 6144 + column]), + static_cast(weight[expert * 6144 + column]))); + sums[threadIdx.x] = sum; + __syncthreads(); + for (int stride = blockDim.x / 2; stride; stride /= 2) { + if (threadIdx.x < stride) + sums[threadIdx.x] = __dadd_rn(sums[threadIdx.x], sums[threadIdx.x + stride]); + __syncthreads(); + } + if (threadIdx.x == 0) { + const double logit = __double2float_rn(sums[0]); + output[row * 128 + expert] = __double2float_rn(__ddiv_rn(1.0, __dadd_rn(1.0, exp(-logit)))); + } +} + +__global__ void router_weights(const float* selected, float* output, int rows) { + const int row = blockIdx.x * blockDim.x + threadIdx.x; + if (row >= rows) + return; + double total = 0.0; + for (int slot = 0; slot < 4; ++slot) + total = __dadd_rn(total, static_cast(selected[row * 4 + slot])); + for (int slot = 0; slot < 4; ++slot) + output[row * 4 + slot] = __double2float_rn( + __ddiv_rn(__dmul_rn(2.0, static_cast(selected[row * 4 + slot])), total)); +} + +void check_float(tvm::ffi::TensorView tensor, int device) { + const auto dtype = tensor.dtype(); + if (!tensor.IsContiguous() || tensor.device().device_type != kDLCUDA || + tensor.device().device_id != device || dtype.code != kDLFloat || dtype.bits != 32 || + dtype.lanes != 1) + TVM_FFI_THROW(ValueError) << "minimax_m3 routing requires contiguous CUDA FP32 tensors"; +} +float* data(tvm::ffi::TensorView tensor) { + return reinterpret_cast(static_cast(tensor.data_ptr()) + tensor.byte_offset()); +} +void scores(tvm::ffi::TensorView logits, tvm::ffi::TensorView hidden, tvm::ffi::TensorView weight, + tvm::ffi::TensorView output) { + for (const auto& tensor : {logits, hidden, weight, output}) + check_float(tensor, hidden.device().device_id); + if (hidden.ndim() != 2 || hidden.size(0) < 1 || hidden.size(0) > 128 || + hidden.size(1) != 6144 || weight.ndim() != 2 || weight.size(0) != 128 || + weight.size(1) != 6144 || logits.ndim() != 2 || logits.size(0) != hidden.size(0) || + logits.size(1) != 128 || output.ndim() != 2 || output.size(0) != hidden.size(0) || + output.size(1) != 128) + TVM_FFI_THROW(ValueError) << "minimax_m3 routing scores shape mismatch"; + const auto stream = + reinterpret_cast(TVMFFIEnvGetStream(kDLCUDA, hidden.device().device_id)); + router_scores<<(hidden.size(0)), 128), 256, 0, stream>>>( + data(hidden), data(weight), data(output)); + const auto error = cudaGetLastError(); + if (error != cudaSuccess) + TVM_FFI_THROW(RuntimeError) + << "minimax_m3 routing scores launch failed: " << cudaGetErrorString(error); +} +void routing_weights(tvm::ffi::TensorView selected, tvm::ffi::TensorView output) { + for (const auto& tensor : {selected, output}) + check_float(tensor, selected.device().device_id); + if (selected.ndim() != 2 || selected.size(0) < 1 || selected.size(0) > 128 || + selected.size(1) != 4 || output.ndim() != 2 || output.size(0) != selected.size(0) || + output.size(1) != 4) + TVM_FFI_THROW(ValueError) << "minimax_m3 routing weights shape mismatch"; + const auto stream = + reinterpret_cast(TVMFFIEnvGetStream(kDLCUDA, selected.device().device_id)); + router_weights<<<1, 128, 0, stream>>>(data(selected), data(output), + static_cast(selected.size(0))); + const auto error = cudaGetLastError(); + if (error != cudaSuccess) + TVM_FFI_THROW(RuntimeError) + << "minimax_m3 routing weights launch failed: " << cudaGetErrorString(error); +} +// One bounded causal head per block. Preserve FP32 score/probability +// boundaries while evaluating each reduction before its rounding boundary. +__global__ void causal_attention(const float* query, const float* key, const float* value, + float* output) { + __shared__ float probabilities[128]; + __shared__ double exponentials[128]; + __shared__ float scores[128]; + const int row = blockIdx.x; + const int head = blockIdx.y; + const int column = threadIdx.x; + if (column <= row) { + double dot = 0.0; + for (int d = 0; d < 128; ++d) + dot = __dadd_rn( + dot, __dmul_rn(static_cast(query[(row * 64 + head) * 128 + d]), + static_cast(key[(column * 4 + head / 16) * 128 + d]))); + scores[column] = __fmul_rn(__double2float_rn(dot), 0.08838834764831845f); + } + __syncthreads(); + if (column == 0) { + float maximum = scores[0]; + for (int position = 1; position <= row; ++position) + maximum = fmaxf(maximum, scores[position]); + double total = 0.0; + for (int position = 0; position <= row; ++position) { + exponentials[position] = exp(static_cast(scores[position]) - maximum); + total = __dadd_rn(total, exponentials[position]); + } + for (int position = 0; position <= row; ++position) + probabilities[position] = __double2float_rn(__ddiv_rn(exponentials[position], total)); + } + __syncthreads(); + double sum = 0.0; + for (int position = 0; position <= row; ++position) + sum = __dadd_rn( + sum, __dmul_rn(static_cast(probabilities[position]), + static_cast(value[(position * 4 + head / 16) * 128 + column]))); + output[(row * 64 + head) * 128 + column] = + __bfloat162float(__float2bfloat16_rn(__double2float_rn(sum))); +} +void attention(tvm::ffi::TensorView query, tvm::ffi::TensorView key, tvm::ffi::TensorView value, + tvm::ffi::TensorView output) { + for (const auto& tensor : {query, key, value, output}) + check_float(tensor, query.device().device_id); + const auto valid = [](tvm::ffi::TensorView tensor, int rows, int heads) { + return tensor.ndim() == 3 && tensor.size(0) == rows && tensor.size(1) == heads && + tensor.size(2) == 128; + }; + if (query.ndim() != 3 || query.size(0) < 1 || query.size(0) > 128 || + !valid(query, static_cast(query.size(0)), 64) || + !valid(key, static_cast(query.size(0)), 4) || + !valid(value, static_cast(query.size(0)), 4) || + !valid(output, static_cast(query.size(0)), 64)) + TVM_FFI_THROW(ValueError) << "minimax_m3 causal attention shape mismatch"; + const auto stream = + reinterpret_cast(TVMFFIEnvGetStream(kDLCUDA, query.device().device_id)); + causal_attention<<(query.size(0)), 64), 128, 0, stream>>>( + data(query), data(key), data(value), data(output)); + const auto error = cudaGetLastError(); + if (error != cudaSuccess) + TVM_FFI_THROW(RuntimeError) + << "minimax_m3 causal attention launch failed: " << cudaGetErrorString(error); +} +// Pinned sgl-deep-gemm 0.2.7 NVFP4 pre-dispatch: per-token outer +// multiplier, FP8 per-16 scale, then FP4 codes. The outer multiplier remains +// factored until the first projection's FP32 epilogue. +__global__ void nv_input_quantize(const float* input, float* encoded, float* outer, int width) { + __shared__ float maxima[256]; + const int row = blockIdx.x; + float maximum = 0.0f; + for (int column = threadIdx.x; column < width; column += blockDim.x) + maximum = fmaxf(maximum, fabsf(input[row * width + column])); + maxima[threadIdx.x] = maximum; + __syncthreads(); + for (int stride = blockDim.x / 2; stride; stride /= 2) { + if (threadIdx.x < stride) + maxima[threadIdx.x] = fmaxf(maxima[threadIdx.x], maxima[threadIdx.x + stride]); + __syncthreads(); + } + const float multiplier = __fdiv_rn(fmaxf(maxima[0], 1e-4f), 2688.0f); + const double midpoints[] = {0.25, 0.75, 1.25, 1.75, 2.5, 3.5, 5.0}; + const float levels[] = {0, 0.5f, 1, 1.5f, 2, 3, 4, 6}; + for (int column = threadIdx.x; column < width; column += blockDim.x) { + const float value = input[row * width + column]; + float group_maximum = fabsf(value); + for (int stride = 8; stride; stride /= 2) + group_maximum = + fmaxf(group_maximum, __shfl_xor_sync(0xffffffffu, group_maximum, stride, 16)); + const float raw_scale = __fdiv_rn(group_maximum, __fmul_rn(6.0f, multiplier)); + const auto sf_byte = __nv_cvt_float_to_fp8(raw_scale, __NV_SATFINITE, __NV_E4M3); + const auto sf_half = __nv_cvt_fp8_to_halfraw(sf_byte, __NV_E4M3); + const float scale = __half2float(*reinterpret_cast(&sf_half)); + // Compare exact dyadic boundaries in FP64, avoiding reciprocal noise + // crossing a FP4 tie. No rounding to BF16 occurs before this quantizer. + const double quantum = + __dmul_rn(static_cast(scale), static_cast(multiplier)); + float code = 0.0f; + for (int i = 0; i < 7; ++i) { + const double boundary = __dmul_rn(quantum, midpoints[i]); + if (fabs(static_cast(value)) > boundary || + (i % 2 && fabs(static_cast(value)) == boundary)) + code = levels[i + 1]; + } + encoded[row * width + column] = copysignf(__fmul_rn(code, scale), value); + outer[row * width + column] = multiplier; + } +} +void nv_input(tvm::ffi::TensorView input, tvm::ffi::TensorView encoded, + tvm::ffi::TensorView outer) { + for (const auto& tensor : {input, encoded, outer}) + check_float(tensor, input.device().device_id); + if (input.ndim() != 2 || input.size(0) < 1 || input.size(0) > 128 || input.size(1) != 6144 || + encoded.ndim() != 2 || outer.ndim() != 2 || encoded.size(0) != input.size(0) || + outer.size(0) != input.size(0) || encoded.size(1) != 6144 || outer.size(1) != 6144) + TVM_FFI_THROW(ValueError) << "minimax_m3 NVFP4 input quantization shape mismatch"; + const auto stream = + reinterpret_cast(TVMFFIEnvGetStream(kDLCUDA, input.device().device_id)); + nv_input_quantize<<(input.size(0)), 256, 0, stream>>>( + data(input), data(encoded), data(outer), 6144); + const auto error = cudaGetLastError(); + if (error != cudaSuccess) + TVM_FFI_THROW(RuntimeError) + << "minimax_m3 NVFP4 input quantization launch failed: " << cudaGetErrorString(error); +} +__global__ void rotary_position(const float* input, const float* cosine, const float* sine, + float* output, int heads, std::size_t count) { + const std::size_t index = static_cast(blockIdx.x) * blockDim.x + threadIdx.x; + if (index >= count) + return; + const int column = index % 128; + const std::size_t row = index / (heads * 128); + const std::size_t base = index - column; + if (column >= 64) { + output[index] = input[index]; + return; + } + const int frequency = column % 32; + const double left = input[base + frequency]; + const double right = input[base + frequency + 32]; + const double c = cosine[row * 32 + frequency]; + const double s = sine[row * 32 + frequency]; + const double rotated = column < 32 ? __dsub_rn(__dmul_rn(left, c), __dmul_rn(right, s)) + : __dadd_rn(__dmul_rn(right, c), __dmul_rn(left, s)); + output[index] = __bfloat162float(__float2bfloat16_rn(__double2float_rn(rotated))); +} +void rope(tvm::ffi::TensorView input, tvm::ffi::TensorView cosine, tvm::ffi::TensorView sine, + tvm::ffi::TensorView output) { + for (const auto& tensor : {input, cosine, sine, output}) + check_float(tensor, input.device().device_id); + if (input.ndim() != 3 || input.size(0) < 1 || input.size(0) > 128 || + (input.size(1) != 4 && input.size(1) != 64) || input.size(2) != 128 || output.ndim() != 3 || + output.size(0) != input.size(0) || output.size(1) != input.size(1) || + output.size(2) != 128 || cosine.ndim() != 2 || sine.ndim() != 2 || + cosine.size(0) < input.size(0) || cosine.size(0) > 128 || sine.size(0) != cosine.size(0) || + cosine.size(1) != 32 || sine.size(1) != 32) + TVM_FFI_THROW(ValueError) << "minimax_m3 rotary position shape mismatch"; + const auto stream = + reinterpret_cast(TVMFFIEnvGetStream(kDLCUDA, input.device().device_id)); + const auto count = static_cast(input.numel()); + rotary_position<<((count + 255) / 256), 256, 0, stream>>>( + data(input), data(cosine), data(sine), data(output), static_cast(input.size(1)), + count); + const auto error = cudaGetLastError(); + if (error != cudaSuccess) + TVM_FFI_THROW(RuntimeError) + << "minimax_m3 rotary position launch failed: " << cudaGetErrorString(error); +} +} // namespace + +TVM_FFI_DLL_EXPORT_TYPED_FUNC(run, run); +TVM_FFI_DLL_EXPORT_TYPED_FUNC(merge, merge); + +TVM_FFI_DLL_EXPORT_TYPED_FUNC(scores, scores); +TVM_FFI_DLL_EXPORT_TYPED_FUNC(routing_weights, routing_weights); + +TVM_FFI_DLL_EXPORT_TYPED_FUNC(attention, attention); + +TVM_FFI_DLL_EXPORT_TYPED_FUNC(nv_input, nv_input); + +TVM_FFI_DLL_EXPORT_TYPED_FUNC(rope, rope); diff --git a/families/minimax_m3/runtime/tokenizer.h b/families/minimax_m3/runtime/tokenizer.h new file mode 100644 index 0000000000..2c98fb58a9 --- /dev/null +++ b/families/minimax_m3/runtime/tokenizer.h @@ -0,0 +1,29 @@ +/* + * 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 { + +class ITokenizer { + public: + virtual ~ITokenizer() = default; + virtual std::vector encode(const std::string& text) const = 0; + virtual std::string decode(const std::vector& ids) const = 0; + virtual std::int32_t id_for_token(std::string_view token) const = 0; + virtual std::string token_for_id(std::int32_t id) const = 0; +}; + +std::unique_ptr CreateBpeTokenizer(const char* tokenizer_json_data, + std::size_t tokenizer_json_size, + bool add_special_tokens = false); + +} // namespace trtmc diff --git a/families/minimax_m3/runtime/weights.cpp b/families/minimax_m3/runtime/weights.cpp new file mode 100644 index 0000000000..695d02731e --- /dev/null +++ b/families/minimax_m3/runtime/weights.cpp @@ -0,0 +1,138 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + */ +#include "families/minimax_m3/runtime/weights.h" + +#include +#include +#include +#include +#include +#include + +namespace trtmc::minimax_m3 { +namespace { +const std::array e4m3_table = [] { + std::array table{}; + for (int byte = 0; byte < 256; ++byte) { + const int exponent = (byte >> 3) & 15; + const int mantissa = byte & 7; + if (exponent == 15 && mantissa == 7) { + table[byte] = std::numeric_limits::quiet_NaN(); + continue; + } + const float value = exponent ? std::ldexp(1.0F + mantissa / 8.0F, exponent - 7) + : std::ldexp(mantissa / 8.0F, -6); + table[byte] = byte & 128 ? -value : value; + } + return table; +}(); +float e4m3(unsigned char byte) { + const auto value = e4m3_table[byte]; + if (!std::isfinite(value)) + throw std::runtime_error("minimax_m3 non-finite FP8 checkpoint value"); + return value; +} +} // namespace +Weights::Weights(BundleReader reader) : reader_(std::move(reader)) { + auto data = reader_.read_section("weights.json"); + metadata_ = nlohmann::json::parse(data.begin(), data.end()); +} +void Weights::shape(const std::string& name, const std::vector& expected) const { + if (metadata_.at(name).at("shape").get>() != expected) + throw std::runtime_error("minimax_m3 checkpoint shape mismatch: " + name); +} +Weights::Bytes Weights::bytes(const std::string& name) { + const auto& entry = metadata_.at(name); + const auto section = entry.at("section").get(); + const auto offset = entry.at("offset").get(); + const auto count = entry.at("bytes").get(); + auto owner = + std::make_shared>(reader_.read_section_range(section, offset, count)); + return {owner, reinterpret_cast(owner->data()), count}; +} +std::vector Weights::values(const std::string& name) { + const auto& entry = metadata_.at(name); + if (entry.contains("values")) { + auto result = entry.at("values").get>(); + if (!std::all_of(result.begin(), result.end(), [](float x) { return std::isfinite(x); })) + throw std::runtime_error("minimax_m3 non-finite checkpoint value"); + return result; + } + auto raw = bytes(name); + const auto dtype = entry.at("dtype").get(); + const int width = dtype == "float32" ? 4 : dtype == "bfloat16" ? 2 : 1; + if (raw.size % width) + throw std::runtime_error("minimax_m3 invalid checkpoint scalar width"); + std::vector result(raw.size / width); + if (dtype == "float32") + std::memcpy(result.data(), raw.data, raw.size); + else if (dtype == "bfloat16") { + for (std::size_t i = 0; i < result.size(); ++i) { + uint32_t bits = (static_cast(raw.data[2 * i]) | + (static_cast(raw.data[2 * i + 1]) << 8)) + << 16; + std::memcpy(&result[i], &bits, 4); + } + } else if (dtype == "float8_e4m3fn") { + for (std::size_t i = 0; i < result.size(); ++i) + result[i] = e4m3(raw.data[i]); + } else + throw std::runtime_error("minimax_m3 expected floating-point checkpoint values"); + if (!std::all_of(result.begin(), result.end(), [](float x) { return std::isfinite(x); })) + throw std::runtime_error("minimax_m3 non-finite checkpoint projection"); + return result; +} +std::vector Weights::projection(const std::string& prefix, int n, int k) { + const auto packed = prefix + ".weight_packed"; + if (metadata_.contains(packed)) { + shape(packed, {n, k / 2}); + shape(prefix + ".weight_scale", {n, k / 16}); + if (metadata_.at(packed).at("dtype") != "uint8" || + metadata_.at(prefix + ".weight_scale").at("dtype") != "float8_e4m3fn") + throw std::runtime_error("minimax_m3 NVFP4 format mismatch"); + auto raw = bytes(packed); + auto scales = bytes(prefix + ".weight_scale"); + if (raw.size != static_cast(n) * k / 2 || + scales.size != static_cast(n) * k / 16) + throw std::runtime_error("minimax_m3 NVFP4 payload size mismatch"); + const auto global = values(prefix + ".weight_global_scale"); + if (global.size() != 1 || !std::isfinite(global[0]) || global[0] <= 0) + throw std::runtime_error("minimax_m3 invalid NVFP4 global scale"); + static constexpr float table[] = {0, .5, 1, 1.5, 2, 3, 4, 6, + 0, -.5, -1, -1.5, -2, -3, -4, -6}; + std::vector result(static_cast(n) * k); + for (std::size_t block = 0; block < result.size() / 16; ++block) { + const float scale = e4m3(scales.data[block]) / global[0]; + for (std::size_t j = 0; j < 16; ++j) { + const auto i = block * 16 + j; + const auto code = (raw.data[i / 2] >> ((i % 2) * 4)) & 15; + result[i] = table[code] * scale; + } + } + return result; + } + shape(prefix + ".weight", {n, k}); + auto result = values(prefix + ".weight"); + if (result.size() != static_cast(n) * k) + throw std::runtime_error("minimax_m3 projection payload size mismatch"); + if (metadata_.contains(prefix + ".weight_scale_inv")) { + shape(prefix + ".weight_scale_inv", {n, k / 32}); + auto scales = bytes(prefix + ".weight_scale_inv"); + if (scales.size != static_cast(n) * k / 32) + throw std::runtime_error("minimax_m3 MXFP8 scale size mismatch"); + if (metadata_.at(prefix + ".weight").at("dtype") != "float8_e4m3fn" || + metadata_.at(prefix + ".weight_scale_inv").at("dtype") != "uint8") + throw std::runtime_error("minimax_m3 MXFP8 format mismatch"); + for (std::size_t block = 0; block < result.size() / 32; ++block) { + if (scales.data[block] == 255) + throw std::runtime_error("minimax_m3 invalid E8M0 scale"); + const float scale = std::ldexp(1.0F, static_cast(scales.data[block]) - 127); + for (std::size_t j = 0; j < 32; ++j) + result[block * 32 + j] *= scale; + } + } + return result; +} +} // namespace trtmc::minimax_m3 diff --git a/families/minimax_m3/runtime/weights.h b/families/minimax_m3/runtime/weights.h new file mode 100644 index 0000000000..6a26b6131b --- /dev/null +++ b/families/minimax_m3/runtime/weights.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::minimax_m3 { +class Weights { + public: + explicit Weights(BundleReader reader); + std::vector values(const std::string& name); + std::vector projection(const std::string& prefix, int n, int k); + + private: + struct Bytes { + std::shared_ptr> owner; + const unsigned char* data; + std::size_t size; + }; + Bytes bytes(const std::string& name); + void shape(const std::string& name, const std::vector& expected) const; + BundleReader reader_; + nlohmann::json metadata_; +}; +} // namespace trtmc::minimax_m3 diff --git a/families/minimax_m3/support.py b/families/minimax_m3/support.py new file mode 100644 index 0000000000..d144443fbc --- /dev/null +++ b/families/minimax_m3/support.py @@ -0,0 +1,14 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Exact MiniMax M3 sparse checkpoint ownership.""" + +from tensorrt_model_connect.model_support import family_support + +describe = family_support( + model_types=("minimax_m3_vl",), + architectures=("MiniMaxM3SparseForConditionalGeneration",), + tasks=("text_continuation",), + default_task="text_continuation", + default_precision="bf16", +) diff --git a/families/minimax_m3/tests/__init__.py b/families/minimax_m3/tests/__init__.py new file mode 100644 index 0000000000..52a7a9daf0 --- /dev/null +++ b/families/minimax_m3/tests/__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/minimax_m3/tests/fixtures/config.json b/families/minimax_m3/tests/fixtures/config.json new file mode 100644 index 0000000000..513845ce32 --- /dev/null +++ b/families/minimax_m3/tests/fixtures/config.json @@ -0,0 +1,357 @@ +{ + "architectures": [ + "MiniMaxM3SparseForConditionalGeneration" + ], + "auto_map": { + "AutoConfig": "configuration_minimax_m3_vl.MiniMaxM3VLConfig" + }, + "model_type": "minimax_m3_vl", + "text_config": { + "hidden_size": 6144, + "intermediate_size": 3072, + "num_hidden_layers": 60, + "num_attention_heads": 64, + "num_key_value_heads": 4, + "head_dim": 128, + "vocab_size": 200064, + "max_position_embeddings": 1048576, + "rms_norm_eps": 1e-06, + "use_gemma_norm": true, + "attention_output_gate": false, + "rope_theta": 10000000, + "rotary_dim": 64, + "partial_rotary_factor": 0.5, + "hidden_act": "swigluoai", + "use_qk_norm": true, + "tie_word_embeddings": false, + "dense_intermediate_size": 12288, + "shared_intermediate_size": 3072, + "num_local_experts": 128, + "num_experts_per_tok": 4, + "n_shared_experts": 1, + "scoring_func": "sigmoid", + "use_routing_bias": true, + "moe_layer_freq": [ + 0, + 0, + 0, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1 + ], + "qk_norm_type": "per_head", + "swiglu_alpha": 1.702, + "swiglu_limit": 7.0, + "routed_scaling_factor": 2.0, + "sparse_attention_config": { + "use_sparse_attention": true, + "sparse_index_dim": 128, + "sparse_num_index_heads": 4, + "sparse_topk_blocks": 16, + "sparse_block_size": 128, + "sparse_score_type": "max", + "sparse_init_block": 0, + "sparse_local_block": 1, + "sparse_attention_freq": [ + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1 + ], + "sparse_disable_index_value": [ + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1 + ] + }, + "architectures": [ + "MiniMaxM3SparseForCausalLM" + ] + }, + "vision_config": { + "hidden_size": 1280, + "num_attention_heads": 16, + "num_hidden_layers": 32, + "intermediate_size": 5120, + "patch_size": 14, + "image_size": 672, + "projection_dim": 6144, + "position_embedding_type": "rope", + "rope_mode": "3d", + "rope_theta": 10000.0, + "attention_dropout": 0.0, + "hidden_act": "gelu", + "initializer_factor": 1.0, + "initializer_range": 0.02, + "layer_norm_eps": 1e-05, + "model_type": "clip_vision_model", + "num_channels": 3, + "vocab_size": 32000, + "img_token_compression_config": { + "image_token_compression_method": "patch_merge", + "spatial_merge_size": 2, + "temporal_patch_size": 2 + }, + "vision_segment_max_frames": 4 + }, + "img_token_compression_config": { + "image_token_compression_method": "patch_merge", + "spatial_merge_size": 2, + "temporal_patch_size": 2 + }, + "image_grid_pinpoints": "[(336, 336), (336, 672), (336, 1008), (336, 1344), (336, 1680), (336, 2016), (672, 336), (672, 672), (672, 1008), (672, 1344), (672, 1680), (672, 2016), (1008, 336), (1008, 672), (1008, 1008), (1008, 1344), (1008, 1680), (1008, 2016), (1344, 336), (1344, 672), (1344, 1008), (1344, 1344), (1344, 1680), (1344, 2016), (1680, 336), (1680, 672), (1680, 1008), (1680, 1344), (1680, 1680), (1680, 2016), (2016, 336), (2016, 672), (2016, 1008), (2016, 1344), (2016, 1680), (2016, 2016)]", + "image_seq_length": 576, + "image_token_index": 200025, + "video_token_index": 200026, + "multimodal_projector_bias": true, + "num_reward_heads": 0, + "process_image_mode": "dynamic_res", + "projector_hidden_act": "gelu", + "vision_feature_layer": -1, + "vision_feature_select_strategy": "full", + "torch_dtype": "bfloat16", + "transformers_version": "4.52.4", + "projector_hidden_size": 6144, + "quantization_config": { + "quant_method": "mxfp8", + "activation_scheme": "dynamic", + "weight_block_size": [ + 1, + 32 + ], + "ignored_layers": [ + "language_model.model.layers.10.block_sparse_moe.gate", + "language_model.model.layers.11.block_sparse_moe.gate", + "language_model.model.layers.12.block_sparse_moe.gate", + "language_model.model.layers.13.block_sparse_moe.gate", + "language_model.model.layers.14.block_sparse_moe.gate", + "language_model.model.layers.15.block_sparse_moe.gate", + "language_model.model.layers.16.block_sparse_moe.gate", + "language_model.model.layers.17.block_sparse_moe.gate", + "language_model.model.layers.18.block_sparse_moe.gate", + "language_model.model.layers.19.block_sparse_moe.gate", + "language_model.model.layers.20.block_sparse_moe.gate", + "language_model.model.layers.21.block_sparse_moe.gate", + "language_model.model.layers.22.block_sparse_moe.gate", + "language_model.model.layers.23.block_sparse_moe.gate", + "language_model.model.layers.24.block_sparse_moe.gate", + "language_model.model.layers.25.block_sparse_moe.gate", + "language_model.model.layers.26.block_sparse_moe.gate", + "language_model.model.layers.27.block_sparse_moe.gate", + "language_model.model.layers.28.block_sparse_moe.gate", + "language_model.model.layers.29.block_sparse_moe.gate", + "language_model.model.layers.3.block_sparse_moe.gate", + "language_model.model.layers.30.block_sparse_moe.gate", + "language_model.model.layers.31.block_sparse_moe.gate", + "language_model.model.layers.32.block_sparse_moe.gate", + "language_model.model.layers.33.block_sparse_moe.gate", + "language_model.model.layers.34.block_sparse_moe.gate", + "language_model.model.layers.35.block_sparse_moe.gate", + "language_model.model.layers.36.block_sparse_moe.gate", + "language_model.model.layers.37.block_sparse_moe.gate", + "language_model.model.layers.38.block_sparse_moe.gate", + "language_model.model.layers.39.block_sparse_moe.gate", + "language_model.model.layers.4.block_sparse_moe.gate", + "language_model.model.layers.40.block_sparse_moe.gate", + "language_model.model.layers.41.block_sparse_moe.gate", + "language_model.model.layers.42.block_sparse_moe.gate", + "language_model.model.layers.43.block_sparse_moe.gate", + "language_model.model.layers.44.block_sparse_moe.gate", + "language_model.model.layers.45.block_sparse_moe.gate", + "language_model.model.layers.46.block_sparse_moe.gate", + "language_model.model.layers.47.block_sparse_moe.gate", + "language_model.model.layers.48.block_sparse_moe.gate", + "language_model.model.layers.49.block_sparse_moe.gate", + "language_model.model.layers.5.block_sparse_moe.gate", + "language_model.model.layers.50.block_sparse_moe.gate", + "language_model.model.layers.51.block_sparse_moe.gate", + "language_model.model.layers.52.block_sparse_moe.gate", + "language_model.model.layers.53.block_sparse_moe.gate", + "language_model.model.layers.54.block_sparse_moe.gate", + "language_model.model.layers.55.block_sparse_moe.gate", + "language_model.model.layers.56.block_sparse_moe.gate", + "language_model.model.layers.57.block_sparse_moe.gate", + "language_model.model.layers.58.block_sparse_moe.gate", + "language_model.model.layers.59.block_sparse_moe.gate", + "language_model.model.layers.6.block_sparse_moe.gate", + "language_model.model.layers.7.block_sparse_moe.gate", + "language_model.model.layers.8.block_sparse_moe.gate", + "language_model.model.layers.9.block_sparse_moe.gate", + "lm_head", + "model.embed_tokens", + "multi_modal_projector", + "patch_merge_mlp", + "vision_tower" + ], + "group_size": 16, + "moe_quant_algo": "NVFP4", + "moe_quant_format": "nvfp4-pack-quantized" + } +} diff --git a/families/minimax_m3/tests/logits_consumer.cpp b/families/minimax_m3/tests/logits_consumer.cpp new file mode 100644 index 0000000000..5243d95e82 --- /dev/null +++ b/families/minimax_m3/tests/logits_consumer.cpp @@ -0,0 +1,53 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + */ +#include "families/minimax_m3/runtime/pipeline.h" + +#include +#include +#include +#include + +int main(int argc, char** argv) { + if (argc != 5) + return 2; + try { + const auto path = std::filesystem::path(argv[2]) / "libtrtmc_backend_trt.so"; + std::unique_ptr library(dlopen(path.c_str(), RTLD_NOW | RTLD_LOCAL), + dlclose); + if (!library) + throw std::runtime_error(dlerror()); + auto create = + reinterpret_cast(dlsym(library.get(), "trtmc_create_backend")); + auto destroy = reinterpret_cast( + dlsym(library.get(), "trtmc_destroy_backend")); + if (!create || !destroy) + throw std::runtime_error("missing backend factory"); + std::unique_ptr backend(create(), destroy); + trtmc::minimax_m3::Pipeline model(trtmc::BundleReader(argv[1]), *backend); + const auto ids = nlohmann::json::parse(argv[3]).get>(); + std::filesystem::create_directories(argv[4]); + const auto destination = std::filesystem::path(argv[4]); + const auto values = model.logits(ids, [&](int layer, const std::vector& hidden) { + std::cerr << "completed layer " << layer << '\n'; + if (layer == 0 || layer == 2 || layer == 3 || layer == 15 || layer == 31 || + layer == 59) { + std::ofstream file(destination / ("layer-" + std::to_string(layer) + ".f32"), + std::ios::binary); + file.write(reinterpret_cast(hidden.data()), + hidden.size() * sizeof(float)); + if (!file) + throw std::runtime_error("cannot write native layer capture"); + } + }); + std::ofstream file(destination / "logits.f32", std::ios::binary); + file.write(reinterpret_cast(values.data()), values.size() * sizeof(float)); + if (!file) + throw std::runtime_error("cannot write native logits"); + return 0; + } catch (const std::exception& error) { + std::cerr << error.what() << '\n'; + return 1; + } +} diff --git a/families/minimax_m3/tests/manifests/minimax-m3.1-flash-bf16.json b/families/minimax_m3/tests/manifests/minimax-m3.1-flash-bf16.json new file mode 100644 index 0000000000..9830bb0e74 --- /dev/null +++ b/families/minimax_m3/tests/manifests/minimax-m3.1-flash-bf16.json @@ -0,0 +1,19 @@ +{ + "name": "minimax-m3.1-flash-bf16", + "hf_id": "MiniMaxAI/MiniMax-M3.1-Flash", + "hf_revision": "ce7f4df87d2e05262f5775f373dac4772f134041", + "bundle": "minimax-m3.1-flash-bf16.bundle", + "family": "minimax_m3", + "task": "text_continuation", + "precision": "bf16", + "max_sequence_length": 128, + "tensor_parallel_size": 1, + "testcases": [ + { + "name": "minimax-m3.1-flash-native", + "premerge": true, + "prompt": "The capital of France is", + "max_new_tokens": 1 + } + ] +} diff --git a/families/minimax_m3/tests/reference.py b/families/minimax_m3/tests/reference.py new file mode 100644 index 0000000000..56460e772b --- /dev/null +++ b/families/minimax_m3/tests/reference.py @@ -0,0 +1,217 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Independent precision-aware PyTorch equations from the pinned SGLang MiniMax M3 implementation. + +Upstream: sgl-project/sglang b2568f706b5caa2daf800355b015b042d8dbb535, +python/sglang/srt/models/minimax_m3.py and layers/quantization/minimax_m3_nvfp4.py. +The <=128-token case is entirely covered by the mandatory local sparse block; +the index value path is disabled in all 60 checkpoint layers. +""" + +import json +from pathlib import Path +import torch +from safetensors import safe_open + + +def quantize(x, mode): + block = 32 if mode == "mx" else 16 + grouped = x.reshape(*x.shape[:-1], -1, block) + maximum = grouped.abs().amax(dim=-1, keepdim=True) + if mode == "mx": + scale = torch.pow(2.0, torch.ceil(torch.log2(torch.clamp(maximum / 448, min=2.0**-126)))) + return ((grouped / scale).to(torch.float8_e4m3fn).float() * scale).reshape_as(x) + scale = (maximum / 6).to(torch.float8_e4m3fn).float() + normalized = torch.where(scale > 0, grouped / scale, 0) + boundaries = torch.tensor([0.25, 0.75, 1.25, 1.75, 2.5, 3.5, 5], dtype=torch.float32) + codes = torch.bucketize(normalized.abs().contiguous(), boundaries, right=False) + for i in [1, 3, 5]: + codes += (normalized.abs() == boundaries[i]).to(torch.int64) + table = torch.tensor([0, 0.5, 1, 1.5, 2, 3, 4, 6], dtype=torch.float32) + return (table[codes] * normalized.sign() * scale).reshape_as(x) + + +def nv_input_quantize(x): + grouped = x.reshape(x.shape[0], -1, 16) + row_max = x.abs().amax(dim=-1, keepdim=True).clamp(min=1e-4) + outer = row_max / 2688 + group_max = grouped.abs().amax(dim=-1, keepdim=True) + scale = (group_max / (6 * outer[..., None])).to(torch.float8_e4m3fn).float() + quantum = scale.double() * outer.double()[..., None] + absolute = grouped.double().abs() + codes = torch.zeros_like(grouped, dtype=torch.int64) + for index, midpoint in enumerate([0.25, 0.75, 1.25, 1.75, 2.5, 3.5, 5]): + boundary = quantum * midpoint + codes += (absolute > boundary).long() + if index % 2: + codes += (absolute == boundary).long() + table = torch.tensor([0, 0.5, 1, 1.5, 2, 3, 4, 6], dtype=torch.float32) + encoded = table[codes] * grouped.sign() * scale + return encoded.reshape_as(x), outer + + +def norm(x, weight): + return x * torch.rsqrt(x.square().mean(dim=-1, keepdim=True) + 1e-6) * (1 + weight) + + +def swiglu(gate, up): + gate = gate.clamp(max=7) + return gate * torch.sigmoid(1.702 * gate) * (up.clamp(-7, 7) + 1) + + +def routing_scores(logits): + return torch.sigmoid(logits.double()).float() + + +def routing_weights(selected): + values = selected.double() + return (2 * values / values.sum(dim=-1, keepdim=True)).float() + + +def weighted_expert_sum(values, weights): + return (values.double() * weights.double()[..., None]).sum(dim=1).float() + + +class Reference: + def __init__(self, directory, precision="bf16"): + if precision not in {"bf16", "fp32"}: + raise ValueError("Unsupported reference precision") + self.precision = precision + self.root = Path(directory) + self.mapping = json.loads((self.root / "model.safetensors.index.json").read_text())[ + "weight_map" + ] + self.readers = {} + + def round(self, x): + return x.to(torch.bfloat16).float() if self.precision == "bf16" else x + + def normalize(self, x, weight): + if self.precision == "bf16": + return self.round(norm(x.double(), weight.double()).float()) + return self.round(norm(x, weight)) + + def tensor(self, name): + shard = self.mapping[name] + if shard not in self.readers: + self.readers[shard] = safe_open(str(self.root / shard), framework="pt", device="cpu") + return self.readers[shard].get_tensor(name) + + def weight(self, prefix): + if prefix + ".weight_packed" in self.mapping: + packed = self.tensor(prefix + ".weight_packed") + codes = torch.stack((packed & 15, packed >> 4), dim=-1).flatten(-2).long() + table = torch.tensor([0, 0.5, 1, 1.5, 2, 3, 4, 6, 0, -0.5, -1, -1.5, -2, -3, -4, -6]) + scale = self.tensor(prefix + ".weight_scale").float() + scale = scale / self.tensor(prefix + ".weight_global_scale").float() + values = table[codes].reshape(packed.shape[0], -1, 16) * scale[..., None] + return values.reshape(packed.shape[0], -1) + values = self.tensor(prefix + ".weight").float() + if prefix + ".weight_scale_inv" in self.mapping: + scale = torch.pow(2.0, self.tensor(prefix + ".weight_scale_inv").float() - 127) + return (values.reshape(values.shape[0], -1, 32) * scale[..., None]).reshape_as(values) + return values + + def linear(self, x, prefix, output_scale=None): + weight = self.weight(prefix) + if prefix == "language_model.lm_head": + return torch.nn.functional.linear(x, weight) + if prefix.endswith(".block_sparse_moe.gate"): + return torch.nn.functional.linear(x.double(), weight.double()).float() + if self.precision == "bf16": + # Establish the FP32 result before its BF16 boundary using a wider + # independent reduction. FP32 accumulation noise can cross an exact + # BF16 midpoint, even for the original dyadic MXFP8 projections. + output = torch.nn.functional.linear(x.double(), weight.double()).float() + else: + output = torch.nn.functional.linear(x, weight) + if output_scale is not None: + output = output * output_scale + return self.round(output) + + def ffn(self, x, prefix, mode): + q, outer = nv_input_quantize(x) if mode == "nv" else (quantize(x, mode), None) + gate_name, up_name, down_name = ( + ("w1", "w3", "w2") if mode == "nv" else ("gate_proj", "up_proj", "down_proj") + ) + gate = self.linear(q, prefix + "." + gate_name, outer) + up = self.linear(q, prefix + "." + up_name, outer) + return self.linear(quantize(self.round(swiglu(gate, up)), mode), prefix + "." + down_name) + + @staticmethod + def rope(x): + sequence = x.shape[0] + inverse = 1 / torch.pow(1e7, torch.arange(0, 64, 2, dtype=torch.float64) / 64) + angles = torch.arange(sequence, dtype=torch.float64)[:, None] * inverse + cosine, sine = ( + angles.cos().float().double()[:, None, :], + angles.sin().float().double()[:, None, :], + ) + x = x.double() + left, right = x[..., :32], x[..., 32:64] + return torch.cat( + (left * cosine - right * sine, right * cosine + left * sine, x[..., 64:]), dim=-1 + ).float() + + def attention(self, x, prefix): + qinput = quantize( + self.normalize(x, self.tensor(prefix + ".input_layernorm.weight").float()), "mx" + ) + key = prefix + ".self_attn" + query = self.linear(qinput, key + ".q_proj").reshape(-1, 64, 128) + keys = self.linear(qinput, key + ".k_proj").reshape(-1, 4, 128) + values = self.linear(qinput, key + ".v_proj").reshape(-1, 4, 128) + query = self.round( + self.rope(self.normalize(query, self.tensor(key + ".q_norm.weight").float())) + ).transpose(0, 1) + keys = ( + self.round(self.rope(self.normalize(keys, self.tensor(key + ".k_norm.weight").float()))) + .transpose(0, 1) + .repeat_interleave(16, dim=0) + ) + values = values.transpose(0, 1).repeat_interleave(16, dim=0) + scores = (query.double() @ keys.double().transpose(-2, -1)).float() * (128**-0.5) + mask = torch.ones((x.shape[0], x.shape[0]), dtype=torch.bool).triu(1) + scores.masked_fill_(mask, -1e9) + probabilities = torch.softmax(scores.double(), dim=-1).float() + attended = (probabilities.double() @ values.double()).float() + attended = attended.transpose(0, 1).reshape(-1, 8192) + return self.round(x + self.linear(quantize(self.round(attended), "mx"), key + ".o_proj")) + + @torch.no_grad() + def logits(self, ids, progress=None): + x = self.tensor("language_model.model.embed_tokens.weight")[torch.tensor(ids)].float() + snapshots = {} + for layer in range(60): + prefix = f"language_model.model.layers.{layer}" + x = self.attention(x, prefix) + normalized = self.normalize( + x, self.tensor(prefix + ".post_attention_layernorm.weight").float() + ) + if layer < 3: + x = self.round(x + self.ffn(normalized, prefix + ".mlp", "mx")) + else: + moe = prefix + ".block_sparse_moe" + scores = routing_scores(self.linear(normalized, moe + ".gate")) + bias = self.tensor(moe + ".e_score_correction_bias").float() + selected = torch.topk(scores + bias, 4, dim=-1).indices + weights = scores.gather(1, selected) + weights = routing_weights(weights) + expert_values = torch.empty((x.shape[0], 4, x.shape[1]), dtype=torch.float32) + for expert in selected.unique().tolist(): + positions = torch.nonzero(selected == expert, as_tuple=False) + rows, slots = positions[:, 0], positions[:, 1] + output = self.ffn(normalized[rows], moe + f".experts.{expert}", "nv") + expert_values[rows, slots] = output + contribution = weighted_expert_sum(expert_values, weights) + mixture = self.round( + self.ffn(normalized, moe + ".shared_experts", "mx") + self.round(contribution) + ) + x = self.round(x + mixture) + if progress: + progress(layer, x) + if layer in [0, 2, 3, 15, 31, 59]: + snapshots[str(layer)] = x.numpy().copy() + hidden = self.normalize(x[-1:], self.tensor("language_model.model.norm.weight").float()) + return self.linear(hidden, "language_model.lm_head")[0].numpy(), snapshots diff --git a/families/minimax_m3/tests/sdk_consumer.c b/families/minimax_m3/tests/sdk_consumer.c new file mode 100644 index 0000000000..3fd921b444 --- /dev/null +++ b/families/minimax_m3/tests/sdk_consumer.c @@ -0,0 +1,68 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + */ +#include +#include +#include +#include +static trtmc_string_view string(const char* s) { + trtmc_string_view v = {s, strlen(s)}; + return v; +} +int main(int argc, char** argv) { + const trtmc_core_api_v1* core = NULL; + const trtmc_api_header* header = NULL; + const trtmc_text_continuation_api_v1* task = NULL; + trtmc_model* model = NULL; + trtmc_result* result = NULL; + trtmc_error* error = NULL; + trtmc_load_options_v1 options = {0}; + trtmc_text_continuation_request_v1 request = {0}; + trtmc_config_entry_v1 entry = {0}; + trtmc_config_view_v1 config = {&entry, 1}; + trtmc_text_result_view_v1 view = {0}; + uint64_t i; + int status = 1; + if (argc != 4) + return 2; + if (trtmc_get_api(1, 0, &core) != TRTMC_OK || !core) + return 1; + options.struct_size = sizeof(options); + options.runtime_root = string(argv[2]); + if (core->model_load(string(argv[1]), &options, &model, &error) != TRTMC_OK) + goto cleanup; + if (core->model_get_task_api(model, string(TRTMC_TASK_TEXT_CONTINUATION), 1, 0, &header, + &error) != TRTMC_OK) + goto cleanup; + task = (const trtmc_text_continuation_api_v1*)header; + request.prefix.kind = TRTMC_TEXT_UTF8; + request.prefix.as.text = string(argv[3]); + entry.name = string("max_new_tokens"); + entry.value.kind = TRTMC_CONFIG_I64; + entry.value.as.i64 = 1; + if (task->run(model, &request, &config, &result, &error) != TRTMC_OK) + goto cleanup; + core->model_release(model); + model = NULL; + if (task->result_view(result, &view, &error) != TRTMC_OK) + goto cleanup; + fputs("{\"text_hex\":\"", stdout); + for (i = 0; i < view.text.size; ++i) + printf("%02x", (unsigned char)view.text.data[i]); + fputs("\",\"token_ids\":[", stdout); + for (i = 0; i < view.token_ids.size; ++i) + printf("%s%" PRId32, i ? "," : "", view.token_ids.data[i]); + puts("]}"); + status = 0; +cleanup: + if (error) { + trtmc_string_view message = core->error_message(error); + fwrite(message.data, 1, message.size, stderr); + fputc('\n', stderr); + core->error_release(error); + } + core->result_release(result); + core->model_release(model); + return status; +} diff --git a/families/minimax_m3/tests/sdk_consumer.cpp b/families/minimax_m3/tests/sdk_consumer.cpp new file mode 100644 index 0000000000..3ac24958d0 --- /dev/null +++ b/families/minimax_m3/tests/sdk_consumer.cpp @@ -0,0 +1,37 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + */ +#include +#include +#include + +int main(int argc, char** argv) { + if (argc != 4) + return 2; + try { + std::vector results; + { + trtmc::LoadOptions options; + options.runtime_root = argv[2]; + auto model = trtmc::Model::load(argv[1], options); + auto task = model.task(); + trtmc::Config config{{"max_new_tokens", int64_t{1}}}; + for (int i = 0; i < 2; ++i) + results.push_back(task.run({std::string(argv[3])}, config)); + } + for (const auto& result : results) { + std::cout << "{\"text_hex\":\""; + for (unsigned char c : result.text()) + std::cout << std::hex << std::setw(2) << std::setfill('0') << static_cast(c); + std::cout << std::dec << "\",\"token_ids\":["; + for (std::size_t i = 0; i < result.token_ids().size(); ++i) + std::cout << (i ? "," : "") << result.token_ids()[i]; + std::cout << "]}\n"; + } + return 0; + } catch (const std::exception& error) { + std::cerr << error.what() << '\n'; + return 1; + } +} diff --git a/families/minimax_m3/tests/test_attention_precision.py b/families/minimax_m3/tests/test_attention_precision.py new file mode 100644 index 0000000000..a87640fc36 --- /dev/null +++ b/families/minimax_m3/tests/test_attention_precision.py @@ -0,0 +1,74 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +"""Independent Decimal/rational causal attention checks, including GQA mapping.""" + +from decimal import Decimal, localcontext +from fractions import Fraction +import os + +import numpy as np +import pytest +import torch +from cuda.bindings import runtime as cuda + +from families.minimax_m3.precision import add_precision_kernel +from .trt_runner import Runner + + +@pytest.fixture(scope="module") +def attention(): + status, count = cuda.cudaGetDeviceCount() + if int(status) != 0 or count == 0: + pytest.skip("attention precision requires a CUDA GPU") + if not os.environ.get("TRTMC_RUNTIME_ROOT"): + pytest.skip("attention precision requires TRTMC_RUNTIME_ROOT") + + def definition(graph): + query = graph.input("query", (-1, 64, 128)) + key = graph.input("key", (-1, 4, 128)) + value = graph.input("value", (-1, 4, 128)) + return {"result": add_precision_kernel(graph.net, "causal_attention", [query, key, value])} + + return Runner(definition) + + +@pytest.mark.gpu +@pytest.mark.parametrize("uniform", [False, True]) +def test_attention_matches_decimal_probabilities_and_exact_weighted_sum(attention, uniform): + query = np.zeros((3, 64, 128), np.float32) + key = np.zeros((3, 4, 128), np.float32) + values = np.zeros_like(key) + expected = np.empty_like(query) + for row in range(3): + query[row, :, 0] = 0 if uniform else row + 1 + for head in range(4): + key[row, head, 0] = (row - 1) * (head + 1) / 4 + values[row, head, :] = (row * 3 - 2) * (head + 1) / 8 + for row in range(3): + for head in range(64): + scores = [ + np.float32(query[row, head, 0] * key[p, head // 16, 0]) * np.float32(128**-0.5) + for p in range(row + 1) + ] + with localcontext() as context: + context.prec = 80 + exponents = [Decimal(float(s)).exp() for s in scores] + total = sum(exponents) + probabilities = [np.float32(float(e / total)) for e in exponents] + exact = sum( + ( + Fraction(float(probabilities[p])) * Fraction(float(values[p, head // 16, 0])) + for p in range(row + 1) + ), + Fraction(), + ) + expected[row, head, :] = ( + torch.tensor(float(exact), dtype=torch.float32).bfloat16().float().item() + ) + actual = attention(query=query, key=key, value=values)["result"] + np.testing.assert_array_equal(actual, expected) + # Future keys/values must not influence earlier causal outputs. + key[2] = 8192 + values[2] = -8192 + changed = attention(query=query, key=key, value=values)["result"] + np.testing.assert_array_equal(changed[:2], actual[:2]) diff --git a/families/minimax_m3/tests/test_e2e.py b/families/minimax_m3/tests/test_e2e.py new file mode 100644 index 0000000000..1ac142ee87 --- /dev/null +++ b/families/minimax_m3/tests/test_e2e.py @@ -0,0 +1,208 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +"""Full pinned-checkpoint qualification, independent layer/logit oracle and public consumers.""" + +import json +import os +from pathlib import Path +import subprocess +import numpy as np +import pytest +import torch +from tokenizers import Tokenizer +from tensorrt_model_connect import BuildRequest, build +from .reference import Reference + +MANIFEST = json.loads( + (Path(__file__).parent / "manifests/minimax-m3.1-flash-bf16.json").read_text() +) + + +def required(name): + value = os.environ.get(name) + assert value, f"selected MiniMax E2E requires {name}" + path = Path(value) + assert path.exists(), path + return path + + +def command(arguments): + result = subprocess.run( + [str(x) for x in arguments], check=True, text=True, capture_output=True, timeout=7200 + ) + return [json.loads(line) for line in result.stdout.splitlines() if line.startswith("{")] + + +def compare(actual, expected): + assert actual.shape == expected.shape + assert np.isfinite(actual).all() and np.isfinite(expected).all() + relative = float(np.linalg.norm(actual - expected) / max(np.linalg.norm(expected), 1e-20)) + cosine = float( + np.vdot(actual.ravel(), expected.ravel()) + / (np.linalg.norm(actual) * np.linalg.norm(expected)) + ) + assert relative < 1e-2 and cosine > 0.9999, (relative, cosine) + return dict( + relative_l2=relative, cosine=cosine, max_abs=float(np.max(np.abs(actual - expected))) + ) + + +def test_full_checkpoint_native_continuation(pytestconfig, tmp_path): + selected = [] + for name in ["--e2e-model", "--e2e-testcase"]: + selected.extend( + x.strip() for raw in (pytestconfig.getoption(name) or []) for x in str(raw).split(",") + ) + selection_file = pytestconfig.getoption("--e2e-models-file") + if selection_file: + selected.extend(Path(selection_file).read_text().splitlines()) + names = {"minimax_m3", MANIFEST["name"]} + names.update(case["name"] for case in MANIFEST["testcases"]) + if not set(selected) & names: + pytest.skip("MiniMax full checkpoint E2E requires an explicit selection") + if os.environ.get("TRTMC_MINIMAX_M3_MODEL_DIR"): + checkpoint = required("TRTMC_MINIMAX_M3_MODEL_DIR") + else: + from huggingface_hub import snapshot_download + + checkpoint = Path( + snapshot_download( + MANIFEST["hf_id"], revision=MANIFEST["hf_revision"], local_files_only=True + ) + ) + binary = required("TRTMC_BINARY") + runtime = required("TRTMC_RUNTIME_ROOT") + native = required("TRTMC_NATIVE_BUILD_DIR") + if os.environ.get("TRTMC_MINIMAX_M3_BUNDLE"): + bundle = required("TRTMC_MINIMAX_M3_BUNDLE") + else: + bundle = tmp_path / MANIFEST["bundle"] + build( + BuildRequest( + model_dir=checkpoint, + output_path=bundle, + family=MANIFEST["family"], + task=MANIFEST["task"], + precision=MANIFEST["precision"], + max_sequence_length=MANIFEST["max_sequence_length"], + tensor_parallel_size=MANIFEST["tensor_parallel_size"], + ) + ) + case = MANIFEST["testcases"][0] + assert case["max_new_tokens"] == 1 + tokenizer = Tokenizer.from_file(str(checkpoint / "tokenizer.json")) + texts = [ + case["prompt"], + "Hello world!", + "HTTPServer 1234", + "مرحبا بالعالم", + "你好世界", + "A café and a cafe\u0301.", + "I'm testing\n\nthis.", + " trailing spaces ", + "hello", + ] + (tmp_path / "tokenizer-inputs.json").write_text(json.dumps(texts, ensure_ascii=False)) + encoded = subprocess.run( + [ + str(native / "test_minimax_m3_tokenizer"), + str(checkpoint / "tokenizer.json"), + str(tmp_path / "tokenizer-inputs.json"), + ], + check=True, + text=True, + capture_output=True, + timeout=60, + ) + for text, actual in zip(texts, json.loads(encoded.stdout), strict=True): + wanted = tokenizer.encode(text, add_special_tokens=False).ids + assert actual["ids"] == wanted, (text, actual, wanted) + assert actual["decoded"] == tokenizer.decode(wanted, skip_special_tokens=True) + # Every single-byte token and malformed/truncated UTF-8 sequence must + # decode like the checkpoint, including when generation stops mid-character. + decode_ids = [[index] for index in range(256)] + [ + [0xE4, 0xBD], + [0xE4, 0xBD, 0xA0], + [0xE4, ord("a")], + [0xC0, 0xAF], + [0xED, 0xA0, 0x80], + [0xF4, 0x90, 0x80, 0x80], + [0, ord("a")], + ] + (tmp_path / "tokenizer-decode-inputs.json").write_text(json.dumps(decode_ids)) + decoded = subprocess.run( + [ + str(native / "test_minimax_m3_tokenizer"), + str(checkpoint / "tokenizer.json"), + str(tmp_path / "tokenizer-decode-inputs.json"), + ], + check=True, + text=True, + capture_output=True, + timeout=60, + ) + for wanted, actual in zip(decode_ids, json.loads(decoded.stdout), strict=True): + assert actual["ids"] == wanted + assert actual["decoded"] == tokenizer.decode(wanted, skip_special_tokens=True) + ids = tokenizer.encode(case["prompt"], add_special_tokens=False).ids + reference = Reference(checkpoint, precision=MANIFEST["precision"]) + torch.set_num_threads(4) + expected, snapshots = reference.logits( + ids, lambda layer, _: print(f"reference layer {layer}", flush=True) + ) + np.save(tmp_path / "reference-logits.npy", expected) + for layer, values in snapshots.items(): + np.save(tmp_path / f"reference-layer-{layer}.npy", values) + native_output = tmp_path / "native" + subprocess.run( + [ + str(native / "test_minimax_m3_logits"), + str(bundle), + str(runtime), + json.dumps(ids), + str(native_output), + ], + check=True, + timeout=7200, + ) + evidence = {"prompt": case["prompt"], "prefix_ids": ids, "layers": {}} + for layer, wanted in snapshots.items(): + actual = np.fromfile(native_output / f"layer-{layer}.f32", dtype=np.float32).reshape( + wanted.shape + ) + evidence["layers"][layer] = compare(actual, wanted) + actual = np.fromfile(native_output / "logits.f32", dtype=np.float32) + evidence["logits"] = compare(actual, expected) + assert int(actual.argmax()) == int(expected.argmax()) + eos = json.loads((checkpoint / "generation_config.json").read_text())["eos_token_id"] + eos = eos if isinstance(eos, list) else [eos] + generated = [] if int(expected.argmax()) in eos else [int(expected.argmax())] + text = tokenizer.decode(generated, skip_special_tokens=True) + evidence.update(token_ids=generated, text=text) + cli = command( + [ + binary, + "run", + bundle, + "--runtime-root", + runtime, + "--task", + MANIFEST["task"], + "--prompt", + case["prompt"], + "--set", + f"max_new_tokens={case['max_new_tokens']}", + ] + )[0] + assert cli["token_ids"] == generated and cli["text"] == text, cli + for language in ["c", "cpp"]: + results = command( + [native / f"test_minimax_m3_sdk_{language}", bundle, runtime, case["prompt"]] + ) + assert len(results) == (2 if language == "cpp" else 1) + for result in results: + assert result["token_ids"] == generated + assert bytes.fromhex(result["text_hex"]).decode("utf-8") == text + if language == "cpp": + assert results[0] == results[1], "loaded Task changed between repeated requests" + (tmp_path / "parity.json").write_text(json.dumps(evidence, indent=2, ensure_ascii=False) + "\n") diff --git a/families/minimax_m3/tests/test_e2e_selection.py b/families/minimax_m3/tests/test_e2e_selection.py new file mode 100644 index 0000000000..1c403962d9 --- /dev/null +++ b/families/minimax_m3/tests/test_e2e_selection.py @@ -0,0 +1,59 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +"""Declared CI testcase selectors must reach checkpoint validation.""" + +from types import SimpleNamespace + +import pytest + +from . import test_e2e as owning + + +class CheckpointRequested(Exception): + pass + + +@pytest.fixture +def checkpoint_boundary(monkeypatch): + monkeypatch.setenv("TRTMC_MINIMAX_M3_MODEL_DIR", "/not-needed-for-selection") + + def required(name): + assert name == "TRTMC_MINIMAX_M3_MODEL_DIR" + raise CheckpointRequested + + monkeypatch.setattr(owning, "required", required) + + +@pytest.mark.parametrize( + "option,values", + [ + ("--e2e-model", ["minimax_m3"]), + ("--e2e-model", [owning.MANIFEST["name"]]), + ("--e2e-testcase", [owning.MANIFEST["testcases"][0]["name"]]), + ("--e2e-testcase", ["unrelated," + owning.MANIFEST["testcases"][0]["name"]]), + ("--e2e-testcase", ["unrelated", owning.MANIFEST["testcases"][0]["name"]]), + ], +) +def test_explicit_selection_reaches_checkpoint(checkpoint_boundary, tmp_path, option, values): + config = SimpleNamespace(getoption=lambda name: values if name == option else None) + with pytest.raises(CheckpointRequested): + owning.test_full_checkpoint_native_continuation(config, tmp_path) + + +def test_testcase_selection_file_reaches_checkpoint(checkpoint_boundary, tmp_path): + selection = tmp_path / "selection.txt" + selection.write_text(owning.MANIFEST["testcases"][0]["name"] + "\n") + config = SimpleNamespace( + getoption=lambda name: str(selection) if name == "--e2e-models-file" else None + ) + with pytest.raises(CheckpointRequested): + owning.test_full_checkpoint_native_continuation(config, tmp_path) + + +@pytest.mark.parametrize( + "options", [{}, {"--e2e-model": ["unrelated"]}, {"--e2e-testcase": ["unrelated"]}] +) +def test_unselected_case_skips_before_checkpoint(checkpoint_boundary, tmp_path, options): + config = SimpleNamespace(getoption=options.get) + with pytest.raises(pytest.skip.Exception): + owning.test_full_checkpoint_native_continuation(config, tmp_path) diff --git a/families/minimax_m3/tests/test_model.py b/families/minimax_m3/tests/test_model.py new file mode 100644 index 0000000000..ec2839e407 --- /dev/null +++ b/families/minimax_m3/tests/test_model.py @@ -0,0 +1,68 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +from dataclasses import replace +import json +from pathlib import Path +import pytest +from tensorrt_model_connect import BuildRequest +from families.minimax_m3.model import _validate_config, build + + +@pytest.fixture +def config(): + return json.loads((Path(__file__).parent / "fixtures/config.json").read_text()) + + +def request(tmp_path): + return BuildRequest( + model_dir=tmp_path, + output_path=tmp_path / "model.bundle", + family="minimax_m3", + task="text_continuation", + precision="bf16", + max_sequence_length=128, + ) + + +@pytest.mark.parametrize( + "field,value", + [ + ("task", "chat"), + ("backend", "trt_rtx"), + ("precision", "fp16"), + ("precision", "fp32"), + ("max_batch_size", 2), + ("tensor_parallel_size", 2), + ("context_parallel_size", 2), + ("dynamic_kv_cache", True), + ("quantization", "nvfp4"), + ("fp32_layers", (1,)), + ("mtp_seq_len", 2), + ("image_height", 672), + ("image_width", 672), + ("video_num_frames", 2), + ("max_sequence_length", 1), + ("max_sequence_length", 129), + ], +) +def test_unsupported_requests_rejected(tmp_path, config, field, value): + with pytest.raises((ValueError, NotImplementedError)): + build(replace(request(tmp_path), **{field: value}), None) + + +def test_published_short_context_profile(tmp_path, config): + _validate_config(config) + + +@pytest.mark.parametrize("mutation", ["index_values", "local_block", "layers", "quantization"]) +def test_incompatible_mathematical_contract_rejected(tmp_path, config, mutation): + if mutation == "index_values": + config["text_config"]["sparse_attention_config"]["sparse_disable_index_value"][0] = 0 + elif mutation == "local_block": + config["text_config"]["sparse_attention_config"]["sparse_local_block"] = 0 + elif mutation == "layers": + config["text_config"]["num_hidden_layers"] = 1 + else: + config["quantization_config"]["moe_quant_algo"] = "INT4" + with pytest.raises(ValueError): + _validate_config(config) diff --git a/families/minimax_m3/tests/test_normalization.py b/families/minimax_m3/tests/test_normalization.py new file mode 100644 index 0000000000..19c8cdae92 --- /dev/null +++ b/families/minimax_m3/tests/test_normalization.py @@ -0,0 +1,64 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +"""Check native normalization against the independently checked CPU equations.""" + +import os +import numpy as np +import pytest +import tensorrt as trt +import torch +from cuda.bindings import runtime as cuda + +from families.minimax_m3.graph import Graph +from .reference import norm + + +@pytest.mark.gpu +@pytest.mark.parametrize("width,heads", [(6144, None), (128, 64), (128, 4)]) +def test_bf16_normalization_precision(width, heads): + status, count = cuda.cudaGetDeviceCount() + if int(status) != 0 or count == 0: + pytest.skip("native normalization requires a CUDA GPU") + if not os.environ.get("TRTMC_RUNTIME_ROOT"): + pytest.skip("native normalization requires TRTMC_RUNTIME_ROOT") + shape = (43, width) if heads is None else (2, heads, width) + values = torch.randn(shape, generator=torch.Generator().manual_seed(7042)).bfloat16().float() + weight = torch.randn(width, generator=torch.Generator().manual_seed(7043)) * 0.25 + expected = norm(values.double(), weight.double()).float().bfloat16().float().numpy() + logger = trt.Logger(trt.Logger.ERROR) + builder = trt.Builder(logger) + network = builder.create_network(1 << int(trt.NetworkDefinitionCreationFlag.STRONGLY_TYPED)) + config = builder.create_builder_config() + profile = builder.create_optimization_profile() + graph = Graph(network, profile, 128) + result = graph.norm( + graph.input("hidden", (-1,) + shape[1:]), graph.input("weight", (width,)), width + ) + result.name = "result" + network.mark_output(result) + config.add_optimization_profile(profile) + plan = builder.build_serialized_network(network, config) + assert plan is not None + runtime = trt.Runtime(logger) + engine = runtime.deserialize_cuda_engine(plan) + context = engine.create_execution_context() + assert context.set_input_shape("hidden", shape) + actual = np.empty(shape, dtype=np.float32) + arrays = {"hidden": values.numpy(), "weight": weight.numpy(), "result": actual} + pointers = {} + try: + for name, value in arrays.items(): + status, pointer = cuda.cudaMalloc(value.nbytes) + assert int(status) == 0 + pointers[name] = pointer + assert context.set_tensor_address(name, pointer) + if name != "result": + assert int(cuda.cudaMemcpy(pointer, value.ctypes.data, value.nbytes, 1)[0]) == 0 + assert context.execute_async_v3(0) + assert ( + int(cuda.cudaMemcpy(actual.ctypes.data, pointers["result"], actual.nbytes, 2)[0]) == 0 + ) + np.testing.assert_array_equal(actual, expected) + finally: + for pointer in pointers.values(): + assert int(cuda.cudaFree(pointer)[0]) == 0 diff --git a/families/minimax_m3/tests/test_nv_input.py b/families/minimax_m3/tests/test_nv_input.py new file mode 100644 index 0000000000..a8af950328 --- /dev/null +++ b/families/minimax_m3/tests/test_nv_input.py @@ -0,0 +1,70 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +"""Pinned NVFP4 pre-dispatch recipe, independent dyadic outer-scale fixtures.""" + +import os +import numpy as np +import pytest +import torch +from cuda.bindings import runtime as cuda + +from families.minimax_m3.precision import add_nv_input +from .reference import nv_input_quantize +from .trt_runner import Runner + + +def fixture(): + multipliers = np.array([2.0**-20, 0.5, 1, 1024], dtype=np.float32) + values = np.zeros((4, 6144), np.float32) + values[:, :16] = [ + 0, + 0.25, + 0.75, + 1.25, + 1.75, + 2.5, + 3.5, + 5, + 6, + -0.25, + -0.75, + -1.25, + -1.75, + -2.5, + -3.5, + -5, + ] + values[:, -1] = 2688 + values *= multipliers[:, None] + # Each row has outer scale multiplier, group zero has FP8 scale exactly + # one, and the final group has scale 448. The expected codes follow the + # FP4 round-to-even table directly, with no quantizer implementation used. + expected = np.zeros_like(values) + expected[:, :16] = [0, 0, 1, 1, 2, 2, 4, 4, 6, 0, -1, -1, -2, -2, -4, -4] + expected[:, -1] = 2688 + return values, expected, multipliers[:, None] + + +def test_reference_nv_input_preserves_outer_scale_and_fp4_ties(): + values, expected, outer = fixture() + encoded, actual_outer = nv_input_quantize(torch.from_numpy(values)) + np.testing.assert_array_equal(encoded.numpy(), expected) + np.testing.assert_array_equal(actual_outer.numpy(), outer) + + +@pytest.mark.gpu +def test_native_nv_input_preserves_outer_scale_and_fp4_ties(): + status, count = cuda.cudaGetDeviceCount() + if int(status) != 0 or count == 0: + pytest.skip("NVFP4 pre-dispatch requires a CUDA GPU") + if not os.environ.get("TRTMC_RUNTIME_ROOT"): + pytest.skip("NVFP4 pre-dispatch requires a native precision module") + + def definition(graph): + encoded, outer = add_nv_input(graph.net, graph.input("hidden", (-1, 6144))) + return {"encoded": encoded, "outer": outer} + + values, expected, outer = fixture() + result = Runner(definition)(hidden=values) + np.testing.assert_array_equal(result["encoded"], expected) + np.testing.assert_array_equal(result["outer"], np.broadcast_to(outer, values.shape)) diff --git a/families/minimax_m3/tests/test_projection_precision.py b/families/minimax_m3/tests/test_projection_precision.py new file mode 100644 index 0000000000..7d879507cd --- /dev/null +++ b/families/minimax_m3/tests/test_projection_precision.py @@ -0,0 +1,82 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +"""Exercise exact reduction, cancellation, rounding, and safe fallback on CUDA.""" + +from fractions import Fraction + +import numpy as np +import pytest +import torch +from cuda.bindings import runtime as cuda + +from .trt_runner import Runner + + +@pytest.fixture(scope="module", params=["mx", "nv"]) +def projection(request): + status, count = cuda.cudaGetDeviceCount() + if int(status) != 0 or count == 0: + pytest.skip("projection precision requires a CUDA GPU") + + def definition(graph): + result = graph.projection(graph.input("x", (-1, 128)), "w", 1, 128, request.param) + return {"result": result, "exact": graph.precision_checks[-1]} + + return Runner(definition) + + +@pytest.mark.gpu +@pytest.mark.parametrize("numerator", [337, 335, -337, -335]) +@pytest.mark.parametrize("reverse", [False, True]) +def test_projection_cancellation_and_bf16_ties(projection, numerator, reverse): + x = np.ones((1, 128), np.float32) + w = np.zeros((1, 128), np.float32) + sign = 1 if numerator > 0 else -1 + last = 1 if abs(numerator) == 337 else -1 + # Cancel large terms within one source block. Remaining independent blocks + # form a BF16 midpoint, testing both tie parities and both signs. + w[0, [0, 16, 32, 64, 96]] = [ + sign * 2.0**24, + -sign * 2.0**24, + sign * 5 / 64, + sign / 256, + sign * last / 4096, + ] + exact = sum((Fraction(float(v)) for v in w[0]), Fraction()) + assert exact == Fraction(numerator, 4096) + if reverse: + x, w = x[:, ::-1], w[:, ::-1] + result = projection(x=x, w=w) + assert int(result["exact"]) == 1 + expected = torch.tensor([[float(exact)]]).bfloat16().float().numpy() + np.testing.assert_array_equal(result["result"], expected) + + +@pytest.mark.gpu +def test_unrepresentable_tiny_inputs_use_fp32_fallback(projection): + x = np.zeros((1, 128), np.float32) + w = np.zeros((1, 128), np.float32) + x[0, 0], w[0, 0] = 1e-30, 1 + result = projection(x=x, w=w) + assert int(result["exact"]) == 0 + expected = torch.tensor([[1e-30]]).bfloat16().float().numpy() + np.testing.assert_array_equal(result["result"], expected) + + +@pytest.mark.gpu +def test_nv_outer_scale_precedes_bf16_projection_rounding(): + status, count = cuda.cudaGetDeviceCount() + if int(status) != 0 or count == 0: + pytest.skip("projection precision requires a CUDA GPU") + + def definition(graph): + x = graph.input("x", (-1, 128)) + outer = graph.input("outer", (-1, 1)) + return {"result": graph.projection(x, "w", 1, 128, "nv", outer)} + + w = np.zeros((1, 128), np.float32) + w[0, [0, 1, 2]] = [5 / 64, 1 / 256, 1 / 4096] + outer = torch.tensor([[0.5001]], dtype=torch.float32) + expected = (torch.tensor([[337 / 4096]]) * outer).bfloat16().float().numpy() + actual = Runner(definition)(x=np.ones((1, 128), np.float32), w=w, outer=outer.numpy()) + np.testing.assert_array_equal(actual["result"], expected) diff --git a/families/minimax_m3/tests/test_quantization.py b/families/minimax_m3/tests/test_quantization.py new file mode 100644 index 0000000000..3cda8b3bd9 --- /dev/null +++ b/families/minimax_m3/tests/test_quantization.py @@ -0,0 +1,72 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +"""Exercise BF16 activation scales and exact FP4 midpoint rounding on TensorRT.""" + +import numpy as np +import pytest +import tensorrt as trt +import torch +from cuda.bindings import runtime as cuda + +from families.minimax_m3.graph import Graph +from .reference import quantize + + +def execute(kind, values): + logger = trt.Logger(trt.Logger.ERROR) + builder = trt.Builder(logger) + network = builder.create_network(1 << int(trt.NetworkDefinitionCreationFlag.STRONGLY_TYPED)) + config = builder.create_builder_config() + config.clear_flag(trt.BuilderFlag.TF32) + config.builder_optimization_level = 1 + profile = builder.create_optimization_profile() + graph = Graph(network, profile, 128) + result = graph.quantize(graph.input("hidden", (-1, 6144)), kind) + result.name = "result" + network.mark_output(result) + config.add_optimization_profile(profile) + plan = builder.build_serialized_network(network, config) + assert plan is not None + runtime = trt.Runtime(logger) + engine = runtime.deserialize_cuda_engine(plan) + context = engine.create_execution_context() + assert context.set_input_shape("hidden", values.shape) + actual = np.empty_like(values) + pointers = [] + try: + for name, value in [("hidden", values), ("result", actual)]: + status, pointer = cuda.cudaMalloc(value.nbytes) + assert int(status) == 0 + pointers.append(pointer) + assert context.set_tensor_address(name, pointer) + assert int(cuda.cudaMemcpy(pointers[0], values.ctypes.data, values.nbytes, 1)[0]) == 0 + assert context.execute_async_v3(0) + assert int(cuda.cudaMemcpy(actual.ctypes.data, pointers[1], actual.nbytes, 2)[0]) == 0 + return actual + finally: + for pointer in pointers: + assert int(cuda.cudaFree(pointer)[0]) == 0 + + +@pytest.mark.gpu +@pytest.mark.parametrize("kind", ["nv", "mx"]) +def test_bf16_scale_sweep_and_fp4_round_to_even(kind): + status, count = cuda.cudaGetDeviceCount() + if int(status) != 0 or count == 0: + pytest.skip("TensorRT activation quantization requires a CUDA GPU") + block = 16 if kind == "nv" else 32 + # Every positive BF16 mantissa across 17 exponents, including subnormal + # FP8 scales. NVFP4 inputs include all seven signed rounding midpoints. + maxima = torch.arange(119 * 128, 136 * 128, dtype=torch.int16).view(torch.bfloat16).float() + per_row = 6144 // block + maxima = torch.cat([maxima, maxima[: (-maxima.numel()) % per_row]]) + if kind == "nv": + scales = (maxima / 6).to(torch.float8_e4m3fn).float() + ties = torch.tensor( + [0.25, -0.25, 0.75, -0.75, 1.25, -1.25, 1.75, -1.75, 2.5, -2.5, 3.5, -3.5, 5, -5, 0] + ) + grouped = torch.cat([maxima[:, None], scales[:, None] * ties], -1) + else: + grouped = maxima[:, None] * torch.linspace(-1, 1, block)[None] + values = grouped.to(torch.bfloat16).float().reshape(-1, 6144) + np.testing.assert_array_equal(execute(kind, values.numpy()), quantize(values, kind).numpy()) diff --git a/families/minimax_m3/tests/test_reference_precision.py b/families/minimax_m3/tests/test_reference_precision.py new file mode 100644 index 0000000000..119b7f7a4d --- /dev/null +++ b/families/minimax_m3/tests/test_reference_precision.py @@ -0,0 +1,116 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +"""Independent exact-rational fixtures for projection rounding boundaries.""" + +from fractions import Fraction +from decimal import Decimal, localcontext +from itertools import permutations + +import pytest +import torch + +from .reference import Reference, weighted_expert_sum, routing_scores, routing_weights + + +class FixtureReference(Reference): + def __init__(self, weight): + self.precision = "bf16" + self.fixture_weight = weight + + def weight(self, prefix): + return self.fixture_weight + + +@pytest.mark.parametrize("numerator", [337, 335, -337, -335]) +@pytest.mark.parametrize("reverse", [False, True]) +def test_projection_midpoint_rounding_survives_cancellation(numerator, reverse): + # All nonzero operands have at most four significand bits and can be + # represented by the source MXFP8 format with independent block scales. + # The exact small result survives cancellation of the two large terms. + values = torch.ones((1, 160), dtype=torch.float32) + weight = torch.zeros((1, 160), dtype=torch.float32) + sign = 1 if numerator > 0 else -1 + last = 1 if abs(numerator) == 337 else -1 + weight[0, [0, 32, 64, 96, 128]] = torch.tensor( + [sign * 2.0**24, sign * 5 / 64, sign / 256, sign * last / 4096, -sign * 2.0**24] + ) + exact = sum( + (Fraction(float(a)) * Fraction(float(b)) for a, b in zip(values[0], weight[0])), + Fraction(), + ) + assert exact == Fraction(numerator, 4096) + if reverse: + values, weight = values.flip(-1), weight.flip(-1) + expected = torch.tensor([[float(exact)]], dtype=torch.float32).to(torch.bfloat16).float() + actual = FixtureReference(weight).linear(values, "projection") + torch.testing.assert_close(actual, expected, rtol=0, atol=0) + + +@pytest.mark.parametrize( + "row,column,expected", [(3, 4412, 0.88671875), (14, 3003, -0.83203125), (42, 1891, 0.328125)] +) +def test_normalization_matches_independent_decimal_equations(row, column, expected): + values = torch.randn((43, 6144), generator=torch.Generator().manual_seed(7042)) + values = values.bfloat16().float()[row : row + 1] + weight = torch.randn(6144, generator=torch.Generator().manual_seed(7043)) * 0.25 + variance = sum((Fraction(float(x)) ** 2 for x in values[0]), Fraction()) / 6144 + variance += Fraction(1, 1_000_000) + numerator = Fraction(float(values[0, column])) * (1 + Fraction(float(weight[column]))) + with localcontext() as context: + context.prec = 80 + precise = (Decimal(numerator.numerator) / Decimal(numerator.denominator)) / ( + Decimal(variance.numerator) / Decimal(variance.denominator) + ).sqrt() + wanted = torch.tensor(float(precise), dtype=torch.float32).bfloat16().float() + assert wanted.item() == expected + actual = FixtureReference(weight).normalize(values, weight)[0, column] + torch.testing.assert_close(actual, wanted, rtol=0, atol=0) + + +@pytest.mark.parametrize("order", list(permutations(range(4)))) +def test_weighted_expert_sum_matches_exact_rational_value(order): + values = [-0.1015625, -0.064453125, -0.0284423828125, -0.373046875] + weights = [0.6337959170341492, 0.45559805631637573, 0.5365517139434814, 0.3740541934967041] + exact = sum((Fraction(x) * Fraction(w) for x, w in zip(values, weights)), Fraction()) + assert exact == Fraction(-8539603537, 34359738368) + actual = weighted_expert_sum( + torch.tensor([[[values[i]] for i in order]], dtype=torch.float32), + torch.tensor([[weights[i] for i in order]], dtype=torch.float32), + ) + expected = torch.tensor([[float(exact)]], dtype=torch.float32) + torch.testing.assert_close(actual, expected, rtol=0, atol=0) + assert actual.bfloat16().item() == -0.2490234375 + + +@pytest.mark.parametrize("logit", [-2.0, -0.5, 0.0, 0.5, 2.0]) +def test_routing_sigmoid_matches_decimal(logit): + with localcontext() as context: + context.prec = 80 + expected = float(1 / (1 + (-Decimal(logit)).exp())) + actual = routing_scores(torch.tensor([logit], dtype=torch.float32)) + torch.testing.assert_close(actual, torch.tensor([expected]), rtol=0, atol=0) + + +def test_routing_normalization_matches_exact_rational_arithmetic(): + values = [0.125, 0.734375, 0.0078125, 0.9921875] + exact = [Fraction(x) for x in values] + expected = torch.tensor([[float(2 * value / sum(exact)) for value in exact]]) + actual = routing_weights(torch.tensor([values])) + torch.testing.assert_close(actual, expected, rtol=0, atol=0) + + +def test_router_dot_retains_small_term_after_exact_cancellation(): + weight = torch.tensor([[2.0**24, 1.0, -(2.0**24)]]) + actual = FixtureReference(weight).linear(torch.ones((1, 3)), "layer.block_sparse_moe.gate") + torch.testing.assert_close(actual, torch.tensor([[1.0]]), rtol=0, atol=0) + + +def test_projection_outer_scale_is_applied_before_bf16_rounding(): + values = torch.ones((1, 3)) + weight = torch.tensor([[5 / 64, 1 / 256, 1 / 4096]]) + outer = torch.tensor([[0.5001]], dtype=torch.float32) + actual = FixtureReference(weight).linear(values, "expert.w1", outer) + exact_dot = torch.tensor([[337 / 4096]], dtype=torch.float32) + expected = (exact_dot * outer).bfloat16().float() + torch.testing.assert_close(actual, expected, rtol=0, atol=0) + assert actual.item() != (exact_dot.bfloat16().float() * outer).bfloat16().item() diff --git a/families/minimax_m3/tests/test_rope_precision.py b/families/minimax_m3/tests/test_rope_precision.py new file mode 100644 index 0000000000..02132d0288 --- /dev/null +++ b/families/minimax_m3/tests/test_rope_precision.py @@ -0,0 +1,74 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +"""Decimal phase tables and exact-rational rotation, independent of the graph.""" + +from decimal import Decimal, localcontext +from fractions import Fraction +import os + +import numpy as np +import pytest +import torch +from cuda.bindings import runtime as cuda + +from .reference import Reference +from .trt_runner import Runner + + +def decimal_coefficients(position, frequency): + with localcontext() as context: + context.prec = 80 + phase = Decimal(position) / (Decimal(10_000_000) ** (Decimal(2 * frequency) / 64)) + cosine, sine = Decimal(1), phase + cos_term, sin_term = Decimal(1), phase + for index in range(1, 80): + cos_term *= -(phase * phase) / ((2 * index - 1) * (2 * index)) + sin_term *= -(phase * phase) / ((2 * index) * (2 * index + 1)) + cosine += cos_term + sine += sin_term + return [float(torch.tensor(float(x), dtype=torch.float32)) for x in (cosine, sine)] + + +@pytest.mark.parametrize( + "position,frequency,left,right", + [ + (4, 6, -0.376953125, 0.298828125), + (1, 0, 32768, 32768), + (2, 12, 31.75, -12.125), + ], +) +def test_reference_rotation_matches_decimal_table_and_exact_products( + position, frequency, left, right +): + values = torch.zeros((position + 1, 1, 128), dtype=torch.float32) + values[position, 0, frequency] = left + values[position, 0, frequency + 32] = right + c, s = map(Fraction, decimal_coefficients(position, frequency)) + expected = [Fraction(left) * c - Fraction(right) * s, Fraction(right) * c + Fraction(left) * s] + wanted = torch.tensor([float(x) for x in expected], dtype=torch.float32) + actual = Reference.rope(values)[position, 0, [frequency, frequency + 32]] + torch.testing.assert_close(actual, wanted, rtol=0, atol=0) + if position == 4: + assert actual[1].bfloat16().item() == 0.2197265625 + + +@pytest.mark.gpu +@pytest.mark.parametrize("heads", [4, 64]) +def test_native_rotation_matches_independent_reference_across_capacity(heads): + status, count = cuda.cudaGetDeviceCount() + if int(status) != 0 or count == 0: + pytest.skip("rotary precision requires a CUDA GPU") + if not os.environ.get("TRTMC_RUNTIME_ROOT"): + pytest.skip("rotary precision requires the native precision module") + + def definition(graph): + return {"result": graph.rope(graph.input("hidden", (-1, heads, 128)), heads)} + + values = ( + torch.randn((128, heads, 128), generator=torch.Generator().manual_seed(7048)) + .bfloat16() + .float() + ) + expected = Reference.rope(values).bfloat16().float().numpy() + actual = Runner(definition)(hidden=values.numpy())["result"] + np.testing.assert_array_equal(actual, expected) diff --git a/families/minimax_m3/tests/test_routing_precision.py b/families/minimax_m3/tests/test_routing_precision.py new file mode 100644 index 0000000000..af57beb5ef --- /dev/null +++ b/families/minimax_m3/tests/test_routing_precision.py @@ -0,0 +1,84 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +"""CUDA reductions checked against independent exact and Decimal equations.""" + +from decimal import Decimal, localcontext +from fractions import Fraction +from itertools import permutations +import os + +import numpy as np +import pytest +from cuda.bindings import runtime as cuda + +from families.minimax_m3.precision import add_precision_kernel +from .trt_runner import Runner + + +@pytest.fixture(scope="module", autouse=True) +def native_precision(): + status, count = cuda.cudaGetDeviceCount() + if int(status) != 0 or count == 0: + pytest.skip("routing precision requires a CUDA GPU") + if not os.environ.get("TRTMC_RUNTIME_ROOT"): + pytest.skip("routing precision requires TRTMC_RUNTIME_ROOT") + + +@pytest.mark.gpu +def test_expert_merge_is_invariant_to_slot_order(): + runner = Runner(lambda graph: graph.merge()) + values = [-0.1015625, -0.064453125, -0.0284423828125, -0.373046875] + weights = [0.6337959170341492, 0.45559805631637573, 0.5365517139434814, 0.3740541934967041] + exact = sum((Fraction(x) * Fraction(w) for x, w in zip(values, weights)), Fraction()) + assert exact == Fraction(-8539603537, 34359738368) + for order in permutations(range(4)): + result = runner( + residual=np.zeros((1, 6144), np.float32), + base=np.zeros((1, 6144), np.float32), + values=np.broadcast_to( + np.array([values[i] for i in order], np.float32)[None, :, None], (1, 4, 6144) + ), + weights=np.array([[weights[i] for i in order]], np.float32), + )["result"] + np.testing.assert_array_equal(result, np.full((1, 6144), -0.2490234375, np.float32)) + + +@pytest.mark.gpu +def test_routing_scores_match_decimal_sigmoid_after_exact_dot(): + def definition(graph): + hidden = graph.input("hidden", (-1, 6144)) + weight = graph.input("weight", (128, 6144)) + return { + "scores": add_precision_kernel( + graph.net, "router_scores", [graph.mm(hidden, weight), hidden, weight] + ) + } + + runner = Runner(definition) + hidden = np.ones((1, 6144), np.float32) + weight = np.zeros((128, 6144), np.float32) + expected = np.empty((1, 128), np.float32) + for row in range(128): + weight[row, [0, 1, 32]] = [2.0**24, (row - 64) / 32, -(2.0**24)] + exact = sum((Fraction(float(v)) for v in weight[row]), Fraction()) + with localcontext() as context: + context.prec = 80 + logit = Decimal(exact.numerator) / Decimal(exact.denominator) + expected[0, row] = float(1 / (1 + (-logit).exp())) + np.testing.assert_array_equal(runner(hidden=hidden, weight=weight)["scores"], expected) + + +@pytest.mark.gpu +def test_routing_weights_match_exact_rational_normalization(): + def definition(graph): + selected = graph.input("selected", (-1, 4)) + return {"weights": add_precision_kernel(graph.net, "router_weights", [selected])} + + runner = Runner(definition) + selected = np.array(list(permutations([0.125, 0.734375, 0.0078125, 0.9921875])), np.float32) + expected = np.empty_like(selected) + for row, values in enumerate(selected): + exact = [Fraction(float(v)) for v in values] + for slot, value in enumerate(exact): + expected[row, slot] = float(2 * value / sum(exact)) + np.testing.assert_array_equal(runner(selected=selected)["weights"], expected) diff --git a/families/minimax_m3/tests/test_support.py b/families/minimax_m3/tests/test_support.py new file mode 100644 index 0000000000..7df63e5619 --- /dev/null +++ b/families/minimax_m3/tests/test_support.py @@ -0,0 +1,30 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +import json +from pathlib import Path +import pytest +from tensorrt_model_connect.model_support import ModelMetadata, resolve_family +from families.minimax_m3.support import describe + + +def test_published_checkpoint_has_one_owner(): + config = json.loads((Path(__file__).parent / "fixtures/config.json").read_text()) + family, support = resolve_family(ModelMetadata(config=config, model_index={})) + assert family == "minimax_m3" + assert support.default_task == "text_continuation" + assert support.tasks == ("text_continuation",) + assert support.default_precision == "bf16" + + +@pytest.mark.parametrize( + "config", + [ + {"model_type": "minimax_music3"}, + {"model_type": "minimax_h3"}, + {"model_type": "minimax_m2"}, + {"architectures": ["LlamaForCausalLM"]}, + {}, + ], +) +def test_unrelated_model_metadata_is_not_owned(config): + assert describe(ModelMetadata(config=config, model_index={})) is None diff --git a/families/minimax_m3/tests/tokenizer_consumer.cpp b/families/minimax_m3/tests/tokenizer_consumer.cpp new file mode 100644 index 0000000000..ea4c37ed5b --- /dev/null +++ b/families/minimax_m3/tests/tokenizer_consumer.cpp @@ -0,0 +1,32 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + */ +#include "families/minimax_m3/runtime/tokenizer.h" + +#include +#include +#include +int main(int argc, char** argv) { + if (argc != 3) + return 2; + try { + std::ifstream input(argv[1], std::ios::binary); + std::string raw((std::istreambuf_iterator(input)), {}); + auto tokenizer = trtmc::CreateBpeTokenizer(raw.data(), raw.size(), false); + std::ifstream requests(argv[2]); + nlohmann::json samples; + requests >> samples; + nlohmann::json result = nlohmann::json::array(); + for (const auto& sample : samples) { + auto ids = sample.is_array() ? sample.get>() + : tokenizer->encode(sample.get()); + result.push_back({{"ids", ids}, {"decoded", tokenizer->decode(ids)}}); + } + std::cout << result.dump() << '\n'; + return 0; + } catch (const std::exception& error) { + std::cerr << error.what() << '\n'; + return 1; + } +} diff --git a/families/minimax_m3/tests/trt_runner.py b/families/minimax_m3/tests/trt_runner.py new file mode 100644 index 0000000000..ff945384d8 --- /dev/null +++ b/families/minimax_m3/tests/trt_runner.py @@ -0,0 +1,63 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +"""Small family-local TensorRT executor for precision regression tests.""" + +import numpy as np +import tensorrt as trt +from cuda.bindings import runtime as cuda +from families.minimax_m3.graph import Graph + + +class Runner: + def __init__(self, definition): + self.logger = trt.Logger(trt.Logger.ERROR) + builder = trt.Builder(self.logger) + network = builder.create_network(1 << int(trt.NetworkDefinitionCreationFlag.STRONGLY_TYPED)) + settings = builder.create_builder_config() + settings.clear_flag(trt.BuilderFlag.TF32) + settings.builder_optimization_level = 1 + settings.max_aux_streams = 0 + settings.set_memory_pool_limit(trt.MemoryPoolType.WORKSPACE, 8 << 30) + profile = builder.create_optimization_profile() + graph = Graph(network, profile, 128) + for name, value in definition(graph).items(): + value.name = name + network.mark_output(value) + settings.add_optimization_profile(profile) + self.plan = builder.build_serialized_network(network, settings) + assert self.plan is not None + self.runtime = trt.Runtime(self.logger) + self.engine = self.runtime.deserialize_cuda_engine(self.plan) + self.context = self.engine.create_execution_context() + + def __call__(self, **inputs): + arrays = {k: np.ascontiguousarray(v) for k, v in inputs.items()} + for name, value in arrays.items(): + assert self.context.set_input_shape(name, value.shape) + for i in range(self.engine.num_io_tensors): + name = self.engine.get_tensor_name(i) + if name not in arrays: + arrays[name] = np.empty( + self.context.get_tensor_shape(name), + dtype=trt.nptype(self.engine.get_tensor_dtype(name)), + ) + pointers = {} + try: + for name, value in arrays.items(): + status, pointer = cuda.cudaMalloc(value.nbytes) + assert int(status) == 0 + pointers[name] = pointer + assert self.context.set_tensor_address(name, pointer) + if name in inputs: + assert int(cuda.cudaMemcpy(pointer, value.ctypes.data, value.nbytes, 1)[0]) == 0 + assert self.context.execute_async_v3(0) + for name, value in arrays.items(): + if name not in inputs: + assert ( + int(cuda.cudaMemcpy(value.ctypes.data, pointers[name], value.nbytes, 2)[0]) + == 0 + ) + return {k: v for k, v in arrays.items() if k not in inputs} + finally: + for pointer in pointers.values(): + assert int(cuda.cudaFree(pointer)[0]) == 0 diff --git a/website/data/hf-model-metadata.json b/website/data/hf-model-metadata.json index cff1f5d540..647ed51918 100644 --- a/website/data/hf-model-metadata.json +++ b/website/data/hf-model-metadata.json @@ -1711,6 +1711,17 @@ "EsmcForMaskedLM" ], "architecture_source": "config.architectures" + }, + { + "hf_id": "MiniMaxAI/MiniMax-M3.1-Flash", + "revision": "ce7f4df87d2e05262f5775f373dac4772f134041", + "revision_source": "resolved", + "metadata_file": "config.json", + "model_type": "minimax_m3_vl", + "architectures": [ + "MiniMaxM3SparseForConditionalGeneration" + ], + "architecture_source": "config.architectures" } ] } From 67057588ccf96c836d6a53c27e54ad256d05fa0b Mon Sep 17 00:00:00 2001 From: Will Guo Date: Mon, 30 Nov 2026 00:47:28 -0800 Subject: [PATCH 02/10] fix(minimax_m3): link logits JSON dependency The logits consumer includes JSON through the family weight header. Link the JSON target explicitly so builds with a separately installed header prefix find it. Native targets and all 115 family tests pass locally. Signed-off-by: Will Guo --- families/minimax_m3/runtime/CMakeLists.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/families/minimax_m3/runtime/CMakeLists.txt b/families/minimax_m3/runtime/CMakeLists.txt index 674dd1aa04..2d66d0296c 100644 --- a/families/minimax_m3/runtime/CMakeLists.txt +++ b/families/minimax_m3/runtime/CMakeLists.txt @@ -30,7 +30,7 @@ if(TRTMC_BUILD_TESTS) add_executable(test_minimax_m3_logits ${PROJECT_SOURCE_DIR}/families/minimax_m3/tests/logits_consumer.cpp) target_include_directories(test_minimax_m3_logits PRIVATE ${PROJECT_SOURCE_DIR} ${PROJECT_SOURCE_DIR}/core/runtime/include) target_include_directories(test_minimax_m3_logits SYSTEM PRIVATE ${TRTMC_CUDA_INCLUDE_DIR}) - target_link_libraries(test_minimax_m3_logits PRIVATE trtmc_model_minimax_m3 trtmc_core ${CMAKE_DL_LIBS}) + target_link_libraries(test_minimax_m3_logits PRIVATE trtmc_model_minimax_m3 trtmc_core nlohmann_json::nlohmann_json ${CMAKE_DL_LIBS}) set_target_properties(test_minimax_m3_logits PROPERTIES RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}") foreach(_language IN ITEMS c cpp) add_executable(test_minimax_m3_sdk_${_language} ${PROJECT_SOURCE_DIR}/families/minimax_m3/tests/sdk_consumer.${_language}) From 342e1c4a6a8dfbba56834ce9bac54db5377687a3 Mon Sep 17 00:00:00 2001 From: Will Guo Date: Mon, 30 Nov 2026 01:13:03 -0800 Subject: [PATCH 03/10] fix(minimax_m3): report declared E2E case ID Parameterize the existing checkpoint test with its manifest case name so result validation can identify the executed workload. Update the existing selector checks for the renamed function. All 16 E2E assertions are preserved; nine selector tests and collection of the declared case pass locally. Signed-off-by: Will Guo --- families/minimax_m3/tests/test_e2e.py | 7 +++++-- families/minimax_m3/tests/test_e2e_selection.py | 12 +++++++++--- 2 files changed, 14 insertions(+), 5 deletions(-) diff --git a/families/minimax_m3/tests/test_e2e.py b/families/minimax_m3/tests/test_e2e.py index 1ac142ee87..26e7207868 100644 --- a/families/minimax_m3/tests/test_e2e.py +++ b/families/minimax_m3/tests/test_e2e.py @@ -47,7 +47,10 @@ def compare(actual, expected): ) -def test_full_checkpoint_native_continuation(pytestconfig, tmp_path): +@pytest.mark.e2e +@pytest.mark.gpu +@pytest.mark.parametrize("case_name", [case["name"] for case in MANIFEST["testcases"]]) +def test_full_checkpoint_native_continuation_e2e(pytestconfig, tmp_path, case_name): selected = [] for name in ["--e2e-model", "--e2e-testcase"]: selected.extend( @@ -88,7 +91,7 @@ def test_full_checkpoint_native_continuation(pytestconfig, tmp_path): tensor_parallel_size=MANIFEST["tensor_parallel_size"], ) ) - case = MANIFEST["testcases"][0] + case = next(case for case in MANIFEST["testcases"] if case["name"] == case_name) assert case["max_new_tokens"] == 1 tokenizer = Tokenizer.from_file(str(checkpoint / "tokenizer.json")) texts = [ diff --git a/families/minimax_m3/tests/test_e2e_selection.py b/families/minimax_m3/tests/test_e2e_selection.py index 1c403962d9..b86cb18924 100644 --- a/families/minimax_m3/tests/test_e2e_selection.py +++ b/families/minimax_m3/tests/test_e2e_selection.py @@ -37,7 +37,9 @@ def required(name): def test_explicit_selection_reaches_checkpoint(checkpoint_boundary, tmp_path, option, values): config = SimpleNamespace(getoption=lambda name: values if name == option else None) with pytest.raises(CheckpointRequested): - owning.test_full_checkpoint_native_continuation(config, tmp_path) + owning.test_full_checkpoint_native_continuation_e2e( + config, tmp_path, owning.MANIFEST["testcases"][0]["name"] + ) def test_testcase_selection_file_reaches_checkpoint(checkpoint_boundary, tmp_path): @@ -47,7 +49,9 @@ def test_testcase_selection_file_reaches_checkpoint(checkpoint_boundary, tmp_pat getoption=lambda name: str(selection) if name == "--e2e-models-file" else None ) with pytest.raises(CheckpointRequested): - owning.test_full_checkpoint_native_continuation(config, tmp_path) + owning.test_full_checkpoint_native_continuation_e2e( + config, tmp_path, owning.MANIFEST["testcases"][0]["name"] + ) @pytest.mark.parametrize( @@ -56,4 +60,6 @@ def test_testcase_selection_file_reaches_checkpoint(checkpoint_boundary, tmp_pat def test_unselected_case_skips_before_checkpoint(checkpoint_boundary, tmp_path, options): config = SimpleNamespace(getoption=options.get) with pytest.raises(pytest.skip.Exception): - owning.test_full_checkpoint_native_continuation(config, tmp_path) + owning.test_full_checkpoint_native_continuation_e2e( + config, tmp_path, owning.MANIFEST["testcases"][0]["name"] + ) From c8906bba1097025f7ff73340b62ba9841e6738e4 Mon Sep 17 00:00:00 2001 From: Will Guo Date: Mon, 30 Nov 2026 18:10:42 -0800 Subject: [PATCH 04/10] fix(minimax_m3): tighten precision and tokenizer checks Remove dead regex rewriting and unsafe half type punning. Strengthen per-channel precision checks and cleanup, document invalid zero-mass routing, and preserve raw added-token decoding. Signed-off-by: Will Guo --- families/minimax_m3/README.md | 7 +++- families/minimax_m3/runtime/bpe_tokenizer.cpp | 22 ++++------- families/minimax_m3/runtime/precision.cu | 2 +- .../tests/test_attention_precision.py | 27 ++++++++----- .../minimax_m3/tests/test_normalization.py | 4 +- .../minimax_m3/tests/test_quantization.py | 4 +- .../tests/test_routing_precision.py | 16 ++++++++ families/minimax_m3/tests/test_tokenizer.py | 39 +++++++++++++++++++ families/minimax_m3/tests/trt_runner.py | 4 +- 9 files changed, 94 insertions(+), 31 deletions(-) create mode 100644 families/minimax_m3/tests/test_tokenizer.py diff --git a/families/minimax_m3/README.md b/families/minimax_m3/README.md index 4f9c838d4b..8ed3b13c60 100644 --- a/families/minimax_m3/README.md +++ b/families/minimax_m3/README.md @@ -22,7 +22,7 @@ family-specific Python package installation is required. cmake -S . -B build -DTRTMC_ENABLE_BYOK=ON -DTRTMC_BUILD_TESTS=ON cmake --build build --parallel 12 --target \ trtmc trtmc_backend_trt trtmc_model_minimax_m3 \ - test_minimax_m3_sdk_c test_minimax_m3_sdk_cpp + test_minimax_m3_sdk_c test_minimax_m3_sdk_cpp test_bundle_format_v1 export PYTHONPATH=core/builder:apps/benchmark:. export LD_LIBRARY_PATH="$PWD/build${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}" python -m tensorrt_model_connect build MiniMaxAI/MiniMax-M3.1-Flash \ @@ -68,6 +68,10 @@ static activation global scale. Dyadic regression cases cover multiple token amplitudes, including inputs that a missing outer multiplier collapses to zero. This follows the pre-dispatch contract in SGLang's pinned `sgl-deep-gemm==0.2.7`. +A router row with no representable positive score mass has no normalized +mixture. The native Task rejects its nonfinite routing weights; it does not +substitute a uniform mixture or change the independent reference equation. + All 60 decoder layers, 128 routed experts per MoE layer, the four-expert router, shared experts, Gemma RMS norms, partial RoPE, and the checkpoint's clipped SwiGLU-OAI activation are retained. For prefixes within one 128-token block, @@ -110,6 +114,7 @@ decoded text are compared against the checkpoint tokenizer on English, Arabic, Chinese, normalization, whitespace, number, contraction, and special-token cases. ```bash +export LD_LIBRARY_PATH="$PWD/build${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}" export TRTMC_BINARY="$PWD/build/trtmc" export TRTMC_RUNTIME_ROOT="$PWD/build" export TRTMC_NATIVE_BUILD_DIR="$PWD/build" diff --git a/families/minimax_m3/runtime/bpe_tokenizer.cpp b/families/minimax_m3/runtime/bpe_tokenizer.cpp index 361e82b8a1..dccf4c0b82 100644 --- a/families/minimax_m3/runtime/bpe_tokenizer.cpp +++ b/families/minimax_m3/runtime/bpe_tokenizer.cpp @@ -84,17 +84,6 @@ class Tokenizer final : public ITokenizer { pre.at(1).at("use_regex").get()) throw std::runtime_error("unsupported MiniMax pre-tokenizer contract"); std::string pattern = pre.at(0).at("pattern").at("Regex"); - // The published converter serializes this O200K pattern with doubled - // escapes. tokenizers treats these as the underlying regex escapes. - if (pattern.find("\\\\p") != std::string::npos) { - std::string decoded; - for (std::size_t i = 0; i < pattern.size(); ++i) { - if (pattern[i] == '\\' && i + 1 < pattern.size() && pattern[i + 1] == '\\') - ++i; - decoded.push_back(pattern[i]); - } - pattern = std::move(decoded); - } UErrorCode status = U_ZERO_ERROR; pattern_.reset( icu::RegexPattern::compile(icu::UnicodeString::fromUTF8(pattern), 0, status)); @@ -136,14 +125,19 @@ class Tokenizer final : public ITokenizer { const auto& piece = pieces_.at(id); const auto* data = reinterpret_cast(piece.data()); int32_t at = 0; + std::string decoded_piece; + bool byte_level = true; while (at < static_cast(piece.size())) { UChar32 point; U8_NEXT(data, at, static_cast(piece.size()), point); const auto found = inverse_.find(point); - if (found == inverse_.end()) - throw std::runtime_error("invalid MiniMax byte-level vocabulary piece"); - result.push_back(static_cast(found->second)); + if (found == inverse_.end()) { + byte_level = false; + break; + } + decoded_piece.push_back(static_cast(found->second)); } + result += byte_level ? decoded_piece : piece; } // Byte-level tokens can end partway through a UTF-8 character. Match // the checkpoint decoder's replacement of malformed byte sequences. diff --git a/families/minimax_m3/runtime/precision.cu b/families/minimax_m3/runtime/precision.cu index 902468a0e2..6e3cb24876 100644 --- a/families/minimax_m3/runtime/precision.cu +++ b/families/minimax_m3/runtime/precision.cu @@ -290,7 +290,7 @@ __global__ void nv_input_quantize(const float* input, float* encoded, float* out const float raw_scale = __fdiv_rn(group_maximum, __fmul_rn(6.0f, multiplier)); const auto sf_byte = __nv_cvt_float_to_fp8(raw_scale, __NV_SATFINITE, __NV_E4M3); const auto sf_half = __nv_cvt_fp8_to_halfraw(sf_byte, __NV_E4M3); - const float scale = __half2float(*reinterpret_cast(&sf_half)); + const float scale = __half2float(__half{sf_half}); // Compare exact dyadic boundaries in FP64, avoiding reciprocal noise // crossing a FP4 tie. No rounding to BF16 occurs before this quantizer. const double quantum = diff --git a/families/minimax_m3/tests/test_attention_precision.py b/families/minimax_m3/tests/test_attention_precision.py index a87640fc36..3cbc8d4d79 100644 --- a/families/minimax_m3/tests/test_attention_precision.py +++ b/families/minimax_m3/tests/test_attention_precision.py @@ -43,7 +43,9 @@ def test_attention_matches_decimal_probabilities_and_exact_weighted_sum(attentio query[row, :, 0] = 0 if uniform else row + 1 for head in range(4): key[row, head, 0] = (row - 1) * (head + 1) / 4 - values[row, head, :] = (row * 3 - 2) * (head + 1) / 8 + values[row, head, :] = (row * 3 - 2) * (head + 1) / 8 + np.arange( + 128, dtype=np.float32 + ) / 512 for row in range(3): for head in range(64): scores = [ @@ -55,15 +57,22 @@ def test_attention_matches_decimal_probabilities_and_exact_weighted_sum(attentio exponents = [Decimal(float(s)).exp() for s in scores] total = sum(exponents) probabilities = [np.float32(float(e / total)) for e in exponents] - exact = sum( - ( - Fraction(float(probabilities[p])) * Fraction(float(values[p, head // 16, 0])) - for p in range(row + 1) - ), - Fraction(), - ) + exact = [ + sum( + ( + Fraction(float(probabilities[p])) + * Fraction(float(values[p, head // 16, channel])) + for p in range(row + 1) + ), + Fraction(), + ) + for channel in range(128) + ] expected[row, head, :] = ( - torch.tensor(float(exact), dtype=torch.float32).bfloat16().float().item() + torch.tensor([float(value) for value in exact], dtype=torch.float32) + .bfloat16() + .float() + .numpy() ) actual = attention(query=query, key=key, value=values)["result"] np.testing.assert_array_equal(actual, expected) diff --git a/families/minimax_m3/tests/test_normalization.py b/families/minimax_m3/tests/test_normalization.py index 19c8cdae92..0f4843404e 100644 --- a/families/minimax_m3/tests/test_normalization.py +++ b/families/minimax_m3/tests/test_normalization.py @@ -60,5 +60,5 @@ def test_bf16_normalization_precision(width, heads): ) np.testing.assert_array_equal(actual, expected) finally: - for pointer in pointers.values(): - assert int(cuda.cudaFree(pointer)[0]) == 0 + free_statuses = [int(cuda.cudaFree(pointer)[0]) for pointer in pointers.values()] + assert all(status == 0 for status in free_statuses), free_statuses diff --git a/families/minimax_m3/tests/test_quantization.py b/families/minimax_m3/tests/test_quantization.py index 3cda8b3bd9..e4a7cf7f6a 100644 --- a/families/minimax_m3/tests/test_quantization.py +++ b/families/minimax_m3/tests/test_quantization.py @@ -44,8 +44,8 @@ def execute(kind, values): assert int(cuda.cudaMemcpy(actual.ctypes.data, pointers[1], actual.nbytes, 2)[0]) == 0 return actual finally: - for pointer in pointers: - assert int(cuda.cudaFree(pointer)[0]) == 0 + free_statuses = [int(cuda.cudaFree(pointer)[0]) for pointer in pointers] + assert all(status == 0 for status in free_statuses), free_statuses @pytest.mark.gpu diff --git a/families/minimax_m3/tests/test_routing_precision.py b/families/minimax_m3/tests/test_routing_precision.py index af57beb5ef..c3499d8d01 100644 --- a/families/minimax_m3/tests/test_routing_precision.py +++ b/families/minimax_m3/tests/test_routing_precision.py @@ -9,6 +9,7 @@ import numpy as np import pytest +import torch from cuda.bindings import runtime as cuda from families.minimax_m3.precision import add_precision_kernel @@ -82,3 +83,18 @@ def definition(graph): for slot, value in enumerate(exact): expected[row, slot] = float(2 * value / sum(exact)) np.testing.assert_array_equal(runner(selected=selected)["weights"], expected) + + +@pytest.mark.gpu +def test_zero_mass_router_row_remains_invalid(): + from .reference import routing_weights + + def definition(graph): + selected = graph.input("selected", (-1, 4)) + return {"weights": add_precision_kernel(graph.net, "router_weights", [selected])} + + selected = np.zeros((1, 4), np.float32) + actual = Runner(definition)(selected=selected)["weights"] + expected = routing_weights(torch.from_numpy(selected)).numpy() + assert not np.isfinite(actual).any() + assert not np.isfinite(expected).any() diff --git a/families/minimax_m3/tests/test_tokenizer.py b/families/minimax_m3/tests/test_tokenizer.py new file mode 100644 index 0000000000..c0217a3048 --- /dev/null +++ b/families/minimax_m3/tests/test_tokenizer.py @@ -0,0 +1,39 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +"""Native ByteLevel decoding against the independent Rust tokenizer.""" + +import json +import os +from pathlib import Path +import subprocess + +import pytest +from tokenizers import AddedToken, Regex, Tokenizer, decoders, models, normalizers, pre_tokenizers + + +@pytest.mark.parametrize("piece", [" ", "a b", "λ", "你好", "Ġλ"]) +def test_non_special_added_piece_uses_bytelevel_decoder_fallback(tmp_path, piece): + reference = Tokenizer(models.BPE(vocab={"a": 0}, merges=[])) + reference.normalizer = normalizers.NFC() + reference.pre_tokenizer = pre_tokenizers.Sequence( + [ + pre_tokenizers.Split(Regex(r"[\s\S]+"), behavior="removed", invert=True), + pre_tokenizers.ByteLevel(add_prefix_space=False, use_regex=False), + ] + ) + reference.decoder = decoders.ByteLevel() + reference.add_tokens([AddedToken(piece, normalized=False)]) + tokenizer = tmp_path / "tokenizer.json" + tokenizer.write_text(reference.to_str()) + token = reference.token_to_id(piece) + requests = [[token], [0, token, 0]] + path = tmp_path / "requests.json" + path.write_text(json.dumps(requests)) + binary = Path(os.environ["TRTMC_NATIVE_BUILD_DIR"]) / "test_minimax_m3_tokenizer" + completed = subprocess.run( + [str(binary), str(tokenizer), str(path)], capture_output=True, text=True, check=True + ) + actual = json.loads(completed.stdout) + assert [item["decoded"] for item in actual] == [ + reference.decode(ids, skip_special_tokens=True) for ids in requests + ] diff --git a/families/minimax_m3/tests/trt_runner.py b/families/minimax_m3/tests/trt_runner.py index ff945384d8..795f0a12ec 100644 --- a/families/minimax_m3/tests/trt_runner.py +++ b/families/minimax_m3/tests/trt_runner.py @@ -59,5 +59,5 @@ def __call__(self, **inputs): ) return {k: v for k, v in arrays.items() if k not in inputs} finally: - for pointer in pointers.values(): - assert int(cuda.cudaFree(pointer)[0]) == 0 + free_statuses = [int(cuda.cudaFree(pointer)[0]) for pointer in pointers.values()] + assert all(status == 0 for status in free_statuses), free_statuses From 3fd71179b923c4750c26fc4b65ddb2bd97317044 Mon Sep 17 00:00:00 2001 From: Will Guo Date: Mon, 30 Nov 2026 18:18:25 -0800 Subject: [PATCH 05/10] fix(minimax_m3): build native tokenizer test consumers Build family-owned test helpers during fixture setup so native regressions also work in a freshly configured build tree. Keep runtime execution and numerical checks unchanged. Signed-off-by: Will Guo --- families/minimax_m3/tests/test_tokenizer.py | 29 ++++++++++++++++++--- 1 file changed, 26 insertions(+), 3 deletions(-) diff --git a/families/minimax_m3/tests/test_tokenizer.py b/families/minimax_m3/tests/test_tokenizer.py index c0217a3048..1129c275d6 100644 --- a/families/minimax_m3/tests/test_tokenizer.py +++ b/families/minimax_m3/tests/test_tokenizer.py @@ -11,8 +11,29 @@ from tokenizers import AddedToken, Regex, Tokenizer, decoders, models, normalizers, pre_tokenizers +@pytest.fixture(scope="module") +def tokenizer_binary(): + build = Path(os.environ["TRTMC_NATIVE_BUILD_DIR"]) + subprocess.run( + [ + "cmake", + "--build", + str(build), + "--parallel", + "2", + "--target", + "test_minimax_m3_tokenizer", + ], + check=True, + timeout=600, + ) + binary = build / "test_minimax_m3_tokenizer" + assert binary.is_file(), "native tokenizer consumer was not built" + return binary + + @pytest.mark.parametrize("piece", [" ", "a b", "λ", "你好", "Ġλ"]) -def test_non_special_added_piece_uses_bytelevel_decoder_fallback(tmp_path, piece): +def test_non_special_added_piece_uses_bytelevel_decoder_fallback(tmp_path, piece, tokenizer_binary): reference = Tokenizer(models.BPE(vocab={"a": 0}, merges=[])) reference.normalizer = normalizers.NFC() reference.pre_tokenizer = pre_tokenizers.Sequence( @@ -29,9 +50,11 @@ def test_non_special_added_piece_uses_bytelevel_decoder_fallback(tmp_path, piece requests = [[token], [0, token, 0]] path = tmp_path / "requests.json" path.write_text(json.dumps(requests)) - binary = Path(os.environ["TRTMC_NATIVE_BUILD_DIR"]) / "test_minimax_m3_tokenizer" completed = subprocess.run( - [str(binary), str(tokenizer), str(path)], capture_output=True, text=True, check=True + [str(tokenizer_binary), str(tokenizer), str(path)], + capture_output=True, + text=True, + check=True, ) actual = json.loads(completed.stdout) assert [item["decoded"] for item in actual] == [ From f6e8797bd3217884664d65509776648d9446688d Mon Sep 17 00:00:00 2001 From: Will Guo Date: Mon, 30 Nov 2026 19:26:08 -0800 Subject: [PATCH 06/10] fix(minimax_m3): explicitly reject zero-mass routing Mark rows with zero selected score mass as NaN before dividing. Keep the native request error and independent reference behavior, and cover a zero row next to a valid row in the same batch. Signed-off-by: Will Guo --- families/minimax_m3/README.md | 7 ++++--- families/minimax_m3/runtime/precision.cu | 6 ++++++ families/minimax_m3/tests/test_routing_precision.py | 7 ++++--- 3 files changed, 14 insertions(+), 6 deletions(-) diff --git a/families/minimax_m3/README.md b/families/minimax_m3/README.md index 8ed3b13c60..d8d133e221 100644 --- a/families/minimax_m3/README.md +++ b/families/minimax_m3/README.md @@ -68,9 +68,10 @@ static activation global scale. Dyadic regression cases cover multiple token amplitudes, including inputs that a missing outer multiplier collapses to zero. This follows the pre-dispatch contract in SGLang's pinned `sgl-deep-gemm==0.2.7`. -A router row with no representable positive score mass has no normalized -mixture. The native Task rejects its nonfinite routing weights; it does not -substitute a uniform mixture or change the independent reference equation. +A router row with zero selected score mass has no normalized mixture. The +kernel marks its weights as NaN before division. The native Task rejects the +request before dispatching routed experts. The independent reference equation +also produces NaN for that row. All 60 decoder layers, 128 routed experts per MoE layer, the four-expert router, shared experts, Gemma RMS norms, partial RoPE, and the checkpoint's clipped diff --git a/families/minimax_m3/runtime/precision.cu b/families/minimax_m3/runtime/precision.cu index 6e3cb24876..74aea9c64b 100644 --- a/families/minimax_m3/runtime/precision.cu +++ b/families/minimax_m3/runtime/precision.cu @@ -149,6 +149,12 @@ __global__ void router_weights(const float* selected, float* output, int rows) { double total = 0.0; for (int slot = 0; slot < 4; ++slot) total = __dadd_rn(total, static_cast(selected[row * 4 + slot])); + if (total == 0.0) { + // The Task rejects nonfinite weights before dispatching routed experts. + for (int slot = 0; slot < 4; ++slot) + output[row * 4 + slot] = nanf(""); + return; + } for (int slot = 0; slot < 4; ++slot) output[row * 4 + slot] = __double2float_rn( __ddiv_rn(__dmul_rn(2.0, static_cast(selected[row * 4 + slot])), total)); diff --git a/families/minimax_m3/tests/test_routing_precision.py b/families/minimax_m3/tests/test_routing_precision.py index c3499d8d01..1db0221265 100644 --- a/families/minimax_m3/tests/test_routing_precision.py +++ b/families/minimax_m3/tests/test_routing_precision.py @@ -93,8 +93,9 @@ def definition(graph): selected = graph.input("selected", (-1, 4)) return {"weights": add_precision_kernel(graph.net, "router_weights", [selected])} - selected = np.zeros((1, 4), np.float32) + selected = np.array([[0, 0, 0, 0], [0.125, 0, 0.375, 0]], dtype=np.float32) actual = Runner(definition)(selected=selected)["weights"] expected = routing_weights(torch.from_numpy(selected)).numpy() - assert not np.isfinite(actual).any() - assert not np.isfinite(expected).any() + assert np.isnan(actual[0]).all() + assert np.isnan(expected[0]).all() + np.testing.assert_array_equal(actual[1], expected[1]) From a5895464c78b67d941bc62d18383b6bbc1070c09 Mon Sep 17 00:00:00 2001 From: Will Guo Date: Mon, 30 Nov 2026 19:45:22 -0800 Subject: [PATCH 07/10] test(minimax_m3): cover two-token continuation Run explicit and default continuation requests against the independent greedy reference. Exercise FP32 router rounding ties and document the local validation hardware. Signed-off-by: Will Guo --- families/minimax_m3/README.md | 14 +++- .../manifests/minimax-m3.1-flash-bf16.json | 7 ++ families/minimax_m3/tests/sdk_consumer.c | 19 ++++-- families/minimax_m3/tests/sdk_consumer.cpp | 12 +++- families/minimax_m3/tests/test_e2e.py | 66 ++++++++++++------- .../minimax_m3/tests/test_e2e_selection.py | 31 +++++---- .../tests/test_routing_precision.py | 9 ++- 7 files changed, 107 insertions(+), 51 deletions(-) diff --git a/families/minimax_m3/README.md b/families/minimax_m3/README.md index d8d133e221..c880e0d7fe 100644 --- a/families/minimax_m3/README.md +++ b/families/minimax_m3/README.md @@ -93,6 +93,11 @@ space for staged bundle sections and the final bundle. The staged execution path bounds resident weight memory at the cost of host decoding and transfers. It is an initial correctness path, not a latency or throughput qualification. +Local validation uses one NVIDIA Blackwell GPU (compute capability 10.3) with +143 GiB of visible GPU memory, 251 GiB of host RAM, and TensorRT 11.4 on +Linux x86-64. These capacities describe the validation machine. Minimum +memory requirements have not been measured. + ## Validate The family oracle independently evaluates the complete 60-layer text model in @@ -108,7 +113,10 @@ not reproduce the accumulation order of an upstream fused serving kernel. The direct E2E compares six intermediate layer outputs and final full-vocabulary logits (relative L2 below `1e-2`, cosine above `0.9999`), then requires an exact -greedy token and text match through the CLI and public C/C++ SDKs. The C++ +greedy token and text match through the CLI and public C/C++ SDKs. The manifest +exercises an explicit one-token request and a two-token request using the +default configuration. The independent oracle recomputes logits after the +first generated token to check the second decode step. The C++ consumer repeats a request through one loaded Task. Both SDK consumers inspect owned results after releasing the model wrapper. Native tokenizer IDs and decoded text are compared against the checkpoint tokenizer on English, Arabic, @@ -127,6 +135,6 @@ ctest --test-dir build -R '^bundle_format_v1$' --output-on-failure Set `TRTMC_MINIMAX_M3_BUNDLE` only to reuse an already-built bundle. Tests still execute the independent reference and real native inference. The manifest pins -the checkpoint and declares the prompt and build profile. This small exact -case does not establish corpus-level accuracy, chat/vision/video support, +the checkpoint and declares the prompt and build profile. These cases do not +establish corpus-level accuracy, chat/vision/video support, long-context behavior, performance, or other hardware/TensorRT cohorts. diff --git a/families/minimax_m3/tests/manifests/minimax-m3.1-flash-bf16.json b/families/minimax_m3/tests/manifests/minimax-m3.1-flash-bf16.json index 9830bb0e74..07d889b2f3 100644 --- a/families/minimax_m3/tests/manifests/minimax-m3.1-flash-bf16.json +++ b/families/minimax_m3/tests/manifests/minimax-m3.1-flash-bf16.json @@ -14,6 +14,13 @@ "premerge": true, "prompt": "The capital of France is", "max_new_tokens": 1 + }, + { + "name": "minimax-m3.1-flash-default-continuation", + "premerge": true, + "prompt": "The capital of France is", + "max_new_tokens": 2, + "use_default_config": true } ] } diff --git a/families/minimax_m3/tests/sdk_consumer.c b/families/minimax_m3/tests/sdk_consumer.c index 3fd921b444..654e06be62 100644 --- a/families/minimax_m3/tests/sdk_consumer.c +++ b/families/minimax_m3/tests/sdk_consumer.c @@ -4,6 +4,7 @@ */ #include #include +#include #include #include static trtmc_string_view string(const char* s) { @@ -20,12 +21,23 @@ int main(int argc, char** argv) { trtmc_load_options_v1 options = {0}; trtmc_text_continuation_request_v1 request = {0}; trtmc_config_entry_v1 entry = {0}; - trtmc_config_view_v1 config = {&entry, 1}; + trtmc_config_view_v1 config = {0}; trtmc_text_result_view_v1 view = {0}; uint64_t i; int status = 1; - if (argc != 4) + if (argc != 4 && argc != 5) return 2; + if (argc == 5) { + char* end; + long count = strtol(argv[4], &end, 10); + if (end == argv[4] || *end != '\0' || count < 1 || count > 128) + return 2; + entry.name = string("max_new_tokens"); + entry.value.kind = TRTMC_CONFIG_I64; + entry.value.as.i64 = count; + config.entries = &entry; + config.count = 1; + } if (trtmc_get_api(1, 0, &core) != TRTMC_OK || !core) return 1; options.struct_size = sizeof(options); @@ -38,9 +50,6 @@ int main(int argc, char** argv) { task = (const trtmc_text_continuation_api_v1*)header; request.prefix.kind = TRTMC_TEXT_UTF8; request.prefix.as.text = string(argv[3]); - entry.name = string("max_new_tokens"); - entry.value.kind = TRTMC_CONFIG_I64; - entry.value.as.i64 = 1; if (task->run(model, &request, &config, &result, &error) != TRTMC_OK) goto cleanup; core->model_release(model); diff --git a/families/minimax_m3/tests/sdk_consumer.cpp b/families/minimax_m3/tests/sdk_consumer.cpp index 3ac24958d0..1bb238277c 100644 --- a/families/minimax_m3/tests/sdk_consumer.cpp +++ b/families/minimax_m3/tests/sdk_consumer.cpp @@ -4,10 +4,11 @@ */ #include #include +#include #include int main(int argc, char** argv) { - if (argc != 4) + if (argc != 4 && argc != 5) return 2; try { std::vector results; @@ -16,7 +17,14 @@ int main(int argc, char** argv) { options.runtime_root = argv[2]; auto model = trtmc::Model::load(argv[1], options); auto task = model.task(); - trtmc::Config config{{"max_new_tokens", int64_t{1}}}; + trtmc::Config config; + if (argc == 5) { + std::size_t parsed = 0; + const auto count = std::stoll(argv[4], &parsed); + if (argv[4][parsed] != '\0' || count < 1 || count > 128) + return 2; + config = {{"max_new_tokens", static_cast(count)}}; + } for (int i = 0; i < 2; ++i) results.push_back(task.run({std::string(argv[3])}, config)); } diff --git a/families/minimax_m3/tests/test_e2e.py b/families/minimax_m3/tests/test_e2e.py index 26e7207868..602ef2e5d3 100644 --- a/families/minimax_m3/tests/test_e2e.py +++ b/families/minimax_m3/tests/test_e2e.py @@ -47,22 +47,8 @@ def compare(actual, expected): ) -@pytest.mark.e2e -@pytest.mark.gpu -@pytest.mark.parametrize("case_name", [case["name"] for case in MANIFEST["testcases"]]) -def test_full_checkpoint_native_continuation_e2e(pytestconfig, tmp_path, case_name): - selected = [] - for name in ["--e2e-model", "--e2e-testcase"]: - selected.extend( - x.strip() for raw in (pytestconfig.getoption(name) or []) for x in str(raw).split(",") - ) - selection_file = pytestconfig.getoption("--e2e-models-file") - if selection_file: - selected.extend(Path(selection_file).read_text().splitlines()) - names = {"minimax_m3", MANIFEST["name"]} - names.update(case["name"] for case in MANIFEST["testcases"]) - if not set(selected) & names: - pytest.skip("MiniMax full checkpoint E2E requires an explicit selection") +@pytest.fixture(scope="module") +def checkpoint_bundle(tmp_path_factory): if os.environ.get("TRTMC_MINIMAX_M3_MODEL_DIR"): checkpoint = required("TRTMC_MINIMAX_M3_MODEL_DIR") else: @@ -73,13 +59,10 @@ def test_full_checkpoint_native_continuation_e2e(pytestconfig, tmp_path, case_na MANIFEST["hf_id"], revision=MANIFEST["hf_revision"], local_files_only=True ) ) - binary = required("TRTMC_BINARY") - runtime = required("TRTMC_RUNTIME_ROOT") - native = required("TRTMC_NATIVE_BUILD_DIR") if os.environ.get("TRTMC_MINIMAX_M3_BUNDLE"): bundle = required("TRTMC_MINIMAX_M3_BUNDLE") else: - bundle = tmp_path / MANIFEST["bundle"] + bundle = tmp_path_factory.mktemp("minimax-m3-bundle") / MANIFEST["bundle"] build( BuildRequest( model_dir=checkpoint, @@ -91,8 +74,29 @@ def test_full_checkpoint_native_continuation_e2e(pytestconfig, tmp_path, case_na tensor_parallel_size=MANIFEST["tensor_parallel_size"], ) ) + return checkpoint, bundle + + +@pytest.mark.e2e +@pytest.mark.gpu +@pytest.mark.parametrize("case_name", [case["name"] for case in MANIFEST["testcases"]]) +def test_full_checkpoint_native_continuation_e2e(request, tmp_path, case_name): + selected = [] + for name in ["--e2e-model", "--e2e-testcase"]: + selected.extend( + x.strip() for raw in (request.config.getoption(name) or []) for x in str(raw).split(",") + ) + selection_file = request.config.getoption("--e2e-models-file") + if selection_file: + selected.extend(Path(selection_file).read_text().splitlines()) + if not set(selected) & {"minimax_m3", MANIFEST["name"], case_name}: + pytest.skip("MiniMax full checkpoint E2E requires an explicit selection") + checkpoint, bundle = request.getfixturevalue("checkpoint_bundle") + binary = required("TRTMC_BINARY") + runtime = required("TRTMC_RUNTIME_ROOT") + native = required("TRTMC_NATIVE_BUILD_DIR") case = next(case for case in MANIFEST["testcases"] if case["name"] == case_name) - assert case["max_new_tokens"] == 1 + max_new_tokens = case["max_new_tokens"] tokenizer = Tokenizer.from_file(str(checkpoint / "tokenizer.json")) texts = [ case["prompt"], @@ -179,9 +183,22 @@ def test_full_checkpoint_native_continuation_e2e(pytestconfig, tmp_path, case_na assert int(actual.argmax()) == int(expected.argmax()) eos = json.loads((checkpoint / "generation_config.json").read_text())["eos_token_id"] eos = eos if isinstance(eos, list) else [eos] - generated = [] if int(expected.argmax()) in eos else [int(expected.argmax())] + generated = [] + for step in range(max_new_tokens): + if step: + print(f"reference decode step {step + 1}/{max_new_tokens}", flush=True) + expected, _ = reference.logits(ids + generated) + assert np.isfinite(expected).all() + np.save(tmp_path / f"reference-logits-step-{step}.npy", expected) + next_token = int(expected.argmax()) + if next_token in eos: + break + generated.append(next_token) + assert len(generated) == max_new_tokens, "Reference stopped before exercising every decode step" text = tokenizer.decode(generated, skip_special_tokens=True) evidence.update(token_ids=generated, text=text) + config = [] if case.get("use_default_config") else [str(max_new_tokens)] + cli_config = ["--set", f"max_new_tokens={max_new_tokens}"] if config else [] cli = command( [ binary, @@ -193,14 +210,13 @@ def test_full_checkpoint_native_continuation_e2e(pytestconfig, tmp_path, case_na MANIFEST["task"], "--prompt", case["prompt"], - "--set", - f"max_new_tokens={case['max_new_tokens']}", + *cli_config, ] )[0] assert cli["token_ids"] == generated and cli["text"] == text, cli for language in ["c", "cpp"]: results = command( - [native / f"test_minimax_m3_sdk_{language}", bundle, runtime, case["prompt"]] + [native / f"test_minimax_m3_sdk_{language}", bundle, runtime, case["prompt"], *config] ) assert len(results) == (2 if language == "cpp" else 1) for result in results: diff --git a/families/minimax_m3/tests/test_e2e_selection.py b/families/minimax_m3/tests/test_e2e_selection.py index b86cb18924..c30222cbea 100644 --- a/families/minimax_m3/tests/test_e2e_selection.py +++ b/families/minimax_m3/tests/test_e2e_selection.py @@ -13,15 +13,12 @@ class CheckpointRequested(Exception): pass -@pytest.fixture -def checkpoint_boundary(monkeypatch): - monkeypatch.setenv("TRTMC_MINIMAX_M3_MODEL_DIR", "/not-needed-for-selection") - - def required(name): - assert name == "TRTMC_MINIMAX_M3_MODEL_DIR" +def request_for(config): + def getfixturevalue(name): + assert name == "checkpoint_bundle" raise CheckpointRequested - monkeypatch.setattr(owning, "required", required) + return SimpleNamespace(config=config, getfixturevalue=getfixturevalue) @pytest.mark.parametrize( @@ -34,15 +31,15 @@ def required(name): ("--e2e-testcase", ["unrelated", owning.MANIFEST["testcases"][0]["name"]]), ], ) -def test_explicit_selection_reaches_checkpoint(checkpoint_boundary, tmp_path, option, values): +def test_explicit_selection_reaches_checkpoint(tmp_path, option, values): config = SimpleNamespace(getoption=lambda name: values if name == option else None) with pytest.raises(CheckpointRequested): owning.test_full_checkpoint_native_continuation_e2e( - config, tmp_path, owning.MANIFEST["testcases"][0]["name"] + request_for(config), tmp_path, owning.MANIFEST["testcases"][0]["name"] ) -def test_testcase_selection_file_reaches_checkpoint(checkpoint_boundary, tmp_path): +def test_testcase_selection_file_reaches_checkpoint(tmp_path): selection = tmp_path / "selection.txt" selection.write_text(owning.MANIFEST["testcases"][0]["name"] + "\n") config = SimpleNamespace( @@ -50,16 +47,22 @@ def test_testcase_selection_file_reaches_checkpoint(checkpoint_boundary, tmp_pat ) with pytest.raises(CheckpointRequested): owning.test_full_checkpoint_native_continuation_e2e( - config, tmp_path, owning.MANIFEST["testcases"][0]["name"] + request_for(config), tmp_path, owning.MANIFEST["testcases"][0]["name"] ) @pytest.mark.parametrize( - "options", [{}, {"--e2e-model": ["unrelated"]}, {"--e2e-testcase": ["unrelated"]}] + "options", + [ + {}, + {"--e2e-model": ["unrelated"]}, + {"--e2e-testcase": ["unrelated"]}, + {"--e2e-testcase": [owning.MANIFEST["testcases"][1]["name"]]}, + ], ) -def test_unselected_case_skips_before_checkpoint(checkpoint_boundary, tmp_path, options): +def test_unselected_case_skips_before_checkpoint(tmp_path, options): config = SimpleNamespace(getoption=options.get) with pytest.raises(pytest.skip.Exception): owning.test_full_checkpoint_native_continuation_e2e( - config, tmp_path, owning.MANIFEST["testcases"][0]["name"] + request_for(config), tmp_path, owning.MANIFEST["testcases"][0]["name"] ) diff --git a/families/minimax_m3/tests/test_routing_precision.py b/families/minimax_m3/tests/test_routing_precision.py index 1db0221265..a1b840d7c4 100644 --- a/families/minimax_m3/tests/test_routing_precision.py +++ b/families/minimax_m3/tests/test_routing_precision.py @@ -59,12 +59,17 @@ def definition(graph): hidden = np.ones((1, 6144), np.float32) weight = np.zeros((128, 6144), np.float32) expected = np.empty((1, 128), np.float32) - for row in range(128): + for row in range(126): weight[row, [0, 1, 32]] = [2.0**24, (row - 64) / 32, -(2.0**24)] + # The first dot is halfway between FP32 values and rounds to -1. + # The second is exactly representable in FP32 but rounds to -1 in BF16. + weight[126, :2] = [-1, -(2.0**-24)] + weight[127, :2] = [-1, -(2.0**-8)] + for row in range(128): exact = sum((Fraction(float(v)) for v in weight[row]), Fraction()) with localcontext() as context: context.prec = 80 - logit = Decimal(exact.numerator) / Decimal(exact.denominator) + logit = Decimal(float(np.float32(float(exact)))) expected[0, row] = float(1 / (1 + (-logit).exp())) np.testing.assert_array_equal(runner(hidden=hidden, weight=weight)["scores"], expected) From 22b6a32ca19aa47274a24ce26eb2844e085bab6d Mon Sep 17 00:00:00 2001 From: Will Guo Date: Mon, 30 Nov 2026 21:17:07 -0800 Subject: [PATCH 08/10] fix(minimax_m3): reject empty added tokens Reject malformed tokenizer metadata before encoding can enter a loop without consuming input. Exercise the production tokenizer constructor with a malformed added token. Signed-off-by: Will Guo --- families/minimax_m3/runtime/bpe_tokenizer.cpp | 2 ++ families/minimax_m3/tests/test_tokenizer.py | 33 +++++++++++++++++-- 2 files changed, 32 insertions(+), 3 deletions(-) diff --git a/families/minimax_m3/runtime/bpe_tokenizer.cpp b/families/minimax_m3/runtime/bpe_tokenizer.cpp index dccf4c0b82..9fb4477913 100644 --- a/families/minimax_m3/runtime/bpe_tokenizer.cpp +++ b/families/minimax_m3/runtime/bpe_tokenizer.cpp @@ -70,6 +70,8 @@ class Tokenizer final : public ITokenizer { token.at("rstrip").get() || token.at("normalized").get()) throw std::runtime_error("unsupported MiniMax added-token matching contract"); const auto text = token.at("content").get(); + if (text.empty()) + throw std::runtime_error("empty MiniMax added-token content"); const int id = token.at("id"); added_.emplace_back(text, id); pieces_[id] = text; diff --git a/families/minimax_m3/tests/test_tokenizer.py b/families/minimax_m3/tests/test_tokenizer.py index 1129c275d6..18a6e0bc8f 100644 --- a/families/minimax_m3/tests/test_tokenizer.py +++ b/families/minimax_m3/tests/test_tokenizer.py @@ -1,6 +1,6 @@ # SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 -"""Native ByteLevel decoding against the independent Rust tokenizer.""" +"""Native tokenizer validation and ByteLevel parity with the Rust tokenizer.""" import json import os @@ -32,8 +32,8 @@ def tokenizer_binary(): return binary -@pytest.mark.parametrize("piece", [" ", "a b", "λ", "你好", "Ġλ"]) -def test_non_special_added_piece_uses_bytelevel_decoder_fallback(tmp_path, piece, tokenizer_binary): +@pytest.fixture +def reference_tokenizer(): reference = Tokenizer(models.BPE(vocab={"a": 0}, merges=[])) reference.normalizer = normalizers.NFC() reference.pre_tokenizer = pre_tokenizers.Sequence( @@ -43,6 +43,14 @@ def test_non_special_added_piece_uses_bytelevel_decoder_fallback(tmp_path, piece ] ) reference.decoder = decoders.ByteLevel() + return reference + + +@pytest.mark.parametrize("piece", [" ", "a b", "λ", "你好", "Ġλ"]) +def test_non_special_added_piece_uses_bytelevel_decoder_fallback( + tmp_path, piece, tokenizer_binary, reference_tokenizer +): + reference = reference_tokenizer reference.add_tokens([AddedToken(piece, normalized=False)]) tokenizer = tmp_path / "tokenizer.json" tokenizer.write_text(reference.to_str()) @@ -60,3 +68,22 @@ def test_non_special_added_piece_uses_bytelevel_decoder_fallback(tmp_path, piece assert [item["decoded"] for item in actual] == [ reference.decode(ids, skip_special_tokens=True) for ids in requests ] + + +def test_rejects_empty_added_token_at_load(tmp_path, tokenizer_binary, reference_tokenizer): + reference_tokenizer.add_tokens([AddedToken("added", normalized=False)]) + config = json.loads(reference_tokenizer.to_str()) + config["added_tokens"][0]["content"] = "" + tokenizer = tmp_path / "tokenizer.json" + tokenizer.write_text(json.dumps(config)) + # No encode request is sent. The malformed tokenizer must fail construction. + requests = tmp_path / "requests.json" + requests.write_text("[]") + completed = subprocess.run( + [str(tokenizer_binary), str(tokenizer), str(requests)], + capture_output=True, + text=True, + timeout=10, + ) + assert completed.returncode == 1 + assert "empty MiniMax added-token content" in completed.stderr From 3095bf4aa2b0beb08e19e9b8991738c214d9fd49 Mon Sep 17 00:00:00 2001 From: Will Guo Date: Tue, 1 Dec 2026 19:52:01 -0800 Subject: [PATCH 09/10] fix(minimax_m3): ship a native TensorRT precision plugin Register the existing CUDA precision kernels from the packaged family library. Resolve that library by path during Python graph construction and use the same plugin for native engine deserialization. Signed-off-by: Will Guo --- families/minimax_m3/README.md | 18 +- families/minimax_m3/graph.py | 5 +- families/minimax_m3/model.py | 2 +- families/minimax_m3/precision.py | 133 ++--- families/minimax_m3/runtime/CMakeLists.txt | 29 +- families/minimax_m3/runtime/pipeline.cpp | 37 +- families/minimax_m3/runtime/precision.cu | 469 +++++++++++------- .../tests/test_routing_precision.py | 6 +- 8 files changed, 382 insertions(+), 317 deletions(-) diff --git a/families/minimax_m3/README.md b/families/minimax_m3/README.md index c880e0d7fe..d20a637908 100644 --- a/families/minimax_m3/README.md +++ b/families/minimax_m3/README.md @@ -13,17 +13,17 @@ parallelism, streaming, and KV caching are not implemented by this path. ## Build and run Use the repository development environment with TensorRT 11.1 or newer and -ICU development libraries (`libicu-dev` on Ubuntu), and the public TVM-FFI -BYOK bridge (`apache-tvm-ffi==0.1.12`, CMake `TRTMC_ENABLE_BYOK=ON`). Python -dependencies are provided by the repository's base environment. No +ICU development libraries (`libicu-dev` on Ubuntu). Python dependencies are +provided by the repository's base environment. No family-specific Python package installation is required. ```bash -cmake -S . -B build -DTRTMC_ENABLE_BYOK=ON -DTRTMC_BUILD_TESTS=ON +cmake -S . -B build -DTRTMC_BUILD_TESTS=ON cmake --build build --parallel 12 --target \ trtmc trtmc_backend_trt trtmc_model_minimax_m3 \ test_minimax_m3_sdk_c test_minimax_m3_sdk_cpp test_bundle_format_v1 export PYTHONPATH=core/builder:apps/benchmark:. +export CMAKE_PREFIX_PATH="$PWD/build${CMAKE_PREFIX_PATH:+:$CMAKE_PREFIX_PATH}" export LD_LIBRARY_PATH="$PWD/build${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}" python -m tensorrt_model_connect build MiniMaxAI/MiniMax-M3.1-Flash \ --revision ce7f4df87d2e05262f5775f373dac4772f134041 \ @@ -42,14 +42,15 @@ This is not a new quantization or calibration pass. The native runtime expands only projections needed for the current stage and passes their values through the ordinary backend Tensor API. -Family-owned TVM-FFI BYOK bindings evaluate Gemma normalization, the small router, +The family-owned TensorRT plugin evaluates Gemma normalization, the small router, rotary products, causal attention reductions, and the weighted expert merge in FP64 before the specified FP32/BF16 rounding boundaries. Attention scores and probabilities retain FP32 boundaries; final vocabulary logits use FP32 GEMM. These precision reductions limit summation noise before quantization. -The family DSO loads its adjacent `libtrtmc_minimax_m3_precision.so` through the -public BYOK bridge. Build that module before constructing the Python graphs; -the builder resolves native libraries through the standard dynamic loader. +The native wheel provides the precision plugin in `libtrtmc_model_minimax_m3.so`. +For source builds, include the native build directory in `CMAKE_PREFIX_PATH`, +as shown above. The family registers its plugin before deserializing engine +plans. Rebuild MiniMax M3 bundles created with earlier precision plans. Rotary tables are calculated in FP64 before FP32 storage; rotation products are reduced before the FP32/BF16 boundaries. All model topology, kernels, and orchestration remain inside this family. The runtime validates each bundle @@ -127,6 +128,7 @@ export LD_LIBRARY_PATH="$PWD/build${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}" export TRTMC_BINARY="$PWD/build/trtmc" export TRTMC_RUNTIME_ROOT="$PWD/build" export TRTMC_NATIVE_BUILD_DIR="$PWD/build" +export CMAKE_PREFIX_PATH="$PWD/build${CMAKE_PREFIX_PATH:+:$CMAKE_PREFIX_PATH}" export TRTMC_MINIMAX_M3_MODEL_DIR=/path/to/pinned/checkpoint PYTHONPATH=core/builder:apps/benchmark:. python -m pytest \ families/minimax_m3/tests --e2e-model minimax_m3 -q -s diff --git a/families/minimax_m3/graph.py b/families/minimax_m3/graph.py index 6e09c4206d..e901f73186 100644 --- a/families/minimax_m3/graph.py +++ b/families/minimax_m3/graph.py @@ -1,7 +1,7 @@ # SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 -"""Bounded short-context M3 graphs; TensorRT graphs with family-owned BYOK precision reductions.""" +"""Bounded short-context M3 graphs with native TensorRT precision reductions.""" import numpy as np import tensorrt as trt @@ -167,8 +167,7 @@ def route(self): hidden = self.input("hidden", (-1, 6144)) normalized = self.norm(hidden, self.input("norm", (6144,)), 6144) router = self.input("router", (128, 6144)) - logits = self.mm(normalized, router) - scores = add_precision_kernel(self.net, "router_scores", [logits, normalized, router]) + scores = add_precision_kernel(self.net, "router_scores", [normalized, router]) biased = self.op(scores, self.reshape(self.input("bias", (128,)), (1, 128))) topk = self.net.add_topk(biased, trt.TopKOperation.MAX, 4, 1 << 1) ids = topk.get_output(1) diff --git a/families/minimax_m3/model.py b/families/minimax_m3/model.py index bb01c8a510..419cdfdbef 100644 --- a/families/minimax_m3/model.py +++ b/families/minimax_m3/model.py @@ -171,7 +171,7 @@ def build(request, writer): "runtime.json", dict( precision=request.precision, - normalization="fp64_byok", + normalization="fp64_trt_plugin", nvfp4_input_scale="per_token", rotary_precision="fp64", max_sequence_length=capacity, diff --git a/families/minimax_m3/precision.py b/families/minimax_m3/precision.py index eeccfad831..95e12db5a2 100644 --- a/families/minimax_m3/precision.py +++ b/families/minimax_m3/precision.py @@ -1,73 +1,82 @@ # SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 -"""Bind the family's reduction precision islands through the public BYOK API.""" + +"""Add the family CUDA precision kernels as native TensorRT layers.""" import ctypes from functools import lru_cache +from importlib import metadata from pathlib import Path -from tensorrt_model_connect.byok import add_kernel +import numpy as np +import tensorrt as trt +from tensorrt_model_connect.build import cmake_prefixes + +_LIBRARY = "libtrtmc_model_minimax_m3.so" +# Serialized operation IDs defined in runtime/precision.cu. +_OPERATIONS = { + "gemma_norm": 0, + "moe_merge": 1, + "router_scores": 2, + "causal_attention": 3, + "nv_input": 4, + "rope": 5, + "router_weights": 6, +} + + +def _model_library(): + roots = cmake_prefixes() + try: + installed = metadata.distribution("tensorrt-model-connect") + except metadata.PackageNotFoundError: + pass + else: + roots.append(Path(installed.locate_file("tensorrt_model_connect/bin"))) + for root in roots: + library = root / _LIBRARY + if library.is_file(): + return library.resolve() + raise FileNotFoundError( + f"MiniMax M3 requires {_LIBRARY}. Install the native wheel or include " + "the native build directory in CMAKE_PREFIX_PATH." + ) @lru_cache(maxsize=None) -def _load(root=None): - if root is None: - # Resolve through the standard native loader, exactly as other native - # dependencies. Model policy does not read environment/profile switches. - library = ctypes.CDLL("libtrtmc_byok_tvm_ffi.so", mode=ctypes.RTLD_GLOBAL) - - class Location(ctypes.Structure): - _fields_ = [ - ("filename", ctypes.c_char_p), - ("base", ctypes.c_void_p), - ("symbol", ctypes.c_char_p), - ("address", ctypes.c_void_p), - ] - - location = Location() - dladdr = ctypes.CDLL(None).dladdr - dladdr.argtypes = [ctypes.c_void_p, ctypes.POINTER(Location)] - dladdr.restype = ctypes.c_int - if not dladdr( - ctypes.cast(library.trtmc_load_byok_kernel, ctypes.c_void_p), ctypes.byref(location) - ): - raise RuntimeError("Cannot locate the MiniMax native BYOK bridge") - root = Path(location.filename.decode()).resolve().parent - bridge = root / "libtrtmc_byok_tvm_ffi.so" - kernel = root / "libtrtmc_minimax_m3_precision.so" - for path in (bridge, kernel): - if not path.is_file(): - raise FileNotFoundError(f"minimax_m3 native BYOK dependency is missing: {path}") - library = ctypes.CDLL(str(bridge), mode=ctypes.RTLD_GLOBAL) - library.trtmc_load_byok_kernel.argtypes = [ctypes.c_char_p] * 3 - library.trtmc_load_byok_kernel.restype = ctypes.c_char_p - for exported, name in ( - ("run", "gemma_norm"), - ("merge", "moe_merge"), - ("scores", "router_scores"), - ("attention", "causal_attention"), - ("nv_input", "nv_input"), - ("rope", "rope"), - ("routing_weights", "router_weights"), - ): - error = library.trtmc_load_byok_kernel( - str(kernel).encode(), exported.encode(), ("minimax_m3." + name).encode() - ) - if error: - raise RuntimeError(error.decode()) - return bridge, library +def _load(path): + library = ctypes.CDLL(str(path)) + try: + initialize = library.trtmc_minimax_m3_initialize_precision + except AttributeError as error: + raise RuntimeError("MiniMax M3 requires a matching native model library") from error + initialize.argtypes = [] + initialize.restype = ctypes.c_char_p + if error := initialize(): + raise RuntimeError(error.decode()) + return library -def add_precision_kernel(network, name, inputs): - bridge, _owner = _load() - (result,) = add_kernel( - network, - plugin_library=bridge, - kernel_name="minimax_m3." + name, - inputs=inputs, - output_specs=[{"dims": "same_as_input_0", "dtype": "float32"}], +def _add_precision_layer(network, name, inputs): + _load(_model_library()) + creator = trt.get_plugin_registry().get_creator("MiniMaxM3Precision", "1", "") + if creator is None: + raise RuntimeError("MiniMax M3 TensorRT precision plugin is not registered") + operation = np.array([_OPERATIONS[name]], dtype=np.int32) + fields = trt.PluginFieldCollection( + [trt.PluginField("operation", operation, trt.PluginFieldType.INT32)] ) - return result + plugin = creator.create_plugin("minimax_m3_" + name, fields, trt.TensorRTPhase.BUILD) + if plugin is None: + raise RuntimeError(f"MiniMax M3 could not create its {name} CUDA plugin") + layer = network.add_plugin_v3(inputs, [], plugin) + if layer is None: + raise RuntimeError(f"MiniMax M3 could not add its {name} CUDA plugin") + return layer + + +def add_precision_kernel(network, name, inputs): + return _add_precision_layer(network, name, inputs).get_output(0) def add_normalization(network, hidden, weight): @@ -79,11 +88,5 @@ def add_merge(network, residual, shared, values, weights): def add_nv_input(network, hidden): - bridge, _owner = _load() - return add_kernel( - network, - plugin_library=bridge, - kernel_name="minimax_m3.nv_input", - inputs=[hidden], - output_specs=[{"dims": "same_as_input_0", "dtype": "float32"}] * 2, - ) + layer = _add_precision_layer(network, "nv_input", [hidden]) + return layer.get_output(0), layer.get_output(1) diff --git a/families/minimax_m3/runtime/CMakeLists.txt b/families/minimax_m3/runtime/CMakeLists.txt index 2d66d0296c..cc8c7d63dc 100644 --- a/families/minimax_m3/runtime/CMakeLists.txt +++ b/families/minimax_m3/runtime/CMakeLists.txt @@ -1,27 +1,18 @@ # 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_minimax_m3 SHARED bpe_tokenizer.cpp weights.cpp pipeline.cpp plugin.cpp) +add_library(trtmc_model_minimax_m3 SHARED bpe_tokenizer.cpp weights.cpp pipeline.cpp plugin.cpp precision.cu) target_include_directories(trtmc_model_minimax_m3 PRIVATE ${PROJECT_SOURCE_DIR} ${PROJECT_SOURCE_DIR}/core/runtime/include) -target_include_directories(trtmc_model_minimax_m3 SYSTEM PRIVATE ${TRTMC_CUDA_INCLUDE_DIR}) -target_link_libraries(trtmc_model_minimax_m3 PRIVATE trtmc_core nlohmann_json::nlohmann_json ${TRTMC_CUDART_LIBRARY} ICU::uc ICU::i18n) -target_compile_options(trtmc_model_minimax_m3 PRIVATE -Wall -Wextra -Wpedantic) -set_target_properties(trtmc_model_minimax_m3 PROPERTIES LIBRARY_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}" BUILD_RPATH "\$ORIGIN" INSTALL_RPATH "\$ORIGIN") +target_include_directories(trtmc_model_minimax_m3 SYSTEM PRIVATE ${TRTMC_CUDA_INCLUDE_DIR} ${TRTMC_TRT_INCLUDE_DIR}) +target_link_libraries(trtmc_model_minimax_m3 PRIVATE + trtmc_core nlohmann_json::nlohmann_json CUDA::cudart ${TRTMC_TRT_LIBRARY} ICU::uc ICU::i18n) +target_compile_options(trtmc_model_minimax_m3 PRIVATE "$<$:-Wall;-Wextra;-Wpedantic>") +# TensorRT retains the creator pointer after the last family instance is released. +target_link_options(trtmc_model_minimax_m3 PRIVATE LINKER:-z,nodelete) +set_target_properties(trtmc_model_minimax_m3 PROPERTIES + CUDA_STANDARD 17 CUDA_STANDARD_REQUIRED ON + LIBRARY_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}" BUILD_RPATH "\$ORIGIN" INSTALL_RPATH "\$ORIGIN") install(TARGETS trtmc_model_minimax_m3 LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR}) -if(TARGET trtmc_byok_tvm_ffi) - add_library(trtmc_minimax_m3_precision SHARED precision.cu) - target_include_directories(trtmc_minimax_m3_precision SYSTEM PRIVATE ${TRTMC_TVM_FFI_INCLUDE_DIR}) - target_link_libraries(trtmc_minimax_m3_precision PRIVATE CUDA::cudart ${TRTMC_TVM_FFI_LIBRARY}) - set_target_properties(trtmc_minimax_m3_precision PROPERTIES - CUDA_STANDARD 17 CUDA_STANDARD_REQUIRED ON - LIBRARY_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}" - BUILD_RPATH "\$ORIGIN;${TRTMC_TVM_FFI_LIBRARY_DIR}" - INSTALL_RPATH "\$ORIGIN;${TRTMC_TVM_FFI_LIBRARY_DIR}") - target_compile_definitions(trtmc_model_minimax_m3 PRIVATE TRTMC_MINIMAX_M3_HAS_PRECISION=1) - target_link_libraries(trtmc_model_minimax_m3 PRIVATE trtmc_byok_tvm_ffi ${CMAKE_DL_LIBS}) - add_dependencies(trtmc_model_minimax_m3 trtmc_minimax_m3_precision) - install(TARGETS trtmc_minimax_m3_precision LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR}) -endif() if(TRTMC_BUILD_TESTS) add_executable(test_minimax_m3_tokenizer ${PROJECT_SOURCE_DIR}/families/minimax_m3/tests/tokenizer_consumer.cpp) target_include_directories(test_minimax_m3_tokenizer PRIVATE ${PROJECT_SOURCE_DIR}) diff --git a/families/minimax_m3/runtime/pipeline.cpp b/families/minimax_m3/runtime/pipeline.cpp index 754074d5ae..c077d398d1 100644 --- a/families/minimax_m3/runtime/pipeline.cpp +++ b/families/minimax_m3/runtime/pipeline.cpp @@ -9,39 +9,10 @@ #include #include #include -#if TRTMC_MINIMAX_M3_HAS_PRECISION -#include "trtmc/byok.h" - -#include -#include -#include -#endif +extern "C" const char* trtmc_minimax_m3_initialize_precision() noexcept; namespace trtmc::minimax_m3 { namespace { -void load_precision() { -#if TRTMC_MINIMAX_M3_HAS_PRECISION - static std::once_flag once; - std::call_once(once, [] { - static const int location_anchor = 0; - Dl_info location{}; - if (!dladdr(&location_anchor, &location) || !location.dli_fname) - throw std::runtime_error("minimax_m3 cannot locate its precision module"); - const auto library = std::filesystem::canonical(location.dli_fname).parent_path() / - "libtrtmc_minimax_m3_precision.so"; - trtmc::load_byok_kernel(library.string(), "run", "minimax_m3.gemma_norm"); - trtmc::load_byok_kernel(library.string(), "merge", "minimax_m3.moe_merge"); - trtmc::load_byok_kernel(library.string(), "scores", "minimax_m3.router_scores"); - trtmc::load_byok_kernel(library.string(), "attention", "minimax_m3.causal_attention"); - trtmc::load_byok_kernel(library.string(), "nv_input", "minimax_m3.nv_input"); - trtmc::load_byok_kernel(library.string(), "rope", "minimax_m3.rope"); - trtmc::load_byok_kernel(library.string(), "routing_weights", "minimax_m3.router_weights"); - }); -#else - throw std::runtime_error( - "minimax_m3 precision module requires a native build with BYOK enabled"); -#endif -} const internal::ConfigField fields[] = { {"max_new_tokens", internal::ConfigKind::I64, internal::ConfigValue{int64_t{2}}, "Maximum greedy continuation tokens; prefix and output must fit the bundle capacity."}}; @@ -76,10 +47,12 @@ Pipeline::Pipeline(BundleReader reader, IBackend& backend) : weights_(reader) { config.at("precision") != "bf16" || config.at("hidden_size") != 6144 || config.at("vocab_size") != 200064 || eos_.empty() || config.value("nvfp4_input_scale", std::string{}) != "per_token" || - config.value("normalization", std::string{}) != "fp64_byok" || config.value("rotary_precision", std::string{}) != "fp64") throw std::runtime_error("minimax_m3 bundle contract mismatch"); - load_precision(); + if (config.value("normalization", std::string{}) != "fp64_trt_plugin") + throw std::runtime_error("minimax_m3 precision plans require a rebuilt bundle"); + if (const char* error = trtmc_minimax_m3_initialize_precision()) + throw std::runtime_error(error); raw = reader.read_section("tokenizer.json"); tokenizer_ = CreateBpeTokenizer(raw.data(), raw.size(), false); for (const std::string kind : diff --git a/families/minimax_m3/runtime/precision.cu b/families/minimax_m3/runtime/precision.cu index 74aea9c64b..49611c984e 100644 --- a/families/minimax_m3/runtime/precision.cu +++ b/families/minimax_m3/runtime/precision.cu @@ -2,14 +2,18 @@ * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. * SPDX-License-Identifier: Apache-2.0 */ +#include +#include #include +#include +#include #include #include #include +#include #include -#include -#include -#include +#include +#include namespace { __global__ void gemma_norm(const float* input, const float* weight, float* output, int width) { @@ -37,39 +41,6 @@ __global__ void gemma_norm(const float* input, const float* weight, float* outpu } } -void run(tvm::ffi::TensorView input, tvm::ffi::TensorView weight, tvm::ffi::TensorView output) { - for (const auto& tensor : {input, weight, output}) { - const auto dtype = tensor.dtype(); - if (!tensor.IsContiguous() || tensor.device().device_type != kDLCUDA || - tensor.device().device_id != input.device().device_id || dtype.code != kDLFloat || - dtype.bits != 32 || dtype.lanes != 1) - TVM_FFI_THROW(ValueError) - << "minimax_m3 normalization requires contiguous CUDA FP32 tensors"; - } - if ((input.ndim() != 2 && input.ndim() != 3) || weight.ndim() != 1 || - output.ndim() != input.ndim() || input.size(input.ndim() - 1) != weight.size(0) || - (weight.size(0) != 128 && weight.size(0) != 6144) || input.numel() < 1 || - input.numel() / weight.size(0) > std::numeric_limits::max()) - TVM_FFI_THROW(ValueError) << "minimax_m3 normalization tensor shape mismatch"; - for (int dimension = 0; dimension < input.ndim(); ++dimension) - if (input.size(dimension) != output.size(dimension)) - TVM_FFI_THROW(ValueError) << "minimax_m3 normalization output shape mismatch"; - const auto stream = - reinterpret_cast(TVMFFIEnvGetStream(kDLCUDA, input.device().device_id)); - const auto* source = reinterpret_cast(static_cast(input.data_ptr()) + - input.byte_offset()); - const auto* scale = reinterpret_cast(static_cast(weight.data_ptr()) + - weight.byte_offset()); - auto* destination = - reinterpret_cast(static_cast(output.data_ptr()) + output.byte_offset()); - gemma_norm<<(input.numel() / weight.size(0)), 256, 0, stream>>>( - source, scale, destination, static_cast(weight.size(0))); - const auto error = cudaGetLastError(); - if (error != cudaSuccess) - TVM_FFI_THROW(RuntimeError) - << "minimax_m3 normalization launch failed: " << cudaGetErrorString(error); -} - __global__ void merge_experts(const float* residual, const float* shared, const float* values, const float* weights, float* output, std::size_t count) { const std::size_t index = static_cast(blockIdx.x) * blockDim.x + threadIdx.x; @@ -87,40 +58,7 @@ __global__ void merge_experts(const float* residual, const float* shared, const output[index] = __bfloat162float(__float2bfloat16_rn(__fadd_rn(residual[index], mixture))); } -void merge(tvm::ffi::TensorView residual, tvm::ffi::TensorView shared, tvm::ffi::TensorView values, - tvm::ffi::TensorView weights, tvm::ffi::TensorView output) { - for (const auto& tensor : {residual, shared, values, weights, output}) { - const auto dtype = tensor.dtype(); - if (!tensor.IsContiguous() || tensor.device().device_type != kDLCUDA || - tensor.device().device_id != residual.device().device_id || dtype.code != kDLFloat || - dtype.bits != 32 || dtype.lanes != 1) - TVM_FFI_THROW(ValueError) - << "minimax_m3 expert merge requires contiguous CUDA FP32 tensors"; - } - if (residual.ndim() != 2 || shared.ndim() != 2 || values.ndim() != 3 || weights.ndim() != 2 || - output.ndim() != 2 || residual.size(0) < 1 || residual.size(0) > 128 || - residual.size(1) != 6144 || shared.size(0) != residual.size(0) || shared.size(1) != 6144 || - output.size(0) != residual.size(0) || output.size(1) != 6144 || - values.size(0) != residual.size(0) || values.size(1) != 4 || values.size(2) != 6144 || - weights.size(0) != residual.size(0) || weights.size(1) != 4) - TVM_FFI_THROW(ValueError) << "minimax_m3 expert merge tensor shape mismatch"; - const auto pointer = [](tvm::ffi::TensorView tensor) { - return reinterpret_cast(static_cast(tensor.data_ptr()) + - tensor.byte_offset()); - }; - const auto stream = - reinterpret_cast(TVMFFIEnvGetStream(kDLCUDA, residual.device().device_id)); - const auto count = static_cast(residual.numel()); - merge_experts<<((count + 255) / 256), 256, 0, stream>>>( - pointer(residual), pointer(shared), pointer(values), pointer(weights), pointer(output), - count); - const auto error = cudaGetLastError(); - if (error != cudaSuccess) - TVM_FFI_THROW(RuntimeError) - << "minimax_m3 expert merge launch failed: " << cudaGetErrorString(error); -} -// Re-evaluate the small router in FP64. Its FP32 GEMM tensor supplies the -// output shape; the independently reduced logits define the numeric result. +// Reduce the router dot product in FP64, then round the logit before sigmoid. __global__ void router_scores(const float* hidden, const float* weight, float* output) { __shared__ double sums[256]; const int row = blockIdx.x; @@ -160,51 +98,6 @@ __global__ void router_weights(const float* selected, float* output, int rows) { __ddiv_rn(__dmul_rn(2.0, static_cast(selected[row * 4 + slot])), total)); } -void check_float(tvm::ffi::TensorView tensor, int device) { - const auto dtype = tensor.dtype(); - if (!tensor.IsContiguous() || tensor.device().device_type != kDLCUDA || - tensor.device().device_id != device || dtype.code != kDLFloat || dtype.bits != 32 || - dtype.lanes != 1) - TVM_FFI_THROW(ValueError) << "minimax_m3 routing requires contiguous CUDA FP32 tensors"; -} -float* data(tvm::ffi::TensorView tensor) { - return reinterpret_cast(static_cast(tensor.data_ptr()) + tensor.byte_offset()); -} -void scores(tvm::ffi::TensorView logits, tvm::ffi::TensorView hidden, tvm::ffi::TensorView weight, - tvm::ffi::TensorView output) { - for (const auto& tensor : {logits, hidden, weight, output}) - check_float(tensor, hidden.device().device_id); - if (hidden.ndim() != 2 || hidden.size(0) < 1 || hidden.size(0) > 128 || - hidden.size(1) != 6144 || weight.ndim() != 2 || weight.size(0) != 128 || - weight.size(1) != 6144 || logits.ndim() != 2 || logits.size(0) != hidden.size(0) || - logits.size(1) != 128 || output.ndim() != 2 || output.size(0) != hidden.size(0) || - output.size(1) != 128) - TVM_FFI_THROW(ValueError) << "minimax_m3 routing scores shape mismatch"; - const auto stream = - reinterpret_cast(TVMFFIEnvGetStream(kDLCUDA, hidden.device().device_id)); - router_scores<<(hidden.size(0)), 128), 256, 0, stream>>>( - data(hidden), data(weight), data(output)); - const auto error = cudaGetLastError(); - if (error != cudaSuccess) - TVM_FFI_THROW(RuntimeError) - << "minimax_m3 routing scores launch failed: " << cudaGetErrorString(error); -} -void routing_weights(tvm::ffi::TensorView selected, tvm::ffi::TensorView output) { - for (const auto& tensor : {selected, output}) - check_float(tensor, selected.device().device_id); - if (selected.ndim() != 2 || selected.size(0) < 1 || selected.size(0) > 128 || - selected.size(1) != 4 || output.ndim() != 2 || output.size(0) != selected.size(0) || - output.size(1) != 4) - TVM_FFI_THROW(ValueError) << "minimax_m3 routing weights shape mismatch"; - const auto stream = - reinterpret_cast(TVMFFIEnvGetStream(kDLCUDA, selected.device().device_id)); - router_weights<<<1, 128, 0, stream>>>(data(selected), data(output), - static_cast(selected.size(0))); - const auto error = cudaGetLastError(); - if (error != cudaSuccess) - TVM_FFI_THROW(RuntimeError) - << "minimax_m3 routing weights launch failed: " << cudaGetErrorString(error); -} // One bounded causal head per block. Preserve FP32 score/probability // boundaries while evaluating each reduction before its rounding boundary. __global__ void causal_attention(const float* query, const float* key, const float* value, @@ -245,29 +138,6 @@ __global__ void causal_attention(const float* query, const float* key, const flo output[(row * 64 + head) * 128 + column] = __bfloat162float(__float2bfloat16_rn(__double2float_rn(sum))); } -void attention(tvm::ffi::TensorView query, tvm::ffi::TensorView key, tvm::ffi::TensorView value, - tvm::ffi::TensorView output) { - for (const auto& tensor : {query, key, value, output}) - check_float(tensor, query.device().device_id); - const auto valid = [](tvm::ffi::TensorView tensor, int rows, int heads) { - return tensor.ndim() == 3 && tensor.size(0) == rows && tensor.size(1) == heads && - tensor.size(2) == 128; - }; - if (query.ndim() != 3 || query.size(0) < 1 || query.size(0) > 128 || - !valid(query, static_cast(query.size(0)), 64) || - !valid(key, static_cast(query.size(0)), 4) || - !valid(value, static_cast(query.size(0)), 4) || - !valid(output, static_cast(query.size(0)), 64)) - TVM_FFI_THROW(ValueError) << "minimax_m3 causal attention shape mismatch"; - const auto stream = - reinterpret_cast(TVMFFIEnvGetStream(kDLCUDA, query.device().device_id)); - causal_attention<<(query.size(0)), 64), 128, 0, stream>>>( - data(query), data(key), data(value), data(output)); - const auto error = cudaGetLastError(); - if (error != cudaSuccess) - TVM_FFI_THROW(RuntimeError) - << "minimax_m3 causal attention launch failed: " << cudaGetErrorString(error); -} // Pinned sgl-deep-gemm 0.2.7 NVFP4 pre-dispatch: per-token outer // multiplier, FP8 per-16 scale, then FP4 codes. The outer multiplier remains // factored until the first projection's FP32 epilogue. @@ -312,23 +182,6 @@ __global__ void nv_input_quantize(const float* input, float* encoded, float* out outer[row * width + column] = multiplier; } } -void nv_input(tvm::ffi::TensorView input, tvm::ffi::TensorView encoded, - tvm::ffi::TensorView outer) { - for (const auto& tensor : {input, encoded, outer}) - check_float(tensor, input.device().device_id); - if (input.ndim() != 2 || input.size(0) < 1 || input.size(0) > 128 || input.size(1) != 6144 || - encoded.ndim() != 2 || outer.ndim() != 2 || encoded.size(0) != input.size(0) || - outer.size(0) != input.size(0) || encoded.size(1) != 6144 || outer.size(1) != 6144) - TVM_FFI_THROW(ValueError) << "minimax_m3 NVFP4 input quantization shape mismatch"; - const auto stream = - reinterpret_cast(TVMFFIEnvGetStream(kDLCUDA, input.device().device_id)); - nv_input_quantize<<(input.size(0)), 256, 0, stream>>>( - data(input), data(encoded), data(outer), 6144); - const auto error = cudaGetLastError(); - if (error != cudaSuccess) - TVM_FFI_THROW(RuntimeError) - << "minimax_m3 NVFP4 input quantization launch failed: " << cudaGetErrorString(error); -} __global__ void rotary_position(const float* input, const float* cosine, const float* sine, float* output, int heads, std::size_t count) { const std::size_t index = static_cast(blockIdx.x) * blockDim.x + threadIdx.x; @@ -350,38 +203,286 @@ __global__ void rotary_position(const float* input, const float* cosine, const f : __dadd_rn(__dmul_rn(right, c), __dmul_rn(left, s)); output[index] = __bfloat162float(__float2bfloat16_rn(__double2float_rn(rotated))); } -void rope(tvm::ffi::TensorView input, tvm::ffi::TensorView cosine, tvm::ffi::TensorView sine, - tvm::ffi::TensorView output) { - for (const auto& tensor : {input, cosine, sine, output}) - check_float(tensor, input.device().device_id); - if (input.ndim() != 3 || input.size(0) < 1 || input.size(0) > 128 || - (input.size(1) != 4 && input.size(1) != 64) || input.size(2) != 128 || output.ndim() != 3 || - output.size(0) != input.size(0) || output.size(1) != input.size(1) || - output.size(2) != 128 || cosine.ndim() != 2 || sine.ndim() != 2 || - cosine.size(0) < input.size(0) || cosine.size(0) > 128 || sine.size(0) != cosine.size(0) || - cosine.size(1) != 32 || sine.size(1) != 32) - TVM_FFI_THROW(ValueError) << "minimax_m3 rotary position shape mismatch"; - const auto stream = - reinterpret_cast(TVMFFIEnvGetStream(kDLCUDA, input.device().device_id)); - const auto count = static_cast(input.numel()); - rotary_position<<((count + 255) / 256), 256, 0, stream>>>( - data(input), data(cosine), data(sine), data(output), static_cast(input.size(1)), - count); - const auto error = cudaGetLastError(); - if (error != cudaSuccess) - TVM_FFI_THROW(RuntimeError) - << "minimax_m3 rotary position launch failed: " << cudaGetErrorString(error); + +constexpr char kPluginName[] = "MiniMaxM3Precision"; +constexpr char kPluginVersion[] = "1"; + +// These values are serialized and are also used by precision.py. +enum class Operation : int32_t { + kNorm = 0, + kMerge = 1, + kScores = 2, + kAttention = 3, + kNvInput = 4, + kRope = 5, + kWeights = 6, +}; + +bool matches(const nvinfer1::Dims& dims, std::initializer_list expected) noexcept { + return dims.nbDims == static_cast(expected.size()) && + std::equal(expected.begin(), expected.end(), dims.d); } -} // namespace -TVM_FFI_DLL_EXPORT_TYPED_FUNC(run, run); -TVM_FFI_DLL_EXPORT_TYPED_FUNC(merge, merge); +bool float_linear(const nvinfer1::PluginTensorDesc& tensor) noexcept { + return tensor.type == nvinfer1::DataType::kFLOAT && + tensor.format == nvinfer1::TensorFormat::kLINEAR; +} -TVM_FFI_DLL_EXPORT_TYPED_FUNC(scores, scores); -TVM_FFI_DLL_EXPORT_TYPED_FUNC(routing_weights, routing_weights); +class PrecisionPlugin final : public nvinfer1::IPluginV3, + public nvinfer1::IPluginV3OneCore, + public nvinfer1::IPluginV3OneBuild, + public nvinfer1::IPluginV3OneRuntime { + public: + explicit PrecisionPlugin(int32_t operation) noexcept : operation_(operation) {} -TVM_FFI_DLL_EXPORT_TYPED_FUNC(attention, attention); + const char* getPluginName() const noexcept override { return kPluginName; } + const char* getPluginVersion() const noexcept override { return kPluginVersion; } + const char* getPluginNamespace() const noexcept override { return ""; } -TVM_FFI_DLL_EXPORT_TYPED_FUNC(nv_input, nv_input); + nvinfer1::IPluginCapability* + getCapabilityInterface(nvinfer1::PluginCapabilityType type) noexcept override { + switch (type) { + case nvinfer1::PluginCapabilityType::kCORE: + return static_cast(this); + case nvinfer1::PluginCapabilityType::kBUILD: + return static_cast(this); + case nvinfer1::PluginCapabilityType::kRUNTIME: + return static_cast(this); + } + return nullptr; + } + + PrecisionPlugin* clone() noexcept override { + return new (std::nothrow) PrecisionPlugin(operation_); + } + + nvinfer1::IPluginV3* attachToContext(nvinfer1::IPluginResourceContext*) noexcept override { + return clone(); + } + + int32_t getNbOutputs() const noexcept override { + return operation() == Operation::kNvInput ? 2 : 1; + } + + int32_t getOutputDataTypes(nvinfer1::DataType* outputs, int32_t output_count, + const nvinfer1::DataType* inputs, + int32_t count) const noexcept override { + if (!inputs || !outputs || count != input_count() || output_count != getNbOutputs()) + return -1; + if (!std::all_of(inputs, inputs + count, + [](auto dtype) { return dtype == nvinfer1::DataType::kFLOAT; })) + return -1; + std::fill_n(outputs, output_count, nvinfer1::DataType::kFLOAT); + return 0; + } + + int32_t getOutputShapes(const nvinfer1::DimsExprs* inputs, int32_t count, + const nvinfer1::DimsExprs*, int32_t shape_count, + nvinfer1::DimsExprs* outputs, int32_t output_count, + nvinfer1::IExprBuilder&) noexcept override { + if (!inputs || !outputs || count != input_count() || shape_count != 0 || + output_count != getNbOutputs() || inputs[0].nbDims < 2 || inputs[0].nbDims > 3) + return -1; + std::fill_n(outputs, output_count, inputs[0]); + if (operation() == Operation::kScores) { + if (inputs[0].nbDims != 2 || inputs[1].nbDims != 2) + return -1; + outputs[0].d[1] = inputs[1].d[0]; + } + return 0; + } + + bool supportsFormatCombination(int32_t index, const nvinfer1::DynamicPluginTensorDesc* tensors, + int32_t count, int32_t output_count) noexcept override { + return tensors && count == input_count() && output_count == getNbOutputs() && index >= 0 && + index < count + output_count && float_linear(tensors[index].desc); + } -TVM_FFI_DLL_EXPORT_TYPED_FUNC(rope, rope); + int32_t configurePlugin(const nvinfer1::DynamicPluginTensorDesc* inputs, int32_t count, + const nvinfer1::DynamicPluginTensorDesc* outputs, + int32_t output_count) noexcept override { + if (!inputs || !outputs || count != input_count() || output_count != getNbOutputs()) + return -1; + return 0; + } + + int32_t onShapeChange(const nvinfer1::PluginTensorDesc* inputs, int32_t count, + const nvinfer1::PluginTensorDesc* outputs, + int32_t output_count) noexcept override { + if (!inputs || !outputs || count != input_count() || output_count != getNbOutputs() || + !std::all_of(inputs, inputs + count, float_linear) || + !std::all_of(outputs, outputs + output_count, float_linear)) + return -1; + return valid_shapes(inputs, outputs) ? 0 : -1; + } + + int32_t enqueue(const nvinfer1::PluginTensorDesc* input_desc, + const nvinfer1::PluginTensorDesc* output_desc, const void* const* inputs, + void* const* outputs, void*, cudaStream_t stream) noexcept override { + if (onShapeChange(input_desc, input_count(), output_desc, getNbOutputs()) != 0 || !inputs || + !outputs || !std::all_of(inputs, inputs + input_count(), nonnull) || + !std::all_of(outputs, outputs + getNbOutputs(), nonnull)) + return -1; + + const auto& shape = input_desc[0].dims; + const auto rows = static_cast(shape.d[0]); + const auto input = [inputs](int index) { return static_cast(inputs[index]); }; + auto* output = static_cast(outputs[0]); + switch (operation()) { + case Operation::kNorm: + gemma_norm<<(shape.nbDims == 3 ? rows * shape.d[1] : rows), 256, + 0, stream>>>(input(0), input(1), output, + static_cast(shape.d[shape.nbDims - 1])); + break; + case Operation::kMerge: { + const int size = rows * 6144; + merge_experts<<<(size + 255) / 256, 256, 0, stream>>>(input(0), input(1), input(2), + input(3), output, size); + break; + } + case Operation::kScores: + router_scores<<>>(input(0), input(1), output); + break; + case Operation::kAttention: + causal_attention<<>>(input(0), input(1), input(2), + output); + break; + case Operation::kNvInput: + nv_input_quantize<<>>(input(0), output, + static_cast(outputs[1]), 6144); + break; + case Operation::kRope: { + const int heads = static_cast(shape.d[1]); + const int size = rows * heads * 128; + rotary_position<<<(size + 255) / 256, 256, 0, stream>>>(input(0), input(1), input(2), + output, heads, size); + break; + } + case Operation::kWeights: + router_weights<<<1, 128, 0, stream>>>(input(0), output, rows); + break; + } + return cudaGetLastError() == cudaSuccess ? 0 : -1; + } + + const nvinfer1::PluginFieldCollection* getFieldsToSerialize() noexcept override { + return &fields_; + } + + private: + static bool nonnull(const void* pointer) noexcept { return pointer != nullptr; } + + Operation operation() const noexcept { return static_cast(operation_); } + + int input_count() const noexcept { + switch (operation()) { + case Operation::kNorm: + case Operation::kScores: + return 2; + case Operation::kMerge: + return 4; + case Operation::kAttention: + case Operation::kRope: + return 3; + case Operation::kNvInput: + case Operation::kWeights: + return 1; + } + return 0; + } + + bool valid_shapes(const nvinfer1::PluginTensorDesc* inputs, + const nvinfer1::PluginTensorDesc* outputs) const noexcept { + const auto& shape = inputs[0].dims; + if (shape.nbDims < 2 || shape.nbDims > 3 || shape.d[0] < 1 || shape.d[0] > 128) + return false; + const auto rows = shape.d[0]; + const auto& result = outputs[0].dims; + switch (operation()) { + case Operation::kNorm: { + const auto width = shape.d[shape.nbDims - 1]; + if ((width != 128 && width != 6144) || !matches(inputs[1].dims, {width})) + return false; + if (shape.nbDims == 2) + return matches(result, {rows, width}); + const auto heads = shape.d[1]; + return heads > 0 && heads <= std::numeric_limits::max() / rows && + matches(result, {rows, heads, width}); + } + case Operation::kMerge: + return matches(shape, {rows, 6144}) && matches(inputs[1].dims, {rows, 6144}) && + matches(inputs[2].dims, {rows, 4, 6144}) && matches(inputs[3].dims, {rows, 4}) && + matches(result, {rows, 6144}); + case Operation::kScores: + return matches(shape, {rows, 6144}) && matches(inputs[1].dims, {128, 6144}) && + matches(result, {rows, 128}); + case Operation::kAttention: + return matches(shape, {rows, 64, 128}) && matches(inputs[1].dims, {rows, 4, 128}) && + matches(inputs[2].dims, {rows, 4, 128}) && matches(result, {rows, 64, 128}); + case Operation::kNvInput: + return matches(shape, {rows, 6144}) && matches(result, {rows, 6144}) && + matches(outputs[1].dims, {rows, 6144}); + case Operation::kRope: { + const auto heads = shape.d[1]; + const auto positions = inputs[1].dims.d[0]; + return (heads == 4 || heads == 64) && matches(shape, {rows, heads, 128}) && + positions >= rows && positions <= 128 && + matches(inputs[1].dims, {positions, 32}) && + matches(inputs[2].dims, {positions, 32}) && matches(result, {rows, heads, 128}); + } + case Operation::kWeights: + return matches(shape, {rows, 4}) && matches(result, {rows, 4}); + } + return false; + } + + const int32_t operation_; + const nvinfer1::PluginField field_{"operation", &operation_, nvinfer1::PluginFieldType::kINT32, + 1}; + const nvinfer1::PluginFieldCollection fields_{1, &field_}; +}; + +class PrecisionCreator final : public nvinfer1::IPluginCreatorV3One { + public: + const char* getPluginName() const noexcept override { return kPluginName; } + const char* getPluginVersion() const noexcept override { return kPluginVersion; } + const char* getPluginNamespace() const noexcept override { return ""; } + const nvinfer1::PluginFieldCollection* getFieldNames() noexcept override { return &fields_; } + + nvinfer1::IPluginV3* createPlugin(const char*, const nvinfer1::PluginFieldCollection* fields, + nvinfer1::TensorRTPhase) noexcept override { + if (!fields || fields->nbFields != 1 || !fields->fields) + return nullptr; + const auto& field = fields->fields[0]; + if (!field.name || std::strcmp(field.name, "operation") != 0 || !field.data || + field.type != nvinfer1::PluginFieldType::kINT32 || field.length != 1) + return nullptr; + int32_t operation; + std::memcpy(&operation, field.data, sizeof(operation)); + if (operation < static_cast(Operation::kNorm) || + operation > static_cast(Operation::kWeights)) + return nullptr; + return new (std::nothrow) PrecisionPlugin(operation); + } + + private: + const nvinfer1::PluginField field_{"operation", nullptr, nvinfer1::PluginFieldType::kINT32, 1}; + const nvinfer1::PluginFieldCollection fields_{1, &field_}; +}; +} // namespace + +extern "C" const char* trtmc_minimax_m3_initialize_precision() noexcept { + static PrecisionCreator creator; + static std::mutex mutex; + try { + std::lock_guard lock(mutex); + auto* registry = getPluginRegistry(); + if (registry && (registry->getCreator(kPluginName, kPluginVersion, "") || + registry->registerCreator(creator, "") || + registry->getCreator(kPluginName, kPluginVersion, ""))) + return nullptr; + } catch (...) { + return "MiniMax M3 TensorRT plugin registration failed"; + } + return "MiniMax M3 TensorRT plugin registration failed"; +} diff --git a/families/minimax_m3/tests/test_routing_precision.py b/families/minimax_m3/tests/test_routing_precision.py index a1b840d7c4..870d99f197 100644 --- a/families/minimax_m3/tests/test_routing_precision.py +++ b/families/minimax_m3/tests/test_routing_precision.py @@ -49,11 +49,7 @@ def test_routing_scores_match_decimal_sigmoid_after_exact_dot(): def definition(graph): hidden = graph.input("hidden", (-1, 6144)) weight = graph.input("weight", (128, 6144)) - return { - "scores": add_precision_kernel( - graph.net, "router_scores", [graph.mm(hidden, weight), hidden, weight] - ) - } + return {"scores": add_precision_kernel(graph.net, "router_scores", [hidden, weight])} runner = Runner(definition) hidden = np.ones((1, 6144), np.float32) From 31e8e4a16b59e459ef39ca8553d46c5ed87657ab Mon Sep 17 00:00:00 2001 From: Will Guo Date: Tue, 1 Dec 2026 21:17:24 -0800 Subject: [PATCH 10/10] fix(minimax_m3): bound prefix encoding and pin bundle reads Reject over-capacity prefixes before copying token spans or allocating tokenization buffers. Limit text preparation by the tokenizer vocabulary and preserve checkpoint merge ordering. Keep staged section reads on the validated bundle file across pathname replacement. Signed-off-by: Will Guo --- core/runtime/bundle/bundle_format.cpp | 39 ++++-- core/runtime/include/trtmc/bundle.h | 9 +- core/runtime/tests/test_bundle_format_v1.cpp | 24 ++++ families/minimax_m3/runtime/bpe_tokenizer.cpp | 129 ++++++++++++++---- families/minimax_m3/runtime/pipeline.cpp | 6 +- families/minimax_m3/runtime/tokenizer.h | 5 +- families/minimax_m3/tests/test_tokenizer.py | 39 ++++++ .../minimax_m3/tests/tokenizer_consumer.cpp | 10 +- 8 files changed, 212 insertions(+), 49 deletions(-) diff --git a/core/runtime/bundle/bundle_format.cpp b/core/runtime/bundle/bundle_format.cpp index c524965e88..82cd226352 100644 --- a/core/runtime/bundle/bundle_format.cpp +++ b/core/runtime/bundle/bundle_format.cpp @@ -12,6 +12,7 @@ #include #include #include +#include #include #include #include @@ -141,6 +142,24 @@ std::uint64_t checked_section_file_offset(const BundleSectionInfo& section, } // namespace +struct BundleReader::File { + explicit File(const std::string& path) { + // Section reads supply their own buffers. + stream.rdbuf()->pubsetbuf(nullptr, 0); + stream.open(path, std::ios::binary); + } + + bool read(std::uint64_t offset, char* data, std::streamsize size) { + const std::scoped_lock lock(mutex); + stream.clear(); + stream.seekg(static_cast(offset)); + return static_cast(stream.read(data, size)); + } + + std::ifstream stream; + std::mutex mutex; +}; + BundleReader::BundleReader(std::string bundle_path) { std::error_code error; path_ = std::filesystem::absolute(std::filesystem::path(bundle_path), error) @@ -148,7 +167,8 @@ BundleReader::BundleReader(std::string bundle_path) { .string(); if (error) throw std::runtime_error("Failed to resolve bundle path: " + error.message()); - std::ifstream in(path_, std::ios::binary); + file_ = std::make_shared(path_); + auto& in = file_->stream; if (!in) { throw std::runtime_error("Failed to open bundle file: " + path_); } @@ -218,12 +238,7 @@ std::vector BundleReader::read_section_range(std::string_view name, std::u std::vector data(static_cast(length)); if (data.empty()) return data; - std::ifstream in(path_, std::ios::binary); - if (!in) - throw std::runtime_error("Failed to open bundle file: " + path_); - in.seekg(static_cast(file_offset)); - in.read(data.data(), static_cast(data.size())); - if (!in) { + if (!file_->read(file_offset, data.data(), static_cast(data.size()))) { throw std::runtime_error("Failed to read bundle section '" + section->name + "' from: " + path_); } @@ -234,25 +249,23 @@ void BundleReader::copy_section(std::string_view name, std::ostream& output) con const auto* section = find_section(name); if (section == nullptr) throw std::runtime_error("Bundle section not found: " + std::string(name)); - const auto offset = checked_section_file_offset(*section, data_offset_, file_size_, path_); + auto offset = checked_section_file_offset(*section, data_offset_, file_size_, path_); if (offset > static_cast(std::numeric_limits::max())) throw std::runtime_error("Bundle section has an unsupported file offset: " + path_); - std::ifstream input(path_, std::ios::binary); - input.seekg(static_cast(offset)); - if (!input || !output) + if (!output) throw std::runtime_error("Cannot copy bundle section: " + std::string(name)); std::array buffer; auto remaining = section->length; while (remaining != 0) { const auto count = static_cast(std::min(remaining, buffer.size())); - input.read(buffer.data(), count); - if (!input) + if (!file_->read(offset, buffer.data(), count)) throw std::runtime_error("Failed reading bundle section: " + std::string(name)); output.write(buffer.data(), count); if (!output) throw std::runtime_error("Failed writing bundle section: " + std::string(name)); remaining -= static_cast(count); + offset += static_cast(count); } } diff --git a/core/runtime/include/trtmc/bundle.h b/core/runtime/include/trtmc/bundle.h index ff6f3161bd..628d9fca61 100644 --- a/core/runtime/include/trtmc/bundle.h +++ b/core/runtime/include/trtmc/bundle.h @@ -7,6 +7,7 @@ #include #include +#include #include #include #include @@ -33,9 +34,9 @@ struct BundleInfo { std::vector sections; }; -// Validates a bundle once and reads named sections directly from the file. -// The reader owns its path and metadata, so copies remain valid after the -// caller that created them returns. +// Validates a bundle once and reads named sections from the same open file. +// Copies share the file handle. Publish updates by replacing the file, and +// keep the contents of each opened bundle immutable. class BundleReader { public: explicit BundleReader(std::string bundle_path); @@ -57,10 +58,12 @@ class BundleReader { void copy_section(std::string_view name, std::ostream& output) const; private: + struct File; std::string path_; BundleInfo info_; std::uint64_t data_offset_{0}; std::uint64_t file_size_{0}; + std::shared_ptr file_; }; // Read metadata without loading the engine. diff --git a/core/runtime/tests/test_bundle_format_v1.cpp b/core/runtime/tests/test_bundle_format_v1.cpp index a360da958a..bea9e72639 100644 --- a/core/runtime/tests/test_bundle_format_v1.cpp +++ b/core/runtime/tests/test_bundle_format_v1.cpp @@ -83,6 +83,29 @@ void test_copy_section(const std::filesystem::path& directory) { check(fails("data", output), "stream copy detects truncation after validation"); } +void test_replaced_bundle(const std::filesystem::path& directory) { + const auto path = directory / "published.bundle"; + const auto replacement = directory / "replacement.bundle"; + const std::string header = + R"({"format":1,"family":"fake","task":"text","backend":"fake","sections":{"data":{"offset":0,"length":4}}})"; + write_bundle(path, header, "old!"); + const auto open_reader = [&] { + const trtmc::BundleReader reader(path.string()); + return trtmc::BundleReader(reader); + }; + const auto existing = open_reader(); + write_bundle(replacement, header, "new!"); + std::filesystem::rename(replacement, path); + + const auto range = existing.read_section_range("data", 0, 3); + check(std::string(range.begin(), range.end()) == "old", "open reader keeps original range"); + std::ostringstream original; + existing.copy_section("data", original); + check(original.str() == "old!", "open reader streams original file"); + const auto current = open_reader().read_section("data"); + check(std::string(current.begin(), current.end()) == "new!", "new reader sees replacement"); +} + } // namespace int main() { @@ -162,6 +185,7 @@ int main() { check(read_throws(out_of_bounds), "out of bounds section rejected"); test_copy_section(directory); + test_replaced_bundle(directory); std::filesystem::remove_all(directory); std::cerr << (failures == 0 ? "ALL PASSED\n" : "SOME FAILED\n"); return failures; diff --git a/families/minimax_m3/runtime/bpe_tokenizer.cpp b/families/minimax_m3/runtime/bpe_tokenizer.cpp index 9fb4477913..d6212b9fb4 100644 --- a/families/minimax_m3/runtime/bpe_tokenizer.cpp +++ b/families/minimax_m3/runtime/bpe_tokenizer.cpp @@ -7,11 +7,13 @@ #include #include #include -#include +#include #include +#include #include #include #include +#include #include #include #include @@ -19,6 +21,15 @@ namespace trtmc { namespace { +// Canonically equivalent strings have the same NFD code-point count. A +// canonical decomposition has at most four code points, and each source +// code point takes at most four UTF-8 bytes. +constexpr std::size_t kRawBytesPerNormalizedByte = 16; + +[[noreturn]] void prefix_too_long() { + throw std::invalid_argument("minimax_m3 prefix and requested output must fit bundle capacity"); +} + std::string utf8(UChar32 point) { char buffer[4]; int32_t size = 0; @@ -48,6 +59,10 @@ class Tokenizer final : public ITokenizer { const int id = item.value(); vocabulary_[item.key()] = id; pieces_[id] = item.key(); + // The ByteLevel alphabet maps each source byte to one code point. + const auto byte_count = std::count_if(item.key().begin(), item.key().end(), + [](unsigned char c) { return !U8_IS_TRAIL(c); }); + max_piece_bytes_ = std::max(max_piece_bytes_, static_cast(byte_count)); } int rank = 0; for (const auto& merge : config.at("model").at("merges")) { @@ -73,6 +88,7 @@ class Tokenizer final : public ITokenizer { if (text.empty()) throw std::runtime_error("empty MiniMax added-token content"); const int id = token.at("id"); + max_piece_bytes_ = std::max(max_piece_bytes_, text.size()); added_.emplace_back(text, id); pieces_[id] = text; vocabulary_[text] = id; @@ -92,28 +108,35 @@ class Tokenizer final : public ITokenizer { if (U_FAILURE(status) || !pattern_) throw std::runtime_error("invalid MiniMax tokenizer regex"); } - std::vector encode(const std::string& text) const override { + std::vector encode(std::string_view text, std::size_t max_tokens) const override { if (text.size() > INT_MAX) throw std::invalid_argument("MiniMax tokenizer input is too large"); + if (!text.empty() && + (text.size() - 1) / kRawBytesPerNormalizedByte / max_piece_bytes_ >= max_tokens) + prefix_too_long(); std::vector result; std::size_t position = 0; while (position < text.size()) { - std::size_t found = std::string::npos; + if (result.size() == max_tokens) + prefix_too_long(); + std::size_t found = std::string_view::npos; const std::pair* token = nullptr; for (const auto& item : added_) { auto at = text.find(item.first, position); - if (at != std::string::npos && + if (at != std::string_view::npos && (at < found || (at == found && token && item.first.size() > token->first.size()))) { found = at; token = &item; } } - const auto end = found == std::string::npos ? text.size() : found; + const auto end = found == std::string_view::npos ? text.size() : found; if (end > position) - encode_plain(text.substr(position, end - position), result); + encode_plain(text.substr(position, end - position), result, max_tokens); if (!token) break; + if (result.size() == max_tokens) + prefix_too_long(); result.push_back(token->second); position = found + token->first.size(); } @@ -154,11 +177,79 @@ class Tokenizer final : public ITokenizer { std::string token_for_id(int32_t id) const override { return pieces_.at(id); } private: - void encode_plain(const std::string& text, std::vector& result) const { + void encode_piece(std::string_view bytes, std::vector& result, + std::size_t max_tokens) const { + struct Symbol { + std::string text; + std::size_t previous; + std::size_t next; + }; + const auto end = bytes.size(); + std::vector symbols; + symbols.reserve(end); + for (std::size_t i = 0; i < end; ++i) + symbols.push_back( + {bytes_[static_cast(bytes[i])], i ? i - 1 : end, i + 1}); + + // Rank first, then the leftmost occurrence, as in the checkpoint BPE. + using Candidate = std::pair; + std::priority_queue, std::greater> queue; + const auto rank = [&](std::size_t left) { + const auto& symbol = symbols[left]; + return ranks_.find(symbol.text + '\0' + symbols[symbol.next].text); + }; + const auto consider = [&](std::size_t left) { + if (left != end && symbols[left].next != end) { + const auto it = rank(left); + if (it != ranks_.end()) + queue.emplace(it->second, left); + } + }; + for (std::size_t i = 0; i < end; ++i) + consider(i); + while (!queue.empty()) { + const auto [expected_rank, left] = queue.top(); + queue.pop(); + auto& symbol = symbols[left]; + if (symbol.text.empty() || symbol.next == end) + continue; + const auto it = rank(left); + if (it == ranks_.end() || it->second != expected_rank) + continue; + auto& right = symbols[symbol.next]; + symbol.text += right.text; + right.text.clear(); + symbol.next = right.next; + if (symbol.next != end) + symbols[symbol.next].previous = left; + consider(symbol.previous); + consider(left); + } + for (const auto& symbol : symbols) { + if (symbol.text.empty()) + continue; + if (result.size() == max_tokens) + prefix_too_long(); + result.push_back(vocabulary_.at(symbol.text)); + } + } + + void encode_plain(std::string_view text, std::vector& result, + std::size_t max_tokens) const { UErrorCode status = U_ZERO_ERROR; const auto* nfc = icu::Normalizer2::getNFCInstance(status); + if (U_FAILURE(status) || !nfc) + throw std::runtime_error("MiniMax tokenizer initialization failed"); icu::UnicodeString normalized; - nfc->normalize(icu::UnicodeString::fromUTF8(text), normalized, status); + nfc->normalize(icu::UnicodeString::fromUTF8(icu::StringPiece(text.data(), text.size())), + normalized, status); + if (U_FAILURE(status)) + throw std::runtime_error("MiniMax tokenizer normalization failed"); + std::string normalized_bytes; + normalized.toUTF8String(normalized_bytes); + if (!normalized_bytes.empty() && + (normalized_bytes.size() - 1) / max_piece_bytes_ >= max_tokens - result.size()) + prefix_too_long(); std::unique_ptr matcher(pattern_->matcher(normalized, status)); if (U_FAILURE(status) || !matcher) throw std::runtime_error("MiniMax tokenizer normalization failed"); @@ -170,26 +261,7 @@ class Tokenizer final : public ITokenizer { consumed = end; std::string bytes; normalized.tempSubStringBetween(start, end).toUTF8String(bytes); - std::vector parts; - for (unsigned char byte : bytes) - parts.push_back(bytes_[byte]); - while (parts.size() > 1) { - std::size_t selected = parts.size(); - int best = std::numeric_limits::max(); - for (std::size_t i = 0; i + 1 < parts.size(); ++i) { - auto it = ranks_.find(parts[i] + std::string(1, '\0') + parts[i + 1]); - if (it != ranks_.end() && it->second < best) { - best = it->second; - selected = i; - } - } - if (selected == parts.size()) - break; - parts[selected] += parts[selected + 1]; - parts.erase(parts.begin() + selected + 1); - } - for (const auto& part : parts) - result.push_back(vocabulary_.at(part)); + encode_piece(bytes, result, max_tokens); } if (U_FAILURE(status) || consumed != normalized.length()) throw std::runtime_error("MiniMax tokenizer regex failed"); @@ -201,6 +273,7 @@ class Tokenizer final : public ITokenizer { std::unordered_set special_; std::vector> added_; std::unique_ptr pattern_; + std::size_t max_piece_bytes_ = 1; }; } // namespace std::unique_ptr CreateBpeTokenizer(const char* data, std::size_t size, diff --git a/families/minimax_m3/runtime/pipeline.cpp b/families/minimax_m3/runtime/pipeline.cpp index c077d398d1..415020978f 100644 --- a/families/minimax_m3/runtime/pipeline.cpp +++ b/families/minimax_m3/runtime/pipeline.cpp @@ -224,11 +224,15 @@ TextResult Pipeline::run(const internal::TextContinuationRequest& request, const auto count = *internal::config_get(config, {fields, 1}, "max_new_tokens"); if (count < 1 || count > capacity_) throw internal::ConfigError("minimax_m3 invalid max_new_tokens"); + const auto max_prefix = static_cast(capacity_ - count); std::vector ids; if (const auto* text = std::get_if(&request.prefix)) - ids = tokenizer_->encode(std::string(*text)); + ids = tokenizer_->encode(*text, max_prefix); else { auto span = std::get>(request.prefix); + if (span.size() > max_prefix) + throw std::invalid_argument( + "minimax_m3 prefix and requested output must fit bundle capacity"); ids.assign(span.begin(), span.end()); } return generate_ids(std::move(ids), static_cast(count)); diff --git a/families/minimax_m3/runtime/tokenizer.h b/families/minimax_m3/runtime/tokenizer.h index 2c98fb58a9..56bdd9253a 100644 --- a/families/minimax_m3/runtime/tokenizer.h +++ b/families/minimax_m3/runtime/tokenizer.h @@ -6,6 +6,7 @@ #pragma once #include +#include #include #include #include @@ -16,7 +17,9 @@ namespace trtmc { class ITokenizer { public: virtual ~ITokenizer() = default; - virtual std::vector encode(const std::string& text) const = 0; + virtual std::vector + encode(std::string_view text, + std::size_t max_tokens = std::numeric_limits::max()) const = 0; virtual std::string decode(const std::vector& ids) const = 0; virtual std::int32_t id_for_token(std::string_view token) const = 0; virtual std::string token_for_id(std::int32_t id) const = 0; diff --git a/families/minimax_m3/tests/test_tokenizer.py b/families/minimax_m3/tests/test_tokenizer.py index 18a6e0bc8f..ec38c4bd69 100644 --- a/families/minimax_m3/tests/test_tokenizer.py +++ b/families/minimax_m3/tests/test_tokenizer.py @@ -87,3 +87,42 @@ def test_rejects_empty_added_token_at_load(tmp_path, tokenizer_binary, reference ) assert completed.returncode == 1 assert "empty MiniMax added-token content" in completed.stderr + + +@pytest.mark.parametrize( + ("text", "budget", "fits"), + [ + ("aaaa", 2, True), + ("aaaaa", 2, False), + ("aaaaa", 4, True), + ("aaaaa", 3, False), + ("e\u0301", 1, True), + ("a" * 8192, 1, False), + ], +) +def test_prefix_budget(tmp_path, tokenizer_binary, reference_tokenizer, text, budget, fits): + reference = reference_tokenizer + reference.model = models.BPE( + vocab={"a": 0, "aa": 1, "Ã": 2, "©": 3, "é": 4}, + merges=[("a", "a"), ("Ã", "©")], + ) + reference.add_tokens([AddedToken("", normalized=False)]) + tokenizer_path = tmp_path / "tokenizer.json" + tokenizer_path.write_text(reference.to_str()) + requests = tmp_path / "requests.json" + requests.write_text(json.dumps([text])) + expected = reference.encode(text).ids + assert (len(expected) <= budget) == fits + + completed = subprocess.run( + [str(tokenizer_binary), str(tokenizer_path), str(requests), str(budget)], + capture_output=True, + text=True, + timeout=10, + ) + if fits: + completed.check_returncode() + assert json.loads(completed.stdout)[0]["ids"] == expected + else: + assert completed.returncode == 1 + assert "prefix and requested output must fit bundle capacity" in completed.stderr diff --git a/families/minimax_m3/tests/tokenizer_consumer.cpp b/families/minimax_m3/tests/tokenizer_consumer.cpp index ea4c37ed5b..efa4085b85 100644 --- a/families/minimax_m3/tests/tokenizer_consumer.cpp +++ b/families/minimax_m3/tests/tokenizer_consumer.cpp @@ -6,11 +6,14 @@ #include #include +#include #include int main(int argc, char** argv) { - if (argc != 3) + if (argc != 3 && argc != 4) return 2; try { + const auto max_tokens = + argc == 4 ? std::stoul(argv[3]) : std::numeric_limits::max(); std::ifstream input(argv[1], std::ios::binary); std::string raw((std::istreambuf_iterator(input)), {}); auto tokenizer = trtmc::CreateBpeTokenizer(raw.data(), raw.size(), false); @@ -19,8 +22,9 @@ int main(int argc, char** argv) { requests >> samples; nlohmann::json result = nlohmann::json::array(); for (const auto& sample : samples) { - auto ids = sample.is_array() ? sample.get>() - : tokenizer->encode(sample.get()); + auto ids = sample.is_array() + ? sample.get>() + : tokenizer->encode(sample.get_ref(), max_tokens); result.push_back({{"ids", ids}, {"decoded", tokenizer->decode(ids)}}); } std::cout << result.dump() << '\n';