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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
57 changes: 42 additions & 15 deletions core/runtime/bundle/bundle_format.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
#include <fstream>
#include <initializer_list>
#include <limits>
#include <mutex>
#include <nlohmann/json.hpp>
#include <stdexcept>
#include <string_view>
Expand Down Expand Up @@ -141,14 +142,33 @@ 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<std::streamoff>(offset));
return static_cast<bool>(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)
.lexically_normal()
.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<File>(path_);
auto& in = file_->stream;
if (!in) {
throw std::runtime_error("Failed to open bundle file: " + path_);
}
Expand Down Expand Up @@ -195,21 +215,30 @@ std::vector<char> 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<char> 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::uint64_t>(std::numeric_limits<std::streamoff>::max()))
throw std::runtime_error("Bundle section '" + section->name +
"' has an unsupported file offset: " + path_);

std::vector<char> data(static_cast<std::size_t>(section->length));
if (length > std::vector<char>().max_size() ||
length > static_cast<std::uint64_t>(std::numeric_limits<std::streamsize>::max()))
throw std::runtime_error("Bundle section range cannot be represented: " +
std::string(name));
std::vector<char> data(static_cast<std::size_t>(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<std::streamoff>(file_offset));
in.read(data.data(), static_cast<std::streamsize>(data.size()));
if (!in) {
if (!file_->read(file_offset, data.data(), static_cast<std::streamsize>(data.size()))) {
throw std::runtime_error("Failed to read bundle section '" + section->name +
"' from: " + path_);
}
Expand All @@ -220,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::uint64_t>(std::numeric_limits<std::streamoff>::max()))
throw std::runtime_error("Bundle section has an unsupported file offset: " + path_);
std::ifstream input(path_, std::ios::binary);
input.seekg(static_cast<std::streamoff>(offset));
if (!input || !output)
if (!output)
throw std::runtime_error("Cannot copy bundle section: " + std::string(name));
std::array<char, 64 * 1024> buffer;
auto remaining = section->length;
while (remaining != 0) {
const auto count =
static_cast<std::streamsize>(std::min<std::uint64_t>(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<std::uint64_t>(count);
offset += static_cast<std::uint64_t>(count);
}
}

Expand Down
14 changes: 11 additions & 3 deletions core/runtime/include/trtmc/bundle.h
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@

#include <cstdint>
#include <iosfwd>
#include <memory>
#include <string>
#include <string_view>
#include <utility>
Expand All @@ -33,9 +34,9 @@ struct BundleInfo {
std::vector<BundleSectionInfo> 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);
Expand All @@ -45,17 +46,24 @@ class BundleReader {
const BundleSectionInfo* find_section(std::string_view name) const noexcept;
std::vector<char> 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<char> 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.
/// @throws std::runtime_error If the section is absent or input/output fails.
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> file_;
};

// Read metadata without loading the engine.
Expand Down
51 changes: 51 additions & 0 deletions core/runtime/tests/test_bundle_format_v1.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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() {
Expand All @@ -101,6 +124,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<std::pair<uint64_t, uint64_t>>{
{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);
Expand Down Expand Up @@ -135,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;
Expand Down
142 changes: 142 additions & 0 deletions families/minimax_m3/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,142 @@
# 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). Python dependencies are
provided by the repository's base environment. No
family-specific Python package installation is required.

```bash
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 \
--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.

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

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
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
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
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.
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
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
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 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,
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"
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
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. These cases do not
establish corpus-level accuracy, chat/vision/video support,
long-context behavior, performance, or other hardware/TensorRT cohorts.
4 changes: 4 additions & 0 deletions families/minimax_m3/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0

"""MiniMax M3 sparse mixture-of-experts text continuation."""
Loading
Loading