From 4a2b338d132abf415959f93c55a50c27788d0fa7 Mon Sep 17 00:00:00 2001 From: Will Guo Date: Thu, 12 Nov 2026 22:44:01 -0800 Subject: [PATCH 1/3] feat(pegasus): add native summarization Signed-off-by: Will Guo --- families/pegasus/__init__.py | 4 + families/pegasus/model.py | 261 +++++++ families/pegasus/requirements.txt | 1 + families/pegasus/runtime/CMakeLists.txt | 30 + families/pegasus/runtime/pipeline.cpp | 131 ++++ families/pegasus/runtime/pipeline.h | 40 ++ families/pegasus/runtime/plugin.cpp | 55 ++ families/pegasus/runtime/tokenizer.h | 30 + .../pegasus/runtime/unigram_tokenizer.cpp | 640 ++++++++++++++++++ families/pegasus/support.py | 13 + families/pegasus/tests/__init__.py | 2 + families/pegasus/tests/cpp/e2e_consumer.cpp | 60 ++ families/pegasus/tests/cpp/test_tokenizer.cpp | 27 + .../pegasus/tests/manifests/pegasus-xsum.json | 23 + families/pegasus/tests/test_e2e.py | 132 ++++ families/pegasus/tests/test_model.py | 70 ++ 16 files changed, 1519 insertions(+) create mode 100644 families/pegasus/__init__.py create mode 100644 families/pegasus/model.py create mode 100644 families/pegasus/requirements.txt create mode 100644 families/pegasus/runtime/CMakeLists.txt create mode 100644 families/pegasus/runtime/pipeline.cpp create mode 100644 families/pegasus/runtime/pipeline.h create mode 100644 families/pegasus/runtime/plugin.cpp create mode 100644 families/pegasus/runtime/tokenizer.h create mode 100644 families/pegasus/runtime/unigram_tokenizer.cpp create mode 100644 families/pegasus/support.py create mode 100644 families/pegasus/tests/__init__.py create mode 100644 families/pegasus/tests/cpp/e2e_consumer.cpp create mode 100644 families/pegasus/tests/cpp/test_tokenizer.cpp create mode 100644 families/pegasus/tests/manifests/pegasus-xsum.json create mode 100644 families/pegasus/tests/test_e2e.py create mode 100644 families/pegasus/tests/test_model.py diff --git a/families/pegasus/__init__.py b/families/pegasus/__init__.py new file mode 100644 index 0000000000..03460a97a0 --- /dev/null +++ b/families/pegasus/__init__.py @@ -0,0 +1,4 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Pegasus encoder-decoder summarization.""" diff --git a/families/pegasus/model.py b/families/pegasus/model.py new file mode 100644 index 0000000000..060110e4c5 --- /dev/null +++ b/families/pegasus/model.py @@ -0,0 +1,261 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Build the Pegasus encoder and one-token cached decoder with TensorRT. + +All engine I/O is FP32, except token IDs and positions. Cache updates are ordinary +TensorRT operations. Each request starts with empty caches; the encoder runs once. +""" + +from __future__ import annotations + +import json +from pathlib import Path + +import numpy as np +import tensorrt as trt + + +def sinusoidal_positions(length: int, width: int) -> np.ndarray: + """PegasusSinusoidalPositionalEmbedding uses contiguous sine/cosine halves.""" + positions = np.arange(length, dtype=np.float64)[:, None] + dimensions = np.arange(width, dtype=np.int64)[None, :] + angles = positions / np.power(10000, 2 * (dimensions // 2) / width) + split = (width + 1) // 2 + result = np.empty((length, width), dtype=np.float32) + result[:, :split] = np.sin(angles[:, 0::2]) + result[:, split:] = np.cos(angles[:, 1::2]) + return result + + +def validate_config(config: dict) -> dict: + if config.get("model_type") != "pegasus": + raise ValueError("pegasus requires model_type=pegasus") + for key in ("d_model", "vocab_size", "encoder_layers", "decoder_layers", + "encoder_attention_heads", "decoder_attention_heads", "encoder_ffn_dim", + "decoder_ffn_dim", "max_position_embeddings"): + if type(config.get(key)) is not int or config[key] <= 0: + raise ValueError(f"pegasus requires positive integer {key}") + for side in ("encoder", "decoder"): + if config["d_model"] % config[f"{side}_attention_heads"]: + raise ValueError(f"pegasus {side} heads must divide d_model") + if config.get("activation_function", "gelu") != "relu": + raise NotImplementedError("pegasus currently requires activation_function=relu") + if not config.get("scale_embedding", True): + raise NotImplementedError("pegasus currently requires scaled token embeddings") + return config + + +def load_weights(model_dir: Path, config: dict) -> dict[str, np.ndarray]: + """Read safetensors or the upstream legacy state dictionary without executable pickle.""" + safe = model_dir / "model.safetensors" + if safe.is_file(): + from safetensors.numpy import load_file + source = load_file(str(safe)) + else: + import torch + source = torch.load(model_dir / "pytorch_model.bin", map_location="cpu", weights_only=True) + result = {} + for name, value in source.items(): + if hasattr(value, "detach"): + value = value.detach().float().numpy() + result[name] = np.asarray(value, dtype=np.float32) + if "model.shared.weight" not in result: + raise ValueError("pegasus checkpoint lacks model.shared.weight") + if result["model.shared.weight"].shape != (config["vocab_size"], config["d_model"]): + raise ValueError("pegasus shared embedding shape disagrees with config") + # Missing tied aliases are expected in safetensors checkpoints. + result.setdefault("lm_head.weight", result["model.shared.weight"]) + result.setdefault("final_logits_bias", np.zeros((1, config["vocab_size"]), np.float32)) + return result + + +class Graph: + """Static batch-one Pegasus graph; TensorRT owns all GPU lowering.""" + + def __init__(self, network, config, weights): + self.n, self.c, self.w = network, config, weights + self.hidden = config["d_model"] + self.constants = [] + + def constant(self, values, dtype=np.float32): + array = np.ascontiguousarray(values, dtype=dtype) + self.constants.append(array) + return self.n.add_constant(array.shape, trt.Weights(array)).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 binary(self, x, y, operation=trt.ElementWiseOperation.SUM): + return self.n.add_elementwise(x, y, operation).get_output(0) + + def linear(self, x, prefix): + weight = self.constant(self.w[prefix + ".weight"].T) + out = self.n.add_matrix_multiply(x, trt.MatrixOperation.NONE, + weight, trt.MatrixOperation.NONE).get_output(0) + return self.binary(out, self.constant(self.w[prefix + ".bias"].reshape(1, -1))) + + def norm(self, x, prefix): + layer = self.n.add_normalization( + x, self.constant(self.w[prefix + ".weight"].reshape(1, -1)), + self.constant(self.w[prefix + ".bias"].reshape(1, -1)), 1 << 1) + layer.epsilon = 1e-5 + return layer.get_output(0) + + def embeddings(self, ids, positions, length, side): + weight = self.w.get(f"model.{side}.embed_tokens.weight", self.w["model.shared.weight"]) + token = self.n.add_gather(self.constant(weight), ids, 0).get_output(0) + token = self.binary(token, self.constant([[self.hidden ** 0.5]]), + trt.ElementWiseOperation.PROD) + table = self.w.get(f"model.{side}.embed_positions.weight") + if table is None: + table = sinusoidal_positions(self.c["max_position_embeddings"], self.hidden) + position = self.n.add_gather(self.constant(table), positions, 0).get_output(0) + return self.binary(self.reshape(token, (length, self.hidden)), + self.reshape(position, (length, self.hidden))) + + def heads(self, x, length, count): + return self.reshape(x, (length, count, self.hidden // count), (1, 0, 2)) + + def attention(self, q, k, v, mask, prefix, heads, qlen, klen): + query = self.heads(self.linear(q, prefix + ".q_proj"), qlen, heads) + key = self.heads(k, klen, heads) + value = self.heads(v, klen, heads) + query = self.binary(query, self.constant([[[1 / (self.hidden // heads) ** 0.5]]]), + trt.ElementWiseOperation.PROD) + scores = self.n.add_matrix_multiply(query, trt.MatrixOperation.NONE, + key, trt.MatrixOperation.TRANSPOSE).get_output(0) + scores = self.binary(scores, mask) + softmax = self.n.add_softmax(scores) + softmax.axes = 1 << 2 + context = self.n.add_matrix_multiply(softmax.get_output(0), trt.MatrixOperation.NONE, + value, trt.MatrixOperation.NONE).get_output(0) + transposed = self.n.add_shuffle(context) + transposed.first_transpose = (1, 0, 2) + transposed.reshape_dims = (qlen, self.hidden) + return self.linear(transposed.get_output(0), prefix + ".out_proj") + + def feed_forward(self, x, prefix): + normed = self.norm(x, prefix + ".final_layer_norm") + hidden = self.linear(normed, prefix + ".fc1") + hidden = self.n.add_activation(hidden, trt.ActivationType.RELU).get_output(0) + return self.binary(x, self.linear(hidden, prefix + ".fc2")) + + def output(self, x, name): + x.name = name + self.n.mark_output(x) + + def encoder(self, length): + ids = self.n.add_input("input_ids", trt.int32, (length,)) + mask = self.reshape(self.n.add_input("attention_mask", trt.float32, (length,)), (1, 1, length)) + positions = self.constant(np.arange(length), np.int32) + x = self.embeddings(ids, positions, length, "encoder") + heads = self.c["encoder_attention_heads"] + for layer in range(self.c["encoder_layers"]): + prefix = f"model.encoder.layers.{layer}" + normed = self.norm(x, prefix + ".self_attn_layer_norm") + key = self.linear(normed, prefix + ".self_attn.k_proj") + value = self.linear(normed, prefix + ".self_attn.v_proj") + x = self.binary(x, self.attention(normed, key, value, mask, + prefix + ".self_attn", heads, length, length)) + x = self.feed_forward(x, prefix) + self.output(self.norm(x, "model.encoder.layer_norm"), "encoder_output") + + def decoder(self, length): + ids = self.n.add_input("input_ids", trt.int32, (1,)) + position = self.n.add_input("position", trt.int32, (1,)) + memory = self.n.add_input("encoder_output", trt.float32, (length, self.hidden)) + memory_mask = self.reshape(self.n.add_input("attention_mask", trt.float32, (length,)), + (1, 1, length)) + positions = self.constant(np.arange(length), np.int32) + future = self.binary(positions, position, trt.ElementWiseOperation.GREATER) + future = self.n.add_cast(future, trt.float32).get_output(0) + mask = self.reshape(self.binary(future, self.constant([-1e9]), trt.ElementWiseOperation.PROD), + (1, 1, length)) + insert = self.binary(positions, position, trt.ElementWiseOperation.EQUAL) + insert = self.reshape(insert, (length, 1)) + x = self.embeddings(ids, position, 1, "decoder") + heads = self.c["decoder_attention_heads"] + for layer in range(self.c["decoder_layers"]): + prefix = f"model.decoder.layers.{layer}" + normed = self.norm(x, prefix + ".self_attn_layer_norm") + caches = [] + for component in ("k", "v"): + past = self.n.add_input(f"past_{component}_{layer}", trt.float32, (length, self.hidden)) + current = self.linear(normed, prefix + f".self_attn.{component}_proj") + cache = self.n.add_select(insert, current, past).get_output(0) + self.output(cache, f"present_{component}_{layer}") + caches.append(cache) + x = self.binary(x, self.attention(normed, *caches, mask, + prefix + ".self_attn", heads, 1, length)) + normed = self.norm(x, prefix + ".encoder_attn_layer_norm") + key = self.linear(memory, prefix + ".encoder_attn.k_proj") + value = self.linear(memory, prefix + ".encoder_attn.v_proj") + x = self.binary(x, self.attention(normed, key, value, memory_mask, + prefix + ".encoder_attn", heads, 1, length)) + x = self.feed_forward(x, prefix) + x = self.norm(x, "model.decoder.layer_norm") + logits = self.n.add_matrix_multiply(x, trt.MatrixOperation.NONE, + self.constant(self.w["lm_head.weight"].T), trt.MatrixOperation.NONE).get_output(0) + self.output(self.binary(logits, self.constant(self.w["final_logits_bias"])), "logits") + + +def compile_engine(config, weights, length, *, decoder, verbose=False): + logger = trt.Logger(trt.Logger.VERBOSE if verbose else trt.Logger.WARNING) + builder = trt.Builder(logger) + network = builder.create_network(1 << int(trt.NetworkDefinitionCreationFlag.STRONGLY_TYPED)) + options = builder.create_builder_config() + options.builder_optimization_level = 3 + options.clear_flag(trt.BuilderFlag.TF32) + graph = Graph(network, config, weights) + (graph.decoder if decoder else graph.encoder)(length) + plan = builder.build_serialized_network(network, options) + if plan is None: + raise RuntimeError("pegasus TensorRT engine build failed") + return bytes(plan) + + +def build(request, writer): + """Build one family-owned Pegasus bundle, with a fixed source/cache capacity.""" + if request.backend != "trt": + raise NotImplementedError("pegasus currently supports backend=trt") + if request.task != "text_generation" or request.precision != "fp32": + raise ValueError("pegasus supports text_generation with precision=fp32") + if request.dynamic_kv_cache: + raise NotImplementedError("pegasus does not support dynamic_kv_cache") + 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"pegasus does not support {field}") + if request.quantization not in (None, "none"): + raise NotImplementedError("pegasus does not support quantization") + root = Path(request.model_dir) + config = validate_config(json.loads((root / "config.json").read_text())) + length = request.max_sequence_length or min(128, config["max_position_embeddings"]) + if length > config["max_position_embeddings"]: + raise ValueError("pegasus max_sequence_length exceeds position capacity") + tokenizer = root / "tokenizer.json" + if not tokenizer.is_file(): + raise FileNotFoundError("pegasus requires a fast tokenizer.json") + weights = load_weights(root, config) + writer.set_header(family="pegasus", task=request.task, backend=request.backend) + for decoder, name in ((False, "encoder.plan"), (True, "decoder.plan")): + writer.add_bytes(name, compile_engine(config, weights, length, decoder=decoder, + verbose=request.verbose)) + writer.add_bytes("tokenizer.json", tokenizer.read_bytes()) + writer.add_json("runtime.json", { + "schema_version": 1, "hidden_size": config["d_model"], "vocab_size": config["vocab_size"], + "decoder_layers": config["decoder_layers"], "max_sequence_length": length, + "decoder_start_token_id": config.get("decoder_start_token_id", 0), + "eos_token_id": config.get("eos_token_id", 1), "pad_token_id": config.get("pad_token_id", 0), + }) diff --git a/families/pegasus/requirements.txt b/families/pegasus/requirements.txt new file mode 100644 index 0000000000..90b9e8b11d --- /dev/null +++ b/families/pegasus/requirements.txt @@ -0,0 +1 @@ +torch>=2.6 diff --git a/families/pegasus/runtime/CMakeLists.txt b/families/pegasus/runtime/CMakeLists.txt new file mode 100644 index 0000000000..1a621d55b6 --- /dev/null +++ b/families/pegasus/runtime/CMakeLists.txt @@ -0,0 +1,30 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +add_library(trtmc_model_pegasus SHARED pipeline.cpp plugin.cpp unigram_tokenizer.cpp) +target_include_directories(trtmc_model_pegasus PRIVATE + ${PROJECT_SOURCE_DIR} ${PROJECT_SOURCE_DIR}/core/runtime/include) +target_include_directories(trtmc_model_pegasus SYSTEM PRIVATE ${TRTMC_CUDA_INCLUDE_DIR}) +target_link_libraries(trtmc_model_pegasus PRIVATE + trtmc_core nlohmann_json::nlohmann_json ${TRTMC_CUDART_LIBRARY}) +target_compile_options(trtmc_model_pegasus PRIVATE -Wall -Wextra -Wpedantic) +set_target_properties(trtmc_model_pegasus PROPERTIES + LIBRARY_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}" + BUILD_RPATH "\$ORIGIN" INSTALL_RPATH "\$ORIGIN") +install(TARGETS trtmc_model_pegasus LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR}) + +if(TRTMC_BUILD_TESTS) + add_executable(test_pegasus_tokenizer + ${PROJECT_SOURCE_DIR}/families/pegasus/tests/cpp/test_tokenizer.cpp + unigram_tokenizer.cpp) + target_include_directories(test_pegasus_tokenizer PRIVATE ${PROJECT_SOURCE_DIR}) + target_link_libraries(test_pegasus_tokenizer PRIVATE nlohmann_json::nlohmann_json) + add_test(NAME pegasus_tokenizer COMMAND test_pegasus_tokenizer) + + add_executable(pegasus_e2e ${PROJECT_SOURCE_DIR}/families/pegasus/tests/cpp/e2e_consumer.cpp + unigram_tokenizer.cpp) + target_include_directories(pegasus_e2e PRIVATE + ${PROJECT_SOURCE_DIR} ${PROJECT_SOURCE_DIR}/core/runtime/include) + target_link_libraries(pegasus_e2e PRIVATE trtmc_runtime trtmc_core nlohmann_json::nlohmann_json) + set_target_properties(pegasus_e2e PROPERTIES RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}") +endif() diff --git a/families/pegasus/runtime/pipeline.cpp b/families/pegasus/runtime/pipeline.cpp new file mode 100644 index 0000000000..bd88ed3ec1 --- /dev/null +++ b/families/pegasus/runtime/pipeline.cpp @@ -0,0 +1,131 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + */ + +#include "families/pegasus/runtime/pipeline.h" + +#include +#include +#include +#include +#include + +namespace trtmc::pegasus { +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 it = outputs.find(name); + if (it == outputs.end() || it->second.dtype != DType::kFloat32 || + it->second.shape != shape || it->second.data == nullptr) + throw std::runtime_error("pegasus invalid engine output: " + name); + const auto* start = static_cast(it->second.data); + std::vector values(start, start + it->second.numel()); + if (!std::all_of(values.begin(), values.end(), [](float x) { return std::isfinite(x); })) + throw std::runtime_error("pegasus nonfinite engine output: " + name); + return values; +} + +} // namespace + +Pipeline::Pipeline(std::unique_ptr encoder, std::unique_ptr decoder, + std::unique_ptr tokenizer, Config config) + : encoder_(std::move(encoder)), decoder_(std::move(decoder)), + tokenizer_(std::move(tokenizer)), config_(config) { + if (!encoder_ || !encoder_->ok() || !decoder_ || !decoder_->ok() || !tokenizer_) + throw std::invalid_argument("pegasus requires an encoder, decoder, and tokenizer"); + if (config_.hidden_size <= 0 || config_.vocab_size <= 0 || config_.decoder_layers <= 0 || + config_.max_sequence_length <= 0) + throw std::invalid_argument("pegasus invalid runtime geometry"); + for (auto id : {config_.decoder_start_token_id, config_.eos_token_id, config_.pad_token_id}) { + if (id < 0 || id >= config_.vocab_size) + throw std::invalid_argument("pegasus invalid special token ID"); + } +} + +std::int32_t Pipeline::default_max_new_tokens() const { + return std::min(64, config_.max_sequence_length); +} + +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.text_generation_mode != "auto" && request.text_generation_mode != "raw")) + throw std::invalid_argument("pegasus supports raw greedy generation"); + const auto limit = request.max_new_tokens > 0 ? request.max_new_tokens : default_max_new_tokens(); + if (limit > config_.max_sequence_length) + throw std::invalid_argument("pegasus requested tokens exceed cache capacity"); + const auto eos = request.eos_token_id >= 0 ? request.eos_token_id : config_.eos_token_id; + if (eos >= config_.vocab_size || request.forced_bos_token_id >= config_.vocab_size) + throw std::invalid_argument("pegasus generation token ID exceeds vocabulary"); + const auto length = config_.max_sequence_length; + const auto hidden = config_.hidden_size; + auto ids = tokenizer_->encode(prompt); + if (ids.empty() || ids.back() != config_.eos_token_id) + ids.push_back(config_.eos_token_id); + if (ids.size() > static_cast(length)) { + ids.resize(length); + ids.back() = config_.eos_token_id; + } + if (std::any_of(ids.begin(), ids.end(), [this](auto id) { + return id < 0 || id >= config_.vocab_size; + })) + throw std::runtime_error("pegasus tokenizer emitted an invalid ID"); + std::vector mask(length, -1e9F); + std::fill_n(mask.begin(), ids.size(), 0.0F); + ids.resize(length, config_.pad_token_id); + const auto start = std::chrono::steady_clock::now(); + auto encoded = encoder_->forward({{"input_ids", tensor(ids.data(), {length}, DType::kInt32)}, + {"attention_mask", tensor(mask.data(), {length})}}); + auto memory = copy_output(encoded, "encoder_output", {length, hidden}); + const auto prefilled = std::chrono::steady_clock::now(); + + // These buffers are request-local. A repeated call cannot retain a prior + // prompt's encoder memory, self-attention cache, or decoder position. + const auto count = static_cast(length) * hidden; + std::vector> keys(config_.decoder_layers, std::vector(count)); + std::vector> values(config_.decoder_layers, std::vector(count)); + std::int32_t current = config_.decoder_start_token_id; + TextResult result; + for (std::int32_t position = 0; position < limit; ++position) { + TensorMap inputs{ + {"input_ids", tensor(¤t, {1}, DType::kInt32)}, + {"position", tensor(&position, {1}, DType::kInt32)}, + {"encoder_output", tensor(memory.data(), {length, hidden})}, + {"attention_mask", tensor(mask.data(), {length})}, + }; + for (std::int32_t layer = 0; layer < config_.decoder_layers; ++layer) { + inputs["past_k_" + std::to_string(layer)] = tensor(keys[layer].data(), {length, hidden}); + inputs["past_v_" + std::to_string(layer)] = tensor(values[layer].data(), {length, hidden}); + } + const auto outputs = decoder_->forward(inputs); + const auto logits = copy_output(outputs, "logits", {1, config_.vocab_size}); + for (std::int32_t layer = 0; layer < config_.decoder_layers; ++layer) { + keys[layer] = copy_output(outputs, "present_k_" + std::to_string(layer), {length, hidden}); + values[layer] = copy_output(outputs, "present_v_" + std::to_string(layer), {length, hidden}); + } + current = position == 0 && request.forced_bos_token_id >= 0 + ? request.forced_bos_token_id + : static_cast(std::max_element(logits.begin(), logits.end()) - logits.begin()); + if (current == eos) + break; + result.token_ids.push_back(current); + } + result.text = tokenizer_->decode(result.token_ids); + const auto finished = std::chrono::steady_clock::now(); + result.prefill_ms = std::chrono::duration(prefilled - start).count(); + result.decode_ms = std::chrono::duration(finished - prefilled).count(); + return result; +} + +} // namespace trtmc::pegasus diff --git a/families/pegasus/runtime/pipeline.h b/families/pegasus/runtime/pipeline.h new file mode 100644 index 0000000000..ac887ad56c --- /dev/null +++ b/families/pegasus/runtime/pipeline.h @@ -0,0 +1,40 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + */ + +#pragma once + +#include "families/pegasus/runtime/tokenizer.h" +#include "trtmc/runtime/trt_module.h" +#include "trtmc/task.h" + +#include + +namespace trtmc::pegasus { + +struct Config { + std::int32_t hidden_size{0}; + std::int32_t vocab_size{0}; + std::int32_t decoder_layers{0}; + std::int32_t max_sequence_length{0}; + std::int32_t decoder_start_token_id{0}; + std::int32_t eos_token_id{1}; + std::int32_t pad_token_id{0}; +}; + +class Pipeline final : public ITextGeneration { + public: + Pipeline(std::unique_ptr encoder, 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; + + private: + std::unique_ptr encoder_; + std::unique_ptr decoder_; + std::unique_ptr tokenizer_; + Config config_; +}; + +} // namespace trtmc::pegasus diff --git a/families/pegasus/runtime/plugin.cpp b/families/pegasus/runtime/plugin.cpp new file mode 100644 index 0000000000..9a5a8c9322 --- /dev/null +++ b/families/pegasus/runtime/plugin.cpp @@ -0,0 +1,55 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + */ + +#include "families/pegasus/runtime/pipeline.h" +#include "trtmc/runtime/family_factory.h" +#include "trtmc/runtime/trt_backend.h" + +#include +#include + +namespace trtmc::pegasus { +namespace { + +std::vector section(const BundleReader& reader, const char* name) { + const auto* found = reader.find_section(name); + if (!found || found->length == 0) + throw std::runtime_error(std::string("pegasus missing bundle section: ") + name); + return reader.read_section(name); +} + +std::unique_ptr engine(const FamilyContext& context, const char* name) { + const auto plan = section(context.reader, name); + auto module = context.backend.create_module(plan.data(), plan.size(), {}); + if (!module || !module->ok()) + throw std::runtime_error(std::string("pegasus could not load ") + name); + module->set_timing_label(std::string("pegasus ") + name); + return module; +} + +} // namespace +} // namespace trtmc::pegasus + +extern "C" trtmc::ITask* trtmc_create_family(const trtmc::FamilyContext& context) { + namespace pg = trtmc::pegasus; + if (context.kv_cache_size_bytes != 0) + throw std::invalid_argument("pegasus does not support --kv-cache-size"); + const auto data = pg::section(context.reader, "runtime.json"); + const auto json = nlohmann::json::parse(data.begin(), data.end()); + if (json.at("schema_version").get() != 1) + throw std::invalid_argument("pegasus unsupported runtime schema"); + pg::Config config; + config.hidden_size = json.at("hidden_size").get(); + config.vocab_size = json.at("vocab_size").get(); + config.decoder_layers = json.at("decoder_layers").get(); + config.max_sequence_length = json.at("max_sequence_length").get(); + config.decoder_start_token_id = json.at("decoder_start_token_id").get(); + config.eos_token_id = json.at("eos_token_id").get(); + config.pad_token_id = json.at("pad_token_id").get(); + const auto tokenizer_data = pg::section(context.reader, "tokenizer.json"); + auto tokenizer = pg::CreateUnigramTokenizer(tokenizer_data.data(), tokenizer_data.size(), false); + return new pg::Pipeline(pg::engine(context, "encoder.plan"), pg::engine(context, "decoder.plan"), + std::move(tokenizer), config); +} diff --git a/families/pegasus/runtime/tokenizer.h b/families/pegasus/runtime/tokenizer.h new file mode 100644 index 0000000000..9d014488d3 --- /dev/null +++ b/families/pegasus/runtime/tokenizer.h @@ -0,0 +1,30 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + */ + +#pragma once + +#include +#include +#include +#include +#include +#include + +namespace trtmc::pegasus { + +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 CreateUnigramTokenizer(const char* tokenizer_json_data, + std::size_t tokenizer_json_size, + bool add_special_tokens = true); + +} // namespace trtmc::pegasus diff --git a/families/pegasus/runtime/unigram_tokenizer.cpp b/families/pegasus/runtime/unigram_tokenizer.cpp new file mode 100644 index 0000000000..9326d785ff --- /dev/null +++ b/families/pegasus/runtime/unigram_tokenizer.cpp @@ -0,0 +1,640 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + */ + +#include "families/pegasus/runtime/tokenizer.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace trtmc::pegasus { +namespace { + +// ─── UTF-8 helpers ─── + +// Return the byte length of the UTF-8 codepoint starting at s[pos]. +inline size_t utf8_char_len(const std::string& s, size_t pos) { + unsigned char c = static_cast(s[pos]); + if (c < 0x80) + return 1; + if ((c & 0xE0) == 0xC0) + return 2; + if ((c & 0xF0) == 0xE0) + return 3; + if ((c & 0xF8) == 0xF0) + return 4; + return 1; +} + +class PrecompiledNormalizer { + public: + explicit PrecompiledNormalizer(const std::string& encoded) { + const auto bytes = decode_base64(encoded); + if (bytes.size() <= 4) + throw std::runtime_error("Invalid Precompiled charsmap header"); + const size_t trie_bytes = read_u32(bytes, 0); + if (trie_bytes < 1024 || trie_bytes % 1024 != 0 || trie_bytes >= bytes.size() - 4) + throw std::runtime_error("Invalid Precompiled charsmap trie size"); + mUnits.reserve(trie_bytes / 4); + for (size_t pos = 4; pos < 4 + trie_bytes; pos += 4) + mUnits.push_back(read_u32(bytes, pos)); + mReplacements.assign(bytes.begin() + 4 + trie_bytes, bytes.end()); + if (mReplacements.back() != '\0') + throw std::runtime_error("Invalid Precompiled charsmap string pool"); + if (label(mUnits[0]) != 0 || (mUnits[0] & 256) != 0 || offset(mUnits[0]) == 0) + throw std::runtime_error("Invalid Precompiled charsmap root"); + for (size_t i = 0; i < mUnits.size(); ++i) { + const auto unit = mUnits[i]; + if (label(unit) <= 255) { + const auto child = i ^ offset(unit); + if ((child | 255) >= mUnits.size()) + throw std::runtime_error("Invalid Precompiled charsmap trie offset"); + if ((unit & 256) != 0 && (mUnits[child] & 0x80000000U) == 0) + throw std::runtime_error("Invalid Precompiled charsmap leaf"); + } else if ((unit & 0x7fffffffU) >= mReplacements.size()) { + throw std::runtime_error("Invalid Precompiled charsmap replacement offset"); + } + } + } + + std::string normalize(const std::string& text) const { + std::string result; + result.reserve(text.size()); + for (size_t pos = 0; pos < text.size();) { + size_t node = offset(mUnits[0]); + size_t matched = 0; + size_t replacement = 0; + for (size_t i = pos; i < text.size(); ++i) { + const auto byte = static_cast(text[i]); + if (byte == 0) + break; + node ^= byte; + const auto unit = mUnits[node]; + if (label(unit) != byte) + break; + node ^= offset(unit); + if ((unit & 256) != 0) { + matched = i - pos + 1; + replacement = mUnits[node] & 0x7fffffffU; + } + } + if (matched != 0) { + result.append(mReplacements.data() + replacement); + pos += matched; + } else { + const auto length = std::min(utf8_char_len(text, pos), text.size() - pos); + result.append(text, pos, length); + pos += length; + } + } + return result; + } + + private: + static uint32_t label(uint32_t unit) { return unit & 0x800000ffU; } + static uint32_t offset(uint32_t unit) { return (unit >> 10) << ((unit & 512) >> 6); } + + static uint32_t read_u32(const std::vector& bytes, size_t pos) { + return uint32_t(bytes[pos]) | (uint32_t(bytes[pos + 1]) << 8) | + (uint32_t(bytes[pos + 2]) << 16) | (uint32_t(bytes[pos + 3]) << 24); + } + + static std::vector decode_base64(const std::string& encoded) { + const std::string alphabet = + "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; + if (encoded.empty() || encoded.size() % 4 != 0) + throw std::runtime_error("Invalid Precompiled charsmap base64 length"); + std::vector bytes; + bytes.reserve(encoded.size() / 4 * 3); + for (size_t i = 0; i < encoded.size(); i += 4) { + uint32_t value = 0; + size_t padding = 0; + for (size_t j = 0; j < 4; ++j) { + const auto character = encoded[i + j]; + value <<= 6; + if (character == '=') { + if (i + 4 != encoded.size() || j < 2) + throw std::runtime_error("Invalid Precompiled charsmap base64 padding"); + ++padding; + } else { + const auto digit = alphabet.find(character); + if (padding != 0 || digit == std::string::npos) + throw std::runtime_error("Invalid Precompiled charsmap base64 character"); + value |= static_cast(digit); + } + } + if ((padding == 1 && (value & 255) != 0) || (padding == 2 && (value & 65535) != 0)) + throw std::runtime_error("Invalid Precompiled charsmap base64 trailing bits"); + bytes.push_back(static_cast(value >> 16)); + if (padding < 2) + bytes.push_back(static_cast(value >> 8)); + if (padding == 0) + bytes.push_back(static_cast(value)); + } + return bytes; + } + + std::vector mUnits; + std::string mReplacements; +}; + +std::string lowercase_ascii(std::string text) { + std::transform(text.begin(), text.end(), text.begin(), + [](unsigned char c) { return static_cast(std::tolower(c)); }); + return text; +} + +// ─── Metaspace Pre-tokenizer ─── +// Replaces spaces with ▁ (U+2581) and optionally adds prefix space. + +static const std::string kMetaspaceChar = "\xe2\x96\x81"; // ▁ U+2581 + +inline bool is_ws(char c) { + return c == ' ' || c == '\t' || c == '\n' || c == '\r'; +} + +std::vector whitespace_split(const std::string& text) { + std::vector words; + size_t i = 0; + while (i < text.size()) { + while (i < text.size() && is_ws(text[i])) + ++i; + if (i >= text.size()) + break; + size_t start = i; + while (i < text.size() && !is_ws(text[i])) + ++i; + words.push_back(text.substr(start, i - start)); + } + return words; +} + +[[maybe_unused]] std::string metaspace_pre_tokenize(const std::string& text, + bool add_prefix_space) { + std::string result; + result.reserve(text.size() + 8); + if (add_prefix_space && !text.empty() && text[0] != ' ') { + result += kMetaspaceChar; + } + for (size_t i = 0; i < text.size(); ++i) { + if (text[i] == ' ') { + result += kMetaspaceChar; + } else { + result += text[i]; + } + } + return result; +} + +// ─── Trie for efficient vocab prefix lookup ─── + +struct TrieNode { + std::unordered_map children; + int token_id = -1; // -1 = not a token end + float score = 0.0f; +}; + +class Trie { + public: + Trie() { mNodes.emplace_back(); } // root node + + void insert(const std::string& token, int id, float score) { + int node = 0; + for (char c : token) { + auto it = mNodes[node].children.find(c); + if (it == mNodes[node].children.end()) { + int next = static_cast(mNodes.size()); + mNodes.emplace_back(); + mNodes[node].children[c] = next; + node = next; + } else { + node = it->second; + } + } + mNodes[node].token_id = id; + mNodes[node].score = score; + } + + // Find all tokens that match a prefix of text starting at offset. + // Returns vector of (token_id, byte_length, score). + struct Match { + int token_id; + size_t length; + float score; + }; + + void find_prefixes(const std::string& text, size_t offset, std::vector& out) const { + out.clear(); + int node = 0; + for (size_t i = offset; i < text.size(); ++i) { + char c = text[i]; + auto it = mNodes[node].children.find(c); + if (it == mNodes[node].children.end()) + break; + node = it->second; + if (mNodes[node].token_id >= 0) { + out.push_back({mNodes[node].token_id, i - offset + 1, mNodes[node].score}); + } + } + } + + private: + std::vector mNodes; +}; + +// ─── Viterbi algorithm for Unigram tokenization ─── + +struct ViterbiNode { + float score; + int token_id; + size_t prev_pos; // byte position of previous node +}; + +std::vector viterbi_encode(const std::string& text, const Trie& trie, int32_t unk_id, + float unk_score) { + if (text.empty()) + return {}; + + size_t n = text.size(); + // best[i] = best path score to reach byte position i + std::vector best(n + 1, {-std::numeric_limits::infinity(), -1, 0}); + best[0].score = 0.0f; + + std::vector matches; + + for (size_t i = 0; i < n; ++i) { + if (best[i].score == -std::numeric_limits::infinity()) + continue; + + trie.find_prefixes(text, i, matches); + + for (const auto& m : matches) { + size_t end = i + m.length; + float new_score = best[i].score + m.score; + if (new_score > best[end].score) { + best[end].score = new_score; + best[end].token_id = m.token_id; + best[end].prev_pos = i; + } + } + + // Advance by one UTF-8 codepoint after emitting UNK. + size_t char_len = utf8_char_len(text, i); + size_t end = i + char_len; + if (end <= n) { + float new_score = best[i].score + unk_score; + if (new_score > best[end].score) { + best[end].score = new_score; + best[end].token_id = unk_id; + best[end].prev_pos = i; + } + } + } + + // Backtrack to find the best path + std::vector ids; + size_t pos = n; + while (pos > 0) { + if (best[pos].token_id < 0) { + // Unreachable after emitting UNK. + ids.push_back(unk_id); + break; + } + ids.push_back(best[pos].token_id); + pos = best[pos].prev_pos; + } + + std::reverse(ids.begin(), ids.end()); + return ids; +} + +// ─── UnigramTokenizer ─── + +class UnigramTokenizer final : public ITokenizer { + public: + static std::unique_ptr Create(const char* json_data, std::size_t json_size, + bool add_special_tokens) { + auto tok = std::unique_ptr(new UnigramTokenizer()); + tok->mAddSpecialTokens = add_special_tokens; + tok->parse_tokenizer_json(json_data, json_size); + return tok; + } + + std::vector encode(const std::string& text) const override { + if (text.empty()) { + return mAddSpecialTokens ? make_special_frame({}) : std::vector{}; + } + + // Normalize + std::string normalized = mPrecompiled ? mPrecompiled->normalize(text) : text; + if (mLowercase) + normalized = lowercase_ascii(std::move(normalized)); + + // Pre-tokenize: WhitespaceSplit → Metaspace + auto words = whitespace_split(normalized); + std::vector ids; + for (size_t i = 0; i < words.size(); ++i) { + // Metaspace: prepend ▁ to each word + std::string processed = kMetaspaceChar + words[i]; + auto word_ids = viterbi_encode(processed, mTrie, mUnkId, mUnkScore); + ids.insert(ids.end(), word_ids.begin(), word_ids.end()); + } + + if (mAddSpecialTokens) + ids = make_special_frame(ids); + return ids; + } + + std::string decode(const std::vector& ids) const override { + std::string result; + for (int32_t id : ids) { + if (mDecodeSkipIds.count(id)) + continue; + std::string token = token_for_id(id); + result += token; + } + // Remove metaspace characters and clean up + return decode_metaspace(result); + } + + int32_t id_for_token(std::string_view token) const override { + auto it = mTokenToId.find(std::string(token)); + return it != mTokenToId.end() ? it->second : -1; + } + + std::string token_for_id(int32_t id) const override { + if (id >= 0 && static_cast(id) < mIdToToken.size()) { + return mIdToToken[id]; + } + return ""; + } + + private: + UnigramTokenizer() = default; + + static std::string decode_metaspace(const std::string& text) { + std::string result; + size_t pos = 0; + while (pos < text.size()) { + if (pos + kMetaspaceChar.size() <= text.size() && + text.compare(pos, kMetaspaceChar.size(), kMetaspaceChar) == 0) { + if (!result.empty()) + result += ' '; + pos += kMetaspaceChar.size(); + } else { + result += text[pos]; + ++pos; + } + } + return result; + } + + std::vector make_special_frame(std::vector ids) const { + std::vector result; + if (mBosId >= 0) + result.push_back(mBosId); + result.insert(result.end(), ids.begin(), ids.end()); + if (mEosId >= 0) + result.push_back(mEosId); + return result; + } + + // ─── JSON parsing ─── + + void parse_tokenizer_json(const char* json_data, std::size_t json_size) { + nlohmann::json j; + try { + j = nlohmann::json::parse(json_data, json_data + json_size); + } catch (const std::exception& e) { + throw std::runtime_error(std::string("Failed to parse tokenizer.json: ") + e.what()); + } + + validate_model(j); + parse_vocab(j); + build_trie(); + parse_normalizer(j); + parse_pre_tokenizer(j); + parse_added_tokens(j); + parse_post_processor(j); + resolve_special_ids(); + } + + static void validate_model(const nlohmann::json& j) { + if (!j.contains("model")) + throw std::runtime_error("Invalid tokenizer.json: missing model"); + + auto& model = j["model"]; + + if (!model.contains("vocab") || !model["vocab"].is_array()) + throw std::runtime_error("Invalid tokenizer.json: model.vocab must be an array"); + } + + void parse_vocab(const nlohmann::json& j) { + auto& vocab = j["model"]["vocab"]; + mIdToToken.resize(vocab.size()); + mUnkId = j["model"].value("unk_id", 0); + + for (size_t i = 0; i < vocab.size(); ++i) { + auto& entry = vocab[i]; + std::string token = entry[0].get(); + float score = entry[1].get(); + + mIdToToken[i] = token; + mTokenToId[token] = static_cast(i); + mScores.push_back(score); + } + + // UNK score: must be worse than ANY real vocab token for Viterbi + float min_score = 0.0f; + for (float s : mScores) { + if (s < min_score) + min_score = s; + } + mUnkScore = min_score - 10.0f; + } + + void build_trie() { + for (size_t i = 0; i < mIdToToken.size(); ++i) { + const auto& token = mIdToToken[i]; + if (!token.empty()) { + mTrie.insert(token, static_cast(i), mScores[i]); + } + } + } + + void apply_normalizer_config(const nlohmann::json& norm) { + const std::string ntype = norm.value("type", ""); + if (ntype == "Precompiled") { + if (!norm.contains("precompiled_charsmap") || + !norm.at("precompiled_charsmap").is_string()) + throw std::runtime_error("Precompiled normalizer requires precompiled_charsmap"); + mPrecompiled = std::make_unique(norm.at("precompiled_charsmap")); + return; + } + if (ntype == "Lowercase") { + mLowercase = true; + return; + } + if (ntype == "Prepend") { + // Marian-style: prepend a string (e.g., "▁") to input + mAddPrefixSpace = true; + } + } + + void parse_normalizer(const nlohmann::json& j) { + if (!j.contains("normalizer") || j["normalizer"].is_null()) + return; + const auto& norm = j["normalizer"]; + if (norm.value("type", "") == "Sequence" && norm.contains("normalizers")) { + for (const auto& sub : norm["normalizers"]) + apply_normalizer_config(sub); + return; + } + apply_normalizer_config(norm); + } + + void parse_pre_tokenizer(const nlohmann::json& j) { + if (!j.contains("pre_tokenizer") || j["pre_tokenizer"].is_null()) + return; + auto& pt = j["pre_tokenizer"]; + std::string ptype = pt.value("type", ""); + + if (ptype == "Metaspace") { + mAddPrefixSpace = pt.value("add_prefix_space", true); + } else if (ptype == "Sequence") { + // Look for Metaspace inside the sequence + if (pt.contains("pretokenizers")) { + for (auto& sub : pt["pretokenizers"]) { + if (sub.value("type", "") == "Metaspace") { + mAddPrefixSpace = sub.value("add_prefix_space", true); + break; + } + } + } + } + } + + void parse_added_tokens(const nlohmann::json& j) { + if (!j.contains("added_tokens")) + return; + for (auto& tok : j["added_tokens"]) { + int32_t tok_id = tok.value("id", -1); + std::string content = tok.value("content", ""); + if (tok_id >= 0 && !content.empty()) { + if (static_cast(tok_id) >= mIdToToken.size()) { + mIdToToken.resize(static_cast(tok_id) + 1); + mScores.resize(static_cast(tok_id) + 1, 0.0f); + } + mIdToToken[tok_id] = content; + mTokenToId[content] = tok_id; + } + } + } + + // Extract BOS/EOS from TemplateProcessing "single" array + void extract_template_bos_eos(const nlohmann::json& pp) { + if (!pp.contains("single") || !pp["single"].is_array()) + return; + bool seen_sequence = false; + for (auto& item : pp["single"]) { + if (item.contains("Sequence")) { + seen_sequence = true; + continue; + } + if (!item.contains("SpecialToken")) + continue; + std::string tok_str = item["SpecialToken"].value("id", ""); + auto it = mTokenToId.find(tok_str); + if (it == mTokenToId.end()) + continue; + if (!seen_sequence && mBosId < 0) + mBosId = it->second; + else + mEosId = it->second; + } + } + + // Extract BOS/EOS from RobertaProcessing cls/sep arrays + static int32_t extract_pp_id(const nlohmann::json& pp, const char* key) { + if (pp.contains(key) && pp[key].is_array() && pp[key].size() >= 2) + return pp[key][1].get(); + return -1; + } + + void parse_post_processor(const nlohmann::json& j) { + if (!j.contains("post_processor") || j["post_processor"].is_null()) + return; + auto& pp = j["post_processor"]; + std::string ptype = pp.value("type", ""); + + if (ptype == "TemplateProcessing") + extract_template_bos_eos(pp); + if (ptype == "RobertaProcessing") { + mBosId = extract_pp_id(pp, "cls"); + mEosId = extract_pp_id(pp, "sep"); + } + } + + void resolve_special_ids() { + // Try common special-token names. + auto find_id = [this](const std::string& a, const std::string& b) -> int32_t { + auto it = mTokenToId.find(a); + if (it != mTokenToId.end()) + return it->second; + it = mTokenToId.find(b); + return it != mTokenToId.end() ? it->second : -1; + }; + + if (mBosId < 0) + mBosId = find_id("", "[CLS]"); + if (mEosId < 0) + mEosId = find_id("", "[SEP]"); + int32_t padId = find_id("", "[PAD]"); + + // Build decode skip set + for (int32_t id : {mBosId, mEosId, padId}) { + if (id >= 0) + mDecodeSkipIds.insert(id); + } + } + + // ─── Data members ─── + + std::vector mIdToToken; + std::vector mScores; + std::unordered_map mTokenToId; + std::unordered_set mDecodeSkipIds; + Trie mTrie; + + int32_t mUnkId = 0; + float mUnkScore = -100.0f; + bool mAddSpecialTokens = true; + std::unique_ptr mPrecompiled; + bool mLowercase = false; + bool mAddPrefixSpace = true; + + int32_t mBosId = -1; + int32_t mEosId = -1; +}; + +} // namespace + +std::unique_ptr CreateUnigramTokenizer(const char* tokenizer_json_data, + std::size_t tokenizer_json_size, + bool add_special_tokens) { + return UnigramTokenizer::Create(tokenizer_json_data, tokenizer_json_size, add_special_tokens); +} + +} // namespace trtmc::pegasus diff --git a/families/pegasus/support.py b/families/pegasus/support.py new file mode 100644 index 0000000000..d312df6792 --- /dev/null +++ b/families/pegasus/support.py @@ -0,0 +1,13 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Pegasus owns its sinusoidal positions and pre-normalized seq2seq graph.""" + +from tensorrt_model_connect.model_support import family_support + +describe = family_support( + model_types=("pegasus",), + tasks=("text_generation",), + default_task="text_generation", + default_precision="fp32", +) diff --git a/families/pegasus/tests/__init__.py b/families/pegasus/tests/__init__.py new file mode 100644 index 0000000000..52a7a9daf0 --- /dev/null +++ b/families/pegasus/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/pegasus/tests/cpp/e2e_consumer.cpp b/families/pegasus/tests/cpp/e2e_consumer.cpp new file mode 100644 index 0000000000..ab559b33c2 --- /dev/null +++ b/families/pegasus/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/pegasus/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: pegasus_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("Pegasus must expose the abstract text generation Task"); + const trtmc::BundleReader bundle(argv[1]); + const auto data = bundle.read_section("tokenizer.json"); + auto tokenizer = trtmc::pegasus::CreateUnigramTokenizer(data.data(), data.size(), false); + 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("Pegasus 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("Pegasus 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/pegasus/tests/cpp/test_tokenizer.cpp b/families/pegasus/tests/cpp/test_tokenizer.cpp new file mode 100644 index 0000000000..b3abfbbf8c --- /dev/null +++ b/families/pegasus/tests/cpp/test_tokenizer.cpp @@ -0,0 +1,27 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + */ + +#include "families/pegasus/runtime/tokenizer.h" + +#include +#include +#include + +int main() { + const std::string data = R"({ + "model": {"unk_id": 2, "vocab": [["",0],["",0],["",-10], + ["▁hello",-1],["▁world",-1],["!",-1]]}, + "pre_tokenizer": {"type":"Metaspace", "add_prefix_space":true}, + "added_tokens": [{"id":0,"content":"","special":true}, + {"id":1,"content":"","special":true}] + })"; + auto tokenizer = trtmc::pegasus::CreateUnigramTokenizer(data.data(), data.size(), false); + const std::vector expected{3, 4, 5}; + if (tokenizer->encode("hello world!") != expected || + tokenizer->decode(expected) != "hello world!" || + tokenizer->encode("").size() != 0 || tokenizer->id_for_token("") != 1) + throw std::runtime_error("Pegasus Unigram token IDs or framing changed"); + return 0; +} diff --git a/families/pegasus/tests/manifests/pegasus-xsum.json b/families/pegasus/tests/manifests/pegasus-xsum.json new file mode 100644 index 0000000000..075f87ef74 --- /dev/null +++ b/families/pegasus/tests/manifests/pegasus-xsum.json @@ -0,0 +1,23 @@ +{ + "name": "pegasus-xsum", + "hf_id": "google/pegasus-xsum", + "hf_revision": "8d8ffc158a3bee9fbb03afacdfc347c823c5ec8b", + "bundle": "pegasus-xsum.bundle", + "family": "pegasus", + "task": "text_generation", + "precision": "fp32", + "tensor_parallel_size": 1, + "max_sequence_length": 128, + "testcases": [ + { + "name": "pegasus-xsum-greedy", + "premerge": true, + "reference_precision": "fp32", + "max_new_tokens": 32, + "prompts": [ + "Scientists have discovered a new species of frog in the Amazon rainforest. The small green frog was found during a survey of remote rivers. Researchers say the discovery highlights the need to protect the region's forests.", + "A new public library opened in the city centre on Monday. The building contains more than 50000 books and offers free internet access. Local residents welcomed the new community space." + ] + } + ] +} diff --git a/families/pegasus/tests/test_e2e.py b/families/pegasus/tests/test_e2e.py new file mode 100644 index 0000000000..26ef949c8b --- /dev/null +++ b/families/pegasus/tests/test_e2e.py @@ -0,0 +1,132 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Pinned Pegasus 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/pegasus-xsum.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({"pegasus", 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 Pegasus E2E explicitly")] + parameters.append(pytest.param(case, id=case["name"], marks=marks)) + metafunc.parametrize("case", parameters) + + +def _checkpoint(): + path = os.environ.get("TRTMC_PEGASUS_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, PegasusForConditionalGeneration + + torch.backends.cuda.matmul.allow_tf32 = False + tokenizer = AutoTokenizer.from_pretrained(model_dir, trust_remote_code=False) + model = PegasusForConditionalGeneration.from_pretrained( + model_dir, dtype=torch.float32, attn_implementation="eager", trust_remote_code=False, + ).cuda().eval() + results = [] + for prompt in prompts: + inputs = tokenizer(prompt, max_length=MANIFEST["max_sequence_length"], truncation=True, + padding="max_length", return_tensors="pt").to("cuda") + source_ids = tokenizer(prompt, add_special_tokens=False)["input_ids"] + token = torch.tensor([[model.config.decoder_start_token_id]], device="cuda") + output_ids = [] + with torch.inference_mode(): + encoded = model.get_encoder()(**inputs) + cache = None + for _ in range(max_new_tokens): + result = model(encoder_outputs=encoded, attention_mask=inputs.attention_mask, + decoder_input_ids=token, past_key_values=cache, use_cache=True) + assert torch.isfinite(result.logits).all() + cache = result.past_key_values + next_id = int(result.logits[0, -1].argmax()) + if next_id == model.config.eos_token_id: + break + output_ids.append(next_id) + token.fill_(next_id) + results.append({"source_ids": source_ids, "token_ids": output_ids, + "text": tokenizer.decode(output_ids, skip_special_tokens=True, + clean_up_tokenization_spaces=False)}) + return results + + +def test_official_checkpoint_e2e(case, tmp_path): + assert case["reference_precision"] == "fp32" + model_dir = _checkpoint() + assert resolve_family(load_model_metadata(model_dir))[0] == "pegasus" + runtime = Path(os.environ["TRTMC_RUNTIME_ROOT"]) + binary = Path(os.environ["TRTMC_BINARY"]) + assert (runtime / "libtrtmc_model_pegasus.so").is_file() + assert (runtime / "libtrtmc_backend_trt.so").is_file() + consumer = runtime / "pegasus_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[2] + # 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/pegasus/tests/test_model.py b/families/pegasus/tests/test_model.py new file mode 100644 index 0000000000..6264b47f8c --- /dev/null +++ b/families/pegasus/tests/test_model.py @@ -0,0 +1,70 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Pegasus-specific identity, position layout, and build boundary regressions.""" + +from dataclasses import replace +import json +from pathlib import Path + +import numpy as np +import pytest + +from tensorrt_model_connect import BuildRequest +from tensorrt_model_connect.model_support import ModelMetadata, resolve_family +from families.pegasus.model import build, load_weights, sinusoidal_positions, validate_config + + +def test_unique_pegasus_owner(): + family, support = resolve_family(ModelMetadata( + config={"model_type": "pegasus", "architectures": ["PegasusForConditionalGeneration"]}, + model_index={})) + assert family == "pegasus" + assert support.tasks == ("text_generation",) + assert support.default_precision == "fp32" + + +@pytest.mark.parametrize("width", [7, 8, 1024]) +def test_positions_match_official_reference(width): + from transformers.models.pegasus.modeling_pegasus import PegasusSinusoidalPositionalEmbedding + embedding = PegasusSinusoidalPositionalEmbedding(16, width) + np.testing.assert_array_equal(sinusoidal_positions(16, width), embedding.create_weight().numpy()) + table = sinusoidal_positions(16, width) + np.testing.assert_array_equal(table[0, :(width + 1) // 2], 0) + np.testing.assert_array_equal(table[0, (width + 1) // 2:], 1) + + +def test_reject_unsupported_profile_before_weights(tmp_path): + request = BuildRequest(tmp_path, tmp_path / "model.bundle", "pegasus", "text_generation", "fp32") + for updates in ({"precision": "fp16"}, {"task": "encoding"}, {"quantization": "fp8"}, + {"tensor_parallel_size": 2}, {"dynamic_kv_cache": True}, {"max_batch_size": 2}): + with pytest.raises((ValueError, NotImplementedError)): + build(replace(request, **updates), None) + + +def test_legacy_checkpoint_serialization_and_tied_aliases(tmp_path): + import torch + + embedding = torch.arange(24, dtype=torch.float32).reshape(6, 4) + torch.save({"model.shared.weight": embedding}, tmp_path / "pytorch_model.bin", + _use_new_zipfile_serialization=False) + weights = load_weights(tmp_path, {"vocab_size": 6, "d_model": 4}) + np.testing.assert_array_equal(weights["model.shared.weight"], embedding.numpy()) + np.testing.assert_array_equal(weights["lm_head.weight"], embedding.numpy()) + np.testing.assert_array_equal(weights["final_logits_bias"], np.zeros((1, 6))) + + +def test_reject_wrong_geometry_and_position_overflow(tmp_path): + manifest = json.loads((Path(__file__).parent / "manifests/pegasus-xsum.json").read_text()) + assert len(manifest["hf_revision"]) == 40 + config = {"model_type": "pegasus", "d_model": 8, "vocab_size": 32, "encoder_layers": 1, + "decoder_layers": 1, "encoder_attention_heads": 2, "decoder_attention_heads": 2, + "encoder_ffn_dim": 16, "decoder_ffn_dim": 16, "max_position_embeddings": 8, + "activation_function": "relu"} + validate_config(config) + with pytest.raises(ValueError, match="heads must divide"): + validate_config({**config, "encoder_attention_heads": 3}) + (tmp_path / "config.json").write_text(json.dumps(config)) + with pytest.raises(ValueError, match="position capacity"): + build(BuildRequest(tmp_path, tmp_path / "out.bundle", "pegasus", "text_generation", "fp32", + max_sequence_length=9), None) From 8b70659a887562dab76eda8a8e6d2044437e8261 Mon Sep 17 00:00:00 2001 From: Will Guo Date: Wed, 2 Dec 2026 20:22:47 -0800 Subject: [PATCH 2/3] fix(pegasus): validate checkpoint and tokenizer inputs Signed-off-by: Will Guo --- families/pegasus/model.py | 18 ++++- families/pegasus/requirements.txt | 2 +- families/pegasus/runtime/plugin.cpp | 2 +- families/pegasus/runtime/tokenizer.h | 3 +- .../pegasus/runtime/unigram_tokenizer.cpp | 73 ++++++++++++------- families/pegasus/tests/cpp/e2e_consumer.cpp | 5 +- families/pegasus/tests/cpp/test_tokenizer.cpp | 29 +++++++- families/pegasus/tests/test_e2e.py | 16 ++-- families/pegasus/tests/test_model.py | 10 ++- 9 files changed, 113 insertions(+), 45 deletions(-) diff --git a/families/pegasus/model.py b/families/pegasus/model.py index 060110e4c5..515544f00a 100644 --- a/families/pegasus/model.py +++ b/families/pegasus/model.py @@ -41,19 +41,29 @@ def validate_config(config: dict) -> dict: raise ValueError(f"pegasus {side} heads must divide d_model") if config.get("activation_function", "gelu") != "relu": raise NotImplementedError("pegasus currently requires activation_function=relu") - if not config.get("scale_embedding", True): + if config.get("scale_embedding", False) is not True: raise NotImplementedError("pegasus currently requires scaled token embeddings") + config = dict(config) + for field, default in (("decoder_start_token_id", 0), ("eos_token_id", 1), ("pad_token_id", 0)): + token = config.setdefault(field, default) + if type(token) is not int or not 0 <= token < min(config["vocab_size"], 2**31): + raise ValueError(f"pegasus requires {field} to be an integer in the vocabulary") return config def load_weights(model_dir: Path, config: dict) -> dict[str, np.ndarray]: - """Read safetensors or the upstream legacy state dictionary without executable pickle.""" + """Read safetensors or a legacy state dictionary with the patched weights-only loader.""" safe = model_dir / "model.safetensors" if safe.is_file(): from safetensors.numpy import load_file source = load_file(str(safe)) else: import torch + from packaging.version import Version + + # GHSA-63cw-57p8-fm3p also affects the weights-only loader. + if Version(torch.__version__) < Version("2.10.0"): + raise RuntimeError("pegasus legacy checkpoint loading requires torch>=2.10.0") source = torch.load(model_dir / "pytorch_model.bin", map_location="cpu", weights_only=True) result = {} for name, value in source.items(): @@ -256,6 +266,6 @@ def build(request, writer): writer.add_json("runtime.json", { "schema_version": 1, "hidden_size": config["d_model"], "vocab_size": config["vocab_size"], "decoder_layers": config["decoder_layers"], "max_sequence_length": length, - "decoder_start_token_id": config.get("decoder_start_token_id", 0), - "eos_token_id": config.get("eos_token_id", 1), "pad_token_id": config.get("pad_token_id", 0), + "decoder_start_token_id": config["decoder_start_token_id"], + "eos_token_id": config["eos_token_id"], "pad_token_id": config["pad_token_id"], }) diff --git a/families/pegasus/requirements.txt b/families/pegasus/requirements.txt index 90b9e8b11d..8c72b662c3 100644 --- a/families/pegasus/requirements.txt +++ b/families/pegasus/requirements.txt @@ -1 +1 @@ -torch>=2.6 +torch>=2.10.0 diff --git a/families/pegasus/runtime/plugin.cpp b/families/pegasus/runtime/plugin.cpp index 9a5a8c9322..c178d633b7 100644 --- a/families/pegasus/runtime/plugin.cpp +++ b/families/pegasus/runtime/plugin.cpp @@ -49,7 +49,7 @@ extern "C" trtmc::ITask* trtmc_create_family(const trtmc::FamilyContext& context config.eos_token_id = json.at("eos_token_id").get(); config.pad_token_id = json.at("pad_token_id").get(); const auto tokenizer_data = pg::section(context.reader, "tokenizer.json"); - auto tokenizer = pg::CreateUnigramTokenizer(tokenizer_data.data(), tokenizer_data.size(), false); + auto tokenizer = pg::CreateUnigramTokenizer(tokenizer_data.data(), tokenizer_data.size(), config.vocab_size, false); return new pg::Pipeline(pg::engine(context, "encoder.plan"), pg::engine(context, "decoder.plan"), std::move(tokenizer), config); } diff --git a/families/pegasus/runtime/tokenizer.h b/families/pegasus/runtime/tokenizer.h index 9d014488d3..1631556a72 100644 --- a/families/pegasus/runtime/tokenizer.h +++ b/families/pegasus/runtime/tokenizer.h @@ -25,6 +25,7 @@ class ITokenizer { std::unique_ptr CreateUnigramTokenizer(const char* tokenizer_json_data, std::size_t tokenizer_json_size, - bool add_special_tokens = true); + std::int32_t vocab_size, + bool add_special_tokens); } // namespace trtmc::pegasus diff --git a/families/pegasus/runtime/unigram_tokenizer.cpp b/families/pegasus/runtime/unigram_tokenizer.cpp index 9326d785ff..b0ea04c96d 100644 --- a/families/pegasus/runtime/unigram_tokenizer.cpp +++ b/families/pegasus/runtime/unigram_tokenizer.cpp @@ -312,7 +312,9 @@ std::vector viterbi_encode(const std::string& text, const Trie& trie, i ids.push_back(unk_id); break; } - ids.push_back(best[pos].token_id); + const auto id = best[pos].token_id; + if (id != unk_id || ids.empty() || ids.back() != unk_id) + ids.push_back(id); pos = best[pos].prev_pos; } @@ -325,10 +327,10 @@ std::vector viterbi_encode(const std::string& text, const Trie& trie, i class UnigramTokenizer final : public ITokenizer { public: static std::unique_ptr Create(const char* json_data, std::size_t json_size, - bool add_special_tokens) { + int32_t vocab_size, bool add_special_tokens) { auto tok = std::unique_ptr(new UnigramTokenizer()); tok->mAddSpecialTokens = add_special_tokens; - tok->parse_tokenizer_json(json_data, json_size); + tok->parse_tokenizer_json(json_data, json_size, vocab_size); return tok; } @@ -413,7 +415,7 @@ class UnigramTokenizer final : public ITokenizer { // ─── JSON parsing ─── - void parse_tokenizer_json(const char* json_data, std::size_t json_size) { + void parse_tokenizer_json(const char* json_data, std::size_t json_size, int32_t vocab_size) { nlohmann::json j; try { j = nlohmann::json::parse(json_data, json_data + json_size); @@ -422,11 +424,11 @@ class UnigramTokenizer final : public ITokenizer { } validate_model(j); - parse_vocab(j); + parse_vocab(j, vocab_size); build_trie(); parse_normalizer(j); parse_pre_tokenizer(j); - parse_added_tokens(j); + parse_added_tokens(j, vocab_size); parse_post_processor(j); resolve_special_ids(); } @@ -441,15 +443,25 @@ class UnigramTokenizer final : public ITokenizer { throw std::runtime_error("Invalid tokenizer.json: model.vocab must be an array"); } - void parse_vocab(const nlohmann::json& j) { + void parse_vocab(const nlohmann::json& j, int32_t vocab_size) { auto& vocab = j["model"]["vocab"]; + if (vocab_size <= 0 || vocab.empty() || vocab.size() > static_cast(vocab_size)) + throw std::runtime_error("Pegasus Unigram vocabulary exceeds the model vocabulary or is empty"); + const auto unk_id = j["model"].value("unk_id", nlohmann::json(0)); + if (!unk_id.is_number_integer() || unk_id.get() >= vocab.size()) + throw std::runtime_error("Pegasus Unigram unk_id is outside the tokenizer vocabulary"); + mUnkId = unk_id.get(); mIdToToken.resize(vocab.size()); - mUnkId = j["model"].value("unk_id", 0); for (size_t i = 0; i < vocab.size(); ++i) { auto& entry = vocab[i]; + if (!entry.is_array() || entry.size() != 2 || !entry[0].is_string() || + !entry[1].is_number()) + throw std::runtime_error("Invalid Pegasus Unigram vocabulary row " + std::to_string(i)); std::string token = entry[0].get(); float score = entry[1].get(); + if (!std::isfinite(score)) + throw std::runtime_error("Invalid Pegasus Unigram score at row " + std::to_string(i)); mIdToToken[i] = token; mTokenToId[token] = static_cast(i); @@ -487,10 +499,6 @@ class UnigramTokenizer final : public ITokenizer { mLowercase = true; return; } - if (ntype == "Prepend") { - // Marian-style: prepend a string (e.g., "▁") to input - mAddPrefixSpace = true; - } } void parse_normalizer(const nlohmann::json& j) { @@ -505,6 +513,13 @@ class UnigramTokenizer final : public ITokenizer { apply_normalizer_config(norm); } + static void validate_metaspace(const nlohmann::json& metaspace) { + if (metaspace.value("replacement", kMetaspaceChar) != kMetaspaceChar || + metaspace.value("prepend_scheme", std::string("always")) != "always" || + !metaspace.value("add_prefix_space", true)) + throw std::runtime_error("Pegasus requires prefix-enabled Metaspace with the default replacement"); + } + void parse_pre_tokenizer(const nlohmann::json& j) { if (!j.contains("pre_tokenizer") || j["pre_tokenizer"].is_null()) return; @@ -512,13 +527,13 @@ class UnigramTokenizer final : public ITokenizer { std::string ptype = pt.value("type", ""); if (ptype == "Metaspace") { - mAddPrefixSpace = pt.value("add_prefix_space", true); + validate_metaspace(pt); } else if (ptype == "Sequence") { // Look for Metaspace inside the sequence if (pt.contains("pretokenizers")) { for (auto& sub : pt["pretokenizers"]) { if (sub.value("type", "") == "Metaspace") { - mAddPrefixSpace = sub.value("add_prefix_space", true); + validate_metaspace(sub); break; } } @@ -526,20 +541,23 @@ class UnigramTokenizer final : public ITokenizer { } } - void parse_added_tokens(const nlohmann::json& j) { + void parse_added_tokens(const nlohmann::json& j, int32_t vocab_size) { if (!j.contains("added_tokens")) return; for (auto& tok : j["added_tokens"]) { - int32_t tok_id = tok.value("id", -1); - std::string content = tok.value("content", ""); - if (tok_id >= 0 && !content.empty()) { - if (static_cast(tok_id) >= mIdToToken.size()) { - mIdToToken.resize(static_cast(tok_id) + 1); - mScores.resize(static_cast(tok_id) + 1, 0.0f); - } - mIdToToken[tok_id] = content; - mTokenToId[content] = tok_id; - } + const auto& id = tok.at("id"); + if (!id.is_number_integer() || id.get() >= static_cast(vocab_size)) + throw std::runtime_error("Pegasus added token ID is outside the model vocabulary"); + const auto tok_id = id.get(); + const auto content = tok.at("content").get(); + if (content.empty()) + throw std::runtime_error("Pegasus added token content must be nonempty"); + if (static_cast(tok_id) >= mIdToToken.size()) + mIdToToken.resize(static_cast(tok_id) + 1); + mIdToToken[tok_id] = content; + mTokenToId[content] = tok_id; + if (tok.value("special", false)) + mDecodeSkipIds.insert(tok_id); } } @@ -623,7 +641,6 @@ class UnigramTokenizer final : public ITokenizer { bool mAddSpecialTokens = true; std::unique_ptr mPrecompiled; bool mLowercase = false; - bool mAddPrefixSpace = true; int32_t mBosId = -1; int32_t mEosId = -1; @@ -633,8 +650,8 @@ class UnigramTokenizer final : public ITokenizer { std::unique_ptr CreateUnigramTokenizer(const char* tokenizer_json_data, std::size_t tokenizer_json_size, - bool add_special_tokens) { - return UnigramTokenizer::Create(tokenizer_json_data, tokenizer_json_size, add_special_tokens); + int32_t vocab_size, bool add_special_tokens) { + return UnigramTokenizer::Create(tokenizer_json_data, tokenizer_json_size, vocab_size, add_special_tokens); } } // namespace trtmc::pegasus diff --git a/families/pegasus/tests/cpp/e2e_consumer.cpp b/families/pegasus/tests/cpp/e2e_consumer.cpp index ab559b33c2..d5037c31b1 100644 --- a/families/pegasus/tests/cpp/e2e_consumer.cpp +++ b/families/pegasus/tests/cpp/e2e_consumer.cpp @@ -24,7 +24,10 @@ int main(int argc, char** argv) { throw std::runtime_error("Pegasus must expose the abstract text generation Task"); const trtmc::BundleReader bundle(argv[1]); const auto data = bundle.read_section("tokenizer.json"); - auto tokenizer = trtmc::pegasus::CreateUnigramTokenizer(data.data(), data.size(), false); + const auto config_data = bundle.read_section("runtime.json"); + const auto config = nlohmann::json::parse(config_data.begin(), config_data.end()); + auto tokenizer = trtmc::pegasus::CreateUnigramTokenizer( + data.data(), data.size(), config.at("vocab_size").get(), false); nlohmann::json results = nlohmann::json::array(); for (const auto& request : requests) { trtmc::TextGenerationConfig config; diff --git a/families/pegasus/tests/cpp/test_tokenizer.cpp b/families/pegasus/tests/cpp/test_tokenizer.cpp index b3abfbbf8c..2505944e3c 100644 --- a/families/pegasus/tests/cpp/test_tokenizer.cpp +++ b/families/pegasus/tests/cpp/test_tokenizer.cpp @@ -5,6 +5,7 @@ #include "families/pegasus/runtime/tokenizer.h" +#include #include #include #include @@ -15,13 +16,37 @@ int main() { ["▁hello",-1],["▁world",-1],["!",-1]]}, "pre_tokenizer": {"type":"Metaspace", "add_prefix_space":true}, "added_tokens": [{"id":0,"content":"","special":true}, - {"id":1,"content":"","special":true}] + {"id":1,"content":"","special":true}, + {"id":6,"content":"","special":true}, + {"id":7,"content":"extra","special":false}] })"; - auto tokenizer = trtmc::pegasus::CreateUnigramTokenizer(data.data(), data.size(), false); + auto tokenizer = trtmc::pegasus::CreateUnigramTokenizer(data.data(), data.size(), 8, false); const std::vector expected{3, 4, 5}; if (tokenizer->encode("hello world!") != expected || tokenizer->decode(expected) != "hello world!" || tokenizer->encode("").size() != 0 || tokenizer->id_for_token("") != 1) throw std::runtime_error("Pegasus Unigram token IDs or framing changed"); + if (tokenizer->encode("hello😀😀!😀😀") != std::vector{3, 2, 5, 2} || + tokenizer->decode({3, 6, 7}) != "helloextra") + throw std::runtime_error("Pegasus Unigram unknown spans or added tokens changed"); + + const auto reject = [](const nlohmann::json& fixture) { + const auto text = fixture.dump(); + try { + trtmc::pegasus::CreateUnigramTokenizer(text.data(), text.size(), 8, false); + } catch (const std::runtime_error&) { + return; + } + throw std::runtime_error("Invalid Pegasus tokenizer was accepted"); + }; + auto invalid = nlohmann::json::parse(data); + invalid["model"]["vocab"][0] = {""}; + reject(invalid); + invalid = nlohmann::json::parse(data); + invalid["added_tokens"][0]["id"] = 4294967296ULL; + reject(invalid); + invalid = nlohmann::json::parse(data); + invalid["pre_tokenizer"]["prepend_scheme"] = "never"; + reject(invalid); return 0; } diff --git a/families/pegasus/tests/test_e2e.py b/families/pegasus/tests/test_e2e.py index 26ef949c8b..3cd314b142 100644 --- a/families/pegasus/tests/test_e2e.py +++ b/families/pegasus/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"): @@ -38,8 +38,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 Pegasus 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(): @@ -86,7 +86,8 @@ def _reference(model_dir, prompts, max_new_tokens): return results -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" model_dir = _checkpoint() assert resolve_family(load_model_metadata(model_dir))[0] == "pegasus" @@ -94,7 +95,12 @@ def test_official_checkpoint_e2e(case, tmp_path): binary = Path(os.environ["TRTMC_BINARY"]) assert (runtime / "libtrtmc_model_pegasus.so").is_file() assert (runtime / "libtrtmc_backend_trt.so").is_file() - consumer = runtime / "pegasus_e2e" + native_build = Path(os.environ["TRTMC_NATIVE_BUILD_DIR"]) + command = ["cmake", "--build", str(native_build), "--target", "pegasus_e2e"] + with evidence_stage("native_helpers"): + record_evidence("commands", {"argv": command}) + subprocess.run(command, check=True, timeout=1800) + consumer = native_build / "pegasus_e2e" assert consumer.is_file() prompts = [*case["prompts"], case["prompts"][0]] record_evidence("inputs", {"manifest": MANIFEST, "case": case}) diff --git a/families/pegasus/tests/test_model.py b/families/pegasus/tests/test_model.py index 6264b47f8c..a8ecb1dcb6 100644 --- a/families/pegasus/tests/test_model.py +++ b/families/pegasus/tests/test_model.py @@ -60,8 +60,14 @@ def test_reject_wrong_geometry_and_position_overflow(tmp_path): config = {"model_type": "pegasus", "d_model": 8, "vocab_size": 32, "encoder_layers": 1, "decoder_layers": 1, "encoder_attention_heads": 2, "decoder_attention_heads": 2, "encoder_ffn_dim": 16, "decoder_ffn_dim": 16, "max_position_embeddings": 8, - "activation_function": "relu"} - validate_config(config) + "activation_function": "relu", "scale_embedding": True} + assert validate_config({**config, "eos_token_id": 1})["eos_token_id"] == 1 + with pytest.raises(NotImplementedError, match="scaled token embeddings"): + validate_config({key: value for key, value in config.items() if key != "scale_embedding"}) + for field in ("decoder_start_token_id", "eos_token_id", "pad_token_id"): + for invalid in ([1], True, -1, config["vocab_size"]): + with pytest.raises(ValueError, match=field): + validate_config({**config, field: invalid}) with pytest.raises(ValueError, match="heads must divide"): validate_config({**config, "encoder_attention_heads": 3}) (tmp_path / "config.json").write_text(json.dumps(config)) From 8582e11d2822c3fba9a9750175c6fb4dbe320833 Mon Sep 17 00:00:00 2001 From: Will Guo Date: Wed, 2 Dec 2026 20:25:41 -0800 Subject: [PATCH 3/3] test(pegasus): distinguish bundle and generation configuration Signed-off-by: Will Guo --- families/pegasus/tests/cpp/e2e_consumer.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/families/pegasus/tests/cpp/e2e_consumer.cpp b/families/pegasus/tests/cpp/e2e_consumer.cpp index 58d945b64c..976f4f6691 100644 --- a/families/pegasus/tests/cpp/e2e_consumer.cpp +++ b/families/pegasus/tests/cpp/e2e_consumer.cpp @@ -25,9 +25,9 @@ int main(int argc, char** argv) { const trtmc::BundleReader bundle(argv[1]); const auto data = bundle.read_section("tokenizer.json"); const auto config_data = bundle.read_section("runtime.json"); - const auto config = nlohmann::json::parse(config_data.begin(), config_data.end()); + const auto bundle_config = nlohmann::json::parse(config_data.begin(), config_data.end()); auto tokenizer = trtmc::pegasus::CreateUnigramTokenizer( - data.data(), data.size(), config.at("vocab_size").get(), false); + data.data(), data.size(), bundle_config.at("vocab_size").get(), false); nlohmann::json results = nlohmann::json::array(); for (const auto& request : requests) { trtmc::TextGenerationConfig config;