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

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 43 additions & 0 deletions families/biogpt/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
# BioGPT

This family builds `microsoft/biogpt` revision
`eb0d815e95434dc9e3b78f464e52b899bee7d923` for native `ITextGeneration`.
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
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 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
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
```

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.
4 changes: 4 additions & 0 deletions families/biogpt/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0

"""BioGPT family ownership boundary."""
286 changes: 286 additions & 0 deletions families/biogpt/model.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,286 @@
# 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()))
# 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 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)
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),
},
)
2 changes: 2 additions & 0 deletions families/biogpt/requirements.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
transformers==5.3.0
sacremoses==0.1.1
31 changes: 31 additions & 0 deletions families/biogpt/runtime/CMakeLists.txt
Original file line number Diff line number Diff line change
@@ -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()
Loading
Loading