From f7a3c463f7ace1cc3c7fb0d5039808e5c16ddfeb Mon Sep 17 00:00:00 2001 From: Will Guo Date: Fri, 13 Nov 2026 01:36:38 -0800 Subject: [PATCH 1/6] Add Ling3 hybrid KDA and MLA text runtime Implement family-owned FP32 KDA recurrence, causal convolution history, interleaved MLA position embeddings, and group-limited sparse experts. Add NFC byte-level tokenization and pinned full-prefix reference generation tests. Signed-off-by: Will Guo --- families/bailing_hybrid/__init__.py | 0 families/bailing_hybrid/model.py | 469 +++++ families/bailing_hybrid/requirements.txt | 4 + .../bailing_hybrid/runtime/CMakeLists.txt | 24 + .../bailing_hybrid/runtime/bpe_tokenizer.cpp | 1656 +++++++++++++++++ families/bailing_hybrid/runtime/plugin.cpp | 188 ++ families/bailing_hybrid/runtime/tokenizer.h | 33 + families/bailing_hybrid/support.py | 10 + families/bailing_hybrid/tests/__init__.py | 0 .../bailing_hybrid/tests/cpp/test_runtime.cpp | 28 + .../tests/cpp/test_tokenizer.cpp | 17 + .../tests/manifests/ling-3.0-tiny.json | 23 + .../bailing_hybrid/tests/requirements.txt | 5 + families/bailing_hybrid/tests/test_e2e.py | 227 +++ families/bailing_hybrid/tests/test_support.py | 9 + 15 files changed, 2693 insertions(+) create mode 100644 families/bailing_hybrid/__init__.py create mode 100644 families/bailing_hybrid/model.py create mode 100644 families/bailing_hybrid/requirements.txt create mode 100644 families/bailing_hybrid/runtime/CMakeLists.txt create mode 100644 families/bailing_hybrid/runtime/bpe_tokenizer.cpp create mode 100644 families/bailing_hybrid/runtime/plugin.cpp create mode 100644 families/bailing_hybrid/runtime/tokenizer.h create mode 100644 families/bailing_hybrid/support.py create mode 100644 families/bailing_hybrid/tests/__init__.py create mode 100644 families/bailing_hybrid/tests/cpp/test_runtime.cpp create mode 100644 families/bailing_hybrid/tests/cpp/test_tokenizer.cpp create mode 100644 families/bailing_hybrid/tests/manifests/ling-3.0-tiny.json create mode 100644 families/bailing_hybrid/tests/requirements.txt create mode 100644 families/bailing_hybrid/tests/test_e2e.py create mode 100644 families/bailing_hybrid/tests/test_support.py diff --git a/families/bailing_hybrid/__init__.py b/families/bailing_hybrid/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/families/bailing_hybrid/model.py b/families/bailing_hybrid/model.py new file mode 100644 index 0000000000..e30b41fae0 --- /dev/null +++ b/families/bailing_hybrid/model.py @@ -0,0 +1,469 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +"""Incremental Ling3 hybrid KDA/MLA decoder and group-limited routed experts.""" + +import json +from contextlib import ExitStack +from pathlib import Path + +import numpy as np +import tensorrt as trt + + +class Weights: + def __init__(self, directory, stack): + from safetensors import safe_open + + self.index = json.loads((directory / "model.safetensors.index.json").read_text())[ + "weight_map" + ] + self.files = { + name: stack.enter_context( + safe_open(str(directory / name), framework="pt", device="cpu") + ) + for name in set(self.index.values()) + } + + def read(self, name): + return self.files[self.index[name]].get_tensor(name).float().numpy() + + +class PlanWriter(trt.IStreamWriter): + def __init__(self, stream): + super().__init__() + self.stream = stream + + def write(self, data): + return self.stream.write(data) + + +class Graph: + def __init__(self, weights, cfg, logger): + self.weights, self.cfg, self.logger = weights, cfg, logger + self.builder = trt.Builder(logger) + self.net = self.builder.create_network( + 1 << int(trt.NetworkDefinitionCreationFlag.STRONGLY_TYPED) + ) + + def const(self, value, dtype=np.float32): + value = np.ascontiguousarray(value, dtype=dtype) + return self.net.add_constant(value.shape, value).get_output(0) + + def op(self, a, b, kind): + return self.net.add_elementwise(a, b, kind).get_output(0) + + def add(self, a, b): + return self.op(a, b, trt.ElementWiseOperation.SUM) + + def mul(self, a, b): + return self.op(a, b, trt.ElementWiseOperation.PROD) + + def reshape(self, value, shape): + layer = self.net.add_shuffle(value) + layer.reshape_dims = shape + return layer.get_output(0) + + def concat(self, tensors, axis): + layer = self.net.add_concatenation(tensors) + layer.axis = axis + return layer.get_output(0) + + def reduce(self, x, kind, axes, keep=True): + return self.net.add_reduce(x, kind, axes, keep).get_output(0) + + def unary(self, x, kind): + return self.net.add_unary(x, kind).get_output(0) + + def sigmoid(self, x): + return self.net.add_activation(x, trt.ActivationType.SIGMOID).get_output(0) + + def silu(self, x): + return self.mul(x, self.sigmoid(x)) + + def linear(self, x, name): + return self.net.add_matrix_multiply( + x, + trt.MatrixOperation.NONE, + self.const(self.weights.read(name + ".weight")), + trt.MatrixOperation.TRANSPOSE, + ).get_output(0) + + def norm(self, x, name): + axis = len(x.shape) - 1 + average = self.reduce(self.mul(x, x), trt.ReduceOperation.AVG, 1 << axis) + root = self.unary( + self.add(average, self.const(np.full((1,) * len(x.shape), self.cfg["rms_norm_eps"]))), + trt.UnaryOperation.SQRT, + ) + normalized = self.op(x, root, trt.ElementWiseOperation.DIV) + gamma = self.weights.read(name + ".weight").reshape((1,) * axis + (int(x.shape[-1]),)) + return self.mul(normalized, self.const(gamma)) + + def dense(self, x, name): + return self.linear( + self.mul( + self.silu(self.linear(x, name + ".gate_proj")), self.linear(x, name + ".up_proj") + ), + name + ".down_proj", + ) + + def output(self, value, name): + value.name = name + self.net.mark_output(value) + + def save(self, stream): + options = self.builder.create_builder_config() + options.clear_flag(trt.BuilderFlag.TF32) + options.builder_optimization_level = 3 + if not self.builder.build_serialized_network_to_stream( + self.net, options, PlanWriter(stream) + ): + raise RuntimeError("Ling3 engine build failed") + + def kda(self, hidden, prefix): + net, cfg = self.net, self.cfg + heads, dim, kernel = ( + cfg["num_attention_heads"], + cfg["head_dim"], + cfg["short_conv_kernel_size"], + ) + channels = heads * dim + vectors = [] + for kind in ("q", "k", "v"): + projected = self.reshape(self.linear(hidden, prefix + f".{kind}_proj"), (channels, 1)) + history = net.add_input(f"conv_{kind}", trt.float32, (channels, kernel - 1)) + taps = self.concat([history, projected], 1) + present = net.add_slice(taps, (0, 1), (channels, kernel - 1), (1, 1)).get_output(0) + self.output(present, f"present_conv_{kind}") + weight = self.weights.read(prefix + f".{kind}_conv1d.weight").reshape(channels, kernel) + filtered = self.reduce( + self.mul(taps, self.const(weight)), trt.ReduceOperation.SUM, 2, False + ) + vectors.append(self.reshape(self.silu(filtered), (heads, dim))) + query, key, value = vectors + + def l2norm(x): + squared = self.reduce(self.mul(x, x), trt.ReduceOperation.SUM, 2) + root = self.unary(self.add(squared, self.const([[1e-6]])), trt.UnaryOperation.SQRT) + return self.op(x, root, trt.ElementWiseOperation.DIV) + + query = self.mul(l2norm(query), self.const([[dim**-0.5]])) + key = l2norm(key) + gate = self.reshape(self.linear(hidden, prefix + ".f_proj"), (heads, dim)) + gate = self.add( + gate, self.const(self.weights.read(prefix + ".dt_bias").reshape(heads, dim)) + ) + gate = self.mul( + gate, self.const(np.exp(self.weights.read(prefix + ".A_log")).reshape(heads, 1)) + ) + decay = self.unary( + self.mul(self.sigmoid(gate), self.const([[cfg["kda_lower_bound"]]])), + trt.UnaryOperation.EXP, + ) + state = net.add_input("state", trt.float32, (heads, dim, dim)) + state = self.mul(state, self.reshape(decay, (heads, dim, 1))) + predicted = self.reduce( + self.mul(state, self.reshape(key, (heads, dim, 1))), trt.ReduceOperation.SUM, 2, False + ) + beta = self.reshape(self.sigmoid(self.linear(hidden, prefix + ".b_proj")), (heads, 1)) + innovation = self.mul(self.op(value, predicted, trt.ElementWiseOperation.SUB), beta) + state = self.add( + state, + self.mul(self.reshape(key, (heads, dim, 1)), self.reshape(innovation, (heads, 1, dim))), + ) + self.output(state, "present_state") + attended = self.reduce( + self.mul(state, self.reshape(query, (heads, dim, 1))), trt.ReduceOperation.SUM, 2, False + ) + attended = self.norm(attended, prefix + ".o_norm") + gate = self.reshape(self.sigmoid(self.linear(hidden, prefix + ".g_proj")), (heads, dim)) + return self.linear( + self.reshape(self.mul(attended, gate), (1, channels)), prefix + ".o_proj" + ) + + def mla(self, hidden, prefix, length): + import torch + + net, cfg = self.net, self.cfg + heads, dim, nope, rotary, value_dim = ( + cfg[k] + for k in ( + "num_attention_heads", + "qk_head_dim", + "qk_nope_head_dim", + "qk_rope_head_dim", + "v_head_dim", + ) + ) + position = net.add_input("position", trt.int32, (1,)) + query = self.linear( + self.norm(self.linear(hidden, prefix + ".q_a_proj"), prefix + ".q_a_layernorm"), + prefix + ".q_b_proj", + ) + query = self.reshape(query, (1, heads, 1, dim)) + q_pass = net.add_slice(query, (0, 0, 0, 0), (1, heads, 1, nope), (1, 1, 1, 1)).get_output(0) + q_rot = net.add_slice( + query, (0, 0, 0, nope), (1, heads, 1, rotary), (1, 1, 1, 1) + ).get_output(0) + compressed = self.linear(hidden, prefix + ".kv_a_proj_with_mqa") + rank = cfg["kv_lora_rank"] + latent = net.add_slice(compressed, (0, 0), (1, rank), (1, 1)).get_output(0) + k_rot = self.reshape( + net.add_slice(compressed, (0, rank), (1, rotary), (1, 1)).get_output(0), + (1, 1, 1, rotary), + ) + expanded = self.reshape( + self.linear(self.norm(latent, prefix + ".kv_a_layernorm"), prefix + ".kv_b_proj"), + (1, heads, 1, nope + value_dim), + ) + k_pass = net.add_slice( + expanded, (0, 0, 0, 0), (1, heads, 1, nope), (1, 1, 1, 1) + ).get_output(0) + value = net.add_slice( + expanded, (0, 0, 0, nope), (1, heads, 1, value_dim), (1, 1, 1, 1) + ).get_output(0) + with torch.no_grad(): + inverse = 1 / (cfg["rope_theta"] ** (torch.arange(0, rotary, 2).float() / rotary)) + frequencies = torch.arange(length).float()[:, None] * inverse[None] + frequencies = torch.cat([frequencies, frequencies], -1) + cosine, sine = [ + self.reshape( + net.add_gather(self.const(t.numpy()), position, 0).get_output(0), + (1, 1, 1, rotary), + ) + for t in (frequencies.cos(), frequencies.sin()) + ] + + def rope(x, count): + grouped = self.reshape(x, (1, count, 1, rotary // 2, 2)) + shuffled = net.add_shuffle(grouped) + shuffled.first_transpose = (0, 1, 2, 4, 3) + shuffled.reshape_dims = (1, count, 1, rotary) + x = shuffled.get_output(0) + first = net.add_slice( + x, (0, 0, 0, 0), (1, count, 1, rotary // 2), (1, 1, 1, 1) + ).get_output(0) + second = net.add_slice( + x, (0, 0, 0, rotary // 2), (1, count, 1, rotary // 2), (1, 1, 1, 1) + ).get_output(0) + return self.add( + self.mul(x, cosine), + self.mul(self.concat([self.unary(second, trt.UnaryOperation.NEG), first], 3), sine), + ) + + query = self.concat([q_pass, rope(q_rot, heads)], 3) + key = self.concat( + [k_pass, self.add(rope(k_rot, 1), self.const(np.zeros((1, heads, 1, rotary))))], 3 + ) + old_k = net.add_input("cache_k", trt.float32, (1, heads, length, dim)) + old_v = net.add_input("cache_v", trt.float32, (1, heads, length, value_dim)) + indices = self.const(np.arange(length), np.int32) + write = self.reshape( + self.op(indices, position, trt.ElementWiseOperation.EQUAL), (1, 1, length, 1) + ) + key, value = [ + net.add_select(write, new, old).get_output(0) + for new, old in ((key, old_k), (value, old_v)) + ] + self.output(key, "present_k") + self.output(value, "present_v") + scores = net.add_matrix_multiply( + query, trt.MatrixOperation.NONE, key, trt.MatrixOperation.TRANSPOSE + ).get_output(0) + scores = self.mul(scores, self.const(np.full((1, 1, 1, 1), dim**-0.5))) + future = self.reshape( + self.op(indices, position, trt.ElementWiseOperation.GREATER), (1, 1, 1, length) + ) + scores = net.add_select(future, self.const(np.full((1, 1, 1, 1), -1e9)), scores).get_output( + 0 + ) + probability = net.add_softmax(scores) + probability.axes = 8 + attended = net.add_matrix_multiply( + probability.get_output(0), trt.MatrixOperation.NONE, value, trt.MatrixOperation.NONE + ).get_output(0) + gate = self.reshape(self.sigmoid(self.linear(hidden, prefix + ".g_proj")), (1, heads, 1, 1)) + return self.linear( + self.reshape(self.mul(attended, gate), (1, heads * value_dim)), prefix + ".dense" + ) + + def moe(self, hidden, prefix): + net, cfg = self.net, self.cfg + experts, top, groups, selected_groups, middle, width = ( + cfg[k] + for k in ( + "num_experts", + "num_experts_per_tok", + "n_group", + "topk_group", + "moe_intermediate_size", + "hidden_size", + ) + ) + scores = self.sigmoid(self.linear(hidden, prefix + ".gate")) + corrected = self.add( + scores, self.const(self.weights.read(prefix + ".gate.expert_bias").reshape(1, experts)) + ) + grouped = self.reshape(corrected, (1, groups, experts // groups)) + group_top = net.add_topk(grouped, trt.TopKOperation.MAX, 2, 4).get_output(0) + group_scores = self.reduce(group_top, trt.ReduceOperation.SUM, 4, False) + group_ids = self.reshape( + net.add_topk(group_scores, trt.TopKOperation.MAX, selected_groups, 2).get_output(1), + (selected_groups,), + ) + selected = net.add_gather(self.const(np.eye(groups)), group_ids, 0).get_output(0) + selected = self.reshape( + self.reduce(selected, trt.ReduceOperation.SUM, 1, False), (1, groups, 1) + ) + keep = self.op(selected, self.const([[[0.5]]]), trt.ElementWiseOperation.GREATER) + filtered = net.add_select(keep, grouped, self.const(np.full((1, 1, 1), -1e9))).get_output(0) + ids = self.reshape( + net.add_topk( + self.reshape(filtered, (1, experts)), trt.TopKOperation.MAX, top, 2 + ).get_output(1), + (top,), + ) + weights = net.add_gather(scores, ids, 1).get_output(0) + total = self.add(self.reduce(weights, trt.ReduceOperation.SUM, 2), self.const([[1e-20]])) + weights = self.reshape( + self.mul( + self.op(weights, total, trt.ElementWiseOperation.DIV), + self.const([[cfg["routed_scaling_factor"]]]), + ), + (top, 1, 1), + ) + up = np.empty((experts, 2 * middle, width), np.float32) + down = np.empty((experts, width, middle), np.float32) + for expert in range(experts): + name = prefix + f".experts.{expert}" + up[expert, :middle] = self.weights.read(name + ".gate_proj.weight") + up[expert, middle:] = self.weights.read(name + ".up_proj.weight") + down[expert] = self.weights.read(name + ".down_proj.weight") + up = net.add_gather(self.const(up), ids, 0).get_output(0) + down = net.add_gather(self.const(down), ids, 0).get_output(0) + projected = net.add_matrix_multiply( + self.reshape(hidden, (1, 1, width)), + trt.MatrixOperation.NONE, + up, + trt.MatrixOperation.TRANSPOSE, + ).get_output(0) + gate = net.add_slice(projected, (0, 0, 0), (top, 1, middle), (1, 1, 1)).get_output(0) + value = net.add_slice(projected, (0, 0, middle), (top, 1, middle), (1, 1, 1)).get_output(0) + result = net.add_matrix_multiply( + self.mul(self.silu(gate), value), + trt.MatrixOperation.NONE, + down, + trt.MatrixOperation.TRANSPOSE, + ).get_output(0) + result = self.reduce(self.mul(result, weights), trt.ReduceOperation.SUM, 1, False) + return self.add(result, self.dense(hidden, prefix + ".shared_experts")) + + +def build(request, writer): + if request.task != "text_continuation" or request.backend != "trt": + raise ValueError("Ling3 requires text_continuation with backend=trt") + if ( + request.precision != "fp32" + or request.tensor_parallel_size != 1 + or request.context_parallel_size != 1 + or request.max_batch_size != 1 + or request.quantization not in (None, "none") + or request.fp32_layers + or request.dynamic_kv_cache + or request.image_height is not None + or request.image_width is not None + or request.video_num_frames is not None + or request.mtp_seq_len is not None + ): + raise NotImplementedError( + "Ling3 supports one FP32 sequence with family-owned KDA and MLA state" + ) + directory = Path(request.model_dir) + cfg = json.loads((directory / "config.json").read_text()) + if ( + cfg["model_type"] != "bailing_hybrid" + or cfg["hidden_act"] != "silu" + or cfg["use_qkv_bias"] + or cfg["use_bias"] + or not cfg["no_kda_lora"] + or not cfg["kda_safe_gate"] + or not cfg["rope_interleave"] + or cfg["rope_scaling"] + or cfg["num_shared_experts"] != 1 + or cfg["gated_attention_proj_granularity_type"] != "head_wise" + or cfg["num_nextn_predict_layers"] + or cfg["first_k_dense_replace"] != 1 + or not cfg["norm_topk_prob"] + or cfg["group_norm_size"] != 1 + or cfg["layer_group_size"] < 1 + or cfg["num_hidden_layers"] % cfg["layer_group_size"] + ): + raise ValueError("Unsupported Ling3 hybrid attention or routing configuration") + length = request.max_sequence_length or 128 + if not 2 <= length <= min(512, cfg["max_position_embeddings"]): + raise ValueError("Ling3 fixed KV profile must be in [2, 512]") + from transformers import AutoTokenizer + + tokenizer = AutoTokenizer.from_pretrained(directory) + writer.set_header(family="bailing_hybrid", task=request.task, backend=request.backend) + logger = trt.Logger(trt.Logger.VERBOSE if request.verbose else trt.Logger.WARNING) + kinds = [ + "mla" if (i + 1) % cfg["layer_group_size"] == 0 else "kda" + for i in range(cfg["num_hidden_layers"]) + ] + with ExitStack() as stack: + weights = Weights(directory, stack) + graph = Graph(weights, cfg, logger) + token = graph.net.add_input("input_ids", trt.int32, (1,)) + graph.output( + graph.net.add_gather( + graph.const(weights.read("model.word_embeddings.weight")), token, 0 + ).get_output(0), + "result", + ) + with writer.open_section("embedding.plan") as section: + graph.save(section) + del graph + for layer, kind in enumerate(kinds): + graph = Graph(weights, cfg, logger) + prefix = f"model.layers.{layer}" + hidden = graph.net.add_input("hidden", trt.float32, (1, cfg["hidden_size"])) + normal = graph.norm(hidden, prefix + ".input_layernorm") + attention = ( + graph.mla(normal, prefix + ".attention", length) + if kind == "mla" + else graph.kda(normal, prefix + ".attention") + ) + hidden = graph.add(hidden, attention) + normal = graph.norm(hidden, prefix + ".post_attention_layernorm") + feed_forward = ( + graph.dense(normal, prefix + ".mlp") + if layer == 0 + else graph.moe(normal, prefix + ".mlp") + ) + graph.output(graph.add(hidden, feed_forward), "result") + with writer.open_section(f"layer.{layer}.plan") as section: + graph.save(section) + del graph + graph = Graph(weights, cfg, logger) + hidden = graph.net.add_input("hidden", trt.float32, (1, cfg["hidden_size"])) + graph.output(graph.linear(graph.norm(hidden, "model.norm"), "lm_head"), "logits") + with writer.open_section("head.plan") as section: + graph.save(section) + writer.add_bytes("tokenizer.json", tokenizer.backend_tokenizer.to_str().encode()) + writer.add_json( + "runtime.json", + dict( + sequence_length=length, + layers=cfg["num_hidden_layers"], + layer_types=kinds, + hidden_size=cfg["hidden_size"], + heads=cfg["num_attention_heads"], + head_dim=cfg["head_dim"], + key_dim=cfg["qk_head_dim"], + value_dim=cfg["v_head_dim"], + conv_kernel=cfg["short_conv_kernel_size"], + vocab_size=cfg["vocab_size"], + eos_ids=[cfg["eos_token_id"]], + ), + ) diff --git a/families/bailing_hybrid/requirements.txt b/families/bailing_hybrid/requirements.txt new file mode 100644 index 0000000000..42fcbb0ea7 --- /dev/null +++ b/families/bailing_hybrid/requirements.txt @@ -0,0 +1,4 @@ +numpy +safetensors +torch +transformers>=4.57.6 diff --git a/families/bailing_hybrid/runtime/CMakeLists.txt b/families/bailing_hybrid/runtime/CMakeLists.txt new file mode 100644 index 0000000000..29a2cdae4e --- /dev/null +++ b/families/bailing_hybrid/runtime/CMakeLists.txt @@ -0,0 +1,24 @@ +# 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_bailing_hybrid SHARED bpe_tokenizer.cpp plugin.cpp) +target_include_directories(trtmc_model_bailing_hybrid PRIVATE ${PROJECT_SOURCE_DIR} + ${PROJECT_SOURCE_DIR}/core/runtime/include) +target_include_directories(trtmc_model_bailing_hybrid SYSTEM PRIVATE ${TRTMC_CUDA_INCLUDE_DIR}) +target_link_libraries(trtmc_model_bailing_hybrid PRIVATE trtmc_core nlohmann_json::nlohmann_json + ${TRTMC_CUDART_LIBRARY} ICU::uc ICU::i18n) +target_compile_options(trtmc_model_bailing_hybrid PRIVATE -Wall -Wextra -Wpedantic) +set_target_properties(trtmc_model_bailing_hybrid PROPERTIES + LIBRARY_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}" BUILD_RPATH "\$ORIGIN" INSTALL_RPATH "\$ORIGIN") +install(TARGETS trtmc_model_bailing_hybrid LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR}) + +if(TRTMC_BUILD_TESTS) + add_executable(test_bailing_hybrid_tokenizer ${PROJECT_SOURCE_DIR}/families/bailing_hybrid/tests/cpp/test_tokenizer.cpp) + target_include_directories(test_bailing_hybrid_tokenizer PRIVATE ${PROJECT_SOURCE_DIR}) + target_link_libraries(test_bailing_hybrid_tokenizer PRIVATE trtmc_model_bailing_hybrid nlohmann_json::nlohmann_json) + set_target_properties(test_bailing_hybrid_tokenizer PROPERTIES RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}") + add_executable(test_bailing_hybrid_runtime ${PROJECT_SOURCE_DIR}/families/bailing_hybrid/tests/cpp/test_runtime.cpp) + target_link_libraries(test_bailing_hybrid_runtime PRIVATE trtmc_c nlohmann_json::nlohmann_json) + set_target_properties(test_bailing_hybrid_runtime PROPERTIES RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}") +endif() diff --git a/families/bailing_hybrid/runtime/bpe_tokenizer.cpp b/families/bailing_hybrid/runtime/bpe_tokenizer.cpp new file mode 100644 index 0000000000..faf6dc4601 --- /dev/null +++ b/families/bailing_hybrid/runtime/bpe_tokenizer.cpp @@ -0,0 +1,1656 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + */ + +#include "families/bailing_hybrid/runtime/tokenizer.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace trtmc { +namespace { + +// ─── UTF-8 helpers ─── + +// Decode one UTF-8 codepoint from s starting at pos, advance pos. +inline char32_t utf8_to_char32(const std::string& s, size_t& pos) { + unsigned char c = static_cast(s[pos]); + if (c < 0x80) { + ++pos; + return static_cast(c); + } + if ((c & 0xE0) == 0xC0 && pos + 1 < s.size()) { + char32_t cp = (static_cast(c & 0x1F) << 6) | + static_cast(static_cast(s[pos + 1]) & 0x3F); + pos += 2; + return cp; + } + if ((c & 0xF0) == 0xE0 && pos + 2 < s.size()) { + char32_t cp = (static_cast(c & 0x0F) << 12) | + (static_cast(static_cast(s[pos + 1]) & 0x3F) << 6) | + static_cast(static_cast(s[pos + 2]) & 0x3F); + pos += 3; + return cp; + } + if ((c & 0xF8) == 0xF0 && pos + 3 < s.size()) { + char32_t cp = (static_cast(c & 0x07) << 18) | + (static_cast(static_cast(s[pos + 1]) & 0x3F) << 12) | + (static_cast(static_cast(s[pos + 2]) & 0x3F) << 6) | + static_cast(static_cast(s[pos + 3]) & 0x3F); + pos += 4; + return cp; + } + ++pos; + return 0xFFFD; +} + +inline std::string utf32_to_utf8(char32_t cp) { + std::string r; + if (cp <= 0x7F) { + r.push_back(static_cast(cp)); + } else if (cp <= 0x7FF) { + r.push_back(static_cast(0xC0 | ((cp >> 6) & 0x1F))); + r.push_back(static_cast(0x80 | (cp & 0x3F))); + } else if (cp <= 0xFFFF) { + r.push_back(static_cast(0xE0 | ((cp >> 12) & 0x0F))); + r.push_back(static_cast(0x80 | ((cp >> 6) & 0x3F))); + r.push_back(static_cast(0x80 | (cp & 0x3F))); + } else if (cp <= 0x10FFFF) { + r.push_back(static_cast(0xF0 | ((cp >> 18) & 0x07))); + r.push_back(static_cast(0x80 | ((cp >> 12) & 0x3F))); + r.push_back(static_cast(0x80 | ((cp >> 6) & 0x3F))); + r.push_back(static_cast(0x80 | (cp & 0x3F))); + } + return r; +} + +// Read one UTF-8 codepoint from raw bytes, advance ptr. Returns 0xFFFD on error. +inline char32_t read_utf8(const char*& p, const char* end) { + if (p >= end) + return 0xFFFD; + unsigned char c = static_cast(*p); + if (c < 0x80) { + ++p; + return c; + } + if ((c & 0xE0) == 0xC0 && p + 1 < end) { + char32_t cp = + (static_cast(c & 0x1F) << 6) | (static_cast(p[1]) & 0x3F); + p += 2; + return cp; + } + if ((c & 0xF0) == 0xE0 && p + 2 < end) { + char32_t cp = (static_cast(c & 0x0F) << 12) | + (static_cast(static_cast(p[1]) & 0x3F) << 6) | + (static_cast(p[2]) & 0x3F); + p += 3; + return cp; + } + if ((c & 0xF8) == 0xF0 && p + 3 < end) { + char32_t cp = (static_cast(c & 0x07) << 18) | + (static_cast(static_cast(p[1]) & 0x3F) << 12) | + (static_cast(static_cast(p[2]) & 0x3F) << 6) | + (static_cast(p[3]) & 0x3F); + p += 4; + return cp; + } + ++p; + return 0xFFFD; +} + +// ─── GPT-2 byte encoder: byte value <-> Unicode codepoint ─── + +struct ByteEncoderTables { + // byte -> UTF-8 encoded string (precomputed for speed) + std::string byte_to_utf8[256]; + // Unicode codepoint -> byte value + std::unordered_map cp_to_byte; + + ByteEncoderTables() { + // GPT-2 byte encoder: printable bytes map to themselves, + // others map to 256+ to avoid control chars. + bool direct[256] = {}; + for (int b = 33; b <= 126; ++b) + direct[b] = true; // !"#$...~ + for (int b = 161; b <= 172; ++b) + direct[b] = true; // non-breaking space area + for (int b = 174; b <= 255; ++b) + direct[b] = true; // extended latin + + int n = 0; + for (int b = 0; b < 256; ++b) { + char32_t cp = direct[b] ? static_cast(b) : static_cast(256 + n++); + byte_to_utf8[b] = utf32_to_utf8(cp); + cp_to_byte[cp] = static_cast(b); + } + } +}; + +static const ByteEncoderTables& byte_tables() { + static ByteEncoderTables tables; + return tables; +} + +// ─── Hand-written BPE pre-tokenizer ─── +// +// Supports two regex variants: +// +// GPT-2 (used by GPT-2, Falcon, OPT): +// 'contractions| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+ +// +// Qwen3 (used by Qwen3, LLaMA-3, Mistral, Phi): +// (?i:contractions)|[^\r\n\p{L}\p{N}]?\p{L}+|\p{N}| +// ?[^\s\p{L}\p{N}]+[\r\n]*|\s*[\r\n]+|\s+(?!\S)|\s+ +// +// Key differences: Qwen3 allows any non-CR/LF/letter/digit as optional prefix before +// letters, matches single digits, and has explicit newline handling. + +namespace pretok { + +enum class Variant { kGpt2, kQwen3, kBloom, kDeepSeek, kClip }; + +// ── Character classification ── + +struct UnicodeRange { + char32_t lo, hi; +}; + +constexpr UnicodeRange kLetterRanges[] = { + {'A', 'Z'}, {'a', 'z'}, {0xB5, 0xB5}, // µ (micro sign, treated as letter) + {0xC0, 0xD6}, {0xD8, 0xF6}, {0xF8, 0x1BA}, // Latin-1 + Extended A/B + {0x1BC, 0x1BF}, {0x1C4, 0x293}, {0x295, 0x2AF}, // Latin Extended B cont. + {0x370, 0x373}, {0x376, 0x377}, {0x37B, 0x37D}, {0x37F, 0x37F}, // Greek + {0x386, 0x386}, {0x388, 0x38A}, {0x38C, 0x38C}, {0x38E, 0x3A1}, + {0x3A3, 0x3F5}, {0x3F7, 0x481}, {0x48A, 0x52F}, // Greek + Cyrillic + {0x531, 0x556}, {0x559, 0x559}, // Armenian + {0x560, 0x588}, // Armenian lowercase + {0x600, 0x6FF}, // Arabic + {0x900, 0x97F}, // Devanagari + {0xE00, 0xE7F}, // Thai + {0x10A0, 0x10C5}, // Georgian + {0x13A0, 0x13F5}, // Cherokee + {0x1C90, 0x1CBA}, {0x1CBD, 0x1CBF}, // Georgian Extended + {0x1D00, 0x1D2B}, {0x1D6B, 0x1D77}, {0x1D79, 0x1D9A}, // Phonetic Extensions + {0x1E00, 0x1F15}, {0x1F18, 0x1F1D}, {0x1F20, 0x1F45}, // Latin Ext. Additional + Greek Ext. + {0x2C00, 0x2C5F}, // Glagolitic + {0x3040, 0x309F}, // Hiragana + {0x30A0, 0x30FF}, // Katakana + {0x3400, 0x4DBF}, // CJK Extension A + {0x4E00, 0x9FFF}, // CJK Unified Ideographs + {0xAC00, 0xD7AF}, // Hangul Syllables + {0xFB00, 0xFDFF}, // Alphabetic Presentation Forms + Arabic Forms + {0x10000, 0x1007F}, // Linear B Syllabary +}; + +inline bool is_letter(char32_t cp) { + for (const auto& r : kLetterRanges) { + if (cp >= r.lo && cp <= r.hi) + return true; + } + return false; +} + +inline bool is_digit(char32_t cp) { + return (cp >= '0' && cp <= '9'); +} + +inline bool is_whitespace(char32_t cp) { + return cp == ' ' || cp == '\t' || cp == '\n' || cp == '\r' || cp == 0x0B || cp == 0x0C // VT, FF + || cp == 0xA0 // non-breaking space + || cp == 0x2000 || cp == 0x200A // en space through hair space + || cp == 0x3000; // ideographic space +} + +// BLOOM punctuation set: .,!?... +constexpr char32_t kBloomPunct[] = { + '.', ',', '!', '?', + 0x2026, // ellipsis + 0x3002, // ideographic full stop + 0xFF0C, // fullwidth comma + 0x3001, // ideographic comma + 0x0964, // Devanagari danda + 0x06D4, // Arabic full stop + 0x060C, // Arabic comma +}; + +inline bool is_bloom_punct(char32_t cp) { + for (auto c : kBloomPunct) { + if (cp == c) + return true; + } + return false; +} + +inline bool is_newline(char32_t cp) { + return cp == '\n' || cp == '\r'; +} + +// Is this char a valid optional prefix before a word? +// GPT-2/BLOOM: only space (0x20) +// Qwen3: any char except CR, LF, letter, digit +// DeepSeek: any whitespace (\s?) +inline bool is_prefix(char32_t cp, Variant v) { + if (v == Variant::kClip) { + return false; + } + if (v == Variant::kQwen3) { + return !is_newline(cp) && !is_letter(cp) && !is_digit(cp); + } + if (v == Variant::kDeepSeek) { + return is_whitespace(cp); + } + return cp == ' '; +} + +// BLOOM word char: not whitespace and not BLOOM punctuation +inline bool is_bloom_word_char(char32_t cp) { + // The serialized regex is `[^(\s|[.,!?…。,、।۔،])]`. Parentheses and + // the pipe are literal members of that negated character class. + return !is_whitespace(cp) && !is_bloom_punct(cp) && cp != '(' && cp != ')' && cp != '|'; +} + +// ── Scanning helpers (advance pointer past matching chars) ── + +inline void scan_letters(const char*& p, const char* end) { + while (p < end) { + const char* peek = p; + if (!is_letter(read_utf8(peek, end))) + break; + p = peek; + } +} + +inline void scan_digits(const char*& p, const char* end, int max_group = 0) { + int count = 0; + while (p < end) { + if (max_group > 0 && count >= max_group) + break; + const char* peek = p; + if (!is_digit(read_utf8(peek, end))) + break; + p = peek; + ++count; + } +} + +inline void scan_others(const char*& p, const char* end) { + while (p < end) { + const char* peek = p; + char32_t nc = read_utf8(peek, end); + if (is_whitespace(nc) || is_letter(nc) || is_digit(nc)) + break; + p = peek; + } +} + +inline void scan_newlines(const char*& p, const char* end) { + while (p < end) { + const char* peek = p; + if (!is_newline(read_utf8(peek, end))) + break; + p = peek; + } +} + +inline void scan_all_whitespace(const char*& p, const char* end) { + while (p < end) { + const char* peek = p; + if (!is_whitespace(read_utf8(peek, end))) + break; + p = peek; + } +} + +// Qwen3 regex branch: \s*[\r\n]+ +// Consume any leading whitespace up to the first newline, then consume the +// contiguous newline run itself, but stop before whitespace that follows the +// last newline. +inline void scan_qwen3_newline_chunk(char32_t first_cp, const char*& p, const char* end) { + bool saw_newline = is_newline(first_cp); + while (p < end) { + const char* peek = p; + char32_t nc = read_utf8(peek, end); + if (!saw_newline) { + if (is_newline(nc)) { + saw_newline = true; + p = peek; + continue; + } + if (is_whitespace(nc)) { + p = peek; + continue; + } + break; + } + if (!is_newline(nc)) + break; + p = peek; + } +} + +inline void scan_bloom_words(const char*& p, const char* end) { + while (p < end) { + const char* peek = p; + if (!is_bloom_word_char(read_utf8(peek, end))) + break; + p = peek; + } +} + +// Emit whitespace run, leaving last ws char for next token's optional prefix +inline void emit_whitespace_leave_last(const char*& p, const char* end, const char* start, + std::vector& result) { + const char* last_ws_start = start; + while (p < end) { + const char* peek = p; + char32_t nc = read_utf8(peek, end); + if (!is_whitespace(nc)) + break; + last_ws_start = p; + p = peek; + } + if (p < end && last_ws_start > start) { + p = last_ws_start; + } + result.emplace_back(start, p); +} + +// ── Contraction matching ── + +inline bool is_two_char_contraction(char c1, char c2) { + return (c1 == 'r' && c2 == 'e') || (c1 == 'v' && c2 == 'e') || (c1 == 'l' && c2 == 'l'); +} + +// Returns length of contraction suffix after apostrophe ('s 't 'm 'd 're 've 'll) +inline int match_contraction_suffix(const char* p, const char* end) { + if (p >= end) + return 0; + char c = *p; + if (c == 's' || c == 't' || c == 'm' || c == 'd') + return 1; + if (p + 1 < end && is_two_char_contraction(c, p[1])) + return 2; + return 0; +} + +// ── GPT-2/Qwen3 pre-tokenize dispatch helpers ── + +// Handle apostrophe: either contraction or "other" chars run +inline bool try_contraction(char32_t cp, const char*& p, const char* end, const char* start, + std::vector& result) { + if (cp != '\'') + return false; + int suffix = match_contraction_suffix(p, end); + if (suffix > 0) { + p += suffix; + } else { + scan_others(p, end); + } + result.emplace_back(start, p); + return true; +} + +// Handle optional prefix + letter/digit/other run +inline bool try_prefix_run(char32_t cp, const char*& p, const char* end, const char* start, + Variant variant, std::vector& result) { + if (!is_prefix(cp, variant) || p >= end) + return false; + const char* after_prefix = p; + char32_t next_cp = read_utf8(p, end); + + if (is_letter(next_cp)) { + scan_letters(p, end); + result.emplace_back(start, p); + return true; + } + if (is_digit(next_cp)) { + // The regex prefix [^\r\n\p{L}\p{N}]? only applies before \p{L}+ (letters). + // Digits are matched by standalone \p{N} — no prefix. Back up so the + // digit is handled by try_simple_run instead. + if (variant == Variant::kQwen3) { + p = after_prefix; + return false; + } + scan_digits(p, end); + result.emplace_back(start, p); + return true; + } + if (!is_whitespace(next_cp)) { + scan_others(p, end); + if (variant == Variant::kQwen3) + scan_newlines(p, end); + result.emplace_back(start, p); + return true; + } + // Prefix followed by whitespace — back up, let whitespace handler deal with it + p = after_prefix; + return false; +} + +// Check if a whitespace run contains any newline character +inline bool has_newline_in_ws(char32_t first_cp, const char* p, const char* end) { + if (is_newline(first_cp)) + return true; + const char* scan = p; + while (scan < end) { + const char* peek = scan; + char32_t nc = read_utf8(peek, end); + if (!is_whitespace(nc)) + break; + if (is_newline(nc)) + return true; + scan = peek; + } + return false; +} + +// Handle whitespace (Qwen3 newline sequences + general whitespace) +inline bool try_whitespace_run(char32_t cp, const char*& p, const char* end, const char* start, + Variant variant, std::vector& result) { + if (!is_whitespace(cp)) + return false; + + // kClip is selected only for CLIP's Removed + inverted Split contract, + // which retains regex matches and removes the gaps. Whitespace therefore + // never reaches ByteLevel. + if (variant == Variant::kClip) { + scan_all_whitespace(p, end); + return true; + } + + // Qwen3: \s*[\r\n]+ — newline sequences take priority + if (variant == Variant::kQwen3 && has_newline_in_ws(cp, p, end)) { + scan_qwen3_newline_chunk(cp, p, end); + result.emplace_back(start, p); + return true; + } + + // General whitespace: leave last ws char for next token's prefix + emit_whitespace_leave_last(p, end, start, result); + return true; +} + +// Handle letter or digit run (no prefix) +inline bool try_simple_run(char32_t cp, const char*& p, const char* end, const char* start, + Variant variant, std::vector& result, int digit_group = 0) { + if (is_letter(cp)) { + scan_letters(p, end); + result.emplace_back(start, p); + return true; + } + if (is_digit(cp)) { + if (variant == Variant::kQwen3) { + if (digit_group > 1) + scan_digits(p, end, digit_group - 1); + } else if (variant != Variant::kClip) { + scan_digits(p, end); + } + result.emplace_back(start, p); + return true; + } + return false; +} + +// ── Main pre-tokenize functions ── + +std::vector pre_tokenize(const std::string& text, Variant variant, + int digit_group = 0) { + std::vector result; + if (text.empty()) + return result; + + const char* p = text.data(); + const char* end = p + text.size(); + + while (p < end) { + const char* start = p; + char32_t cp = read_utf8(p, end); + + if (try_contraction(cp, p, end, start, result)) + continue; + if (try_prefix_run(cp, p, end, start, variant, result)) + continue; + if (try_whitespace_run(cp, p, end, start, variant, result)) + continue; + if (try_simple_run(cp, p, end, start, variant, result, digit_group)) + continue; + + // Other chars (punctuation/symbols) + scan_others(p, end); + if (variant == pretok::Variant::kQwen3) { + // Qwen3's ` ?[^\s\p{L}\p{N}]+[\r\n]*` keeps trailing newlines + // attached to punctuation/symbol runs even without an optional prefix. + scan_newlines(p, end); + } + result.emplace_back(start, p); + } + + return result; +} + +// Return the end of a BLOOM Split-regex match beginning at `start`. +// The regex is " ?[^(\s|[.,!?...])]+": an optional ASCII space followed by +// one or more non-whitespace, non-punctuation characters. +const char* bloom_match_end(const char* start, const char* end) { + const char* p = start; + char32_t cp = read_utf8(p, end); + if (cp == ' ') { + if (p >= end) + return nullptr; + cp = read_utf8(p, end); + if (!is_bloom_word_char(cp)) + return nullptr; + } else if (!is_bloom_word_char(cp)) { + return nullptr; + } + scan_bloom_words(p, end); + return p; +} + +// BLOOM uses Split(..., behavior="Isolated", invert=false) followed by +// ByteLevel(use_regex=false). Regex matches are isolated, while every +// contiguous unmatched span remains a single pre-token. In particular, +// punctuation and adjacent newlines must stay together so BPE can merge +// strings such as ".\n\n". +std::vector bloom_pre_tokenize(const std::string& text) { + std::vector result; + if (text.empty()) + return result; + + const char* p = text.data(); + const char* end = p + text.size(); + + while (p < end) { + const char* start = p; + if (const char* match_end = bloom_match_end(start, end)) { + result.emplace_back(start, match_end); + p = match_end; + continue; + } + + // Preserve one contiguous unmatched span until the next regex match. + read_utf8(p, end); + while (p < end && bloom_match_end(p, end) == nullptr) + read_utf8(p, end); + result.emplace_back(start, p); + } + + return result; +} + +} // namespace pretok + +// ─── BpeTokenizer implementation ─── + +class BpeTokenizer final : public ITokenizer { + public: + static std::unique_ptr Create(const char* tokenizer_json_data, + std::size_t tokenizer_json_size, + bool add_special_tokens = false) { + auto tokenizer = std::unique_ptr(new BpeTokenizer()); + tokenizer->mAddSpecialTokens = add_special_tokens; + tokenizer->parse_tokenizer_json(tokenizer_json_data, tokenizer_json_size); + return tokenizer; + } + + void encode_segment(const std::string& text, std::vector& result) const { + const auto normalized = normalize_text(text); + if (mIsSentencePiece) { + encode_sentencepiece(normalized, result); + } else if (mIsMetaspace) { + encode_metaspace(normalized, result); + } else { + encode_bytelevel(normalized, result); + } + } + + std::vector encode(const std::string& text) const override { + std::vector result; + if (text.empty()) + return result; + + if (mAddSpecialTokens) { + for (int32_t bos_id : mPostBosIds) + result.push_back(bos_id); + } + + auto segments = split_added_tokens(text); + for (const auto& seg : segments) { + if (seg.added_id >= 0) + result.push_back(seg.added_id); + else + encode_segment(seg.text, result); + } + + if (mAddSpecialTokens) { + for (int32_t eos_id : mPostEosIds) + result.push_back(eos_id); + } + + return result; + } + + std::string decode(const std::vector& ids) const override { + std::string joined = join_vocab_tokens(ids); + switch (mDecoderType) { + case DecoderType::kByteLevel: + return byte_decode(joined); + case DecoderType::kMetaspace: + return decode_metaspace(joined); + case DecoderType::kSequence: + return decode_sequence(joined); + } + return byte_decode(joined); + } + + int32_t id_for_token(std::string_view token) const override { + auto it = mTokenToId.find(std::string(token)); + return it != mTokenToId.end() ? it->second : -1; + } + + std::string token_for_id(int32_t id) const override { + if (id >= 0 && static_cast(id) < mVocab.size()) { + return mVocab[id]; + } + return ""; + } + + private: + BpeTokenizer() = default; + + enum class DecoderType { kByteLevel, kMetaspace, kSequence }; + + std::string normalize_text(const std::string& source) const { + UErrorCode nfc_status = U_ZERO_ERROR; + const auto* nfc = icu::Normalizer2::getNFCInstance(nfc_status); + icu::UnicodeString composed; + if (U_FAILURE(nfc_status)) throw std::runtime_error("Ling3 NFC initialization failed"); + nfc->normalize(icu::UnicodeString::fromUTF8(source), composed, nfc_status); + if (U_FAILURE(nfc_status)) throw std::runtime_error("Ling3 NFC normalization failed"); + std::string text; composed.toUTF8String(text); + for (const auto& replacement : mLiteralReplacements) { + std::size_t offset = 0; + while ((offset = text.find(replacement.first, offset)) != std::string::npos) { + text.replace(offset, replacement.first.size(), replacement.second); + offset += replacement.second.size(); + } + } + if (!mNormalizeLowercase && !mNormalizeWhitespace) { + return text; + } + + std::string normalized; + normalized.reserve(text.size()); + const char* cursor = text.data(); + const char* end = cursor + text.size(); + bool previous_was_whitespace = false; + while (cursor < end) { + const char* char_start = cursor; + const char32_t cp = read_utf8(cursor, end); + if (mNormalizeWhitespace && pretok::is_whitespace(cp)) { + if (!previous_was_whitespace) { + normalized.push_back(' '); + } + previous_was_whitespace = true; + continue; + } + previous_was_whitespace = false; + if (mNormalizeLowercase && cp >= 'A' && cp <= 'Z') { + normalized.push_back(static_cast(cp - 'A' + 'a')); + } else { + normalized.append(char_start, cursor); + } + } + return normalized; + } + + // ─── Added token segmentation ─── + + struct Segment { + std::string text; + int32_t added_id; /* -1 = normal */ + }; + + std::pair find_longest_added_token(const std::string& text, size_t pos) const { + int32_t best_id = -1; + size_t best_len = 0; + for (const auto& [content, id] : mAddedTokenPatterns) { + if (pos + content.size() <= text.size() && content.size() > best_len && + text.compare(pos, content.size(), content) == 0) { + best_id = id; + best_len = content.size(); + } + } + return {best_id, best_len}; + } + + static void strip_added_token_left_space(std::string& text) { + const char* begin = text.data(); + const char* cursor = begin; + const char* end = begin + text.size(); + size_t content_end = 0; + while (cursor < end) { + const char32_t cp = read_utf8(cursor, end); + // AddedToken lstrip uses the Unicode White_Space property. + const bool whitespace = (cp >= 0x09 && cp <= 0x0D) || cp == 0x20 || cp == 0x85 || + cp == 0xA0 || cp == 0x1680 || (cp >= 0x2000 && cp <= 0x200A) || + cp == 0x2028 || cp == 0x2029 || cp == 0x202F || cp == 0x205F || + cp == 0x3000; + if (!whitespace) + content_end = static_cast(cursor - begin); + } + text.resize(content_end); + } + + std::vector split_added_tokens(const std::string& text) const { + std::vector segments; + if (mAddedTokenPatterns.empty()) { + segments.push_back({text, -1}); + return segments; + } + size_t pos = 0; + while (pos < text.size()) { + auto [best_id, best_len] = find_longest_added_token(text, pos); + if (best_id >= 0) { + if (mLstripAddedTokenIds.count(best_id) && !segments.empty() && + segments.back().added_id < 0) { + strip_added_token_left_space(segments.back().text); + } + segments.push_back({text.substr(pos, best_len), best_id}); + pos += best_len; + } else { + if (segments.empty() || segments.back().added_id >= 0) { + segments.push_back({"", -1}); + } + segments.back().text.push_back(text[pos]); + ++pos; + } + } + return segments; + } + + // ─── Encoding helpers ─── + + // Metaspace encode (DeepSeek style): raw UTF-8 char split, BPE merge. + // Spaces are dropped (not in vocab), Ġ (U+0120) used as separator. + void encode_metaspace(const std::string& text, std::vector& result) const { + std::vector chars; + const char* cp = text.data(); + const char* ce = cp + text.size(); + while (cp < ce) { + const char* cs = cp; + read_utf8(cp, ce); + std::string ch(cs, cp); + if (mTokenToId.count(ch)) { + chars.push_back(std::move(ch)); + } + } + auto tokens = apply_merges(std::move(chars)); + for (const auto& token : tokens) { + auto it = mTokenToId.find(token); + if (it != mTokenToId.end()) { + result.push_back(it->second); + } + } + } + + // SentencePiece-style encode: replace spaces with ▁, split to chars, BPE merge. + // Used for Metaspace pre-tokenizer and Sequence decoder models (LLaMA, Mistral, Phi-3). + // Normalize text for SentencePiece: replace spaces with ▁, handle prepend + std::string normalize_sentencepiece(const std::string& text) const { + static const std::string sp = "\xe2\x96\x81"; // U+2581 + std::string out; + if (mSentencePiecePrependAlways) { + out = sp; + } + for (char c : text) { + out += (c == ' ') ? sp : std::string(1, c); + } + // Metaspace prepend_scheme=first: prepend if not already starting with ▁ + if (!mSentencePiecePrependAlways && mSentencePiecePrependIfMissing && + (out.empty() || out.compare(0, sp.size(), sp) != 0)) { + out = sp + out; + } + return out; + } + + void encode_sentencepiece(const std::string& text, std::vector& result) const { + std::string normalized = normalize_sentencepiece(text); + + // Split into UTF-8 characters + std::vector chars; + const char* cp = normalized.data(); + const char* ce = cp + normalized.size(); + while (cp < ce) { + const char* cs = cp; + read_utf8(cp, ce); + chars.emplace_back(cs, cp); + } + + // byte_fallback: replace unknown chars with <0xXX> + if (mByteFallback) { + chars = apply_byte_fallback_encode(std::move(chars)); + } + + // BPE merge and lookup + auto tokens = apply_merges(std::move(chars)); + for (const auto& token : tokens) { + auto it = mTokenToId.find(token); + if (it != mTokenToId.end()) { + result.push_back(it->second); + } + } + } + + // For byte_fallback: replace chars not in vocab with <0xXX> byte tokens + std::vector apply_byte_fallback_encode(std::vector chars) const { + std::vector result; + for (auto& ch : chars) { + if (mTokenToId.count(ch)) { + result.push_back(std::move(ch)); + } else { + // Split into individual bytes as <0xXX> + for (unsigned char byte : ch) { + char buf[8]; + std::snprintf(buf, sizeof(buf), "<0x%02X>", byte); + result.push_back(std::string(buf)); + } + } + } + return result; + } + + void encode_bytelevel(const std::string& text, std::vector& result) const { + std::vector words; + if (mRegex) { + UErrorCode status = U_ZERO_ERROR; + const std::string prepared = mAddPrefixSpace && !text.empty() && text.front() != ' ' ? " " + text : text; + const auto unicode = icu::UnicodeString::fromUTF8(prepared); + std::unique_ptr matcher(mRegex->matcher(unicode, status)); + if (U_FAILURE(status)) throw std::runtime_error("Ling3 tokenizer regex matcher failed"); + int32_t previous = 0; + while (matcher->find(status)) { + const int32_t start = matcher->start(status), end = matcher->end(status); + if (start > previous) { + std::string gap; unicode.tempSubStringBetween(previous, start).toUTF8String(gap); + words.push_back(std::move(gap)); + } + if (end > start) { + std::string match; unicode.tempSubStringBetween(start, end).toUTF8String(match); + words.push_back(std::move(match)); + } + previous = end; + } + if (U_FAILURE(status)) throw std::runtime_error("Ling3 tokenizer regex matching failed"); + if (previous < unicode.length()) { + std::string tail; unicode.tempSubString(previous).toUTF8String(tail); + words.push_back(std::move(tail)); + } + } else if (!mUsePreTokenizer) { + words = fallback_pre_tokenize(text); + } else if (mPreTokenizerVariant == pretok::Variant::kBloom) { + words = pretok::bloom_pre_tokenize(text); + } else { + words = pretok::pre_tokenize(text, mPreTokenizerVariant, mPreTokenizerDigitGroup); + } + + for (const auto& word : words) { + auto chars = byte_encode(word); + if (!chars.empty() && !mEndOfWordSuffix.empty()) { + chars.back() += mEndOfWordSuffix; + } + auto tokens = apply_merges(std::move(chars)); + for (const auto& token : tokens) { + auto it = mTokenToId.find(token); + if (it != mTokenToId.end()) { + result.push_back(it->second); + } + } + } + } + + // ─── Decoding helpers ─── + + std::string join_vocab_tokens(const std::vector& ids) const { + std::string joined; + for (int32_t id : ids) { + if (mSpecialIds.count(id)) + continue; + if (id >= 0 && static_cast(id) < mVocab.size()) { + joined += mVocab[id]; + } + } + return joined; + } + + std::string decode_metaspace(const std::string& joined) const { + std::string result; + const std::string g_char = utf32_to_utf8(0x0120); + const std::string spiece_char = "\xe2\x96\x81"; // U+2581 + size_t pos = 0; + while (pos < joined.size()) { + if (pos + g_char.size() <= joined.size() && + joined.compare(pos, g_char.size(), g_char) == 0) { + result.push_back(' '); + pos += g_char.size(); + } else if (pos + spiece_char.size() <= joined.size() && + joined.compare(pos, spiece_char.size(), spiece_char) == 0) { + result.push_back(' '); + pos += spiece_char.size(); + } else { + result.push_back(joined[pos]); + ++pos; + } + } + if (!result.empty() && result[0] == ' ') { + result.erase(0, 1); + } + return result; + } + + // ─── Sequence decoder (SentencePiece BPE models: LLaMA, Mistral, Phi-3) ─── + + std::string decode_sequence(const std::string& joined) const { + std::string text = joined; + // Step 1: Apply Replace operations (e.g. ▁ → space) + for (const auto& rep : mSeqDecoderReplaces) { + text = string_replace_all(text, rep.pattern, rep.content); + } + // Step 2: ByteFallback — convert <0xXX> tokens to raw bytes + if (mSeqDecoderByteFallback) { + text = apply_byte_fallback(text); + } + // Step 3: Fuse is implicit (tokens already joined) + // Step 4: Strip leading space + if (mSeqDecoderStripLeft && !text.empty() && text[0] == ' ') { + text.erase(0, 1); + } + return text; + } + + static std::string string_replace_all(const std::string& input, const std::string& from, + const std::string& to) { + if (from.empty()) + return input; + std::string result; + result.reserve(input.size()); + size_t pos = 0; + while (pos < input.size()) { + if (pos + from.size() <= input.size() && input.compare(pos, from.size(), from) == 0) { + result += to; + pos += from.size(); + } else { + result.push_back(input[pos]); + ++pos; + } + } + return result; + } + + static int hex_char_value(char c) { + if (c >= '0' && c <= '9') + return c - '0'; + if (c >= 'a' && c <= 'f') + return c - 'a' + 10; + if (c >= 'A' && c <= 'F') + return c - 'A' + 10; + return -1; + } + + // Try to parse <0xXX> at position pos. Returns parsed byte or -1. + static int try_parse_byte_token(const std::string& text, size_t pos) { + if (pos + 6 > text.size()) + return -1; + if (text[pos] != '<' || text[pos + 1] != '0' || text[pos + 2] != 'x' || + text[pos + 5] != '>') + return -1; + int h = hex_char_value(text[pos + 3]); + int l = hex_char_value(text[pos + 4]); + if (h < 0 || l < 0) + return -1; + return (h << 4) | l; + } + + static std::string apply_byte_fallback(const std::string& text) { + std::string result; + result.reserve(text.size()); + size_t pos = 0; + while (pos < text.size()) { + int byte_val = try_parse_byte_token(text, pos); + if (byte_val >= 0) { + result.push_back(static_cast(byte_val)); + pos += 6; + } else { + result.push_back(text[pos]); + ++pos; + } + } + return result; + } + + // ─── Byte-level encoding ─── + + static std::vector byte_encode(const std::string& text) { + const auto& tables = byte_tables(); + std::vector result; + result.reserve(text.size()); + for (unsigned char byte : text) { + result.push_back(tables.byte_to_utf8[byte]); + } + return result; + } + + static std::string byte_decode(const std::string& text) { + const auto& tables = byte_tables(); + std::string result; + result.reserve(text.size()); + size_t pos = 0; + while (pos < text.size()) { + size_t start = pos; + char32_t cp = utf8_to_char32(text, pos); + auto it = tables.cp_to_byte.find(cp); + if (it != tables.cp_to_byte.end()) { + result.push_back(static_cast(it->second)); + } else { + // Not a GPT-2 byte-encoded codepoint — pass through raw UTF-8 + result.append(text, start, pos - start); + } + } + return result; + } + + // Generic pre-tokenizer used when no GPT-2 pattern is declared. + + static std::vector fallback_pre_tokenize(const std::string& text) { + std::vector result; + if (text.empty()) + return result; + result.push_back(text); + return result; + } + + // ─── BPE merge algorithm ─── + + struct MergeCandidate { + int rank; + std::string first; + std::string second; + }; + + MergeCandidate find_best_merge(const std::vector& tokens) const { + MergeCandidate best{INT_MAX, "", ""}; + for (size_t i = 0; i + 1 < tokens.size(); ++i) { + auto it = + mMergeRank.find(std::make_pair(std::cref(tokens[i]), std::cref(tokens[i + 1]))); + if (it != mMergeRank.end() && it->second < best.rank) { + best = {it->second, tokens[i], tokens[i + 1]}; + } + } + return best; + } + + static std::vector merge_all_pairs(std::vector tokens, + const std::string& first, + const std::string& second) { + std::string merged = first + second; + std::vector result; + result.reserve(tokens.size()); + for (size_t i = 0; i < tokens.size(); ++i) { + if (i + 1 < tokens.size() && tokens[i] == first && tokens[i + 1] == second) { + result.push_back(merged); + ++i; // skip next + } else { + result.push_back(std::move(tokens[i])); + } + } + return result; + } + + // Optimized: merge ALL occurrences of the best pair per pass. + std::vector apply_merges(std::vector tokens) const { + if (tokens.size() <= 1) + return tokens; + + while (true) { + auto best = find_best_merge(tokens); + if (best.rank == INT_MAX) + break; + tokens = merge_all_pairs(std::move(tokens), best.first, best.second); + if (tokens.size() <= 1) + break; + } + + return tokens; + } + + // ─── JSON parsing helpers ─── + + static bool is_eos_content(const std::string& s) { + return s == "<|endoftext|>" || s == "" || s == "<|end_of_text|>"; + } + + void parse_vocab(const nlohmann::json& j) { + auto& vocab_obj = j["model"]["vocab"]; + size_t vocab_size = vocab_obj.size(); + mVocab.resize(vocab_size); + + for (auto& [token, id] : vocab_obj.items()) { + int32_t token_id = id.get(); + if (token_id >= 0 && token_id < static_cast(vocab_size)) { + mVocab[token_id] = token; + mTokenToId[token] = token_id; + } + } + } + + void parse_merges(const nlohmann::json& j) { + if (!j["model"].contains("merges")) + throw std::runtime_error("Invalid tokenizer.json: missing model.merges"); + + auto& merges_arr = j["model"]["merges"]; + mMergeRank.reserve(merges_arr.size()); + + for (size_t i = 0; i < merges_arr.size(); ++i) { + std::string first, second; + + if (merges_arr[i].is_array()) { + auto arr = merges_arr[i].get>(); + if (arr.size() != 2) + continue; + first = std::move(arr[0]); + second = std::move(arr[1]); + } else if (merges_arr[i].is_string()) { + std::string merge_str = merges_arr[i].get(); + auto space_pos = merge_str.find(' '); + if (space_pos == std::string::npos) + continue; + first = merge_str.substr(0, space_pos); + second = merge_str.substr(space_pos + 1); + } else { + continue; + } + + auto pair = std::make_pair(std::move(first), std::move(second)); + mMergeRank[pair] = static_cast(i); + } + } + + void parse_added_tokens(const nlohmann::json& j) { + if (!j.contains("added_tokens")) + return; + for (auto& tok : j["added_tokens"]) { + std::string content = tok["content"].get(); + int32_t id = tok["id"].get(); + + if (id >= 0 && static_cast(id) >= mVocab.size()) { + mVocab.resize(static_cast(id) + 1); + } + if (id >= 0) { + mVocab[id] = content; + mTokenToId[content] = id; + } + + if (tok.value("special", false)) { + mSpecialTokens[content] = id; + mSpecialIds.insert(id); + if (is_eos_content(content)) + mEosId = id; + } + // All added tokens (special and non-special) participate in pre-split + // matching during encode, matching HuggingFace's AddedToken behavior. + // The special flag only controls decode filtering (mSpecialIds) and + // post_processor BOS/EOS insertion. + mAddedTokenPatterns.push_back({content, id}); + if (tok.value("lstrip", false)) + mLstripAddedTokenIds.insert(id); + } + // Sort by length descending for longest-match-first + std::sort(mAddedTokenPatterns.begin(), mAddedTokenPatterns.end(), + [](const auto& a, const auto& b) { return a.first.size() > b.first.size(); }); + } + + // Parse digit group size from regex pattern like \p{N}{1,3} → 3. + // Returns 0 if no digit grouping found (single digit or unlimited). + static int parse_digit_group(const std::string& regex) { + // Search for "\p{N}{" — the standalone grouped variant, not [^\p{N}] + auto pos = regex.find("\\p{N}{"); + if (pos == std::string::npos) + return 0; + auto open = pos + 6; // after "\\p{N}{" + auto close = regex.find('}', open); + if (close == std::string::npos) + return 0; + auto comma = regex.find(',', open); + if (comma == std::string::npos || comma >= close) + return 0; + return std::stoi(regex.substr(comma + 1, close - comma - 1)); + } + + static bool is_clip_split_regex(const std::string& regex) { + const bool has_boundary_token = regex.find("startoftext") != std::string::npos || + regex.find("endoftext") != std::string::npos; + return has_boundary_token && regex.find("\\p{L}") != std::string::npos && + regex.find("\\p{N}") != std::string::npos; + } + + static pretok::Variant classify_clip_split(const nlohmann::json& split) { + const auto behavior = split.value("behavior", ""); + const bool invert = split.value("invert", false); + if (behavior == "Removed" && invert) + return pretok::Variant::kClip; + if (behavior == "Isolated" && invert) + return pretok::Variant::kGpt2; + throw std::runtime_error("Unsupported CLIP Split contract: behavior=" + behavior + + ", invert=" + (invert ? "true" : "false")); + } + + static bool is_qwen3_split_regex(const std::string& regex) { + return regex.find("[^\r\n") != std::string::npos || + regex.find("[^\\r\\n") != std::string::npos; + } + + static bool is_bloom_split_regex(const std::string& regex) { + return regex.find("[^(\\s") != std::string::npos || + regex.find("[^(\\\\s") != std::string::npos; + } + + // Classify one Split pre-tokenizer from both its pattern and contract. + static pretok::Variant classify_split(const nlohmann::json& split, int& digit_group_out) { + const auto regex = split["pattern"]["Regex"].get(); + if (is_clip_split_regex(regex)) + return classify_clip_split(split); + if (is_qwen3_split_regex(regex)) { + digit_group_out = parse_digit_group(regex); + return pretok::Variant::kQwen3; + } + if (is_bloom_split_regex(regex)) { + return pretok::Variant::kBloom; + } + if (regex.find("\\s?[A-Za-z") != std::string::npos) { + return pretok::Variant::kDeepSeek; + } + return pretok::Variant::kGpt2; + } + + // Detect variant from the Split inside a Sequence pre_tokenizer. + static pretok::Variant detect_split_variant(const nlohmann::json& pt, int& digit_group_out) { + digit_group_out = 0; + if (!pt.contains("pretokenizers")) + return pretok::Variant::kGpt2; + for (auto& sub : pt["pretokenizers"]) { + if (sub.value("type", "") != "Split") + continue; + if (!sub.contains("pattern") || !sub["pattern"].contains("Regex")) + continue; + return classify_split(sub, digit_group_out); + } + return pretok::Variant::kGpt2; + } + + static bool is_space_split_pre_tokenizer(const nlohmann::json& pt, const std::string& pt_type) { + if (pt_type != "Split") + return false; + if (!pt.contains("pattern") || !pt["pattern"].contains("String")) + return false; + return pt["pattern"]["String"].get() == " "; + } + + void detect_pre_tokenizer(const nlohmann::json& j) { + mUsePreTokenizer = true; + mPreTokenizerVariant = pretok::Variant::kGpt2; + + if (!j.contains("pre_tokenizer") || j["pre_tokenizer"].is_null()) + return; + auto& pt = j["pre_tokenizer"]; + std::string pt_type = pt.value("type", ""); + + if (pt_type == "ByteLevel") { + mPreTokenizerVariant = pretok::Variant::kGpt2; + } else if (pt_type == "Sequence") { + int digit_group = 0; + mPreTokenizerVariant = detect_split_variant(pt, digit_group); + mPreTokenizerDigitGroup = digit_group; + } else if (is_space_split_pre_tokenizer(pt, pt_type)) { + // Gemma SentencePiece-BPE tokenizers use a direct Split(" ") + // pre-tokenizer with spaces already normalized to U+2581. + mUsePreTokenizer = false; + } else if (pt_type == "Metaspace") { + mIsMetaspace = true; + mUsePreTokenizer = false; + } else if (pt_type.empty()) { + mUsePreTokenizer = false; + } else { + throw std::runtime_error("Unsupported pre_tokenizer type: " + pt_type); + } + } + + DecoderType classify_decoder_type(const nlohmann::json& j) const { + if (!j.contains("decoder") || j["decoder"].is_null()) { + return mIsMetaspace ? DecoderType::kMetaspace : DecoderType::kByteLevel; + } + std::string dt = j["decoder"].value("type", ""); + if (dt == "ByteLevel") + return DecoderType::kByteLevel; + if (dt == "Metaspace") + return DecoderType::kMetaspace; + if (dt == "Sequence") + return DecoderType::kSequence; + return mIsMetaspace ? DecoderType::kMetaspace : DecoderType::kByteLevel; + } + + void detect_decoder(const nlohmann::json& j) { + mDecoderType = classify_decoder_type(j); + if (mDecoderType == DecoderType::kSequence) { + parse_sequence_decoder(j["decoder"]); + } + // SentencePiece encode: vocab uses ▁ (U+2581) for spaces. + // Detect by: (1) ▁ in vocabulary, or (2) normalizer prepends ▁. + static const std::string spiece_marker = "\xe2\x96\x81"; // U+2581 + mIsSentencePiece = mTokenToId.count(spiece_marker) > 0 || mSentencePiecePrependAlways; + } + + void parse_seq_decoder_replace(const nlohmann::json& sub) { + SeqDecoderReplace rep; + if (sub.contains("pattern") && sub["pattern"].contains("String")) { + rep.pattern = sub["pattern"]["String"].get(); + } + rep.content = sub.value("content", ""); + if (!rep.pattern.empty()) { + mSeqDecoderReplaces.push_back(std::move(rep)); + } + } + + void parse_sequence_decoder(const nlohmann::json& dec) { + if (!dec.contains("decoders")) + return; + for (auto& sub : dec["decoders"]) { + std::string sub_type = sub.value("type", ""); + if (sub_type == "Replace") { + parse_seq_decoder_replace(sub); + } else if (sub_type == "ByteFallback") { + mSeqDecoderByteFallback = true; + } else if (sub_type == "Strip") { + if (sub.value("content", " ") == " " && sub.value("start", 0) > 0) { + mSeqDecoderStripLeft = true; + } + } + // Fuse is implicit (tokens already joined) + } + } + + static std::string optional_model_string(const nlohmann::json& model, const char* key) { + auto it = model.find(key); + if (it != model.end() && it->is_string()) + return it->get(); + return {}; + } + + void parse_tokenizer_json(const char* json_data, std::size_t json_size) { + nlohmann::json j; + try { + j = nlohmann::json::parse(json_data, json_data + json_size); + } catch (const std::exception& e) { + throw std::runtime_error(std::string("Failed to parse tokenizer.json: ") + e.what()); + } + + if (!j.contains("model")) + throw std::runtime_error("Invalid tokenizer.json: missing model"); + auto& model = j["model"]; + if (!model.contains("vocab") || !model["vocab"].is_object()) + throw std::runtime_error("Invalid tokenizer.json: model.vocab must be an object"); + if (!model.contains("merges") || !model["merges"].is_array()) + throw std::runtime_error("Invalid tokenizer.json: model.merges must be an array"); + + mByteFallback = model.value("byte_fallback", false); + mEndOfWordSuffix = optional_model_string(model, "end_of_word_suffix"); + parse_vocab(j); + parse_merges(j); + parse_added_tokens(j); + parse_post_processor(j); + if (j.at("normalizer").value("type", "") != "NFC") + throw std::runtime_error("Expected Ling3 NFC normalizer"); + detect_normalizer(j); + detect_pre_tokenizer(j); + const auto& pretokenizer = j.at("pre_tokenizer"); + if (pretokenizer.value("type", "") != "Sequence" || + pretokenizer.at("pretokenizers").size() != 2) + throw std::runtime_error("Expected Ling3 Split and ByteLevel pre-tokenizer"); + const auto& split = pretokenizer.at("pretokenizers")[0]; + const auto& bytes = pretokenizer.at("pretokenizers")[1]; + if (split.value("type", "") != "Split" || split.value("behavior", "") != "Isolated" || + split.value("invert", true) || bytes.value("type", "") != "ByteLevel" || + bytes.value("use_regex", true) || bytes.value("add_prefix_space", true)) + throw std::runtime_error("Unsupported Ling3 pre-tokenizer options"); + mAddPrefixSpace = false; + const auto pattern = split.at("pattern").at("Regex").get(); + UErrorCode regex_status = U_ZERO_ERROR; + mRegex.reset(icu::RegexPattern::compile(icu::UnicodeString::fromUTF8(pattern), 0, regex_status)); + if (U_FAILURE(regex_status)) throw std::runtime_error("Ling3 tokenizer regex compilation failed"); + detect_decoder(j); + } + + // Detect normalizer: check for Prepend (always prepend ▁) vs none + static bool normalizer_sequence_prepends(const nlohmann::json& norm, + const std::string& norm_type) { + if (norm_type != "Sequence" || !norm.contains("normalizers")) + return false; + for (auto& sub : norm["normalizers"]) { + if (sub.value("type", "") == "Prepend") + return true; + } + return false; + } + + static bool normalizer_replaces_space_with_sentence_piece(const nlohmann::json& norm, + const std::string& norm_type) { + if (norm_type == "Sequence" && norm.contains("normalizers")) { + for (const auto& sub : norm["normalizers"]) { + if (normalizer_replaces_space_with_sentence_piece(sub, sub.value("type", ""))) { + return true; + } + } + return false; + } + if (norm_type != "Replace") + return false; + if (!norm.contains("pattern") || !norm["pattern"].contains("String")) + return false; + if (norm["pattern"]["String"].get() != " ") + return false; + return norm.value("content", "") == "\xe2\x96\x81"; + } + + void detect_normalizer(const nlohmann::json& j) { + if (!j.contains("normalizer") || j["normalizer"].is_null()) + return; + auto& norm = j["normalizer"]; + std::string norm_type = norm.value("type", ""); + detect_text_normalizers(norm); + if (normalizer_sequence_prepends(norm, norm_type)) { + mSentencePiecePrependAlways = true; + } else if (normalizer_replaces_space_with_sentence_piece(norm, norm_type)) { + // Gemma replaces spaces with ▁ but does not prepend ▁ to the + // first token. Preserve the old prepend-if-missing behavior for + // Metaspace-style SentencePiece models. + mSentencePiecePrependIfMissing = false; + } + } + + void detect_text_normalizers(const nlohmann::json& normalizer) { + const std::string type = normalizer.value("type", ""); + if (type == "Sequence" && normalizer.contains("normalizers")) { + for (const auto& child : normalizer["normalizers"]) { + detect_text_normalizers(child); + } + return; + } + if (type == "Replace" && normalizer.contains("pattern") && normalizer["pattern"].contains("String")) { + const auto pattern = normalizer["pattern"]["String"].get(); + if (pattern.empty()) throw std::runtime_error("Ling3 tokenizer replacement cannot be empty"); + mLiteralReplacements.emplace_back(pattern, normalizer.at("content").get()); + return; + } + if (type == "Lowercase") { + mNormalizeLowercase = true; + return; + } + if (type == "Replace" && normalizer.contains("pattern") && + normalizer["pattern"].contains("Regex") && + normalizer["pattern"]["Regex"].get() == "\\s+" && + normalizer.value("content", "") == " ") { + mNormalizeWhitespace = true; + } + } + + // Parse post_processor to extract BOS/EOS tokens for add_special_tokens + void parse_post_processor(const nlohmann::json& j) { + if (!j.contains("post_processor") || j["post_processor"].is_null()) + return; + auto& pp = j["post_processor"]; + std::string pp_type = pp.value("type", ""); + + if (pp_type == "TemplateProcessing") { + parse_template_post_processor(pp); + } else if (pp_type == "Sequence") { + parse_sequence_post_processor(pp); + } else if (pp_type == "RobertaProcessing") { + parse_roberta_post_processor(pp); + } + // ByteLevel post_processor doesn't add tokens, nothing to do + } + + // Iterate Sequence post_processor's processors array to find TemplateProcessing + void parse_sequence_post_processor(const nlohmann::json& pp) { + if (!pp.contains("processors")) + return; + for (auto& sub : pp["processors"]) { + if (sub.value("type", "") == "TemplateProcessing") { + parse_template_post_processor(sub); + return; // first TemplateProcessing wins + } + } + } + + // RobertaProcessing: {"type":"RobertaProcessing","cls":["",0],"sep":["",2],...} + void parse_roberta_post_processor(const nlohmann::json& pp) { + if (pp.contains("cls") && pp["cls"].is_array() && pp["cls"].size() >= 2) { + int32_t cls_id = pp["cls"][1].get(); + mPostBosIds.push_back(cls_id); + } + if (pp.contains("sep") && pp["sep"].is_array() && pp["sep"].size() >= 2) { + int32_t sep_id = pp["sep"][1].get(); + mPostEosIds.push_back(sep_id); + } + } + + int32_t resolve_special_token_id(const nlohmann::json& entry) const { + if (!entry.contains("SpecialToken")) + return -1; + std::string token_id = entry["SpecialToken"].value("id", ""); + if (token_id.empty()) + return -1; + auto it = mSpecialTokens.find(token_id); + return it != mSpecialTokens.end() ? it->second : -1; + } + + void parse_template_post_processor(const nlohmann::json& pp) { + if (!pp.contains("single")) + return; + bool seen_sequence = false; + for (auto& entry : pp["single"]) { + if (entry.contains("Sequence")) { + seen_sequence = true; + continue; + } + int32_t id = resolve_special_token_id(entry); + if (id < 0) + continue; + if (seen_sequence) { + mPostEosIds.push_back(id); + } else { + mPostBosIds.push_back(id); + } + } + } + + // ─── Data members ─── + + std::vector mVocab; + std::unordered_map mTokenToId; + + struct PairHash { + size_t operator()(const std::pair& p) const { + size_t h1 = std::hash{}(p.first); + size_t h2 = std::hash{}(p.second); + return h1 ^ (h2 * 0x9e3779b97f4a7c15ULL + 0x9e3779b9 + (h1 << 6) + (h1 >> 2)); + } + }; + + std::unordered_map, int, PairHash> mMergeRank; + + std::unordered_map mSpecialTokens; + std::unordered_set mSpecialIds; // O(1) lookup in decode() + int32_t mEosId = -1; + + // Non-special added tokens: matched before pre-tokenization (longest first) + std::vector> mAddedTokenPatterns; + std::unordered_set mLstripAddedTokenIds; + + bool mAddSpecialTokens = false; + bool mUsePreTokenizer = true; + bool mIsMetaspace = false; // Set by detect_pre_tokenizer. + bool mIsSentencePiece = false; + bool mSentencePiecePrependAlways = + false; // true for Normalizer Prepend, false for Metaspace first + bool mSentencePiecePrependIfMissing = true; + bool mByteFallback = false; + bool mAddPrefixSpace{false}; + std::unique_ptr mRegex; + std::vector> mLiteralReplacements; + bool mNormalizeLowercase = false; + bool mNormalizeWhitespace = false; + std::string mEndOfWordSuffix; + + // Post-processor: BOS/EOS token IDs to add when add_special_tokens=true + // Vectors to support multiple BOS/EOS tokens (e.g. GLM-4: [gMASK] + ) + std::vector mPostBosIds; + std::vector mPostEosIds; + pretok::Variant mPreTokenizerVariant = pretok::Variant::kGpt2; + int mPreTokenizerDigitGroup = 0; // 0=unlimited, 3=\p{N}{1,3} (LLaMA 3.1/GLM-4) + + DecoderType mDecoderType = DecoderType::kByteLevel; + + // Sequence decoder config (parsed from tokenizer.json decoder field) + struct SeqDecoderReplace { + std::string pattern; + std::string content; + }; + std::vector mSeqDecoderReplaces; + bool mSeqDecoderByteFallback = false; + bool mSeqDecoderStripLeft = false; +}; + +} // namespace + +std::unique_ptr CreateBpeTokenizer(const char* tokenizer_json_data, + std::size_t tokenizer_json_size, + bool add_special_tokens) { + return BpeTokenizer::Create(tokenizer_json_data, tokenizer_json_size, add_special_tokens); +} + +} // namespace trtmc diff --git a/families/bailing_hybrid/runtime/plugin.cpp b/families/bailing_hybrid/runtime/plugin.cpp new file mode 100644 index 0000000000..f1849043e0 --- /dev/null +++ b/families/bailing_hybrid/runtime/plugin.cpp @@ -0,0 +1,188 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + */ +#include "families/bailing_hybrid/runtime/tokenizer.h" +#include "trtmc/internal/model.h" +#include "trtmc/internal/text.h" +#include "trtmc/runtime/family_factory.h" +#include "trtmc/runtime/trt_backend.h" +#include +#include +#include +#include +#include + +namespace trtmc::bailing_hybrid { +namespace { +std::vector section(const BundleReader& reader, const char* name) { + const auto* found = reader.find_section(name); + if (!found || found->length == 0) throw std::runtime_error(std::string("Ling3 bundle lacks ") + name); + return reader.read_section(name); +} +Tensor tensor(void* data, std::initializer_list shape, DType dtype) { + Tensor result; + result.data = data; result.shape = shape; result.dtype = dtype; + return result; +} +Tensor output(const TensorMap& outputs, const std::string& name, std::size_t count, DType dtype = DType::kFloat32) { + const auto found = outputs.find(name); + if (found == outputs.end() || !found->second.data || found->second.dtype != dtype || + found->second.numel() != count) throw std::runtime_error("Invalid Ling3 output " + name); + return found->second; +} + +class Pipeline final : public internal::IModel, public internal::ITextContinuation { + public: + Pipeline(std::unique_ptr embedding, std::vector> layers, + std::unique_ptr head, std::unique_ptr tokenizer, nlohmann::json cfg) + : embedding_(std::move(embedding)), layers_(std::move(layers)), head_(std::move(head)), + tokenizer_(std::move(tokenizer)), cfg_(std::move(cfg)), fields_{ + {"max_new_tokens", internal::ConfigKind::I64, internal::ConfigValue{int64_t{32}}, "Maximum generated tokens"}, + {"do_sample", internal::ConfigKind::Bool, internal::ConfigValue{false}, "Greedy decoding only"}} {} + const char* task() const noexcept override { return "text_continuation"; } + std::vector task_bindings() override { + return {internal::bind(*this, {fields_.data(), fields_.size()})}; + } + internal::TextResult run(const internal::TextContinuationRequest& request, + internal::ConfigView config) override { + const Span fields{fields_.data(), fields_.size()}; + internal::validate_config(fields, config); + const auto max_new = *internal::config_get(config, fields, "max_new_tokens"); + if (*internal::config_get(config, fields, "do_sample")) + throw std::invalid_argument("Ling3 currently supports greedy decoding"); + const int32_t length = cfg_.at("sequence_length"), vocab = cfg_.at("vocab_size"); + const int32_t layers = cfg_.at("layers"), heads = cfg_.at("heads"), dim = cfg_.at("head_dim"); + if (max_new <= 0 || max_new > length) throw std::invalid_argument("Invalid Ling3 generation length"); + std::vector ids; + if (const auto* text = std::get_if(&request.prefix)) + ids = tokenizer_->encode(std::string(*text)); + else { + const auto tokens = std::get>(request.prefix); + ids.assign(tokens.begin(), tokens.end()); + } + if (ids.empty() || ids.size() + max_new > static_cast(length)) + throw std::invalid_argument("Ling3 prefix and generation exceed the built KV profile"); + for (const auto id : ids) + if (id < 0 || id >= vocab) throw std::invalid_argument("Invalid Ling3 token ID"); + const int32_t width = cfg_.at("hidden_size"); + const int32_t key_dim = cfg_.at("key_dim"), value_dim = cfg_.at("value_dim"), kernel = cfg_.at("conv_kernel"); + const auto kinds = cfg_.at("layer_types").get>(); + const auto key_count = static_cast(heads) * length * key_dim; + const auto value_count = static_cast(heads) * length * value_dim; + const auto state_count = static_cast(heads) * dim * dim; + const auto conv_count = static_cast(heads) * dim * (kernel - 1); + struct State { + std::vector key, value, recurrent; + std::array, 3> convolution; + }; + std::vector states(layers); + for (int32_t i = 0; i < layers; ++i) { + if (kinds[i] == "mla") { + states[i].key.resize(key_count, 0); states[i].value.resize(value_count, 0); + } else { + states[i].recurrent.resize(state_count, 0); + for (auto& history : states[i].convolution) history.resize(conv_count, 0); + } + } + std::vector hidden(width); + std::vector logits; + int32_t position = 0; + auto step = [&](int32_t token) { + if (position >= length) throw std::runtime_error("Ling3 exhausted its KV profile"); + const auto embedded = embedding_->forward({{"input_ids", tensor(&token, {1}, DType::kInt32)}}); + const auto initial = output(embedded, "result", width); + std::copy_n(static_cast(initial.data), width, hidden.data()); + for (int32_t i = 0; i < layers; ++i) { + auto& state = states[i]; + TensorMap inputs{{"hidden", tensor(hidden.data(), {1, width}, DType::kFloat32)}}; + if (kinds[i] == "mla") { + inputs.emplace("position", tensor(&position, {1}, DType::kInt32)); + inputs.emplace("cache_k", tensor(state.key.data(), {1, heads, length, key_dim}, DType::kFloat32)); + inputs.emplace("cache_v", tensor(state.value.data(), {1, heads, length, value_dim}, DType::kFloat32)); + } else { + inputs.emplace("state", tensor(state.recurrent.data(), {heads, dim, dim}, DType::kFloat32)); + for (int j = 0; j < 3; ++j) + inputs.emplace(std::string("conv_") + "qkv"[j], tensor(state.convolution[j].data(), {heads * dim, kernel - 1}, DType::kFloat32)); + } + const auto predicted = layers_[i]->forward(inputs); + const auto result = output(predicted, "result", width); + std::copy_n(static_cast(result.data), width, hidden.data()); + auto retain = [&](const std::string& name, std::vector& storage) { + const auto view = output(predicted, name, storage.size()); + std::copy_n(static_cast(view.data), storage.size(), storage.data()); + }; + if (kinds[i] == "mla") { + retain("present_k", state.key); retain("present_v", state.value); + } else { + retain("present_state", state.recurrent); + for (int j = 0; j < 3; ++j) retain(std::string("present_conv_") + "qkv"[j], state.convolution[j]); + } + } + const auto predicted = head_->forward({{"hidden", tensor(hidden.data(), {1, width}, DType::kFloat32)}}); + const auto& scores = output(predicted, "logits", vocab); + const auto* data = static_cast(scores.data); + logits.assign(data, data + vocab); + for (const auto value : logits) + if (!std::isfinite(value)) throw std::runtime_error("Ling3 logit is nonfinite"); + ++position; + }; + for (const auto token : ids) step(token); + const auto eos = cfg_.at("eos_ids").get>(); + internal::TextResult result; + for (int64_t i = 0; i < max_new; ++i) { + const auto next = static_cast(std::max_element(logits.begin(), logits.end()) - logits.begin()); + result.token_ids.push_back(next); + if (std::find(eos.begin(), eos.end(), next) != eos.end()) break; + if (i + 1 < max_new) step(next); + } + result.text = tokenizer_->decode(result.token_ids); + return result; + } + private: + std::unique_ptr embedding_; + std::vector> layers_; + std::unique_ptr head_; + std::unique_ptr tokenizer_; + nlohmann::json cfg_; + std::vector fields_; +}; +} // namespace +} // namespace trtmc::bailing_hybrid + +extern "C" trtmc::ITask* trtmc_create_family(const trtmc::FamilyContext& context) { + using namespace trtmc; + if (context.kv_cache_size_bytes || context.reader.info().task != "text_continuation") + throw std::invalid_argument("Ling3 uses a family-owned fixed KV profile for text continuation"); + const auto raw = bailing_hybrid::section(context.reader, "runtime.json"); + const auto cfg = nlohmann::json::parse(raw.begin(), raw.end()); + const int32_t length = cfg.at("sequence_length"), layers = cfg.at("layers"); + const int32_t heads = cfg.at("heads"), dim = cfg.at("head_dim"), vocab = cfg.at("vocab_size"); + const int32_t width = cfg.at("hidden_size"); + const auto eos = cfg.at("eos_ids").get>(); + const auto kinds = cfg.at("layer_types").get>(); + const int32_t kernel = cfg.at("conv_kernel"), key_dim = cfg.at("key_dim"), value_dim = cfg.at("value_dim"); + if (length <= 0 || length > 512 || layers <= 0 || layers > 128 || heads <= 0 || heads > 128 || + dim <= 0 || dim > 256 || width <= 0 || width > 65536 || vocab <= 0 || eos.empty() || + kernel < 2 || kernel > 16 || key_dim <= 0 || key_dim > 512 || value_dim <= 0 || value_dim > 512 || + kinds.size() != static_cast(layers)) + throw std::runtime_error("Invalid Ling3 runtime dimensions"); + for (const auto& kind : kinds) + if (kind != "mla" && kind != "kda") throw std::runtime_error("Invalid Ling3 state kind"); + for (auto id : eos) + if (id < 0 || id >= vocab) throw std::runtime_error("Invalid Ling3 EOS token"); + auto load = [&](const std::string& name) { + const auto plan = bailing_hybrid::section(context.reader, name.c_str()); + auto engine = context.backend.create_module(plan.data(), plan.size(), {}); + if (!engine || !engine->ok()) throw std::runtime_error("Ling3 engine failed to load: " + name); + return engine; + }; + // Read and deserialize one plan at a time; never retain a full CPU weight copy. + auto embedding = load("embedding.plan"); + std::vector> engines; + for (int32_t i = 0; i < layers; ++i) engines.push_back(load("layer." + std::to_string(i) + ".plan")); + auto head = load("head.plan"); + const auto raw_tokenizer = bailing_hybrid::section(context.reader, "tokenizer.json"); + auto tokenizer = CreateBpeTokenizer(raw_tokenizer.data(), raw_tokenizer.size(), false); + return new bailing_hybrid::Pipeline(std::move(embedding), std::move(engines), std::move(head), std::move(tokenizer), cfg); +} diff --git a/families/bailing_hybrid/runtime/tokenizer.h b/families/bailing_hybrid/runtime/tokenizer.h new file mode 100644 index 0000000000..abf7ca59ce --- /dev/null +++ b/families/bailing_hybrid/runtime/tokenizer.h @@ -0,0 +1,33 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + */ + +#pragma once + +#include +#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); +std::unique_ptr CreateUnigramTokenizer(const char* tokenizer_json_data, + std::size_t tokenizer_json_size, + bool add_special_tokens = true); + +} // namespace trtmc diff --git a/families/bailing_hybrid/support.py b/families/bailing_hybrid/support.py new file mode 100644 index 0000000000..59c37a8b84 --- /dev/null +++ b/families/bailing_hybrid/support.py @@ -0,0 +1,10 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +from tensorrt_model_connect.model_support import family_support + +describe = family_support( + model_types=("bailing_hybrid",), + tasks=("text_continuation",), + default_task="text_continuation", + default_precision="fp32", +) diff --git a/families/bailing_hybrid/tests/__init__.py b/families/bailing_hybrid/tests/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/families/bailing_hybrid/tests/cpp/test_runtime.cpp b/families/bailing_hybrid/tests/cpp/test_runtime.cpp new file mode 100644 index 0000000000..0749819df5 --- /dev/null +++ b/families/bailing_hybrid/tests/cpp/test_runtime.cpp @@ -0,0 +1,28 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + */ +#include "trtmc/core.hpp" +#include +#include + +int main(int argc, char** argv) { + if (argc != 3) return 2; + try { + trtmc::LoadOptions options; options.runtime_root = argv[2]; + const auto model = trtmc::Model::load(argv[1], options); + const auto task = model.task(); + nlohmann::json requests; std::cin >> requests; + auto results = nlohmann::json::array(); + for (const auto& request : requests) { + trtmc::Config config; + config.add("max_new_tokens", request.at("max_new_tokens").get()); + const auto result = task.run({request.at("prompt").get()}, config); + results.push_back({{"text", result.text()}, {"token_ids", + std::vector(result.token_ids().begin(), result.token_ids().end())}}); + } + std::cout << results.dump() << '\n'; + } catch (const std::exception& error) { + std::cerr << error.what() << '\n'; return 1; + } +} diff --git a/families/bailing_hybrid/tests/cpp/test_tokenizer.cpp b/families/bailing_hybrid/tests/cpp/test_tokenizer.cpp new file mode 100644 index 0000000000..7ab2a09c1a --- /dev/null +++ b/families/bailing_hybrid/tests/cpp/test_tokenizer.cpp @@ -0,0 +1,17 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + */ +#include "families/bailing_hybrid/runtime/tokenizer.h" +#include +#include +#include +#include + +int main(int argc, char** argv) { + if (argc != 3) return 2; + std::ifstream file(argv[1]); + const std::string data((std::istreambuf_iterator(file)), {}); + const auto tokenizer = trtmc::CreateBpeTokenizer(data.data(), data.size(), false); + std::cout << nlohmann::json(tokenizer->encode(argv[2])).dump() << '\n'; +} diff --git a/families/bailing_hybrid/tests/manifests/ling-3.0-tiny.json b/families/bailing_hybrid/tests/manifests/ling-3.0-tiny.json new file mode 100644 index 0000000000..f172bc0aa6 --- /dev/null +++ b/families/bailing_hybrid/tests/manifests/ling-3.0-tiny.json @@ -0,0 +1,23 @@ +{ + "name": "ling-3.0-tiny", + "hf_id": "inclusionAI/Ling-3.0-tiny", + "hf_revision": "9a98e35fe1c9ee255f78dd64771c7ae15a799481", + "bundle": "ling-3.0-tiny.bundle", + "family": "bailing_hybrid", + "task": "text_continuation", + "precision": "fp32", + "max_sequence_length": 128, + "tensor_parallel_size": 1, + "testcases": [ + { + "name": "ling-3.0-tiny", + "premerge": true, + "max_new_tokens": 16, + "prompts": [ + "The capital of Germany is", + "def add(a, b):\n return" + ], + "runtime_timeout_s": 3600 + } + ] +} diff --git a/families/bailing_hybrid/tests/requirements.txt b/families/bailing_hybrid/tests/requirements.txt new file mode 100644 index 0000000000..55635a04c8 --- /dev/null +++ b/families/bailing_hybrid/tests/requirements.txt @@ -0,0 +1,5 @@ +transformers==4.57.6 +fla-core==0.6.0 +einops +accelerate +pytest diff --git a/families/bailing_hybrid/tests/test_e2e.py b/families/bailing_hybrid/tests/test_e2e.py new file mode 100644 index 0000000000..b062d44c02 --- /dev/null +++ b/families/bailing_hybrid/tests/test_e2e.py @@ -0,0 +1,227 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Pinned Ling3 MoE parity through native incremental text continuation.""" + +from __future__ import annotations + +import json +import os +import subprocess +from pathlib import Path + +import pytest + +from tensorrt_model_connect import BuildRequest, build + +FAMILY = "bailing_hybrid" +TASKS = frozenset({"text_continuation"}) +TEST_ROOT = Path(__file__).resolve().parent +MANIFEST_ROOT = TEST_ROOT / "manifests" + + +def _case_index() -> dict[str, tuple[Path, dict, dict]]: + result = {} + for path in sorted(MANIFEST_ROOT.glob("*.json")): + manifest = json.loads(path.read_text(encoding="utf-8")) + assert manifest["family"] == FAMILY + assert manifest["task"] in TASKS + for case in manifest["testcases"]: + name = str(case["name"]) + assert name not in result + result[name] = (path, manifest, case) + return result + + +CASES = _case_index() + + +def _selected_cases(config) -> tuple[list[str], bool]: + model_filters = set() + for raw in config.getoption("--e2e-model") or []: + model_filters.update((item.strip() for item in str(raw).split(",") if item.strip())) + models_file = config.getoption("--e2e-models-file") + if models_file: + model_filters.update( + ( + line.strip() + for line in Path(models_file).read_text(encoding="utf-8").splitlines() + if line.strip() and (not line.lstrip().startswith("#")) + ) + ) + testcase_filters = set() + for raw in config.getoption("--e2e-testcase") or []: + testcase_filters.update((item.strip() for item in str(raw).split(",") if item.strip())) + if not model_filters and (not testcase_filters): + return (sorted(CASES), False) + selected = [] + for name, (_, manifest, _) in CASES.items(): + model_match = ( + not model_filters + or FAMILY in model_filters + or name in model_filters + or (manifest["name"] in model_filters) + ) + testcase_match = not testcase_filters or name in testcase_filters + if model_match and testcase_match: + selected.append(name) + return (sorted(selected), True) + + +def pytest_generate_tests(metafunc) -> None: + if "case_name" in metafunc.fixturenames: + names, enabled = _selected_cases(metafunc.config) + parameters = names + if not enabled: + parameters = [ + pytest.param( + name, + marks=pytest.mark.skip( + reason="direct E2E requires one of the three explicit E2E selectors" + ), + ) + for name in names + ] + metafunc.parametrize("case_name", parameters, ids=names) + + +def _required_path(value: str | None, label: str) -> Path: + assert value, f"selected {FAMILY} E2E requires {label}" + path = Path(value) + assert path.exists(), f"selected {FAMILY} E2E {label} does not exist: {path}" + return path + + +def _model_dir(manifest: dict) -> Path: + explicit = os.environ.get(f"TRTMC_{FAMILY.upper()}_MODEL_DIR") + if explicit: + return _required_path(explicit, f"TRTMC_{FAMILY.upper()}_MODEL_DIR") + from huggingface_hub import snapshot_download + + try: + snapshot = snapshot_download( + repo_id=manifest["hf_id"], revision=manifest.get("hf_revision"), local_files_only=True + ) + except Exception as error: + raise AssertionError( + f"selected {FAMILY} E2E requires the exact cached checkpoint {manifest['hf_id']}" + ) from error + return Path(snapshot) + + +def _runtime() -> tuple[Path, Path]: + binary = _required_path(os.environ.get("TRTMC_BINARY"), "TRTMC_BINARY") + runtime_root = _required_path(os.environ.get("TRTMC_RUNTIME_ROOT"), "TRTMC_RUNTIME_ROOT") + assert (runtime_root / "libtrtmc_backend_trt.so").is_file() + assert (runtime_root / f"libtrtmc_model_{FAMILY}.so").is_file() + import torch + + assert torch.cuda.is_available(), f"selected {FAMILY} E2E requires CUDA" + assert torch.cuda.device_count() >= 1, f"selected {FAMILY} E2E requires one GPU" + return (binary, runtime_root) + + +def _build(model_dir: Path, bundle: Path, manifest: dict) -> None: + build( + BuildRequest( + model_dir=model_dir, + output_path=bundle, + family=FAMILY, + task=manifest["task"], + precision=manifest["precision"], + max_sequence_length=manifest.get("max_sequence_length"), + image_height=manifest.get("image_height"), + image_width=manifest.get("image_width"), + video_num_frames=manifest.get("video_num_frames"), + max_batch_size=int(manifest.get("max_batch_size", 1)), + tensor_parallel_size=int(manifest["tensor_parallel_size"]), + quantization=manifest.get("quantization"), + fp32_layers=tuple((int(layer) for layer in manifest.get("fp32_layers", ()))), + ) + ) + + +def test_official_checkpoint_e2e(case_name, tmp_path): + import gc + import torch + from transformers import AutoModelForCausalLM, AutoTokenizer + + _, manifest, case = CASES[case_name] + directory = _model_dir(manifest) + _, runtime_root = _runtime() + runner = runtime_root / "test_bailing_hybrid_runtime" + assert runner.is_file() + torch.backends.cuda.matmul.allow_tf32 = False + torch.backends.cudnn.allow_tf32 = False + tokenizer = AutoTokenizer.from_pretrained(directory) + # Recompute each prefix in the pinned official model. This checks the + # native KDA recurrence against the full-prefix official recurrent kernel. + reference = AutoModelForCausalLM.from_pretrained( + directory, + dtype=torch.float32, + device_map={"": "cuda:0"}, + trust_remote_code=True, + attn_implementation="eager", + ).eval() + expected = [] + for prompt in case["prompts"]: + inputs = tokenizer(prompt, return_tensors="pt", return_token_type_ids=False).to("cuda") + with torch.no_grad(): + generated = reference.generate( + **inputs, do_sample=False, use_cache=False, max_new_tokens=case["max_new_tokens"] + ) + ids = generated[0, inputs["input_ids"].shape[1] :].tolist() + expected.append({"token_ids": ids, "text": tokenizer.decode(ids, skip_special_tokens=True)}) + print(f"Official Ling3: {expected[-1]!r}", flush=True) + del reference, generated, inputs + gc.collect() + torch.cuda.empty_cache() + bundle = tmp_path / manifest["bundle"] + _build(directory, bundle, manifest) + gc.collect() + torch.cuda.empty_cache() + requests = [ + {"prompt": prompt, "max_new_tokens": case["max_new_tokens"]} for prompt in case["prompts"] + ] + completed = subprocess.run( + [str(runner), str(bundle), str(runtime_root)], + input=json.dumps(requests), + text=True, + capture_output=True, + check=False, + timeout=case.get("runtime_timeout_s", 3600), + ) + assert completed.returncode == 0, completed.stderr + completed.stdout + payload = json.loads(completed.stdout.splitlines()[-1]) + assert payload == expected + assert all(item["text"].strip() for item in payload) + print(f"Ling3 exact native greedy generations: {payload!r}", flush=True) + + +def test_native_tokenizer(case_name): + from transformers import AutoTokenizer + + _, manifest, _ = CASES[case_name] + directory = _model_dir(manifest) + runner = ( + _required_path(os.environ.get("TRTMC_RUNTIME_ROOT"), "TRTMC_RUNTIME_ROOT") + / "test_bailing_hybrid_tokenizer" + ) + reference = AutoTokenizer.from_pretrained(directory) + for text in [ + "The capital of Germany is", + "1234567890 42", + "def f(x):\n return x + 1\n", + "Grüße 世界 Αλφα 😀", + "café cafe\u0301 Å A\u030a", + "We're ready.\t\n", + "<|im_start|>user\nHello<|im_end|>", + ]: + completed = subprocess.run( + [str(runner), str(directory / "tokenizer.json"), text], + text=True, + capture_output=True, + check=False, + ) + assert completed.returncode == 0, completed.stderr + completed.stdout + assert json.loads(completed.stdout) == reference.encode(text) diff --git a/families/bailing_hybrid/tests/test_support.py b/families/bailing_hybrid/tests/test_support.py new file mode 100644 index 0000000000..5c38732728 --- /dev/null +++ b/families/bailing_hybrid/tests/test_support.py @@ -0,0 +1,9 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +from tensorrt_model_connect.model_support import ModelMetadata, resolve_family + + +def test_bailing_hybrid_checkpoint_has_one_owner(): + family, support = resolve_family(ModelMetadata({"model_type": "bailing_hybrid"}, {})) + assert family == "bailing_hybrid" + assert support.tasks == ("text_continuation",) From 2e38488ee9138320d198ae56e860270533c62dcf Mon Sep 17 00:00:00 2001 From: Will Guo Date: Fri, 13 Nov 2026 06:04:41 -0800 Subject: [PATCH 2/6] chore(bailing-hybrid): satisfy source checks Signed-off-by: Will Guo --- .../bailing_hybrid/runtime/bpe_tokenizer.cpp | 43 ++++--- families/bailing_hybrid/runtime/plugin.cpp | 121 ++++++++++++------ .../bailing_hybrid/tests/cpp/test_runtime.cpp | 18 ++- .../tests/cpp/test_tokenizer.cpp | 4 +- 4 files changed, 124 insertions(+), 62 deletions(-) diff --git a/families/bailing_hybrid/runtime/bpe_tokenizer.cpp b/families/bailing_hybrid/runtime/bpe_tokenizer.cpp index faf6dc4601..7b1e1ef164 100644 --- a/families/bailing_hybrid/runtime/bpe_tokenizer.cpp +++ b/families/bailing_hybrid/runtime/bpe_tokenizer.cpp @@ -5,8 +5,6 @@ #include "families/bailing_hybrid/runtime/tokenizer.h" -#include -#include #include #include #include @@ -17,6 +15,8 @@ #include #include #include +#include +#include #include #include #include @@ -679,10 +679,13 @@ class BpeTokenizer final : public ITokenizer { UErrorCode nfc_status = U_ZERO_ERROR; const auto* nfc = icu::Normalizer2::getNFCInstance(nfc_status); icu::UnicodeString composed; - if (U_FAILURE(nfc_status)) throw std::runtime_error("Ling3 NFC initialization failed"); + if (U_FAILURE(nfc_status)) + throw std::runtime_error("Ling3 NFC initialization failed"); nfc->normalize(icu::UnicodeString::fromUTF8(source), composed, nfc_status); - if (U_FAILURE(nfc_status)) throw std::runtime_error("Ling3 NFC normalization failed"); - std::string text; composed.toUTF8String(text); + if (U_FAILURE(nfc_status)) + throw std::runtime_error("Ling3 NFC normalization failed"); + std::string text; + composed.toUTF8String(text); for (const auto& replacement : mLiteralReplacements) { std::size_t offset = 0; while ((offset = text.find(replacement.first, offset)) != std::string::npos) { @@ -879,26 +882,32 @@ class BpeTokenizer final : public ITokenizer { std::vector words; if (mRegex) { UErrorCode status = U_ZERO_ERROR; - const std::string prepared = mAddPrefixSpace && !text.empty() && text.front() != ' ' ? " " + text : text; + const std::string prepared = + mAddPrefixSpace && !text.empty() && text.front() != ' ' ? " " + text : text; const auto unicode = icu::UnicodeString::fromUTF8(prepared); std::unique_ptr matcher(mRegex->matcher(unicode, status)); - if (U_FAILURE(status)) throw std::runtime_error("Ling3 tokenizer regex matcher failed"); + if (U_FAILURE(status)) + throw std::runtime_error("Ling3 tokenizer regex matcher failed"); int32_t previous = 0; while (matcher->find(status)) { const int32_t start = matcher->start(status), end = matcher->end(status); if (start > previous) { - std::string gap; unicode.tempSubStringBetween(previous, start).toUTF8String(gap); + std::string gap; + unicode.tempSubStringBetween(previous, start).toUTF8String(gap); words.push_back(std::move(gap)); } if (end > start) { - std::string match; unicode.tempSubStringBetween(start, end).toUTF8String(match); + std::string match; + unicode.tempSubStringBetween(start, end).toUTF8String(match); words.push_back(std::move(match)); } previous = end; } - if (U_FAILURE(status)) throw std::runtime_error("Ling3 tokenizer regex matching failed"); + if (U_FAILURE(status)) + throw std::runtime_error("Ling3 tokenizer regex matching failed"); if (previous < unicode.length()) { - std::string tail; unicode.tempSubString(previous).toUTF8String(tail); + std::string tail; + unicode.tempSubString(previous).toUTF8String(tail); words.push_back(std::move(tail)); } } else if (!mUsePreTokenizer) { @@ -1439,8 +1448,10 @@ class BpeTokenizer final : public ITokenizer { mAddPrefixSpace = false; const auto pattern = split.at("pattern").at("Regex").get(); UErrorCode regex_status = U_ZERO_ERROR; - mRegex.reset(icu::RegexPattern::compile(icu::UnicodeString::fromUTF8(pattern), 0, regex_status)); - if (U_FAILURE(regex_status)) throw std::runtime_error("Ling3 tokenizer regex compilation failed"); + mRegex.reset( + icu::RegexPattern::compile(icu::UnicodeString::fromUTF8(pattern), 0, regex_status)); + if (U_FAILURE(regex_status)) + throw std::runtime_error("Ling3 tokenizer regex compilation failed"); detect_decoder(j); } @@ -1499,9 +1510,11 @@ class BpeTokenizer final : public ITokenizer { } return; } - if (type == "Replace" && normalizer.contains("pattern") && normalizer["pattern"].contains("String")) { + if (type == "Replace" && normalizer.contains("pattern") && + normalizer["pattern"].contains("String")) { const auto pattern = normalizer["pattern"]["String"].get(); - if (pattern.empty()) throw std::runtime_error("Ling3 tokenizer replacement cannot be empty"); + if (pattern.empty()) + throw std::runtime_error("Ling3 tokenizer replacement cannot be empty"); mLiteralReplacements.emplace_back(pattern, normalizer.at("content").get()); return; } diff --git a/families/bailing_hybrid/runtime/plugin.cpp b/families/bailing_hybrid/runtime/plugin.cpp index f1849043e0..3c9445163a 100644 --- a/families/bailing_hybrid/runtime/plugin.cpp +++ b/families/bailing_hybrid/runtime/plugin.cpp @@ -7,6 +7,7 @@ #include "trtmc/internal/text.h" #include "trtmc/runtime/family_factory.h" #include "trtmc/runtime/trt_backend.h" + #include #include #include @@ -17,43 +18,54 @@ namespace trtmc::bailing_hybrid { namespace { std::vector section(const BundleReader& reader, const char* name) { const auto* found = reader.find_section(name); - if (!found || found->length == 0) throw std::runtime_error(std::string("Ling3 bundle lacks ") + name); + if (!found || found->length == 0) + throw std::runtime_error(std::string("Ling3 bundle lacks ") + name); return reader.read_section(name); } Tensor tensor(void* data, std::initializer_list shape, DType dtype) { Tensor result; - result.data = data; result.shape = shape; result.dtype = dtype; + result.data = data; + result.shape = shape; + result.dtype = dtype; return result; } -Tensor output(const TensorMap& outputs, const std::string& name, std::size_t count, DType dtype = DType::kFloat32) { +Tensor output(const TensorMap& outputs, const std::string& name, std::size_t count, + DType dtype = DType::kFloat32) { const auto found = outputs.find(name); if (found == outputs.end() || !found->second.data || found->second.dtype != dtype || - found->second.numel() != count) throw std::runtime_error("Invalid Ling3 output " + name); + found->second.numel() != count) + throw std::runtime_error("Invalid Ling3 output " + name); return found->second; } class Pipeline final : public internal::IModel, public internal::ITextContinuation { public: Pipeline(std::unique_ptr embedding, std::vector> layers, - std::unique_ptr head, std::unique_ptr tokenizer, nlohmann::json cfg) + std::unique_ptr head, std::unique_ptr tokenizer, + nlohmann::json cfg) : embedding_(std::move(embedding)), layers_(std::move(layers)), head_(std::move(head)), - tokenizer_(std::move(tokenizer)), cfg_(std::move(cfg)), fields_{ - {"max_new_tokens", internal::ConfigKind::I64, internal::ConfigValue{int64_t{32}}, "Maximum generated tokens"}, - {"do_sample", internal::ConfigKind::Bool, internal::ConfigValue{false}, "Greedy decoding only"}} {} + tokenizer_(std::move(tokenizer)), cfg_(std::move(cfg)), + fields_{{"max_new_tokens", internal::ConfigKind::I64, internal::ConfigValue{int64_t{32}}, + "Maximum generated tokens"}, + {"do_sample", internal::ConfigKind::Bool, internal::ConfigValue{false}, + "Greedy decoding only"}} {} const char* task() const noexcept override { return "text_continuation"; } std::vector task_bindings() override { - return {internal::bind(*this, {fields_.data(), fields_.size()})}; + return { + internal::bind(*this, {fields_.data(), fields_.size()})}; } internal::TextResult run(const internal::TextContinuationRequest& request, - internal::ConfigView config) override { + internal::ConfigView config) override { const Span fields{fields_.data(), fields_.size()}; internal::validate_config(fields, config); const auto max_new = *internal::config_get(config, fields, "max_new_tokens"); if (*internal::config_get(config, fields, "do_sample")) throw std::invalid_argument("Ling3 currently supports greedy decoding"); const int32_t length = cfg_.at("sequence_length"), vocab = cfg_.at("vocab_size"); - const int32_t layers = cfg_.at("layers"), heads = cfg_.at("heads"), dim = cfg_.at("head_dim"); - if (max_new <= 0 || max_new > length) throw std::invalid_argument("Invalid Ling3 generation length"); + const int32_t layers = cfg_.at("layers"), heads = cfg_.at("heads"), + dim = cfg_.at("head_dim"); + if (max_new <= 0 || max_new > length) + throw std::invalid_argument("Invalid Ling3 generation length"); std::vector ids; if (const auto* text = std::get_if(&request.prefix)) ids = tokenizer_->encode(std::string(*text)); @@ -64,9 +76,11 @@ class Pipeline final : public internal::IModel, public internal::ITextContinuati if (ids.empty() || ids.size() + max_new > static_cast(length)) throw std::invalid_argument("Ling3 prefix and generation exceed the built KV profile"); for (const auto id : ids) - if (id < 0 || id >= vocab) throw std::invalid_argument("Invalid Ling3 token ID"); + if (id < 0 || id >= vocab) + throw std::invalid_argument("Invalid Ling3 token ID"); const int32_t width = cfg_.at("hidden_size"); - const int32_t key_dim = cfg_.at("key_dim"), value_dim = cfg_.at("value_dim"), kernel = cfg_.at("conv_kernel"); + const int32_t key_dim = cfg_.at("key_dim"), value_dim = cfg_.at("value_dim"), + kernel = cfg_.at("conv_kernel"); const auto kinds = cfg_.at("layer_types").get>(); const auto key_count = static_cast(heads) * length * key_dim; const auto value_count = static_cast(heads) * length * value_dim; @@ -79,18 +93,22 @@ class Pipeline final : public internal::IModel, public internal::ITextContinuati std::vector states(layers); for (int32_t i = 0; i < layers; ++i) { if (kinds[i] == "mla") { - states[i].key.resize(key_count, 0); states[i].value.resize(value_count, 0); + states[i].key.resize(key_count, 0); + states[i].value.resize(value_count, 0); } else { states[i].recurrent.resize(state_count, 0); - for (auto& history : states[i].convolution) history.resize(conv_count, 0); + for (auto& history : states[i].convolution) + history.resize(conv_count, 0); } } std::vector hidden(width); std::vector logits; int32_t position = 0; auto step = [&](int32_t token) { - if (position >= length) throw std::runtime_error("Ling3 exhausted its KV profile"); - const auto embedded = embedding_->forward({{"input_ids", tensor(&token, {1}, DType::kInt32)}}); + if (position >= length) + throw std::runtime_error("Ling3 exhausted its KV profile"); + const auto embedded = + embedding_->forward({{"input_ids", tensor(&token, {1}, DType::kInt32)}}); const auto initial = output(embedded, "result", width); std::copy_n(static_cast(initial.data), width, hidden.data()); for (int32_t i = 0; i < layers; ++i) { @@ -98,47 +116,63 @@ class Pipeline final : public internal::IModel, public internal::ITextContinuati TensorMap inputs{{"hidden", tensor(hidden.data(), {1, width}, DType::kFloat32)}}; if (kinds[i] == "mla") { inputs.emplace("position", tensor(&position, {1}, DType::kInt32)); - inputs.emplace("cache_k", tensor(state.key.data(), {1, heads, length, key_dim}, DType::kFloat32)); - inputs.emplace("cache_v", tensor(state.value.data(), {1, heads, length, value_dim}, DType::kFloat32)); + inputs.emplace("cache_k", tensor(state.key.data(), {1, heads, length, key_dim}, + DType::kFloat32)); + inputs.emplace( + "cache_v", + tensor(state.value.data(), {1, heads, length, value_dim}, DType::kFloat32)); } else { - inputs.emplace("state", tensor(state.recurrent.data(), {heads, dim, dim}, DType::kFloat32)); + inputs.emplace("state", tensor(state.recurrent.data(), {heads, dim, dim}, + DType::kFloat32)); for (int j = 0; j < 3; ++j) - inputs.emplace(std::string("conv_") + "qkv"[j], tensor(state.convolution[j].data(), {heads * dim, kernel - 1}, DType::kFloat32)); + inputs.emplace(std::string("conv_") + "qkv"[j], + tensor(state.convolution[j].data(), + {heads * dim, kernel - 1}, DType::kFloat32)); } const auto predicted = layers_[i]->forward(inputs); const auto result = output(predicted, "result", width); std::copy_n(static_cast(result.data), width, hidden.data()); auto retain = [&](const std::string& name, std::vector& storage) { const auto view = output(predicted, name, storage.size()); - std::copy_n(static_cast(view.data), storage.size(), storage.data()); + std::copy_n(static_cast(view.data), storage.size(), + storage.data()); }; if (kinds[i] == "mla") { - retain("present_k", state.key); retain("present_v", state.value); + retain("present_k", state.key); + retain("present_v", state.value); } else { retain("present_state", state.recurrent); - for (int j = 0; j < 3; ++j) retain(std::string("present_conv_") + "qkv"[j], state.convolution[j]); + for (int j = 0; j < 3; ++j) + retain(std::string("present_conv_") + "qkv"[j], state.convolution[j]); } } - const auto predicted = head_->forward({{"hidden", tensor(hidden.data(), {1, width}, DType::kFloat32)}}); + const auto predicted = + head_->forward({{"hidden", tensor(hidden.data(), {1, width}, DType::kFloat32)}}); const auto& scores = output(predicted, "logits", vocab); const auto* data = static_cast(scores.data); logits.assign(data, data + vocab); for (const auto value : logits) - if (!std::isfinite(value)) throw std::runtime_error("Ling3 logit is nonfinite"); + if (!std::isfinite(value)) + throw std::runtime_error("Ling3 logit is nonfinite"); ++position; }; - for (const auto token : ids) step(token); + for (const auto token : ids) + step(token); const auto eos = cfg_.at("eos_ids").get>(); internal::TextResult result; for (int64_t i = 0; i < max_new; ++i) { - const auto next = static_cast(std::max_element(logits.begin(), logits.end()) - logits.begin()); + const auto next = static_cast(std::max_element(logits.begin(), logits.end()) - + logits.begin()); result.token_ids.push_back(next); - if (std::find(eos.begin(), eos.end(), next) != eos.end()) break; - if (i + 1 < max_new) step(next); + if (std::find(eos.begin(), eos.end(), next) != eos.end()) + break; + if (i + 1 < max_new) + step(next); } result.text = tokenizer_->decode(result.token_ids); return result; } + private: std::unique_ptr embedding_; std::vector> layers_; @@ -153,7 +187,8 @@ class Pipeline final : public internal::IModel, public internal::ITextContinuati extern "C" trtmc::ITask* trtmc_create_family(const trtmc::FamilyContext& context) { using namespace trtmc; if (context.kv_cache_size_bytes || context.reader.info().task != "text_continuation") - throw std::invalid_argument("Ling3 uses a family-owned fixed KV profile for text continuation"); + throw std::invalid_argument( + "Ling3 uses a family-owned fixed KV profile for text continuation"); const auto raw = bailing_hybrid::section(context.reader, "runtime.json"); const auto cfg = nlohmann::json::parse(raw.begin(), raw.end()); const int32_t length = cfg.at("sequence_length"), layers = cfg.at("layers"); @@ -161,28 +196,34 @@ extern "C" trtmc::ITask* trtmc_create_family(const trtmc::FamilyContext& context const int32_t width = cfg.at("hidden_size"); const auto eos = cfg.at("eos_ids").get>(); const auto kinds = cfg.at("layer_types").get>(); - const int32_t kernel = cfg.at("conv_kernel"), key_dim = cfg.at("key_dim"), value_dim = cfg.at("value_dim"); + const int32_t kernel = cfg.at("conv_kernel"), key_dim = cfg.at("key_dim"), + value_dim = cfg.at("value_dim"); if (length <= 0 || length > 512 || layers <= 0 || layers > 128 || heads <= 0 || heads > 128 || dim <= 0 || dim > 256 || width <= 0 || width > 65536 || vocab <= 0 || eos.empty() || - kernel < 2 || kernel > 16 || key_dim <= 0 || key_dim > 512 || value_dim <= 0 || value_dim > 512 || - kinds.size() != static_cast(layers)) + kernel < 2 || kernel > 16 || key_dim <= 0 || key_dim > 512 || value_dim <= 0 || + value_dim > 512 || kinds.size() != static_cast(layers)) throw std::runtime_error("Invalid Ling3 runtime dimensions"); for (const auto& kind : kinds) - if (kind != "mla" && kind != "kda") throw std::runtime_error("Invalid Ling3 state kind"); + if (kind != "mla" && kind != "kda") + throw std::runtime_error("Invalid Ling3 state kind"); for (auto id : eos) - if (id < 0 || id >= vocab) throw std::runtime_error("Invalid Ling3 EOS token"); + if (id < 0 || id >= vocab) + throw std::runtime_error("Invalid Ling3 EOS token"); auto load = [&](const std::string& name) { const auto plan = bailing_hybrid::section(context.reader, name.c_str()); auto engine = context.backend.create_module(plan.data(), plan.size(), {}); - if (!engine || !engine->ok()) throw std::runtime_error("Ling3 engine failed to load: " + name); + if (!engine || !engine->ok()) + throw std::runtime_error("Ling3 engine failed to load: " + name); return engine; }; // Read and deserialize one plan at a time; never retain a full CPU weight copy. auto embedding = load("embedding.plan"); std::vector> engines; - for (int32_t i = 0; i < layers; ++i) engines.push_back(load("layer." + std::to_string(i) + ".plan")); + for (int32_t i = 0; i < layers; ++i) + engines.push_back(load("layer." + std::to_string(i) + ".plan")); auto head = load("head.plan"); const auto raw_tokenizer = bailing_hybrid::section(context.reader, "tokenizer.json"); auto tokenizer = CreateBpeTokenizer(raw_tokenizer.data(), raw_tokenizer.size(), false); - return new bailing_hybrid::Pipeline(std::move(embedding), std::move(engines), std::move(head), std::move(tokenizer), cfg); + return new bailing_hybrid::Pipeline(std::move(embedding), std::move(engines), std::move(head), + std::move(tokenizer), cfg); } diff --git a/families/bailing_hybrid/tests/cpp/test_runtime.cpp b/families/bailing_hybrid/tests/cpp/test_runtime.cpp index 0749819df5..3fcf52da42 100644 --- a/families/bailing_hybrid/tests/cpp/test_runtime.cpp +++ b/families/bailing_hybrid/tests/cpp/test_runtime.cpp @@ -3,26 +3,32 @@ * SPDX-License-Identifier: Apache-2.0 */ #include "trtmc/core.hpp" + #include #include int main(int argc, char** argv) { - if (argc != 3) return 2; + if (argc != 3) + return 2; try { - trtmc::LoadOptions options; options.runtime_root = argv[2]; + trtmc::LoadOptions options; + options.runtime_root = argv[2]; const auto model = trtmc::Model::load(argv[1], options); const auto task = model.task(); - nlohmann::json requests; std::cin >> requests; + nlohmann::json requests; + std::cin >> requests; auto results = nlohmann::json::array(); for (const auto& request : requests) { trtmc::Config config; config.add("max_new_tokens", request.at("max_new_tokens").get()); const auto result = task.run({request.at("prompt").get()}, config); - results.push_back({{"text", result.text()}, {"token_ids", - std::vector(result.token_ids().begin(), result.token_ids().end())}}); + results.push_back({{"text", result.text()}, + {"token_ids", std::vector(result.token_ids().begin(), + result.token_ids().end())}}); } std::cout << results.dump() << '\n'; } catch (const std::exception& error) { - std::cerr << error.what() << '\n'; return 1; + std::cerr << error.what() << '\n'; + return 1; } } diff --git a/families/bailing_hybrid/tests/cpp/test_tokenizer.cpp b/families/bailing_hybrid/tests/cpp/test_tokenizer.cpp index 7ab2a09c1a..c93fea6b02 100644 --- a/families/bailing_hybrid/tests/cpp/test_tokenizer.cpp +++ b/families/bailing_hybrid/tests/cpp/test_tokenizer.cpp @@ -3,13 +3,15 @@ * SPDX-License-Identifier: Apache-2.0 */ #include "families/bailing_hybrid/runtime/tokenizer.h" + #include #include #include #include int main(int argc, char** argv) { - if (argc != 3) return 2; + if (argc != 3) + return 2; std::ifstream file(argv[1]); const std::string data((std::istreambuf_iterator(file)), {}); const auto tokenizer = trtmc::CreateBpeTokenizer(data.data(), data.size(), false); From 0ec39b48d53eb695aa8442fb64697e491af6e23a Mon Sep 17 00:00:00 2001 From: Will Guo Date: Thu, 19 Nov 2026 01:48:07 -0800 Subject: [PATCH 3/6] fix(bailing_hybrid): preserve native validation outputs and own static runtime contracts Signed-off-by: Will Guo --- families/bailing_hybrid/__init__.py | 4 + families/bailing_hybrid/model.py | 2 + families/bailing_hybrid/runtime/plugin.cpp | 4 +- families/bailing_hybrid/tests/__init__.py | 4 + families/bailing_hybrid/tests/test_e2e.py | 153 +++++++++++++++--- families/bailing_hybrid/tests/test_support.py | 1 + 6 files changed, 144 insertions(+), 24 deletions(-) diff --git a/families/bailing_hybrid/__init__.py b/families/bailing_hybrid/__init__.py index e69de29bb2..4ce04d56cc 100644 --- a/families/bailing_hybrid/__init__.py +++ b/families/bailing_hybrid/__init__.py @@ -0,0 +1,4 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""bailing hybrid family package.""" diff --git a/families/bailing_hybrid/model.py b/families/bailing_hybrid/model.py index e30b41fae0..c81bab41ef 100644 --- a/families/bailing_hybrid/model.py +++ b/families/bailing_hybrid/model.py @@ -362,6 +362,8 @@ def moe(self, hidden, prefix): def build(request, writer): if request.task != "text_continuation" or request.backend != "trt": raise ValueError("Ling3 requires text_continuation with backend=trt") + if request.dynamic_kv_cache: + raise NotImplementedError("bailing_hybrid does not support dynamic_kv_cache") if ( request.precision != "fp32" or request.tensor_parallel_size != 1 diff --git a/families/bailing_hybrid/runtime/plugin.cpp b/families/bailing_hybrid/runtime/plugin.cpp index 3c9445163a..455282dece 100644 --- a/families/bailing_hybrid/runtime/plugin.cpp +++ b/families/bailing_hybrid/runtime/plugin.cpp @@ -185,8 +185,10 @@ class Pipeline final : public internal::IModel, public internal::ITextContinuati } // namespace trtmc::bailing_hybrid extern "C" trtmc::ITask* trtmc_create_family(const trtmc::FamilyContext& context) { + if (context.kv_cache_size_bytes != 0) + throw std::invalid_argument("bailing_hybrid does not support --kv-cache-size"); using namespace trtmc; - if (context.kv_cache_size_bytes || context.reader.info().task != "text_continuation") + if (context.reader.info().task != "text_continuation") throw std::invalid_argument( "Ling3 uses a family-owned fixed KV profile for text continuation"); const auto raw = bailing_hybrid::section(context.reader, "runtime.json"); diff --git a/families/bailing_hybrid/tests/__init__.py b/families/bailing_hybrid/tests/__init__.py index e69de29bb2..06ed6d4da2 100644 --- a/families/bailing_hybrid/tests/__init__.py +++ b/families/bailing_hybrid/tests/__init__.py @@ -0,0 +1,4 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""bailing hybrid package.""" diff --git a/families/bailing_hybrid/tests/test_e2e.py b/families/bailing_hybrid/tests/test_e2e.py index b062d44c02..d25de5c243 100644 --- a/families/bailing_hybrid/tests/test_e2e.py +++ b/families/bailing_hybrid/tests/test_e2e.py @@ -8,11 +8,13 @@ import json import os import subprocess +from functools import cache from pathlib import Path import pytest from tensorrt_model_connect import BuildRequest, build +from tools.e2e_evidence import evidence_enabled, evidence_stage, record_evidence FAMILY = "bailing_hybrid" TASKS = frozenset({"text_continuation"}) @@ -92,6 +94,46 @@ def _required_path(value: str | None, label: str) -> Path: return path +@cache +def _native_test_binary(name: str) -> Path: + """Build source-only helpers in the configured native test tree.""" + build_dir = _required_path(os.environ.get("TRTMC_NATIVE_BUILD_DIR"), "TRTMC_NATIVE_BUILD_DIR") + subprocess.run( + ["cmake", "--build", str(build_dir), "--parallel", "2", "--target", name], + check=True, + timeout=600, + ) + return _required_path(str(build_dir / name), name) + + +def _record_comparison(tmp_path, label, native, reference, checks): + """Retain the output pair and the result of already enforced comparisons.""" + if not evidence_enabled(): + return + import numpy as np + + paths = [] + for role, value in (("native", native), ("reference", reference)): + if isinstance(value, np.ndarray): + path = tmp_path / f"{label}-{role}.npz" + np.savez_compressed(path, output=value) + else: + path = tmp_path / f"{label}-{role}.json" + path.write_text(json.dumps(value, ensure_ascii=False) + "\n", encoding="utf-8") + paths.append(path) + record_evidence( + "reference_comparison", + { + "label": label, + "scope": "independent_reference", + "enforced": True, + "native": paths[0], + "reference": paths[1], + "checks": [dict(check, scope="independent_reference") for check in checks], + }, + ) + + def _model_dir(manifest: dict) -> Path: explicit = os.environ.get(f"TRTMC_{FAMILY.upper()}_MODEL_DIR") if explicit: @@ -142,31 +184,62 @@ def _build(model_dir: Path, bundle: Path, manifest: dict) -> None: def test_official_checkpoint_e2e(case_name, tmp_path): + _, manifest, case = CASES[case_name] + record_evidence("inputs", {"manifest": manifest, "case": case}) + record_evidence( + "checkpoint", + { + "repo_id": manifest["hf_id"], + "revision": manifest["hf_revision"], + "precision": manifest["precision"], + }, + ) + record_evidence( + "thresholds", + { + key: value + for key, value in case.items() + if any( + word in key + for word in ("error", "cosine", "atol", "rtol", "snr", "rmse", "max_abs") + ) + }, + ) + for asset_key in ("image", "test_image", "audio"): + if asset_key in case: + for asset_path in (TEST_ROOT / case[asset_key], TEST_ROOT / "data" / case[asset_key]): + if asset_path.is_file(): + record_evidence("inputs", {asset_key: asset_path}) + break import gc import torch from transformers import AutoModelForCausalLM, AutoTokenizer _, manifest, case = CASES[case_name] - directory = _model_dir(manifest) + with evidence_stage("checkpoint"): + directory = _model_dir(manifest) _, runtime_root = _runtime() - runner = runtime_root / "test_bailing_hybrid_runtime" - assert runner.is_file() + runner = _native_test_binary("test_bailing_hybrid_runtime") + with evidence_stage("comparison"): + assert runner.is_file() torch.backends.cuda.matmul.allow_tf32 = False torch.backends.cudnn.allow_tf32 = False - tokenizer = AutoTokenizer.from_pretrained(directory) + with evidence_stage("reference"): + tokenizer = AutoTokenizer.from_pretrained(directory) # Recompute each prefix in the pinned official model. This checks the # native KDA recurrence against the full-prefix official recurrent kernel. - reference = AutoModelForCausalLM.from_pretrained( - directory, - dtype=torch.float32, - device_map={"": "cuda:0"}, - trust_remote_code=True, - attn_implementation="eager", - ).eval() + with evidence_stage("reference"): + reference = AutoModelForCausalLM.from_pretrained( + directory, + dtype=torch.float32, + device_map={"": "cuda:0"}, + trust_remote_code=True, + attn_implementation="eager", + ).eval() expected = [] for prompt in case["prompts"]: inputs = tokenizer(prompt, return_tensors="pt", return_token_type_ids=False).to("cuda") - with torch.no_grad(): + with evidence_stage("reference"), torch.no_grad(): generated = reference.generate( **inputs, do_sample=False, use_cache=False, max_new_tokens=case["max_new_tokens"] ) @@ -177,24 +250,58 @@ def test_official_checkpoint_e2e(case_name, tmp_path): gc.collect() torch.cuda.empty_cache() bundle = tmp_path / manifest["bundle"] - _build(directory, bundle, manifest) + with evidence_stage("build"): + _build(directory, bundle, manifest) + record_evidence("bundle", {"path": str(bundle), "manifest": manifest}) gc.collect() torch.cuda.empty_cache() requests = [ {"prompt": prompt, "max_new_tokens": case["max_new_tokens"]} for prompt in case["prompts"] ] - completed = subprocess.run( - [str(runner), str(bundle), str(runtime_root)], - input=json.dumps(requests), - text=True, - capture_output=True, - check=False, - timeout=case.get("runtime_timeout_s", 3600), + with evidence_stage("runtime"): + completed = subprocess.run( + [str(runner), str(bundle), str(runtime_root)], + input=json.dumps(requests), + text=True, + capture_output=True, + check=False, + timeout=case.get("runtime_timeout_s", 3600), + ) + record_evidence( + "runtime_process", + { + "argv": completed.args, + "returncode": completed.returncode, + "stdout": (completed.stdout or "")[-4096:], + "stderr": (completed.stderr or "")[-16384:], + }, ) - assert completed.returncode == 0, completed.stderr + completed.stdout + with evidence_stage("comparison"): + assert completed.returncode == 0, completed.stderr + completed.stdout payload = json.loads(completed.stdout.splitlines()[-1]) - assert payload == expected - assert all(item["text"].strip() for item in payload) + record_evidence("inputs", {"requests": requests}) + record_evidence("thresholds", {"tokens_and_text": "exact equality for every prompt"}) + record_evidence("native", {"generations": payload}) + record_evidence("reference", {"mode": "hf_transformers", "generations": expected}) + with evidence_stage("comparison"): + assert payload == expected + with evidence_stage("comparison"): + assert all(item["text"].strip() for item in payload) + _record_comparison( + tmp_path, + "greedy-generations", + payload, + expected, + [ + { + "name": "generation_mismatch", + "actual": int(payload != expected), + "operator": "==", + "expected": 0, + "passed": payload == expected, + }, + ], + ) print(f"Ling3 exact native greedy generations: {payload!r}", flush=True) diff --git a/families/bailing_hybrid/tests/test_support.py b/families/bailing_hybrid/tests/test_support.py index 5c38732728..5b75cae10a 100644 --- a/families/bailing_hybrid/tests/test_support.py +++ b/families/bailing_hybrid/tests/test_support.py @@ -7,3 +7,4 @@ def test_bailing_hybrid_checkpoint_has_one_owner(): family, support = resolve_family(ModelMetadata({"model_type": "bailing_hybrid"}, {})) assert family == "bailing_hybrid" assert support.tasks == ("text_continuation",) + assert support.default_task == "text_continuation" From e0822849ebd69ca620b3ace806ce704bc2605cbd Mon Sep 17 00:00:00 2001 From: Will Guo Date: Thu, 19 Nov 2026 01:55:59 -0800 Subject: [PATCH 4/6] fix(bailing_hybrid): serialize and release one native engine at a time Signed-off-by: Will Guo --- families/bailing_hybrid/model.py | 17 +++++------------ 1 file changed, 5 insertions(+), 12 deletions(-) diff --git a/families/bailing_hybrid/model.py b/families/bailing_hybrid/model.py index c81bab41ef..5435caec85 100644 --- a/families/bailing_hybrid/model.py +++ b/families/bailing_hybrid/model.py @@ -28,15 +28,6 @@ def read(self, name): return self.files[self.index[name]].get_tensor(name).float().numpy() -class PlanWriter(trt.IStreamWriter): - def __init__(self, stream): - super().__init__() - self.stream = stream - - def write(self, data): - return self.stream.write(data) - - class Graph: def __init__(self, weights, cfg, logger): self.weights, self.cfg, self.logger = weights, cfg, logger @@ -115,10 +106,12 @@ def save(self, stream): options = self.builder.create_builder_config() options.clear_flag(trt.BuilderFlag.TF32) options.builder_optimization_level = 3 - if not self.builder.build_serialized_network_to_stream( - self.net, options, PlanWriter(stream) - ): + # Keep serialization bounded to the current engine. The caller releases + # this graph before loading the next layer's weights. + plan = self.builder.build_serialized_network(self.net, options) + if plan is None: raise RuntimeError("Ling3 engine build failed") + stream.write(memoryview(plan)) def kda(self, hidden, prefix): net, cfg = self.net, self.cfg From 4bd17d635d31695cb235274cf60c398c2b816680 Mon Sep 17 00:00:00 2001 From: Will Guo Date: Thu, 19 Nov 2026 02:10:37 -0800 Subject: [PATCH 5/6] fix(bailing_hybrid): declare the pinned reference dependencies and builder policy Signed-off-by: Will Guo --- families/bailing_hybrid/model.py | 2 +- families/bailing_hybrid/requirements.txt | 5 ++++- 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/families/bailing_hybrid/model.py b/families/bailing_hybrid/model.py index 5435caec85..8a86deda99 100644 --- a/families/bailing_hybrid/model.py +++ b/families/bailing_hybrid/model.py @@ -104,8 +104,8 @@ def output(self, value, name): def save(self, stream): options = self.builder.create_builder_config() - options.clear_flag(trt.BuilderFlag.TF32) options.builder_optimization_level = 3 + options.clear_flag(trt.BuilderFlag.TF32) # Keep serialization bounded to the current engine. The caller releases # this graph before loading the next layer's weights. plan = self.builder.build_serialized_network(self.net, options) diff --git a/families/bailing_hybrid/requirements.txt b/families/bailing_hybrid/requirements.txt index 42fcbb0ea7..33c9cd75c1 100644 --- a/families/bailing_hybrid/requirements.txt +++ b/families/bailing_hybrid/requirements.txt @@ -1,4 +1,7 @@ numpy safetensors torch -transformers>=4.57.6 +transformers==4.57.6 +fla-core==0.6.0 +einops +accelerate From 72469794ff52e2c39977335d1e2a2599f9733b15 Mon Sep 17 00:00:00 2001 From: Will Guo Date: Thu, 19 Nov 2026 02:33:03 -0800 Subject: [PATCH 6/6] fix(bailing_hybrid): resolve the existing tokenizer helper from the native build Signed-off-by: Will Guo --- families/bailing_hybrid/tests/test_e2e.py | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/families/bailing_hybrid/tests/test_e2e.py b/families/bailing_hybrid/tests/test_e2e.py index d25de5c243..589be26900 100644 --- a/families/bailing_hybrid/tests/test_e2e.py +++ b/families/bailing_hybrid/tests/test_e2e.py @@ -310,10 +310,7 @@ def test_native_tokenizer(case_name): _, manifest, _ = CASES[case_name] directory = _model_dir(manifest) - runner = ( - _required_path(os.environ.get("TRTMC_RUNTIME_ROOT"), "TRTMC_RUNTIME_ROOT") - / "test_bailing_hybrid_tokenizer" - ) + runner = _native_test_binary("test_bailing_hybrid_tokenizer") reference = AutoTokenizer.from_pretrained(directory) for text in [ "The capital of Germany is",