From 593e6e40b0f9e8d40c87b1ee951d8fd3bc7620e2 Mon Sep 17 00:00:00 2001 From: Will Guo Date: Fri, 13 Nov 2026 03:01:04 -0800 Subject: [PATCH 1/5] feat(biogpt): add native text generation Add the FP32 BioGPT decoder, native Moses/BPE tokenization, request-local cache handling, and checkpoint tests. Validate exact greedy tokens and text through the public Task and CLI against Transformers 5.3.0. Signed-off-by: Will Guo --- families/biogpt/README.md | 36 +++ families/biogpt/__init__.py | 1 + families/biogpt/model.py | 285 +++++++++++++++++ families/biogpt/requirements.txt | 2 + families/biogpt/runtime/CMakeLists.txt | 31 ++ families/biogpt/runtime/bpe_tokenizer.cpp | 289 ++++++++++++++++++ families/biogpt/runtime/pipeline.cpp | 104 +++++++ families/biogpt/runtime/pipeline.h | 35 +++ families/biogpt/runtime/plugin.cpp | 38 +++ families/biogpt/runtime/tokenizer.h | 29 ++ families/biogpt/support.py | 10 + families/biogpt/tests/__init__.py | 2 + families/biogpt/tests/cpp/e2e_consumer.cpp | 60 ++++ .../biogpt/tests/cpp/tokenizer_consumer.cpp | 32 ++ families/biogpt/tests/decoder_check.py | 71 +++++ families/biogpt/tests/manifests/biogpt.json | 24 ++ families/biogpt/tests/requirements.txt | 2 + families/biogpt/tests/test_e2e.py | 223 ++++++++++++++ families/biogpt/tests/test_model.py | 43 +++ families/biogpt/tests/test_support.py | 14 + 20 files changed, 1331 insertions(+) create mode 100644 families/biogpt/README.md create mode 100644 families/biogpt/__init__.py create mode 100644 families/biogpt/model.py create mode 100644 families/biogpt/requirements.txt create mode 100644 families/biogpt/runtime/CMakeLists.txt create mode 100644 families/biogpt/runtime/bpe_tokenizer.cpp create mode 100644 families/biogpt/runtime/pipeline.cpp create mode 100644 families/biogpt/runtime/pipeline.h create mode 100644 families/biogpt/runtime/plugin.cpp create mode 100644 families/biogpt/runtime/tokenizer.h create mode 100644 families/biogpt/support.py create mode 100644 families/biogpt/tests/__init__.py create mode 100644 families/biogpt/tests/cpp/e2e_consumer.cpp create mode 100644 families/biogpt/tests/cpp/tokenizer_consumer.cpp create mode 100644 families/biogpt/tests/decoder_check.py create mode 100644 families/biogpt/tests/manifests/biogpt.json create mode 100644 families/biogpt/tests/requirements.txt create mode 100644 families/biogpt/tests/test_e2e.py create mode 100644 families/biogpt/tests/test_model.py create mode 100644 families/biogpt/tests/test_support.py diff --git a/families/biogpt/README.md b/families/biogpt/README.md new file mode 100644 index 0000000000..ac5bc98623 --- /dev/null +++ b/families/biogpt/README.md @@ -0,0 +1,36 @@ +# BioGPT + +This family builds `microsoft/biogpt` revision +`eb0d815e95434dc9e3b78f464e52b899bee7d923` for native `ITextGeneration`. +The selected profile uses FP32, batch size one, tensor parallel size one, +a 128-position cache, and raw greedy generation. + +The decoder preserves scaled token embeddings, learned positions with the +published two-position offset, pre-normalized attention and feed-forward +branches, ERF GELU, final normalization, and the tied output projection. +Upstream BioGPT uses LayerNorm's default epsilon `1e-5` even though its +published configuration contains `layer_norm_eps=1e-12`; this family follows +the reference implementation. All GPU math runs through TensorRT. + +The native tokenizer implements the checkpoint's English Moses preprocessing, +Unicode word BPE, special tokens, and Moses detokenization. The builder stores +the upstream Sacremoses character tables, expressions, and abbreviation lists +as bundle data. The runtime requires ICU and has no Python dependency. + +Install `requirements.txt` and `tests/requirements.txt`. Build +`trtmc_model_biogpt`, `biogpt_e2e`, and `biogpt_tokenizer`, and set +`TRTMC_RUNTIME_ROOT` to the build directory. Set `TRTMC_BIOGPT_MODEL_DIR` to the +pinned local checkpoint. + +```bash +PYTHONPATH=core/builder:apps/benchmark:. python3 -m tools.model_ci validate +PYTHONPATH=core/builder:apps/benchmark:. python3 -m pytest \ + families/biogpt/tests --e2e-model biogpt -q +``` + +The selected test compares all logits and cache tensors with unmodified +Transformers 5.3.0 at FP32 absolute and relative tolerance `5e-5`. It requires +exact token IDs and decoded text for the real checkpoint, including repeated +requests and recovery after cache overflow. Focused native tokenizer cases +cover biomedical punctuation, abbreviations, numbers, Unicode, contractions, +special tokens, and empty inputs. diff --git a/families/biogpt/__init__.py b/families/biogpt/__init__.py new file mode 100644 index 0000000000..4d907ba2a7 --- /dev/null +++ b/families/biogpt/__init__.py @@ -0,0 +1 @@ +"""BioGPT family ownership boundary.""" diff --git a/families/biogpt/model.py b/families/biogpt/model.py new file mode 100644 index 0000000000..ef8df5e071 --- /dev/null +++ b/families/biogpt/model.py @@ -0,0 +1,285 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +"""BioGPT learned positions, pre-normalized decoder, and Moses word BPE.""" + +import json +import math +from pathlib import Path + +import numpy as np +import tensorrt as trt + + +class Graph: + def __init__(self, network, config, weights, capacity): + self.n, self.c, self.w, self.capacity = network, config, weights, capacity + self.constants = [] + + def constant(self, value, dtype=np.float32): + value = np.ascontiguousarray(value, dtype=dtype) + self.constants.append(value) + return self.n.add_constant(value.shape, trt.Weights(value)).get_output(0) + + def binary(self, x, y, op=trt.ElementWiseOperation.SUM): + return self.n.add_elementwise(x, y, op).get_output(0) + + def reshape(self, x, shape, transpose=None): + layer = self.n.add_shuffle(x) + layer.reshape_dims = shape + if transpose is not None: + layer.second_transpose = transpose + return layer.get_output(0) + + def linear(self, x, name): + x = self.n.add_matrix_multiply( + x, + trt.MatrixOperation.NONE, + self.constant(self.w[name + ".weight"]), + trt.MatrixOperation.TRANSPOSE, + ).get_output(0) + if name + ".bias" in self.w: + x = self.binary(x, self.constant(self.w[name + ".bias"].reshape(1, -1))) + return x + + def norm(self, x, name): + mean = self.n.add_reduce(x, trt.ReduceOperation.AVG, 2, True).get_output(0) + x = self.binary(x, mean, trt.ElementWiseOperation.SUB) + square = self.binary(x, x, trt.ElementWiseOperation.PROD) + variance = self.n.add_reduce(square, trt.ReduceOperation.AVG, 2, True).get_output(0) + # Upstream BioGPT constructs nn.LayerNorm without passing config.layer_norm_eps. + denominator = self.n.add_unary( + self.binary(variance, self.constant([[1e-5]])), trt.UnaryOperation.SQRT + ).get_output(0) + x = self.binary(x, denominator, trt.ElementWiseOperation.DIV) + x = self.binary( + x, self.constant(self.w[name + ".weight"].reshape(1, -1)), trt.ElementWiseOperation.PROD + ) + return self.binary(x, self.constant(self.w[name + ".bias"].reshape(1, -1))) + + def output(self, x, name): + x.name = name + self.n.mark_output(x) + + def build(self): + c, cap = self.c, self.capacity + width, heads = c["hidden_size"], c["num_attention_heads"] + dim = width // heads + token = self.n.add_input("input_ids", trt.int32, (1,)) + position = self.n.add_input("position", trt.int32, (1,)) + hidden = self.n.add_gather( + self.constant(self.w["biogpt.embed_tokens.weight"]), token, 0 + ).get_output(0) + if c.get("scale_embedding", True): + hidden = self.binary( + hidden, self.constant([[math.sqrt(width)]]), trt.ElementWiseOperation.PROD + ) + pos = self.binary(position, self.constant([2], np.int32)) + hidden = self.binary( + hidden, + self.n.add_gather( + self.constant(self.w["biogpt.embed_positions.weight"]), pos, 0 + ).get_output(0), + ) + indices = self.constant(np.arange(cap), np.int32) + future = self.binary(indices, position, trt.ElementWiseOperation.GREATER) + mask = self.n.add_select( + future, + self.constant(np.full(cap, np.finfo(np.float32).min)), + self.constant(np.zeros(cap)), + ).get_output(0) + mask = self.reshape(mask, (1, 1, cap)) + replace = self.reshape( + self.binary(indices, position, trt.ElementWiseOperation.EQUAL), (cap, 1) + ) + for layer in range(c["num_hidden_layers"]): + prefix = f"biogpt.layers.{layer}" + normalized = self.norm(hidden, prefix + ".self_attn_layer_norm") + q = self.linear(normalized, prefix + ".self_attn.q_proj") + k = self.linear(normalized, prefix + ".self_attn.k_proj") + v = self.linear(normalized, prefix + ".self_attn.v_proj") + cached = [] + for kind, value in (("k", k), ("v", v)): + past = self.n.add_input(f"past_{kind}_{layer}", trt.float32, (cap, width)) + present = self.n.add_select(replace, value, past).get_output(0) + self.output(present, f"present_{kind}_{layer}") + cached.append(present) + q = self.reshape(q, (1, heads, dim), (1, 0, 2)) + k = self.reshape(cached[0], (cap, heads, dim), (1, 0, 2)) + v = self.reshape(cached[1], (cap, heads, dim), (1, 0, 2)) + scores = self.n.add_matrix_multiply( + q, trt.MatrixOperation.NONE, k, trt.MatrixOperation.TRANSPOSE + ).get_output(0) + scores = self.binary( + scores, self.constant([[[dim**-0.5]]]), trt.ElementWiseOperation.PROD + ) + softmax = self.n.add_softmax(self.binary(scores, mask)) + softmax.axes = 4 + attended = self.n.add_matrix_multiply( + softmax.get_output(0), trt.MatrixOperation.NONE, v, trt.MatrixOperation.NONE + ).get_output(0) + attended = self.reshape(attended, (1, width)) + hidden = self.binary(hidden, self.linear(attended, prefix + ".self_attn.out_proj")) + inner = self.linear(self.norm(hidden, prefix + ".final_layer_norm"), prefix + ".fc1") + erf = self.n.add_unary( + self.binary(inner, self.constant([[math.sqrt(2.0)]]), trt.ElementWiseOperation.DIV), + trt.UnaryOperation.ERF, + ).get_output(0) + inner = self.binary( + self.binary(inner, self.constant([[0.5]]), trt.ElementWiseOperation.PROD), + self.binary(erf, self.constant([[1.0]])), + trt.ElementWiseOperation.PROD, + ) + hidden = self.binary(hidden, self.linear(inner, prefix + ".fc2")) + self.output( + self.linear(self.norm(hidden, "biogpt.layer_norm"), "output_projection"), "logits" + ) + + +def validate_config(config): + if config.get("model_type") != "biogpt" or config.get("hidden_act", "gelu") != "gelu": + raise ValueError("biogpt requires the BioGPT GELU decoder") + for name in ( + "hidden_size", + "intermediate_size", + "num_hidden_layers", + "num_attention_heads", + "vocab_size", + "max_position_embeddings", + ): + if not isinstance(config.get(name), int) or config[name] <= 0: + raise ValueError(f"biogpt invalid {name}") + if config["hidden_size"] % config["num_attention_heads"]: + raise ValueError("biogpt hidden size must divide into attention heads") + return config + + +def required_shapes(config): + width, inner = config["hidden_size"], config["intermediate_size"] + shapes = { + "biogpt.embed_tokens.weight": (config["vocab_size"], width), + "biogpt.embed_positions.weight": (config["max_position_embeddings"] + 2, width), + "biogpt.layer_norm.weight": (width,), + "biogpt.layer_norm.bias": (width,), + "output_projection.weight": (config["vocab_size"], width), + } + for index in range(config["num_hidden_layers"]): + p = f"biogpt.layers.{index}." + for name in ("self_attn_layer_norm", "final_layer_norm"): + shapes[p + name + ".weight"] = shapes[p + name + ".bias"] = (width,) + for name, rows, cols in [ + ("self_attn." + n + "_proj", width, width) for n in ("q", "k", "v", "out") + ] + [("fc1", inner, width), ("fc2", width, inner)]: + shapes[p + name + ".weight"], shapes[p + name + ".bias"] = (rows, cols), (rows,) + return shapes + + +def load_weights(root, config): + import torch + + path = root / "pytorch_model.bin" + with path.open("rb") as file: + is_zip = file.read(2) == b"PK" + source = torch.load(path, map_location="cpu", weights_only=True, mmap=is_zip) + weights = {} + for name, shape in required_shapes(config).items(): + if name not in source or tuple(source[name].shape) != shape: + raise ValueError(f"biogpt missing or invalid tensor: {name}, expected {shape}") + weights[name] = source[name].float().numpy() + return weights + + +def compile_engine(config, weights, capacity, verbose=False): + logger = trt.Logger(trt.Logger.VERBOSE if verbose else trt.Logger.WARNING) + builder = trt.Builder(logger) + network = builder.create_network(0) + graph = Graph(network, config, weights, capacity) + graph.build() + options = builder.create_builder_config() + options.builder_optimization_level = 3 + options.clear_flag(trt.BuilderFlag.TF32) + plan = builder.build_serialized_network(network, options) + if plan is None: + raise RuntimeError("biogpt TensorRT build failed") + return bytes(plan) + + +def tokenizer_spec(root): + from sacremoses import MosesTokenizer, MosesDetokenizer + from sacremoses.util import CJKChars + from transformers import BioGptTokenizer + + tokenizer = BioGptTokenizer.from_pretrained(root, trust_remote_code=False) + moses, detokenizer = MosesTokenizer(lang="en"), MosesDetokenizer(lang="en") + names = [ + "DEDUPLICATE_SPACE", + "ASCII_JUNK", + "PAD_NOT_ISALNUM", + "AGGRESSIVE_HYPHEN_SPLIT", + "COMMA_SEPARATE_1", + "COMMA_SEPARATE_2", + "COMMA_SEPARATE_3", + "TRAILING_DOT_APOSTROPHE", + ] + + def rule(pair): + return [pair[0].pattern, pair[1]] + + return { + "schema_version": 1, + "vocab": tokenizer.encoder, + "merges": [[*pair, rank] for pair, rank in tokenizer.bpe_ranks.items()], + "rules": {name: rule(getattr(moses, name)) for name in names}, + "apostrophes": [rule(pair) for pair in moses.ENGLISH_SPECIFIC_APOSTROPHE], + "escape": [rule(pair) for pair in moses.MOSES_ESCAPE_XML_REGEXES], + "unescape": [rule(pair) for pair in detokenizer.MOSES_UNESCAPE_XML_REGEXES], + "alpha": moses.IsAlpha, + "lower": moses.IsLower, + "prefixes": moses.NONBREAKING_PREFIXES, + "numeric_prefixes": moses.NUMERIC_ONLY_PREFIXES, + "cjk_ranges": CJKChars.ranges, + "currency": detokenizer.IsSc, + "detokenizer_alpha": detokenizer.IsAlpha, + } + + +def build(request, writer): + if request.dynamic_kv_cache: + raise NotImplementedError("biogpt does not support dynamic_kv_cache") + if request.task != "text_generation" or request.precision != "fp32" or request.backend != "trt": + raise ValueError("biogpt requires text_generation, precision=fp32, backend=trt") + for field, value, default in ( + ("max_batch_size", request.max_batch_size, 1), + ("tensor_parallel_size", request.tensor_parallel_size, 1), + ("context_parallel_size", request.context_parallel_size, 1), + ("image_height", request.image_height, None), + ("image_width", request.image_width, None), + ("video_num_frames", request.video_num_frames, None), + ("mtp_seq_len", request.mtp_seq_len, None), + ("fp32_layers", request.fp32_layers, ()), + ): + if value != default: + raise NotImplementedError(f"biogpt does not support {field}") + if request.quantization not in (None, "none"): + raise NotImplementedError("biogpt does not support quantization") + root = Path(request.model_dir) + config = validate_config(json.loads((root / "config.json").read_text())) + capacity = request.max_sequence_length or 128 + if not 1 <= capacity <= config["max_position_embeddings"]: + raise ValueError("biogpt cache capacity exceeds the checkpoint positions") + weights = load_weights(root, config) + plan = compile_engine(config, weights, capacity, request.verbose) + writer.set_header(family="biogpt", task=request.task, backend=request.backend) + writer.add_bytes("decoder.plan", plan) + writer.add_json("tokenizer.json", tokenizer_spec(root)) + writer.add_json( + "runtime.json", + { + "schema_version": 1, + "vocab_size": config["vocab_size"], + "num_layers": config["num_hidden_layers"], + "kv_width": config["hidden_size"], + "max_sequence_length": capacity, + "bos_token_id": config.get("bos_token_id", 0), + "eos_token_id": config.get("eos_token_id", 2), + }, + ) diff --git a/families/biogpt/requirements.txt b/families/biogpt/requirements.txt new file mode 100644 index 0000000000..5c1469fa17 --- /dev/null +++ b/families/biogpt/requirements.txt @@ -0,0 +1,2 @@ +transformers==5.3.0 +sacremoses==0.1.1 diff --git a/families/biogpt/runtime/CMakeLists.txt b/families/biogpt/runtime/CMakeLists.txt new file mode 100644 index 0000000000..94c2b17cfe --- /dev/null +++ b/families/biogpt/runtime/CMakeLists.txt @@ -0,0 +1,31 @@ +# 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_biogpt SHARED pipeline.cpp plugin.cpp bpe_tokenizer.cpp) +target_include_directories(trtmc_model_biogpt PRIVATE + ${PROJECT_SOURCE_DIR} ${PROJECT_SOURCE_DIR}/core/runtime/include) +target_include_directories(trtmc_model_biogpt SYSTEM PRIVATE ${TRTMC_CUDA_INCLUDE_DIR}) +target_link_libraries(trtmc_model_biogpt PRIVATE + trtmc_core nlohmann_json::nlohmann_json ICU::uc ICU::i18n ${TRTMC_CUDART_LIBRARY}) +target_compile_options(trtmc_model_biogpt PRIVATE -Wall -Wextra -Wpedantic) +set_target_properties(trtmc_model_biogpt PROPERTIES + LIBRARY_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}" + BUILD_RPATH "\$ORIGIN" INSTALL_RPATH "\$ORIGIN") +install(TARGETS trtmc_model_biogpt LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR}) + +if(TRTMC_BUILD_TESTS) + add_executable(biogpt_tokenizer + ${PROJECT_SOURCE_DIR}/families/biogpt/tests/cpp/tokenizer_consumer.cpp bpe_tokenizer.cpp) + target_include_directories(biogpt_tokenizer PRIVATE ${PROJECT_SOURCE_DIR}) + target_link_libraries(biogpt_tokenizer PRIVATE nlohmann_json::nlohmann_json ICU::uc ICU::i18n) + set_target_properties(biogpt_tokenizer PROPERTIES RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}") + + add_executable(biogpt_e2e + ${PROJECT_SOURCE_DIR}/families/biogpt/tests/cpp/e2e_consumer.cpp bpe_tokenizer.cpp) + target_include_directories(biogpt_e2e PRIVATE + ${PROJECT_SOURCE_DIR} ${PROJECT_SOURCE_DIR}/core/runtime/include) + target_link_libraries(biogpt_e2e PRIVATE trtmc_runtime trtmc_core nlohmann_json::nlohmann_json ICU::uc ICU::i18n) + set_target_properties(biogpt_e2e PROPERTIES RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}") +endif() diff --git a/families/biogpt/runtime/bpe_tokenizer.cpp b/families/biogpt/runtime/bpe_tokenizer.cpp new file mode 100644 index 0000000000..a9ee5f183e --- /dev/null +++ b/families/biogpt/runtime/bpe_tokenizer.cpp @@ -0,0 +1,289 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + */ +#include "families/biogpt/runtime/tokenizer.h" + +#include +#include +#include + +#include +#include +#include +#include +#include + +namespace trtmc::biogpt { +namespace { +using Json = nlohmann::json; +using Text = icu::UnicodeString; + +Text unicode(const std::string& value) { return Text::fromUTF8(value); } +std::string utf8(const Text& value) { std::string out; value.toUTF8String(out); return out; } + +bool space(UChar32 c) { + return (c >= 9 && c <= 13) || (c >= 28 && c <= 32) || c == 0x85 || c == 0xa0 || + c == 0x1680 || (c >= 0x2000 && c <= 0x200a) || c == 0x2028 || c == 0x2029 || + c == 0x202f || c == 0x205f || c == 0x3000; +} + +std::vector split(const std::string& value) { + const auto text = unicode(value); + std::vector words; + int32_t first = 0; + for (int32_t i = 0; i < text.length();) { + const auto c = text.char32At(i); + if (space(c)) { + if (i > first) words.push_back(utf8(text.tempSubStringBetween(first, i))); + first = i + U16_LENGTH(c); + } + i += U16_LENGTH(c); + } + if (first < text.length()) words.push_back(utf8(text.tempSubString(first))); + return words; +} + +std::string join(const std::vector& values) { + std::string result; + for (const auto& value : values) { if (!result.empty()) result += ' '; result += value; } + return result; +} + +std::unordered_set characters(const std::string& value) { + const auto text = unicode(value); + std::unordered_set result; + for (int32_t i = 0; i < text.length();) { + const auto c = text.char32At(i); result.insert(c); i += U16_LENGTH(c); + } + return result; +} + +void replace_literal(std::string& value, const std::string& from, const std::string& to) { + std::size_t position = 0; + while ((position = value.find(from, position)) != std::string::npos) { + value.replace(position, from.size(), to); position += to.size(); + } +} + +class Rule { + public: + Rule(const std::string& expression, const std::string& replacement) { + std::string pattern; + bool inside_class = false; + const std::string spaces = "\\u0009-\\u000d\\u001c-\\u0020\\u0085\\u00a0\\u1680\\u2000-\\u200a\\u2028\\u2029\\u202f\\u205f\\u3000"; + for (std::size_t i = 0; i < expression.size(); ++i) { + const char c = expression[i]; + if (c == '\\' && i + 1 < expression.size()) { + const char next = expression[++i]; + if (next == 's') pattern += inside_class ? spaces : "[" + spaces + "]"; + else { pattern += '\\'; pattern += next; } + } else { + if (c == '[') inside_class = true; + if (c == ']') inside_class = false; + pattern += c; + } + } + UErrorCode status = U_ZERO_ERROR; + pattern_.reset(icu::RegexPattern::compile(unicode(pattern), 0, status)); + if (U_FAILURE(status) || !pattern_) throw std::invalid_argument("biogpt invalid Moses expression"); + std::string converted; + for (std::size_t i = 0; i < replacement.size(); ++i) { + if (replacement[i] == '\\' && i + 1 < replacement.size() && replacement[i + 1] >= '1' && replacement[i + 1] <= '9') { + converted += '$'; converted += replacement[++i]; + } else { + if (replacement[i] == '$' || replacement[i] == '\\') converted += '\\'; + converted += replacement[i]; + } + } + replacement_ = unicode(converted); + } + explicit Rule(const Json& pair) : Rule(pair.at(0).get(), pair.at(1).get()) {} + std::string apply(const std::string& input) const { + UErrorCode status = U_ZERO_ERROR; + const auto text = unicode(input); + std::unique_ptr matcher(pattern_->matcher(text, status)); + const auto result = matcher->replaceAll(replacement_, status); + if (U_FAILURE(status)) throw std::runtime_error("biogpt Moses replacement failed"); + return utf8(result); + } + bool matches(const std::string& input) const { + UErrorCode status = U_ZERO_ERROR; + const auto text = unicode(input); + std::unique_ptr matcher(pattern_->matcher(text, status)); + const bool result = matcher->find(status); + if (U_FAILURE(status)) throw std::runtime_error("biogpt Moses match failed"); + return result; + } + private: + std::unique_ptr pattern_; + Text replacement_; +}; + +class Tokenizer final : public ITokenizer { + public: + Tokenizer(const Json& spec, bool add_special) : add_special_(add_special), + alpha_(characters(spec.at("alpha"))), lower_(characters(spec.at("lower"))), + detok_alpha_(characters(spec.at("detokenizer_alpha"))), + currency_("^[" + spec.at("currency").get() + "\\(\\[\\{¿¡]+$", ""), + punct_(R"(^[,.?!:;\\%}\]\)]+$)", ""), quote_("^[\\'\\\"„“`]+$", "") { + if (spec.at("schema_version") != 1) throw std::invalid_argument("biogpt invalid tokenizer schema"); + vocab_ = spec.at("vocab").get(); + decoded_.resize(vocab_.size()); + for (const auto& [piece, id] : vocab_) { + if (id < 0 || id >= static_cast(decoded_.size())) throw std::invalid_argument("biogpt invalid vocabulary ID"); + decoded_[id] = piece; + } + for (const auto& merge : spec.at("merges")) + ranks_[merge.at(0).get() + '\x1f' + merge.at(1).get()] = merge.at(2); + for (auto it = spec.at("rules").begin(); it != spec.at("rules").end(); ++it) + rules_.emplace(it.key(), Rule(it.value())); + for (const auto& rule : spec.at("apostrophes")) apostrophes_.emplace_back(rule); + for (const auto& rule : spec.at("escape")) escape_.emplace_back(rule); + for (const auto& rule : spec.at("unescape")) unescape_.emplace_back(rule); + for (const auto& prefix : spec.at("prefixes")) prefixes_.insert(prefix.get()); + for (const auto& prefix : spec.at("numeric_prefixes")) numeric_.insert(prefix.get()); + cjk_ = spec.at("cjk_ranges").get(); + } + + std::vector encode(const std::string& text) const override { + std::vector ids; + if (add_special_) ids.push_back(vocab_.at("")); + std::size_t cursor = 0; + while (cursor < text.size()) { + auto at = std::string::npos; + std::string special; + for (const auto* piece : {"", "", "", ""}) { + const auto found = text.find(piece, cursor); + if (found < at) { at = found; special = piece; } + } + const auto end = at == std::string::npos ? text.size() : at; + for (const auto& word : moses(text.substr(cursor, end - cursor))) + for (const auto& piece : bpe(word)) ids.push_back(id_for_token(piece)); + if (at == std::string::npos) break; + ids.push_back(vocab_.at(special)); cursor = at + special.size(); + } + return ids; + } + + std::string decode(const std::vector& ids) const override { + std::string text; + for (auto id : ids) { + if (id >= 0 && id <= 3) continue; + auto piece = token_for_id(id); + replace_literal(piece, " ", ""); replace_literal(piece, "", " "); text += piece; + } + text = " " + join(split(text)) + " "; + replace_literal(text, " @-@ ", "-"); + for (const auto& rule : unescape_) text = rule.apply(text); + const auto words = split(text); + std::unordered_map quote_counts; + std::string output, prepend = " "; + for (std::size_t i = 0; i < words.size(); ++i) { + const auto& word = words[i]; + const auto u = unicode(word); + const auto first = u.char32At(0); + if (is_cjk(first)) { + const auto previous = i ? unicode(words[i - 1]) : Text(); + const bool consecutive = i && is_cjk(previous.char32At(previous.moveIndex32(previous.length(), -1))); + output += (consecutive ? "" : prepend) + word; prepend = " "; + } else if (currency_.matches(word)) { output += prepend + word; prepend = ""; + } else if (punct_.matches(word)) { output += word; prepend = " "; + } else if (i > 0 && first == '\'' && u.countChar32() > 1 && detok_alpha_.count(u.char32At(1))) { + output += word; prepend = " "; + } else if (quote_.matches(word)) { + const auto chars = characters(word); + const bool curly = std::all_of(chars.begin(), chars.end(), [](auto c) { return c == 0x201e || c == 0x201c || c == 0x201d; }); + auto& count = quote_counts[curly ? "\"" : word]; + if (count % 2 == 0) { + if (word == "'" && i > 0 && !words[i - 1].empty() && words[i - 1].back() == 's') { + output += word; prepend = " "; + } else { output += prepend + word; prepend = ""; ++count; } + } else { output += word; prepend = " "; ++count; } + } else { output += prepend + word; prepend = " "; } + } + return join(split(output)); + } + + int32_t id_for_token(std::string_view token) const override { + const auto it = vocab_.find(std::string(token)); return it == vocab_.end() ? vocab_.at("") : it->second; + } + std::string token_for_id(int32_t id) const override { + return id >= 0 && id < static_cast(decoded_.size()) ? decoded_[id] : ""; + } + + private: + bool is_cjk(UChar32 c) const { + return std::any_of(cjk_.begin(), cjk_.end(), [c](const auto& range) { return c >= range[0] && c <= range[1]; }); + } + std::vector moses(std::string text) const { + auto apply = [&](const char* name) { text = rules_.at(name).apply(text); }; + apply("DEDUPLICATE_SPACE"); apply("ASCII_JUNK"); text = join(split(text)); + apply("PAD_NOT_ISALNUM"); apply("AGGRESSIVE_HYPHEN_SPLIT"); + text = Rule("\\.([.]+)", " DOTMULTI\\1").apply(text); + while (text.find("DOTMULTI.") != std::string::npos) { + text = Rule("DOTMULTI\\.([^\\.])", "DOTDOTMULTI \\1").apply(text); + replace_literal(text, "DOTMULTI.", "DOTDOTMULTI"); + } + apply("COMMA_SEPARATE_1"); apply("COMMA_SEPARATE_2"); apply("COMMA_SEPARATE_3"); + for (const auto& rule : apostrophes_) text = rule.apply(text); + auto words = split(text); + for (std::size_t i = 0; i < words.size(); ++i) { + auto& word = words[i]; + if (word.size() <= 1 || word.back() != '.') continue; + const auto prefix = word.substr(0, word.size() - 1); + const auto chars = characters(prefix); + const bool alpha = std::any_of(chars.begin(), chars.end(), [&](auto c) { return alpha_.count(c); }); + const bool next_lower = i + 1 < words.size() && lower_.count(unicode(words[i + 1]).char32At(0)); + const bool next_number = i + 1 < words.size() && words[i + 1][0] >= '0' && words[i + 1][0] <= '9'; + if (!((prefix.find('.') != std::string::npos && alpha) || (prefixes_.count(prefix) && !numeric_.count(prefix)) || next_lower || (numeric_.count(prefix) && next_number))) + word = prefix + " ."; + } + text = join(split(join(words))); + apply("TRAILING_DOT_APOSTROPHE"); + while (text.find("DOTDOTMULTI") != std::string::npos) replace_literal(text, "DOTDOTMULTI", "DOTMULTI."); + replace_literal(text, "DOTMULTI", "."); + for (const auto& rule : escape_) text = rule.apply(text); + return split(text); + } + std::vector bpe(const std::string& value) const { + const auto text = unicode(value); + std::vector pieces; + for (int32_t i = 0; i < text.length();) { + const auto count = U16_LENGTH(text.char32At(i)); pieces.push_back(utf8(text.tempSubString(i, count))); i += count; + } + if (pieces.empty()) return pieces; + pieces.back() += ""; + while (pieces.size() > 1) { + int rank = std::numeric_limits::max(); + std::string first, second; + for (std::size_t i = 1; i < pieces.size(); ++i) { + const auto found = ranks_.find(pieces[i - 1] + '\x1f' + pieces[i]); + if (found != ranks_.end() && found->second < rank) { rank = found->second; first = pieces[i - 1]; second = pieces[i]; } + } + if (rank == std::numeric_limits::max()) break; + std::vector merged; + for (std::size_t i = 0; i < pieces.size(); ++i) { + if (i + 1 < pieces.size() && pieces[i] == first && pieces[i + 1] == second) { merged.push_back(first + second); ++i; } + else merged.push_back(pieces[i]); + } + pieces = std::move(merged); + } + return pieces; + } + bool add_special_; + std::unordered_map vocab_, ranks_; + std::vector decoded_; + std::unordered_map rules_; + std::vector apostrophes_, escape_, unescape_; + std::unordered_set alpha_, lower_, detok_alpha_; + std::unordered_set prefixes_, numeric_; + std::vector> cjk_; + Rule currency_, punct_, quote_; +}; +} // namespace + +std::unique_ptr CreateBpeTokenizer(const char* data, std::size_t size, bool add_special) { + return std::make_unique(Json::parse(data, data + size), add_special); +} +} // namespace trtmc::biogpt diff --git a/families/biogpt/runtime/pipeline.cpp b/families/biogpt/runtime/pipeline.cpp new file mode 100644 index 0000000000..8cca465fb7 --- /dev/null +++ b/families/biogpt/runtime/pipeline.cpp @@ -0,0 +1,104 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + */ + +#include "families/biogpt/runtime/pipeline.h" + +#include +#include +#include + +namespace trtmc::biogpt { +namespace { + +Tensor tensor(void* data, std::vector shape, DType dtype = DType::kFloat32) { + Tensor value; + value.data = data; + value.shape = std::move(shape); + value.dtype = dtype; + return value; +} + +std::vector copy_output(const TensorMap& outputs, const std::string& name, + const std::vector& shape) { + const auto found = outputs.find(name); + if (found == outputs.end() || found->second.dtype != DType::kFloat32 || + found->second.shape != shape || !found->second.data) + throw std::runtime_error("biogpt invalid engine output: " + name); + const auto* start = static_cast(found->second.data); + std::vector result(start, start + found->second.numel()); + if (!std::all_of(result.begin(), result.end(), [](float value) { return std::isfinite(value); })) + throw std::runtime_error("biogpt nonfinite engine output: " + name); + return result; +} + +} // namespace + +Pipeline::Pipeline(std::unique_ptr decoder, std::unique_ptr tokenizer, + Config config) + : decoder_(std::move(decoder)), tokenizer_(std::move(tokenizer)), config_(config) { + if (!decoder_ || !decoder_->ok() || !tokenizer_ || config_.vocab_size <= 0 || + config_.num_layers <= 0 || config_.kv_width <= 0 || config_.max_sequence_length <= 0 || + config_.bos_token_id < 0 || config_.bos_token_id >= config_.vocab_size || + config_.eos_token_id < 0 || config_.eos_token_id >= config_.vocab_size) + throw std::invalid_argument("biogpt invalid decoder or cache geometry"); +} + +TextResult Pipeline::generate(const std::string& prompt, const TextGenerationConfig& request) { + if (request.top_k != 1 || request.repetition_penalty != 1.0F || request.use_chat_template || + !request.system_prompt.empty() || !request.lora_adapter_id.empty() || + request.source_language_token_id >= 0 || request.forced_bos_token_id >= 0 || + (request.text_generation_mode != "auto" && request.text_generation_mode != "raw")) + throw std::invalid_argument("biogpt supports raw greedy generation"); + const auto limit = request.max_new_tokens > 0 ? request.max_new_tokens : default_max_new_tokens(); + auto ids = tokenizer_->encode(prompt); + if (ids.empty()) + ids.push_back(config_.bos_token_id); + const auto capacity = config_.max_sequence_length; + if (limit > capacity || ids.size() > static_cast(capacity - limit)) + throw std::invalid_argument("biogpt request exceeds the bundle cache capacity"); + if (std::any_of(ids.begin(), ids.end(), [this](auto id) { return id < 0 || id >= config_.vocab_size; })) + throw std::invalid_argument("biogpt tokenizer emitted invalid token IDs"); + const auto eos = request.eos_token_id >= 0 ? request.eos_token_id : config_.eos_token_id; + if (eos >= config_.vocab_size) + throw std::invalid_argument("biogpt invalid EOS override"); + const auto width = config_.kv_width; + const auto count = static_cast(capacity) * width; + std::vector> keys(config_.num_layers, std::vector(count)); + std::vector> values(config_.num_layers, std::vector(count)); + std::int32_t position = 0; + auto step = [&](std::int32_t token) { + TensorMap inputs{ + {"input_ids", tensor(&token, {1}, DType::kInt32)}, + {"position", tensor(&position, {1}, DType::kInt32)}, + }; + for (std::int32_t layer = 0; layer < config_.num_layers; ++layer) { + inputs["past_k_" + std::to_string(layer)] = tensor(keys[layer].data(), {capacity, width}); + inputs["past_v_" + std::to_string(layer)] = tensor(values[layer].data(), {capacity, width}); + } + const auto outputs = decoder_->forward(inputs); + for (std::int32_t layer = 0; layer < config_.num_layers; ++layer) { + keys[layer] = copy_output(outputs, "present_k_" + std::to_string(layer), {capacity, width}); + values[layer] = copy_output(outputs, "present_v_" + std::to_string(layer), {capacity, width}); + } + ++position; + return copy_output(outputs, "logits", {1, config_.vocab_size}); + }; + std::vector logits; + for (auto id : ids) + logits = step(id); + TextResult result; + for (std::int32_t index = 0; index < limit; ++index) { + const auto next = static_cast(std::max_element(logits.begin(), logits.end()) - logits.begin()); + result.token_ids.push_back(next); + if (next == eos) + break; + if (index + 1 < limit) + logits = step(next); + } + result.text = tokenizer_->decode(result.token_ids); + return result; +} + +} // namespace trtmc::biogpt diff --git a/families/biogpt/runtime/pipeline.h b/families/biogpt/runtime/pipeline.h new file mode 100644 index 0000000000..1366751046 --- /dev/null +++ b/families/biogpt/runtime/pipeline.h @@ -0,0 +1,35 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + */ + +#pragma once + +#include "families/biogpt/runtime/tokenizer.h" +#include "trtmc/runtime/trt_module.h" +#include "trtmc/task.h" + +namespace trtmc::biogpt { + +struct Config { + std::int32_t vocab_size{0}; + std::int32_t num_layers{0}; + std::int32_t kv_width{0}; + std::int32_t max_sequence_length{0}; + std::int32_t bos_token_id{1}; + std::int32_t eos_token_id{2}; +}; + +class Pipeline final : public ITextGeneration { + public: + Pipeline(std::unique_ptr decoder, std::unique_ptr tokenizer, Config config); + TextResult generate(const std::string& prompt, const TextGenerationConfig& config) override; + std::int32_t default_max_new_tokens() const override { return 16; } + + private: + std::unique_ptr decoder_; + std::unique_ptr tokenizer_; + Config config_; +}; + +} // namespace trtmc::biogpt diff --git a/families/biogpt/runtime/plugin.cpp b/families/biogpt/runtime/plugin.cpp new file mode 100644 index 0000000000..9a893d9a6f --- /dev/null +++ b/families/biogpt/runtime/plugin.cpp @@ -0,0 +1,38 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + */ + +#include "families/biogpt/runtime/pipeline.h" +#include "trtmc/runtime/family_factory.h" +#include "trtmc/runtime/trt_backend.h" + +#include +#include + +extern "C" trtmc::ITask* trtmc_create_family(const trtmc::FamilyContext& context) { + namespace biogpt = trtmc::biogpt; + if (context.kv_cache_size_bytes != 0) + throw std::invalid_argument("biogpt does not support --kv-cache-size"); + auto section = [&](const char* name) { + const auto* found = context.reader.find_section(name); + if (!found || found->length == 0) + throw std::runtime_error(std::string("biogpt missing section: ") + name); + return context.reader.read_section(name); + }; + const auto data = section("runtime.json"); + const auto json = nlohmann::json::parse(data.begin(), data.end()); + if (json.at("schema_version").get() != 1) + throw std::invalid_argument("biogpt unsupported runtime schema"); + biogpt::Config config; + config.vocab_size = json.at("vocab_size"); + config.num_layers = json.at("num_layers"); + config.kv_width = json.at("kv_width"); + config.max_sequence_length = json.at("max_sequence_length"); + config.bos_token_id = json.at("bos_token_id"); + config.eos_token_id = json.at("eos_token_id"); + const auto plan = section("decoder.plan"); + const auto tokenizer = section("tokenizer.json"); + return new biogpt::Pipeline(context.backend.create_module(plan.data(), plan.size(), {}), + biogpt::CreateBpeTokenizer(tokenizer.data(), tokenizer.size(), true), config); +} diff --git a/families/biogpt/runtime/tokenizer.h b/families/biogpt/runtime/tokenizer.h new file mode 100644 index 0000000000..cb288eb9cf --- /dev/null +++ b/families/biogpt/runtime/tokenizer.h @@ -0,0 +1,29 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + */ + +#pragma once + +#include +#include +#include +#include +#include + +namespace trtmc::biogpt { + +class ITokenizer { + public: + virtual ~ITokenizer() = default; + virtual std::vector encode(const std::string& text) const = 0; + virtual std::string decode(const std::vector& ids) const = 0; + virtual std::int32_t id_for_token(std::string_view token) const = 0; + virtual std::string token_for_id(std::int32_t id) const = 0; +}; + +std::unique_ptr CreateBpeTokenizer(const char* tokenizer_json_data, + std::size_t tokenizer_json_size, + bool add_special_tokens = false); + +} // namespace trtmc diff --git a/families/biogpt/support.py b/families/biogpt/support.py new file mode 100644 index 0000000000..792ee7e80d --- /dev/null +++ b/families/biogpt/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=("biogpt",), + tasks=("text_generation",), + default_task="text_generation", + default_precision="fp32", +) diff --git a/families/biogpt/tests/__init__.py b/families/biogpt/tests/__init__.py new file mode 100644 index 0000000000..52a7a9daf0 --- /dev/null +++ b/families/biogpt/tests/__init__.py @@ -0,0 +1,2 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 diff --git a/families/biogpt/tests/cpp/e2e_consumer.cpp b/families/biogpt/tests/cpp/e2e_consumer.cpp new file mode 100644 index 0000000000..cddcca6357 --- /dev/null +++ b/families/biogpt/tests/cpp/e2e_consumer.cpp @@ -0,0 +1,60 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + */ + +#include "families/biogpt/runtime/tokenizer.h" +#include "trtmc/bundle.h" +#include "trtmc/runtime/family_loader.h" + +#include +#include +#include +#include + +int main(int argc, char** argv) { + try { + if (argc != 4) + throw std::invalid_argument("usage: biogpt_e2e BUNDLE RUNTIME_ROOT REQUESTS_JSON"); + std::ifstream input(argv[3]); + const auto requests = nlohmann::json::parse(input); + auto model = trtmc::load_task(argv[1], argv[2]); + auto* task = dynamic_cast(model.get()); + if (!task || std::string(task->task()) != "text_generation") + throw std::runtime_error("BioGPT must expose the abstract text generation Task"); + const trtmc::BundleReader bundle(argv[1]); + const auto data = bundle.read_section("tokenizer.json"); + auto tokenizer = trtmc::biogpt::CreateBpeTokenizer(data.data(), data.size(), true); + nlohmann::json results = nlohmann::json::array(); + for (const auto& request : requests) { + trtmc::TextGenerationConfig config; + config.max_new_tokens = request.at("max_new_tokens"); + const auto prompt = request.at("prompt").get(); + const auto result = task->generate(prompt, config); + results.push_back({{"token_ids", result.token_ids}, {"text", result.text}, + {"source_ids", tokenizer->encode(prompt)}}); + } + // An invalid request must leave this same loaded Task usable. + trtmc::TextGenerationConfig overflow; + overflow.max_new_tokens = 1000000; + bool rejected = false; + try { + task->generate("overflow", overflow); + } catch (const std::invalid_argument&) { + rejected = true; + } + if (!rejected) + throw std::runtime_error("BioGPT accepted cache overflow"); + const auto& first = requests.at(0); + trtmc::TextGenerationConfig config; + config.max_new_tokens = first.at("max_new_tokens"); + const auto recovered = task->generate(first.at("prompt"), config); + if (recovered.token_ids != results.at(0).at("token_ids").get>()) + throw std::runtime_error("BioGPT request state leaked after rejection"); + std::cout << results.dump() << '\n'; + return 0; + } catch (const std::exception& error) { + std::cerr << error.what() << '\n'; + return 1; + } +} diff --git a/families/biogpt/tests/cpp/tokenizer_consumer.cpp b/families/biogpt/tests/cpp/tokenizer_consumer.cpp new file mode 100644 index 0000000000..d9ff3e8acd --- /dev/null +++ b/families/biogpt/tests/cpp/tokenizer_consumer.cpp @@ -0,0 +1,32 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + */ +#include "families/biogpt/runtime/tokenizer.h" + +#include +#include +#include +#include +#include + +int main(int argc, char** argv) { + try { + if (argc != 3) throw std::invalid_argument("usage: biogpt_tokenizer TOKENIZER_JSON TEXTS_JSON"); + std::ifstream input(argv[1], std::ios::binary); + const std::string data((std::istreambuf_iterator(input)), std::istreambuf_iterator()); + auto tokenizer = trtmc::biogpt::CreateBpeTokenizer(data.data(), data.size(), true); + std::ifstream texts(argv[2]); + const auto requests = nlohmann::json::parse(texts); + nlohmann::json output = nlohmann::json::array(); + for (const auto& text : requests) { + const auto ids = tokenizer->encode(text.get()); + output.push_back({{"ids", ids}, {"text", tokenizer->decode(ids)}}); + } + std::cout << output.dump() << '\n'; + return 0; + } catch (const std::exception& error) { + std::cerr << error.what() << '\n'; + return 1; + } +} diff --git a/families/biogpt/tests/decoder_check.py b/families/biogpt/tests/decoder_check.py new file mode 100644 index 0000000000..14c1ce9aa4 --- /dev/null +++ b/families/biogpt/tests/decoder_check.py @@ -0,0 +1,71 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +"""Compare learned positions, every cache tensor, and all decoder logits.""" + + +def check_cached_decoder(): + import torch + import tensorrt as trt + from transformers import BioGptConfig, BioGptForCausalLM + from families.biogpt.model import compile_engine + + torch.backends.cuda.matmul.allow_tf32 = False + torch.backends.cudnn.allow_tf32 = False + torch.manual_seed(2047) + config = BioGptConfig( + hidden_size=32, + intermediate_size=48, + num_hidden_layers=2, + num_attention_heads=4, + vocab_size=83, + max_position_embeddings=32, + layer_norm_eps=1e-12, + attn_implementation="eager", + ) + model = BioGptForCausalLM(config).eval() + assert model.biogpt.layers[0].self_attn_layer_norm.eps == 1e-5 + weights = {name: value.detach().numpy() for name, value in model.state_dict().items()} + logger = trt.Logger(trt.Logger.WARNING) + runtime = trt.Runtime(logger) + engine = runtime.deserialize_cuda_engine(compile_engine(config.to_dict(), weights, 16)) + assert engine is not None + context = engine.create_execution_context() + model.cuda() + with torch.inference_mode(): + for sequence in ([2, 7, 11, 19, 31, 5], [2, 37, 41, 43, 47, 53], [2, 7, 11, 19, 31, 5]): + cache = { + f"past_{kind}_{layer}": torch.zeros(16, 32, device="cuda") + for layer in range(2) + for kind in ("k", "v") + } + for position, token in enumerate(sequence): + ids = torch.tensor([sequence[: position + 1]], device="cuda") + expected = model(ids, attention_mask=torch.ones_like(ids), use_cache=True) + tensors = { + "input_ids": torch.tensor([token], dtype=torch.int32, device="cuda"), + "position": torch.tensor([position], dtype=torch.int32, device="cuda"), + **cache, + } + for index in range(engine.num_io_tensors): + name = engine.get_tensor_name(index) + if engine.get_tensor_mode(name) == trt.TensorIOMode.OUTPUT: + tensors[name] = torch.empty( + tuple(engine.get_tensor_shape(name)), device="cuda" + ) + for name, value in tensors.items(): + assert context.set_tensor_address(name, value.data_ptr()) + assert context.execute_async_v3(torch.cuda.current_stream().cuda_stream) + torch.cuda.synchronize() + torch.testing.assert_close( + tensors["logits"], expected.logits[:, -1], rtol=5e-5, atol=5e-5 + ) + for layer in range(2): + upstream = expected.past_key_values.layers[layer] + for kind, values in (("k", upstream.keys), ("v", upstream.values)): + observed = tensors[f"present_{kind}_{layer}"] + reference = values[0].transpose(0, 1).reshape(position + 1, 32) + torch.testing.assert_close( + observed[: position + 1], reference, rtol=5e-5, atol=5e-5 + ) + assert torch.count_nonzero(observed[position + 1 :]) == 0 + cache[f"past_{kind}_{layer}"] = observed diff --git a/families/biogpt/tests/manifests/biogpt.json b/families/biogpt/tests/manifests/biogpt.json new file mode 100644 index 0000000000..13fa364849 --- /dev/null +++ b/families/biogpt/tests/manifests/biogpt.json @@ -0,0 +1,24 @@ +{ + "name": "biogpt", + "hf_id": "microsoft/biogpt", + "hf_revision": "eb0d815e95434dc9e3b78f464e52b899bee7d923", + "family": "biogpt", + "task": "text_generation", + "precision": "fp32", + "tensor_parallel_size": 1, + "max_sequence_length": 128, + "bundle": "biogpt.bundle", + "testcases": [ + { + "name": "biogpt-fp32", + "premerge": true, + "reference_precision": "fp32", + "max_new_tokens": 16, + "prompts": [ + "The patient was diagnosed with", + "Aspirin inhibits", + "Tumor necrosis factor alpha is" + ] + } + ] +} diff --git a/families/biogpt/tests/requirements.txt b/families/biogpt/tests/requirements.txt new file mode 100644 index 0000000000..5c1469fa17 --- /dev/null +++ b/families/biogpt/tests/requirements.txt @@ -0,0 +1,2 @@ +transformers==5.3.0 +sacremoses==0.1.1 diff --git a/families/biogpt/tests/test_e2e.py b/families/biogpt/tests/test_e2e.py new file mode 100644 index 0000000000..6ad1009e2c --- /dev/null +++ b/families/biogpt/tests/test_e2e.py @@ -0,0 +1,223 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Pinned BioGPT checkpoint -> TensorRT bundle -> native Task -> exact greedy tokens.""" + +import json +import os +from pathlib import Path +import subprocess + +import pytest + +from tensorrt_model_connect import BuildRequest, build +from tensorrt_model_connect.model_support import load_model_metadata, resolve_family +from tools.e2e_evidence import evidence_stage, record_evidence + +ROOT = Path(__file__).parent +MANIFEST = json.loads((ROOT / "manifests/biogpt.json").read_text()) + + +def pytest_generate_tests(metafunc): + if "case" not in metafunc.fixturenames: + return + model_filters = set() + for value in metafunc.config.getoption("--e2e-model"): + model_filters.update(value.split(",")) + models_file = metafunc.config.getoption("--e2e-models-file") + if models_file: + model_filters.update(Path(models_file).read_text().splitlines()) + case_filters = set() + for value in metafunc.config.getoption("--e2e-testcase"): + case_filters.update(value.split(",")) + enabled = bool(model_filters or case_filters) + parameters = [] + for case in MANIFEST["testcases"]: + if model_filters and not model_filters.intersection( + {"biogpt", MANIFEST["name"], case["name"]} + ): + continue + if case_filters and case["name"] not in case_filters: + continue + marks = [] if enabled else [pytest.mark.skip(reason="select BioGPT E2E explicitly")] + parameters.append(pytest.param(case, id=case["name"], marks=marks)) + metafunc.parametrize("case", parameters) + + +def _checkpoint(): + path = os.environ.get("TRTMC_BIOGPT_MODEL_DIR") + if path: + return Path(path) + from huggingface_hub import snapshot_download + + return Path( + snapshot_download( + repo_id=MANIFEST["hf_id"], revision=MANIFEST["hf_revision"], local_files_only=True + ) + ) + + +def _reference(model_dir, prompts, max_new_tokens): + import torch + from transformers import AutoTokenizer, BioGptForCausalLM + + torch.backends.cuda.matmul.allow_tf32 = False + torch.backends.cudnn.allow_tf32 = False + tokenizer = AutoTokenizer.from_pretrained(model_dir, trust_remote_code=False) + model = ( + BioGptForCausalLM.from_pretrained( + model_dir, dtype=torch.float32, trust_remote_code=False, attn_implementation="eager" + ) + .cuda() + .eval() + ) + stop_ids = {model.config.eos_token_id} + results = [] + for prompt in prompts: + sequence = tokenizer.encode(prompt) or [model.config.bos_token_id] + source = list(sequence) + generated = [] + for _ in range(max_new_tokens): + ids = torch.tensor([sequence], device="cuda") + with torch.inference_mode(): + logits = model( + input_ids=ids, + attention_mask=torch.ones_like(ids), + use_cache=False, + logits_to_keep=1, + ).logits[0, -1] + token = int(logits.argmax()) + generated.append(token) + if token in stop_ids: + break + sequence.append(token) + results.append( + { + "source_ids": source, + "token_ids": generated, + "text": tokenizer.decode( + generated, skip_special_tokens=True, clean_up_tokenization_spaces=False + ), + } + ) + del model, logits, ids + torch.cuda.empty_cache() + return results + + +def _check_native_tokenizer(model_dir, runtime, tmp_path): + from transformers import AutoTokenizer + from families.biogpt.model import tokenizer_spec + + texts = [ + "The patient was diagnosed with diabetes.", + "Dr. Smith prescribed 5,300 mg of aspirin.", + "Anti-inflammatory agents inhibit TNF-α.", + "Café e\u0301 中文かな 한국어", + '"The Jones\' house," she said...', + " A\tB\n\nC / 42! 😀", + "No. 12 vs. Nos. 4 and 5.", + "Hello", + "1980's isn't ordinary.", + "", + ] + tokenizer = AutoTokenizer.from_pretrained(model_dir, trust_remote_code=False) + path = tmp_path / "tokenizer-texts.json" + path.write_text(json.dumps(texts, ensure_ascii=False)) + encoded = tmp_path / "initialized-tokenizer.json" + encoded.write_text(json.dumps(tokenizer_spec(model_dir))) + result = subprocess.run( + [str(runtime / "biogpt_tokenizer"), str(encoded), str(path)], + check=True, + text=True, + capture_output=True, + timeout=60, + ) + expected = [ + { + "ids": tokenizer.encode(text), + "text": tokenizer.decode( + tokenizer.encode(text), skip_special_tokens=True, clean_up_tokenization_spaces=False + ), + } + for text in texts + ] + assert json.loads(result.stdout) == expected + + +def test_official_checkpoint_e2e(case, tmp_path): + assert case["reference_precision"] == "fp32" + from families.biogpt.tests.decoder_check import check_cached_decoder + + check_cached_decoder() + model_dir = _checkpoint() + assert resolve_family(load_model_metadata(model_dir))[0] == "biogpt" + runtime = Path(os.environ["TRTMC_RUNTIME_ROOT"]) + _check_native_tokenizer(model_dir, runtime, tmp_path) + binary = Path(os.environ["TRTMC_BINARY"]) + assert (runtime / "libtrtmc_model_biogpt.so").is_file() + assert (runtime / "libtrtmc_backend_trt.so").is_file() + consumer = runtime / "biogpt_e2e" + assert consumer.is_file() + prompts = [*case["prompts"], case["prompts"][0]] + record_evidence("inputs", {"manifest": MANIFEST, "case": case}) + record_evidence( + "checkpoint", + { + "model_dir": str(model_dir), + "hf_id": MANIFEST["hf_id"], + "hf_revision": MANIFEST["hf_revision"], + }, + ) + with evidence_stage("reference"): + expected = _reference(model_dir, prompts, case["max_new_tokens"]) + assert expected[0]["token_ids"] != expected[1]["token_ids"], ( + "reference must respond to its source" + ) + record_evidence("reference", expected) + bundle = tmp_path / MANIFEST["bundle"] + with evidence_stage("build"): + build( + BuildRequest( + model_dir, + bundle, + MANIFEST["family"], + MANIFEST["task"], + MANIFEST["precision"], + max_sequence_length=MANIFEST["max_sequence_length"], + tensor_parallel_size=MANIFEST["tensor_parallel_size"], + ) + ) + requests = tmp_path / "requests.json" + requests.write_text( + json.dumps([{"prompt": text, "max_new_tokens": case["max_new_tokens"]} for text in prompts]) + ) + with evidence_stage("native"): + command = [str(consumer), str(bundle), str(runtime), str(requests)] + result = subprocess.run(command, check=True, text=True, capture_output=True, timeout=600) + record_evidence("commands", {"argv": command}) + actual = json.loads(result.stdout.strip().splitlines()[-1]) + record_evidence("native", actual) + with evidence_stage("compare"): + assert len(actual) == len(expected) + for native, reference in zip(actual, expected): + assert reference["token_ids"] and reference["text"].strip() + assert native == reference + assert actual[0] == actual[-1] + # Also exercise application dispatch through the ordinary native CLI. + command = [ + str(binary), + "run", + str(bundle), + "--runtime-root", + str(runtime), + "--prompt", + prompts[0], + "--max-new-tokens", + str(case["max_new_tokens"]), + ] + result = subprocess.run(command, check=True, text=True, capture_output=True, timeout=180) + record_evidence("commands", {"argv": command}) + assert ( + json.loads(result.stdout.strip().splitlines()[-1])["token_ids"] == expected[0]["token_ids"] + ) diff --git a/families/biogpt/tests/test_model.py b/families/biogpt/tests/test_model.py new file mode 100644 index 0000000000..a33ad7d815 --- /dev/null +++ b/families/biogpt/tests/test_model.py @@ -0,0 +1,43 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +import pytest + +from families.biogpt.model import load_weights, required_shapes, validate_config + + +def test_checkpoint_geometry_and_shape_validation(tmp_path): + import torch + from transformers import BioGptConfig, BioGptForCausalLM + + config = BioGptConfig( + hidden_size=32, + intermediate_size=48, + num_hidden_layers=2, + num_attention_heads=4, + vocab_size=83, + max_position_embeddings=32, + ) + state = BioGptForCausalLM(config).state_dict() + assert tuple(state["biogpt.embed_positions.weight"].shape) == (34, 32) + assert set(required_shapes(config.to_dict())) == set(state) + state["biogpt.layers.0.self_attn.q_proj.bias"] = torch.zeros(31) + torch.save(state, tmp_path / "pytorch_model.bin") + with pytest.raises(ValueError, match="q_proj.bias"): + load_weights(tmp_path, config.to_dict()) + + +def test_decoder_geometry_rejects_incompatible_heads_and_activation(): + from transformers import BioGptConfig + + config = BioGptConfig( + hidden_size=32, + intermediate_size=48, + num_hidden_layers=2, + num_attention_heads=3, + vocab_size=83, + ).to_dict() + with pytest.raises(ValueError, match="attention heads"): + validate_config(config) + config.update(num_attention_heads=4, hidden_act="relu") + with pytest.raises(ValueError, match="GELU"): + validate_config(config) diff --git a/families/biogpt/tests/test_support.py b/families/biogpt/tests/test_support.py new file mode 100644 index 0000000000..2a5e94f97d --- /dev/null +++ b/families/biogpt/tests/test_support.py @@ -0,0 +1,14 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +from tensorrt_model_connect.model_support import ModelMetadata, resolve_family +from families.biogpt.support import describe + + +def test_biogpt_owner_and_task(): + metadata = ModelMetadata( + config={"model_type": "biogpt", "architectures": ["BioGptForCausalLM"]}, model_index={} + ) + family, support = resolve_family(metadata) + assert family == "biogpt" + assert support.default_task == "text_generation" + assert describe(ModelMetadata(config={"model_type": "gpt2"}, model_index={})) is None From c3a40b14583908fdd2e596758d838121ff4becee Mon Sep 17 00:00:00 2001 From: Will Guo Date: Wed, 2 Dec 2026 20:22:53 -0800 Subject: [PATCH 2/5] fix(biogpt): leave cache space for default generation Signed-off-by: Will Guo --- families/biogpt/README.md | 13 ++++++++----- families/biogpt/__init__.py | 3 +++ families/biogpt/model.py | 3 ++- families/biogpt/runtime/pipeline.cpp | 1 + families/biogpt/runtime/pipeline.h | 3 +++ families/biogpt/tests/cpp/e2e_consumer.cpp | 5 +++++ families/biogpt/tests/manifests/biogpt.json | 2 +- families/biogpt/tests/test_e2e.py | 10 +++++----- 8 files changed, 28 insertions(+), 12 deletions(-) diff --git a/families/biogpt/README.md b/families/biogpt/README.md index ac5bc98623..197a7b9e7b 100644 --- a/families/biogpt/README.md +++ b/families/biogpt/README.md @@ -3,7 +3,8 @@ This family builds `microsoft/biogpt` revision `eb0d815e95434dc9e3b78f464e52b899bee7d923` for native `ITextGeneration`. The selected profile uses FP32, batch size one, tensor parallel size one, -a 128-position cache, and raw greedy generation. +a 256-position default cache, and raw greedy generation. This leaves room +for an input prompt with the public request default of 128 new tokens. The decoder preserves scaled token embeddings, learned positions with the published two-position offset, pre-normalized attention and feed-forward @@ -17,12 +18,14 @@ Unicode word BPE, special tokens, and Moses detokenization. The builder stores the upstream Sacremoses character tables, expressions, and abbreviation lists as bundle data. The runtime requires ICU and has no Python dependency. -Install `requirements.txt` and `tests/requirements.txt`. Build -`trtmc_model_biogpt`, `biogpt_e2e`, and `biogpt_tokenizer`, and set -`TRTMC_RUNTIME_ROOT` to the build directory. Set `TRTMC_BIOGPT_MODEL_DIR` to the -pinned local checkpoint. +Install the family `requirements.txt` and `tests/requirements.txt`. Configure +the native build with `TRTMC_BUILD_TESTS=ON` and use the pinned checkpoint from +the local Hub cache or set `TRTMC_BIOGPT_MODEL_DIR` to its directory. ```bash +cmake --build build --target trtmc trtmc_backend_trt trtmc_model_biogpt biogpt_e2e biogpt_tokenizer +export TRTMC_RUNTIME_ROOT="$PWD/build" +export TRTMC_BINARY="$TRTMC_RUNTIME_ROOT/trtmc" PYTHONPATH=core/builder:apps/benchmark:. python3 -m tools.model_ci validate PYTHONPATH=core/builder:apps/benchmark:. python3 -m pytest \ families/biogpt/tests --e2e-model biogpt -q diff --git a/families/biogpt/__init__.py b/families/biogpt/__init__.py index 4d907ba2a7..567bf25038 100644 --- a/families/biogpt/__init__.py +++ b/families/biogpt/__init__.py @@ -1 +1,4 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + """BioGPT family ownership boundary.""" diff --git a/families/biogpt/model.py b/families/biogpt/model.py index ef8df5e071..48082c4fd0 100644 --- a/families/biogpt/model.py +++ b/families/biogpt/model.py @@ -263,7 +263,8 @@ def build(request, writer): raise NotImplementedError("biogpt does not support quantization") root = Path(request.model_dir) config = validate_config(json.loads((root / "config.json").read_text())) - capacity = request.max_sequence_length or 128 + # Leave room for both prompt tokens and the public 128-token generation default. + capacity = request.max_sequence_length if request.max_sequence_length is not None else 256 if not 1 <= capacity <= config["max_position_embeddings"]: raise ValueError("biogpt cache capacity exceeds the checkpoint positions") weights = load_weights(root, config) diff --git a/families/biogpt/runtime/pipeline.cpp b/families/biogpt/runtime/pipeline.cpp index 8cca465fb7..9ebace505d 100644 --- a/families/biogpt/runtime/pipeline.cpp +++ b/families/biogpt/runtime/pipeline.cpp @@ -46,6 +46,7 @@ Pipeline::Pipeline(std::unique_ptr decoder, std::unique_ptr= 0 || request.forced_bos_token_id >= 0 || diff --git a/families/biogpt/runtime/pipeline.h b/families/biogpt/runtime/pipeline.h index 1366751046..b21497c9ba 100644 --- a/families/biogpt/runtime/pipeline.h +++ b/families/biogpt/runtime/pipeline.h @@ -5,6 +5,8 @@ #pragma once +#include + #include "families/biogpt/runtime/tokenizer.h" #include "trtmc/runtime/trt_module.h" #include "trtmc/task.h" @@ -27,6 +29,7 @@ class Pipeline final : public ITextGeneration { std::int32_t default_max_new_tokens() const override { return 16; } private: + std::mutex execution_; std::unique_ptr decoder_; std::unique_ptr tokenizer_; Config config_; diff --git a/families/biogpt/tests/cpp/e2e_consumer.cpp b/families/biogpt/tests/cpp/e2e_consumer.cpp index cddcca6357..e5a0d01c52 100644 --- a/families/biogpt/tests/cpp/e2e_consumer.cpp +++ b/families/biogpt/tests/cpp/e2e_consumer.cpp @@ -34,6 +34,11 @@ int main(int argc, char** argv) { results.push_back({{"token_ids", result.token_ids}, {"text", result.text}, {"source_ids", tokenizer->encode(prompt)}}); } + const auto& prompt = requests.at(0).at("prompt").get_ref(); + const auto default_result = task->generate(prompt); + if (default_result.token_ids.empty() || default_result.token_ids.size() > 128) + throw std::runtime_error("BioGPT default generation produced invalid output"); + // An invalid request must leave this same loaded Task usable. trtmc::TextGenerationConfig overflow; overflow.max_new_tokens = 1000000; diff --git a/families/biogpt/tests/manifests/biogpt.json b/families/biogpt/tests/manifests/biogpt.json index 13fa364849..a48fa670e0 100644 --- a/families/biogpt/tests/manifests/biogpt.json +++ b/families/biogpt/tests/manifests/biogpt.json @@ -6,7 +6,7 @@ "task": "text_generation", "precision": "fp32", "tensor_parallel_size": 1, - "max_sequence_length": 128, + "max_sequence_length": 256, "bundle": "biogpt.bundle", "testcases": [ { diff --git a/families/biogpt/tests/test_e2e.py b/families/biogpt/tests/test_e2e.py index 6ad1009e2c..75b1e8c7b6 100644 --- a/families/biogpt/tests/test_e2e.py +++ b/families/biogpt/tests/test_e2e.py @@ -19,7 +19,7 @@ def pytest_generate_tests(metafunc): - if "case" not in metafunc.fixturenames: + if "case_name" not in metafunc.fixturenames: return model_filters = set() for value in metafunc.config.getoption("--e2e-model"): @@ -40,8 +40,8 @@ def pytest_generate_tests(metafunc): if case_filters and case["name"] not in case_filters: continue marks = [] if enabled else [pytest.mark.skip(reason="select BioGPT E2E explicitly")] - parameters.append(pytest.param(case, id=case["name"], marks=marks)) - metafunc.parametrize("case", parameters) + parameters.append(pytest.param(case["name"], marks=marks)) + metafunc.parametrize("case_name", parameters) def _checkpoint(): @@ -145,7 +145,8 @@ def _check_native_tokenizer(model_dir, runtime, tmp_path): assert json.loads(result.stdout) == expected -def test_official_checkpoint_e2e(case, tmp_path): +def test_official_checkpoint_e2e(case_name, tmp_path): + case = next(case for case in MANIFEST["testcases"] if case["name"] == case_name) assert case["reference_precision"] == "fp32" from families.biogpt.tests.decoder_check import check_cached_decoder @@ -184,7 +185,6 @@ def test_official_checkpoint_e2e(case, tmp_path): MANIFEST["family"], MANIFEST["task"], MANIFEST["precision"], - max_sequence_length=MANIFEST["max_sequence_length"], tensor_parallel_size=MANIFEST["tensor_parallel_size"], ) ) From f0d5e29c187268d4c891f9f2f386f173a91db35d Mon Sep 17 00:00:00 2001 From: Will Guo Date: Wed, 2 Dec 2026 20:37:22 -0800 Subject: [PATCH 3/5] test(biogpt): exercise the builder default without a profile override Signed-off-by: Will Guo --- families/biogpt/tests/manifests/biogpt.json | 1 - 1 file changed, 1 deletion(-) diff --git a/families/biogpt/tests/manifests/biogpt.json b/families/biogpt/tests/manifests/biogpt.json index a48fa670e0..d7f2d4e795 100644 --- a/families/biogpt/tests/manifests/biogpt.json +++ b/families/biogpt/tests/manifests/biogpt.json @@ -6,7 +6,6 @@ "task": "text_generation", "precision": "fp32", "tensor_parallel_size": 1, - "max_sequence_length": 256, "bundle": "biogpt.bundle", "testcases": [ { From 485b20fcc849e9ee6a1697ad69d919b318af176e Mon Sep 17 00:00:00 2001 From: Will Guo Date: Wed, 2 Dec 2026 20:59:28 -0800 Subject: [PATCH 4/5] fix(biogpt): keep decoder state on GPU and match Moses boundaries Signed-off-by: Will Guo --- families/biogpt/README.md | 8 +- families/biogpt/model.py | 4 +- families/biogpt/runtime/bpe_tokenizer.cpp | 141 ++++++++++++++---- families/biogpt/runtime/pipeline.cpp | 139 ++++++++++------- families/biogpt/runtime/pipeline.h | 1 + families/biogpt/tests/cpp/e2e_consumer.cpp | 3 +- .../biogpt/tests/cpp/tokenizer_consumer.cpp | 3 +- families/biogpt/tests/test_e2e.py | 32 +++- families/biogpt/tests/test_model.py | 31 ++++ 9 files changed, 275 insertions(+), 87 deletions(-) diff --git a/families/biogpt/README.md b/families/biogpt/README.md index 197a7b9e7b..0a16448cd8 100644 --- a/families/biogpt/README.md +++ b/families/biogpt/README.md @@ -18,9 +18,11 @@ Unicode word BPE, special tokens, and Moses detokenization. The builder stores the upstream Sacremoses character tables, expressions, and abbreviation lists as bundle data. The runtime requires ICU and has no Python dependency. -Install the family `requirements.txt` and `tests/requirements.txt`. Configure -the native build with `TRTMC_BUILD_TESTS=ON` and use the pinned checkpoint from -the local Hub cache or set `TRTMC_BIOGPT_MODEL_DIR` to its directory. +Install the family `requirements.txt`, `tests/requirements.txt`, and the ICU +development package with the `uc` and `i18n` components (`libicu-dev` on +Ubuntu). Configure the native build with `TRTMC_BUILD_TESTS=ON` and use the +pinned checkpoint from the local Hub cache or set `TRTMC_BIOGPT_MODEL_DIR` to +its directory. ```bash cmake --build build --target trtmc trtmc_backend_trt trtmc_model_biogpt biogpt_e2e biogpt_tokenizer diff --git a/families/biogpt/model.py b/families/biogpt/model.py index 48082c4fd0..a4a957769d 100644 --- a/families/biogpt/model.py +++ b/families/biogpt/model.py @@ -265,8 +265,8 @@ def build(request, writer): config = validate_config(json.loads((root / "config.json").read_text())) # Leave room for both prompt tokens and the public 128-token generation default. capacity = request.max_sequence_length if request.max_sequence_length is not None else 256 - if not 1 <= capacity <= config["max_position_embeddings"]: - raise ValueError("biogpt cache capacity exceeds the checkpoint positions") + if not 2 <= capacity <= config["max_position_embeddings"]: + raise ValueError("biogpt cache capacity requires 2 to max_position_embeddings positions") weights = load_weights(root, config) plan = compile_engine(config, weights, capacity, request.verbose) writer.set_header(family="biogpt", task=request.task, backend=request.backend) diff --git a/families/biogpt/runtime/bpe_tokenizer.cpp b/families/biogpt/runtime/bpe_tokenizer.cpp index f0a4d76432..17f140eb51 100644 --- a/families/biogpt/runtime/bpe_tokenizer.cpp +++ b/families/biogpt/runtime/bpe_tokenizer.cpp @@ -5,6 +5,7 @@ #include "families/biogpt/runtime/tokenizer.h" #include +#include #include #include #include @@ -80,6 +81,67 @@ void replace_literal(std::string& value, const std::string& from, const std::str } } +constexpr std::string_view kDot = "DOT"; +constexpr std::string_view kDotMulti = "DOTMULTI"; + +std::string replace_multidots(const std::string& text) { + std::string result; + // The first Moses substitution consumes the character immediately after a final dot. + auto consumed = std::string::npos; + for (std::size_t i = 0; i < text.size();) { + // A literal DOTMULTI followed by one dot is also interpreted by Moses. + const auto after_marker = i + kDotMulti.size(); + if (after_marker < text.size() && text[after_marker] == '.' && + (after_marker + 1 == text.size() || text[after_marker + 1] != '.') && + text.compare(i, kDotMulti.size(), kDotMulti) == 0) { + result += "DOTDOTMULTI"; + const auto start = i; + i = after_marker + 1; + if (start != consumed && i < text.size()) { + result += ' '; + consumed = i; + } + continue; + } + if (text[i] != '.' || i + 1 == text.size() || text[i + 1] != '.') { + result += text[i++]; + continue; + } + result += ' '; + const auto start = i++; + do { + result += kDot; + ++i; + } while (i < text.size() && text[i] == '.'); + result += kDotMulti; + if (i < text.size()) { + result += ' '; + if (i - start == 2) + consumed = i; + } + } + return result; +} + +std::string restore_multidots(const std::string& text) { + constexpr std::string_view suffix = "MULTI"; + std::string result; + for (std::size_t i = 0; i < text.size();) { + const auto begin = i; + while (text.compare(i, kDot.size(), kDot) == 0) + i += kDot.size(); + if (i == begin) { + result += text[i++]; + } else if (text.compare(i, suffix.size(), suffix) == 0) { + result.append((i - begin) / kDot.size(), '.'); + i += suffix.size(); + } else { + result.append(text, begin, i - begin); + } + } + return result; +} + class Rule { public: Rule(const std::string& expression, const std::string& replacement) { @@ -129,6 +191,8 @@ class Rule { UErrorCode status = U_ZERO_ERROR; const auto text = unicode(input); std::unique_ptr matcher(pattern_->matcher(text, status)); + if (U_FAILURE(status) || !matcher) + throw std::runtime_error("biogpt Moses replacement failed"); const auto result = matcher->replaceAll(replacement_, status); if (U_FAILURE(status)) throw std::runtime_error("biogpt Moses replacement failed"); @@ -138,6 +202,8 @@ class Rule { UErrorCode status = U_ZERO_ERROR; const auto text = unicode(input); std::unique_ptr matcher(pattern_->matcher(text, status)); + if (U_FAILURE(status) || !matcher) + throw std::runtime_error("biogpt Moses match failed"); const bool result = matcher->find(status); if (U_FAILURE(status)) throw std::runtime_error("biogpt Moses match failed"); @@ -181,33 +247,50 @@ class Tokenizer final : public ITokenizer { prefixes_.insert(prefix.get()); for (const auto& prefix : spec.at("numeric_prefixes")) numeric_.insert(prefix.get()); - cjk_ = spec.at("cjk_ranges").get(); + const auto& ranges = spec.at("cjk_ranges"); + if (!ranges.is_array()) + throw std::invalid_argument("biogpt invalid CJK ranges"); + for (const auto& range : ranges) { + if (!range.is_array() || range.size() != 2 || !range[0].is_number_integer() || + !range[1].is_number_integer()) + throw std::invalid_argument("biogpt CJK range requires two integer endpoints"); + const auto first = range[0].get(); + const auto last = range[1].get(); + if (first >= last || last > 0x10ffff || + (!cjk_.empty() && first < static_cast(cjk_.back()[1]))) + throw std::invalid_argument("biogpt CJK ranges must be ordered Unicode intervals"); + cjk_.push_back({static_cast(first), static_cast(last)}); + } } std::vector encode(const std::string& text) const override { std::vector ids; if (add_special_) ids.push_back(vocab_.at("")); - std::size_t cursor = 0; - while (cursor < text.size()) { - auto at = std::string::npos; - std::string special; - for (const auto* piece : {"", "", "", ""}) { - const auto found = text.find(piece, cursor); - if (found < at) { - at = found; - special = piece; - } - } - const auto end = at == std::string::npos ? text.size() : at; - for (const auto& word : moses(text.substr(cursor, end - cursor))) + auto encode_span = [&](std::size_t start, std::size_t end) { + if (start == end) + return; + for (const auto& word : moses(text.substr(start, end - start))) for (const auto& piece : bpe(word)) ids.push_back(id_for_token(piece)); - if (at == std::string::npos) - break; - ids.push_back(vocab_.at(special)); - cursor = at + special.size(); + }; + std::size_t start = 0; + for (auto pos = text.find('<'); pos != std::string::npos; pos = text.find('<', pos)) { + const std::string_view tail(text.data() + pos, text.size() - pos); + const auto special = std::find_if(kSpecialTokens.begin(), kSpecialTokens.end(), + [&](const std::string_view token) { + return tail.substr(0, token.size()) == token; + }); + if (special == kSpecialTokens.end()) { + ++pos; + continue; + } + encode_span(start, pos); + ids.push_back(vocab_.at(std::string(*special))); + pos += special->size(); + start = pos; } + encode_span(start, text.size()); return ids; } @@ -286,9 +369,15 @@ class Tokenizer final : public ITokenizer { } private: + static constexpr std::array kSpecialTokens{"", "", "", + ""}; + bool is_cjk(UChar32 c) const { - return std::any_of(cjk_.begin(), cjk_.end(), - [c](const auto& range) { return c >= range[0] && c <= range[1]; }); + for (const auto& [start, end] : cjk_) { + if (c < end) + return c > start; + } + return false; } std::vector moses(std::string text) const { auto apply = [&](const char* name) { text = rules_.at(name).apply(text); }; @@ -297,11 +386,7 @@ class Tokenizer final : public ITokenizer { text = join(split(text)); apply("PAD_NOT_ISALNUM"); apply("AGGRESSIVE_HYPHEN_SPLIT"); - text = Rule("\\.([.]+)", " DOTMULTI\\1").apply(text); - while (text.find("DOTMULTI.") != std::string::npos) { - text = Rule("DOTMULTI\\.([^\\.])", "DOTDOTMULTI \\1").apply(text); - replace_literal(text, "DOTMULTI.", "DOTDOTMULTI"); - } + text = replace_multidots(text); apply("COMMA_SEPARATE_1"); apply("COMMA_SEPARATE_2"); apply("COMMA_SEPARATE_3"); @@ -327,9 +412,7 @@ class Tokenizer final : public ITokenizer { } text = join(split(join(words))); apply("TRAILING_DOT_APOSTROPHE"); - while (text.find("DOTDOTMULTI") != std::string::npos) - replace_literal(text, "DOTDOTMULTI", "DOTMULTI."); - replace_literal(text, "DOTMULTI", "."); + text = restore_multidots(text); for (const auto& rule : escape_) text = rule.apply(text); return split(text); @@ -377,7 +460,7 @@ class Tokenizer final : public ITokenizer { std::vector apostrophes_, escape_, unescape_; std::unordered_set alpha_, lower_, detok_alpha_; std::unordered_set prefixes_, numeric_; - std::vector> cjk_; + std::vector> cjk_; Rule currency_, punct_, quote_; }; } // namespace diff --git a/families/biogpt/runtime/pipeline.cpp b/families/biogpt/runtime/pipeline.cpp index 41b8221e02..d1e2ee1555 100644 --- a/families/biogpt/runtime/pipeline.cpp +++ b/families/biogpt/runtime/pipeline.cpp @@ -5,6 +5,8 @@ #include "families/biogpt/runtime/pipeline.h" +#include "trtmc/internal/config.h" + #include #include #include @@ -12,28 +14,26 @@ namespace trtmc::biogpt { namespace { -Tensor tensor(void* data, std::vector shape, DType dtype = DType::kFloat32) { - Tensor value; - value.data = data; - value.shape = std::move(shape); - value.dtype = dtype; - return value; +void check_cuda(cudaError_t status, const char* operation) { + if (status != cudaSuccess) + throw std::runtime_error(std::string("biogpt ") + operation + ": " + + cudaGetErrorString(status)); } -std::vector copy_output(const TensorMap& outputs, const std::string& name, - const std::vector& shape) { - const auto found = outputs.find(name); - if (found == outputs.end() || found->second.dtype != DType::kFloat32 || - found->second.shape != shape || !found->second.data) - throw std::runtime_error("biogpt invalid engine output: " + name); - const auto* start = static_cast(found->second.data); - std::vector result(start, start + found->second.numel()); - if (!std::all_of(result.begin(), result.end(), - [](float value) { return std::isfinite(value); })) - throw std::runtime_error("biogpt nonfinite engine output: " + name); - return result; +void* device_binding(ITrtModule& module, const std::string& name, + const std::vector& shape, DType dtype, bool input) { + auto* ptr = module.device_ptr(name); + if (!ptr || !(input ? module.has_input(name) : module.has_output(name)) || + module.tensor_dtype(name) != dtype || module.tensor_shape(name) != shape) + throw std::runtime_error("biogpt invalid engine binding: " + name); + return ptr; } +struct CacheBinding { + float* past; + const float* present; +}; + } // namespace Pipeline::Pipeline(std::unique_ptr decoder, std::unique_ptr tokenizer, @@ -47,55 +47,94 @@ Pipeline::Pipeline(std::unique_ptr decoder, std::unique_ptr= 0 || request.forced_bos_token_id >= 0 || (request.text_generation_mode != "auto" && request.text_generation_mode != "raw")) - throw std::invalid_argument("biogpt supports raw greedy generation"); + throw internal::ConfigError("biogpt supports raw greedy generation"); const auto limit = request.max_new_tokens > 0 ? request.max_new_tokens : default_max_new_tokens(); + const auto capacity = config_.max_sequence_length; + if (limit >= capacity) + throw internal::ConfigError("biogpt request exceeds the bundle cache capacity"); auto ids = tokenizer_->encode(prompt); if (ids.empty()) ids.push_back(config_.bos_token_id); - const auto capacity = config_.max_sequence_length; - if (limit > capacity || ids.size() > static_cast(capacity - limit)) - throw std::invalid_argument("biogpt request exceeds the bundle cache capacity"); + if (ids.size() > static_cast(capacity - limit)) + throw internal::ConfigError("biogpt request exceeds the bundle cache capacity"); if (std::any_of(ids.begin(), ids.end(), [this](auto id) { return id < 0 || id >= config_.vocab_size; })) throw std::invalid_argument("biogpt tokenizer emitted invalid token IDs"); const auto eos = request.eos_token_id >= 0 ? request.eos_token_id : config_.eos_token_id; if (eos >= config_.vocab_size) - throw std::invalid_argument("biogpt invalid EOS override"); - const auto width = config_.kv_width; - const auto count = static_cast(capacity) * width; - std::vector> keys(config_.num_layers, std::vector(count)); - std::vector> values(config_.num_layers, std::vector(count)); - std::int32_t position = 0; - auto step = [&](std::int32_t token) { - TensorMap inputs{ - {"input_ids", tensor(&token, {1}, DType::kInt32)}, - {"position", tensor(&position, {1}, DType::kInt32)}, - }; - for (std::int32_t layer = 0; layer < config_.num_layers; ++layer) { - inputs["past_k_" + std::to_string(layer)] = - tensor(keys[layer].data(), {capacity, width}); - inputs["past_v_" + std::to_string(layer)] = - tensor(values[layer].data(), {capacity, width}); + throw internal::ConfigError("biogpt invalid EOS override"); + const std::lock_guard lock(execution_); + if (stream_failed_) + throw std::runtime_error("biogpt TensorRT stream failed to synchronize"); + const auto stream = decoder_->stream(); + const auto width = static_cast(config_.kv_width); + const auto cache_bytes = static_cast(capacity) * width * sizeof(float); + const auto token_input = device_binding(*decoder_, "input_ids", {1}, DType::kInt32, true); + const auto position_input = device_binding(*decoder_, "position", {1}, DType::kInt32, true); + const auto logits_output = + device_binding(*decoder_, "logits", {1, config_.vocab_size}, DType::kFloat32, false); + const std::vector shape{capacity, config_.kv_width}; + std::vector cache; + for (std::int32_t layer = 0; layer < config_.num_layers; ++layer) { + for (const char* kind : {"k_", "v_"}) { + const auto suffix = kind + std::to_string(layer); + auto* past = static_cast( + device_binding(*decoder_, "past_" + suffix, shape, DType::kFloat32, true)); + const auto* present = static_cast( + device_binding(*decoder_, "present_" + suffix, shape, DType::kFloat32, false)); + cache.push_back({past, present}); } - const auto outputs = decoder_->forward(inputs); - for (std::int32_t layer = 0; layer < config_.num_layers; ++layer) { - keys[layer] = - copy_output(outputs, "present_k_" + std::to_string(layer), {capacity, width}); - values[layer] = - copy_output(outputs, "present_v_" + std::to_string(layer), {capacity, width}); + } + + std::vector logits(config_.vocab_size); + std::int32_t position = 0; + auto step = [&](std::int32_t token, bool read_logits) { + try { + if (position == 0) { + for (const auto& binding : cache) + check_cuda(cudaMemsetAsync(binding.past, 0, cache_bytes, stream), + "reset KV cache"); + } + check_cuda( + cudaMemcpyAsync(token_input, &token, sizeof(token), cudaMemcpyHostToDevice, stream), + "upload token"); + check_cuda(cudaMemcpyAsync(position_input, &position, sizeof(position), + cudaMemcpyHostToDevice, stream), + "upload position"); + decoder_->forward_device_async({}); + // Only the row at this position differs from the past cache input. + const auto offset = static_cast(position) * width; + for (const auto& binding : cache) { + check_cuda(cudaMemcpyAsync(binding.past + offset, binding.present + offset, + width * sizeof(float), cudaMemcpyDeviceToDevice, stream), + "update KV cache row"); + } + if (read_logits) { + check_cuda(cudaMemcpyAsync(logits.data(), logits_output, + logits.size() * sizeof(float), cudaMemcpyDeviceToHost, + stream), + "download logits"); + } + decoder_->sync(); + } catch (...) { + // Keep the host-side token, position, and logits alive until the stream is drained. + stream_failed_ = true; + decoder_->sync(); + stream_failed_ = false; + throw; } + if (read_logits && !std::all_of(logits.begin(), logits.end(), + [](float value) { return std::isfinite(value); })) + throw std::runtime_error("biogpt nonfinite engine output: logits"); ++position; - return copy_output(outputs, "logits", {1, config_.vocab_size}); }; - std::vector logits; - for (auto id : ids) - logits = step(id); + for (std::size_t i = 0; i < ids.size(); ++i) + step(ids[i], i + 1 == ids.size()); TextResult result; for (std::int32_t index = 0; index < limit; ++index) { const auto next = static_cast(std::max_element(logits.begin(), logits.end()) - @@ -104,7 +143,7 @@ TextResult Pipeline::generate(const std::string& prompt, const TextGenerationCon if (next == eos) break; if (index + 1 < limit) - logits = step(next); + step(next, true); } result.text = tokenizer_->decode(result.token_ids); return result; diff --git a/families/biogpt/runtime/pipeline.h b/families/biogpt/runtime/pipeline.h index f7ce3a6ba4..581cbbb892 100644 --- a/families/biogpt/runtime/pipeline.h +++ b/families/biogpt/runtime/pipeline.h @@ -34,6 +34,7 @@ class Pipeline final : public ITextGeneration { std::unique_ptr decoder_; std::unique_ptr tokenizer_; Config config_; + bool stream_failed_{}; }; } // namespace trtmc::biogpt diff --git a/families/biogpt/tests/cpp/e2e_consumer.cpp b/families/biogpt/tests/cpp/e2e_consumer.cpp index 669a20a490..a81286a867 100644 --- a/families/biogpt/tests/cpp/e2e_consumer.cpp +++ b/families/biogpt/tests/cpp/e2e_consumer.cpp @@ -5,6 +5,7 @@ #include "families/biogpt/runtime/tokenizer.h" #include "trtmc/bundle.h" +#include "trtmc/internal/config.h" #include "trtmc/runtime/family_loader.h" #include @@ -46,7 +47,7 @@ int main(int argc, char** argv) { bool rejected = false; try { task->generate("overflow", overflow); - } catch (const std::invalid_argument&) { + } catch (const trtmc::internal::ConfigError&) { rejected = true; } if (!rejected) diff --git a/families/biogpt/tests/cpp/tokenizer_consumer.cpp b/families/biogpt/tests/cpp/tokenizer_consumer.cpp index fb75353a1e..f1fcb71823 100644 --- a/families/biogpt/tests/cpp/tokenizer_consumer.cpp +++ b/families/biogpt/tests/cpp/tokenizer_consumer.cpp @@ -22,7 +22,8 @@ int main(int argc, char** argv) { const auto requests = nlohmann::json::parse(texts); nlohmann::json output = nlohmann::json::array(); for (const auto& text : requests) { - const auto ids = tokenizer->encode(text.get()); + const auto ids = text.is_array() ? text.get>() + : tokenizer->encode(text.get()); output.push_back({{"ids", ids}, {"text", tokenizer->decode(ids)}}); } std::cout << output.dump() << '\n'; diff --git a/families/biogpt/tests/test_e2e.py b/families/biogpt/tests/test_e2e.py index 75b1e8c7b6..3d67fe7d9e 100644 --- a/families/biogpt/tests/test_e2e.py +++ b/families/biogpt/tests/test_e2e.py @@ -118,6 +118,9 @@ def _check_native_tokenizer(model_dir, runtime, tmp_path): " A\tB\n\nC / 42! 😀", "No. 12 vs. Nos. 4 and 5.", "Hello", + "", + "Three...dots and text....here", + "Finish with many dots" + "." * 128, "1980's isn't ordinary.", "", ] @@ -125,7 +128,8 @@ def _check_native_tokenizer(model_dir, runtime, tmp_path): path = tmp_path / "tokenizer-texts.json" path.write_text(json.dumps(texts, ensure_ascii=False)) encoded = tmp_path / "initialized-tokenizer.json" - encoded.write_text(json.dumps(tokenizer_spec(model_dir))) + spec = tokenizer_spec(model_dir) + encoded.write_text(json.dumps(spec)) result = subprocess.run( [str(runtime / "biogpt_tokenizer"), str(encoded), str(path)], check=True, @@ -144,6 +148,32 @@ def _check_native_tokenizer(model_dir, runtime, tmp_path): ] assert json.loads(result.stdout) == expected + # Use explicit word boundaries so the spacing isolates Moses's CJK predicate. + endpoint, _ = spec["cjk_ranges"][1] + boundary, first, second = map(chr, range(endpoint, endpoint + 3)) + spec["vocab"] = { + "": 0, "": 1, "": 2, "": 3, + boundary + "": 4, first + "": 5, second + "": 6, + } + encoded.write_text(json.dumps(spec)) + path.write_text(json.dumps([[4, 5], [5, 6]])) + result = subprocess.run( + [str(runtime / "biogpt_tokenizer"), str(encoded), str(path)], + check=True, text=True, capture_output=True, timeout=60, + ) + assert [item["text"] for item in json.loads(result.stdout)] == [ + f"{boundary} {first}", first + second, + ] + malformed_ranges = list(spec["cjk_ranges"]) + malformed_ranges[1] = [endpoint] + spec["cjk_ranges"] = malformed_ranges + encoded.write_text(json.dumps(spec)) + result = subprocess.run( + [str(runtime / "biogpt_tokenizer"), str(encoded), str(path)], + text=True, capture_output=True, timeout=60, + ) + assert result.returncode == 1 and "CJK range requires two integer endpoints" in result.stderr + def test_official_checkpoint_e2e(case_name, tmp_path): case = next(case for case in MANIFEST["testcases"] if case["name"] == case_name) diff --git a/families/biogpt/tests/test_model.py b/families/biogpt/tests/test_model.py index a33ad7d815..0ad9a73cc9 100644 --- a/families/biogpt/tests/test_model.py +++ b/families/biogpt/tests/test_model.py @@ -1,5 +1,8 @@ # SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 +import json +from unittest.mock import Mock + import pytest from families.biogpt.model import load_weights, required_shapes, validate_config @@ -41,3 +44,31 @@ def test_decoder_geometry_rejects_incompatible_heads_and_activation(): config.update(num_attention_heads=4, hidden_act="relu") with pytest.raises(ValueError, match="GELU"): validate_config(config) + + +@pytest.mark.parametrize("capacity", [1, 2, 33]) +def test_builder_validates_cache_bounds(tmp_path, monkeypatch, capacity): + from tensorrt_model_connect import BuildRequest + from transformers import BioGptConfig + from families.biogpt import model + + config = BioGptConfig(max_position_embeddings=32).to_dict() + (tmp_path / "config.json").write_text(json.dumps(config)) + weights = Mock(return_value={}) + compile_engine = Mock(return_value=b"decoder") + monkeypatch.setattr(model, "load_weights", weights) + monkeypatch.setattr(model, "compile_engine", compile_engine) + monkeypatch.setattr(model, "tokenizer_spec", lambda _: {}) + request = BuildRequest( + tmp_path, tmp_path / "model.bundle", "biogpt", "text_generation", "fp32", + max_sequence_length=capacity, + ) + writer = Mock() + if capacity == 2: + model.build(request, writer) + assert compile_engine.call_args.args[2] == 2 + assert writer.add_json.call_args.args[1]["max_sequence_length"] == 2 + else: + with pytest.raises(ValueError, match="cache capacity"): + model.build(request, writer) + weights.assert_not_called() From 7c609ac97cc5e6ec2e293590c831acf8bda56cb6 Mon Sep 17 00:00:00 2001 From: Will Guo Date: Wed, 2 Dec 2026 21:16:12 -0800 Subject: [PATCH 5/5] fix(biogpt): bound preprocessing and complete host transfers Signed-off-by: Will Guo --- families/biogpt/README.md | 2 ++ families/biogpt/runtime/pipeline.cpp | 24 +++++++++++++--------- families/biogpt/tests/cpp/e2e_consumer.cpp | 10 +++++++++ 3 files changed, 26 insertions(+), 10 deletions(-) diff --git a/families/biogpt/README.md b/families/biogpt/README.md index 0a16448cd8..62305137b4 100644 --- a/families/biogpt/README.md +++ b/families/biogpt/README.md @@ -5,6 +5,8 @@ This family builds `microsoft/biogpt` revision The selected profile uses FP32, batch size one, tensor parallel size one, a 256-position default cache, and raw greedy generation. This leaves room for an input prompt with the public request default of 128 new tokens. +Prompts are limited to 64 KiB of UTF-8 input before Moses and BPE processing. +The tokenized prompt and requested generation must also fit the bundle cache. The decoder preserves scaled token embeddings, learned positions with the published two-position offset, pre-normalized attention and feed-forward diff --git a/families/biogpt/runtime/pipeline.cpp b/families/biogpt/runtime/pipeline.cpp index d1e2ee1555..fcd000172e 100644 --- a/families/biogpt/runtime/pipeline.cpp +++ b/families/biogpt/runtime/pipeline.cpp @@ -14,6 +14,8 @@ namespace trtmc::biogpt { namespace { +constexpr std::size_t kMaxPromptBytes = 64 * 1024; + void check_cuda(cudaError_t status, const char* operation) { if (status != cudaSuccess) throw std::runtime_error(std::string("biogpt ") + operation + ": " + @@ -57,6 +59,8 @@ TextResult Pipeline::generate(const std::string& prompt, const TextGenerationCon const auto capacity = config_.max_sequence_length; if (limit >= capacity) throw internal::ConfigError("biogpt request exceeds the bundle cache capacity"); + if (prompt.size() > kMaxPromptBytes) + throw internal::ConfigError("biogpt prompt exceeds the 64 KiB preprocessing limit"); auto ids = tokenizer_->encode(prompt); if (ids.empty()) ids.push_back(config_.bos_token_id); @@ -100,12 +104,13 @@ TextResult Pipeline::generate(const std::string& prompt, const TextGenerationCon check_cuda(cudaMemsetAsync(binding.past, 0, cache_bytes, stream), "reset KV cache"); } + // Complete the default-stream uploads before submitting decoder work. + check_cuda(cudaMemcpy(token_input, &token, sizeof(token), cudaMemcpyHostToDevice), + "upload token"); check_cuda( - cudaMemcpyAsync(token_input, &token, sizeof(token), cudaMemcpyHostToDevice, stream), - "upload token"); - check_cuda(cudaMemcpyAsync(position_input, &position, sizeof(position), - cudaMemcpyHostToDevice, stream), - "upload position"); + cudaMemcpy(position_input, &position, sizeof(position), cudaMemcpyHostToDevice), + "upload position"); + check_cuda(cudaStreamSynchronize(nullptr), "finish decoder input uploads"); decoder_->forward_device_async({}); // Only the row at this position differs from the past cache input. const auto offset = static_cast(position) * width; @@ -114,15 +119,14 @@ TextResult Pipeline::generate(const std::string& prompt, const TextGenerationCon width * sizeof(float), cudaMemcpyDeviceToDevice, stream), "update KV cache row"); } + decoder_->sync(); if (read_logits) { - check_cuda(cudaMemcpyAsync(logits.data(), logits_output, - logits.size() * sizeof(float), cudaMemcpyDeviceToHost, - stream), + check_cuda(cudaMemcpy(logits.data(), logits_output, logits.size() * sizeof(float), + cudaMemcpyDeviceToHost), "download logits"); } - decoder_->sync(); } catch (...) { - // Keep the host-side token, position, and logits alive until the stream is drained. + // Only device-owned cache buffers can have outstanding decoder work. stream_failed_ = true; decoder_->sync(); stream_failed_ = false; diff --git a/families/biogpt/tests/cpp/e2e_consumer.cpp b/families/biogpt/tests/cpp/e2e_consumer.cpp index a81286a867..af0c67284f 100644 --- a/families/biogpt/tests/cpp/e2e_consumer.cpp +++ b/families/biogpt/tests/cpp/e2e_consumer.cpp @@ -12,6 +12,7 @@ #include #include #include +#include int main(int argc, char** argv) { try { @@ -55,6 +56,15 @@ int main(int argc, char** argv) { const auto& first = requests.at(0); trtmc::TextGenerationConfig config; config.max_new_tokens = first.at("max_new_tokens"); + rejected = false; + try { + task->generate(std::string(64 * 1024 + 1, ' '), config); + } catch (const trtmc::internal::ConfigError& error) { + rejected = std::string_view(error.what()).find("64 KiB preprocessing limit") != + std::string_view::npos; + } + if (!rejected) + throw std::runtime_error("BioGPT accepted a prompt beyond the byte limit"); const auto recovered = task->generate(first.at("prompt"), config); if (recovered.token_ids != results.at(0).at("token_ids").get>()) throw std::runtime_error("BioGPT request state leaked after rejection");