diff --git a/core/api/include/trtmc/features.h b/core/api/include/trtmc/features.h index 092282fade..1c7fd6afe7 100644 --- a/core/api/include/trtmc/features.h +++ b/core/api/include/trtmc/features.h @@ -729,6 +729,25 @@ typedef struct { trtmc_document_token_features_view_v1*, trtmc_error**); } trtmc_document_words_to_token_features_api_v1; +/* End-exclusive UTF-8 byte offsets into the supplied text. Entity spans are + * nonempty, disjoint and retain subject/object roles regardless of text order. */ +typedef struct { + uint64_t begin, end; +} trtmc_entity_byte_span_v1; +typedef struct { + trtmc_string_view text; + trtmc_entity_byte_span_v1 subject, object; +} trtmc_text_entity_pair_to_relation_scores_request_v1; +#define TRTMC_TASK_TEXT_ENTITY_PAIR_TO_RELATION_SCORES "text_entity_pair_to_relation_scores" +typedef struct { + trtmc_api_header header; + trtmc_status(TRTMC_CALL* run)(trtmc_model*, + const trtmc_text_entity_pair_to_relation_scores_request_v1*, + const trtmc_config_view_v1*, trtmc_result**, trtmc_error**); + trtmc_status(TRTMC_CALL* result_view)(const trtmc_result*, trtmc_label_scores_view_v1*, + trtmc_error**); +} trtmc_text_entity_pair_to_relation_scores_api_v1; + #ifdef __cplusplus } #endif diff --git a/core/api/include/trtmc/features.hpp b/core/api/include/trtmc/features.hpp index a65d5b49f2..0ea1e9c841 100644 --- a/core/api/include/trtmc/features.hpp +++ b/core/api/include/trtmc/features.hpp @@ -76,6 +76,11 @@ struct TextPairToPretrainingRelationScoresRequest { std::string first; std::string second; }; +using EntityByteSpan = trtmc_entity_byte_span_v1; +struct TextEntityPairToRelationScoresRequest { + std::string text; + EntityByteSpan subject, object; +}; struct TextToReplacedTokenScoresRequest { TextSource text; }; @@ -588,6 +593,10 @@ feature_request(const ImageToClassScoresRequest& input) { // The template only repeats ownership and C-table invocation. Each trait below // fixes a distinct request, result, interface ID and table; no runtime type guessing. +inline auto feature_request(const TextEntityPairToRelationScoresRequest& input) { + return trtmc_text_entity_pair_to_relation_scores_request_v1{c_string(input.text), input.subject, + input.object}; +} template class FeatureTask { public: @@ -674,6 +683,12 @@ struct TextPairToPretrainingRelationScoresTraits { using Result = LabelScoresResult; using Table = trtmc_text_pair_to_pretraining_relation_scores_api_v1; }; +struct TextEntityPairToRelationScoresTraits { + static constexpr std::string_view kTask = TRTMC_TASK_TEXT_ENTITY_PAIR_TO_RELATION_SCORES; + using Request = TextEntityPairToRelationScoresRequest; + using Result = LabelScoresResult; + using Table = trtmc_text_entity_pair_to_relation_scores_api_v1; +}; struct TextToReplacedTokenScoresTraits { static constexpr std::string_view kTask = TRTMC_TASK_TEXT_TO_REPLACED_TOKEN_SCORES; using Request = TextToReplacedTokenScoresRequest; @@ -764,6 +779,8 @@ using TitleBodyToEmbedding = detail::FeatureTask; using TextPairToPretrainingRelationScores = detail::FeatureTask; +using TextEntityPairToRelationScores = + detail::FeatureTask; using TextToReplacedTokenScores = detail::FeatureTask; using TextPredictionPositionsToTokenScores = detail::FeatureTask; diff --git a/core/api/runtime/features.cpp b/core/api/runtime/features.cpp index 27d7c92f24..236b624084 100644 --- a/core/api/runtime/features.cpp +++ b/core/api/runtime/features.cpp @@ -545,6 +545,26 @@ const trtmc_document_words_to_token_features_api_v1 document_features_api{ document_features_run, result_view}; +internal::TextEntityPairToRelationScoresRequest +convert(const trtmc_text_entity_pair_to_relation_scores_request_v1& input) { + const auto text = string_view(input.text); + const auto span = [&](const trtmc_entity_byte_span_v1& value) { + require(value.begin < value.end && value.end <= text.size(), + "entity byte span is empty or out of range"); + const auto boundary = [&](uint64_t offset) { + return offset == text.size() || + (static_cast(text[offset]) & 0xC0) != 0x80; + }; + require(boundary(value.begin) && boundary(value.end), + "entity byte span splits a UTF-8 code point"); + return internal::EntityByteSpan{value.begin, value.end}; + }; + const auto subject = span(input.subject), object = span(input.object); + require(subject.end <= object.begin || object.end <= subject.begin, + "entity spans must be disjoint"); + return {text, subject, object}; +} + template trtmc_status TRTMC_CALL run(trtmc_model* model, const Request* input, const trtmc_config_view_v1* config, trtmc_result** out, @@ -566,6 +586,12 @@ trtmc_status TRTMC_CALL run(trtmc_model* model, const Request* input, "pretraining relation scores require explicit relation labels"); if constexpr (std::is_same_v) require_class_identity(result); + if constexpr (std::is_same_v) { + result_require(!result.scores.empty() && result.labels.size() == result.scores.size(), + "entity relation scores require one explicit label per score"); + for (const auto& label : result.labels) + result_require(!label.empty(), "entity relation labels must be nonempty"); + } *out = make_result(std::move(result)); }); } @@ -1052,6 +1078,12 @@ const trtmc_spatial_features_to_class_scores_api_v1 spatial_features_api = { {1, 0, sizeof(spatial_features_api)}, run, view}; static_assert(offsetof(trtmc_spatial_features_to_class_scores_api_v1, header) == 0); +const trtmc_text_entity_pair_to_relation_scores_api_v1 entity_relation_api{ + {1, 0, sizeof(entity_relation_api)}, + run, + label_scores_result_view}; + const TaskBinding bindings[] = { {internal::ISpatialFeaturesToClassScores::kTask, 1, 0, &spatial_features_api.header}, {internal::IVideoToTokenFeatures::kTask, 1, 0, &video_to_token_features_api.header}, @@ -1080,6 +1112,7 @@ const TaskBinding bindings[] = { {internal::IMaskedTextToTokenScores::kTask, 1, 0, &masked_text_to_token_scores_api.header}, {internal::ITextPairToPretrainingRelationScores::kTask, 1, 0, &text_pair_to_pretraining_relation_scores_api.header}, + {internal::ITextEntityPairToRelationScores::kTask, 1, 0, &entity_relation_api.header}, {internal::ITextToReplacedTokenScores::kTask, 1, 0, &text_to_replaced_token_scores_api.header}, {internal::ITextPredictionPositionsToTokenScores::kTask, 1, 0, &text_prediction_positions_to_token_scores_api.header}, diff --git a/core/api/tests/features_family.cpp b/core/api/tests/features_family.cpp index 60e5352569..2d83009826 100644 --- a/core/api/tests/features_family.cpp +++ b/core/api/tests/features_family.cpp @@ -707,6 +707,35 @@ class DocumentFeaturesFixture final : public IModel, public IDocumentWordsToToke std::string mode_; }; +class EntityRelationFixture final : public IModel, public ITextEntityPairToRelationScores { + public: + explicit EntityRelationFixture(std::string mode) : mode_(std::move(mode)) {} + const char* task() const noexcept override { return mode_.c_str(); } + std::vector task_bindings() override { + return {bind(*this)}; + } + LabelScoresResult run(const TextEntityPairToRelationScoresRequest& input, + ConfigView config) override { + validate_config({}, config); + LabelScoresResult result; + result.scores = {-1, + 2, + static_cast(input.subject.begin), + static_cast(input.subject.end), + static_cast(input.object.begin), + static_cast(input.object.end)}; + result.labels = {"unrelated", "knows", "subject_begin", + "subject_end", "object_begin", "object_end"}; + result.kind = ScoreKind::Logit; + if (mode_ == "entity_bad_labels") + result.labels.clear(); + return result; + } + + private: + std::string mode_; +}; + class MissingFixture final : public IModel { public: const char* task() const noexcept override { return "missing"; } @@ -805,6 +834,9 @@ extern "C" trtmc::ITask* trtmc_create_family(const trtmc::FamilyContext& context if (context.reader.info().task.rfind("document_", 0) == 0) return new DocumentFeaturesFixture(context.reader.info().task); + + if (context.reader.info().task.rfind("entity_", 0) == 0) + return new EntityRelationFixture(context.reader.info().task); if (context.reader.info().task == "missing") return new MissingFixture; if (context.reader.info().task.rfind("relevance_video", 0) == 0) diff --git a/core/api/tests/features_test.cpp b/core/api/tests/features_test.cpp index 8fa7f8b43a..790750ac88 100644 --- a/core/api/tests/features_test.cpp +++ b/core/api/tests/features_test.cpp @@ -6,6 +6,7 @@ #include "trtmc/features.hpp" #include +#include #include #include #include @@ -238,6 +239,60 @@ void document_features(const std::filesystem::path& root, const trtmc::LoadOptio std::filesystem::remove(path); } +void entity_relations(const std::filesystem::path& root, const trtmc::LoadOptions& options) { + using namespace trtmc; + const auto path = root / "entity_relations.bundle"; + bundle(path, "entity_relations"); + const TextEntityPairToRelationScoresRequest input{"Éva met Zoë.", {0, 4}, {9, 13}}; + const auto model = Model::load(path.string(), options); + const auto task = model.task(); + auto result = + Model::load(path.string(), options).task().run(input); + constexpr std::array labels{"unrelated", "knows", "subject_begin", + "subject_end", "object_begin", "object_end"}; + constexpr std::array scores{-1.0F, 2.0F, 0.0F, 4.0F, 9.0F, 13.0F}; + const auto matches = [&](const auto& output, const std::array& expected) { + const auto returned_labels = output.labels(); + const auto returned_scores = output.scores(); + return std::equal(labels.begin(), labels.end(), returned_labels.begin(), + returned_labels.end()) && + std::equal(expected.begin(), expected.end(), returned_scores.begin(), + returned_scores.end()) && + output.kind() == TRTMC_SCORE_LOGIT; + }; + check(matches(result, scores), + "entity relation scores retain named classes, raw logits and UTF-8 byte roles"); + auto swapped = input; + std::swap(swapped.subject, swapped.object); + const auto reversed = task.run(swapped); + check(matches(reversed, {-1.0F, 2.0F, 9.0F, 13.0F, 0.0F, 4.0F}), + "subject and object roles survive reversed text order"); + check(model.tasks().size() == 1 && !model.supports(), + "entity relations are independent of document pair pretraining scores"); + auto bad = input; + bad.subject.begin = 1; + rejects([&] { task.run(bad); }, TRTMC_INVALID_ARGUMENT, "entity span splitting UTF-8 rejected"); + bad = input; + bad.object.end = 100; + rejects([&] { task.run(bad); }, TRTMC_INVALID_ARGUMENT, "out-of-range entity span rejected"); + bad = input; + bad.object = {3, 7}; + rejects([&] { task.run(bad); }, TRTMC_INVALID_ARGUMENT, "overlapping entity spans rejected"); + rejects([&] { task.run(input, {{"threshold", 0.5}}); }, TRTMC_INVALID_CONFIG, + "undeclared relation control rejected"); + const auto broken = root / "entity_bad_labels.bundle"; + bundle(broken, "entity_bad_labels"); + rejects( + [&] { + Model::load(broken.string(), options).task().run(input); + }, + TRTMC_INTERNAL_ERROR, "entity relation output requires complete label identity"); + auto moved = std::move(result); + check(matches(moved, scores), "entity relation result retains owned labels and scores"); + std::filesystem::remove(path); + std::filesystem::remove(broken); +} + template void rejects_index(Function function, trtmc_status code, size_t index, const char* message) { bool matched = false; @@ -717,6 +772,8 @@ int main(int argc, char** argv) { spectral_features(root, options); document_features(root, options); + + entity_relations(root, options); global_pooled_contracts(root, options); for (const std::string mode : {"all", "none", "missing", "bad_shape", "bad_count", "missing_pooler", diff --git a/core/runtime/include/trtmc/internal/features.h b/core/runtime/include/trtmc/internal/features.h index 7518624b1c..3a35ef0923 100644 --- a/core/runtime/include/trtmc/internal/features.h +++ b/core/runtime/include/trtmc/internal/features.h @@ -640,4 +640,21 @@ class IDocumentWordsToTokenFeatures { ConfigView) = 0; }; +// End-exclusive UTF-8 byte offsets. Subject and object are ordered semantic +// roles, even when the object precedes the subject in the text. +struct EntityByteSpan { + uint64_t begin{0}, end{0}; +}; +struct TextEntityPairToRelationScoresRequest { + std::string_view text; + EntityByteSpan subject, object; +}; +class ITextEntityPairToRelationScores { + public: + using TaskInterface = ITextEntityPairToRelationScores; + static constexpr std::string_view kTask = "text_entity_pair_to_relation_scores"; + virtual ~ITextEntityPairToRelationScores() = default; + virtual LabelScoresResult run(const TextEntityPairToRelationScoresRequest&, ConfigView) = 0; +}; + } // namespace trtmc::internal diff --git a/families/luke/__init__.py b/families/luke/__init__.py new file mode 100644 index 0000000000..fdd33e7eed --- /dev/null +++ b/families/luke/__init__.py @@ -0,0 +1,4 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""luke family package.""" diff --git a/families/luke/graph.py b/families/luke/graph.py new file mode 100644 index 0000000000..14fa1ae7a7 --- /dev/null +++ b/families/luke/graph.py @@ -0,0 +1,78 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""TensorRT graph operations for the Wav2Vec2Bert codec decoder.""" + +from __future__ import annotations + +import numpy as np +import tensorrt as trt + + +def add_constant(network, shape, values, dtype=np.float32): + data = np.ascontiguousarray(np.asarray(values, dtype=dtype).reshape(shape)) + return network.add_constant(shape, data).get_output(0) + + +def add_sum(network, left, right): + return network.add_elementwise(left, right, trt.ElementWiseOperation.SUM).get_output(0) + + +def _as_float32(network, tensor): + """Cast to fp32 for a reduction's statistics, and remember the way back.""" + if tensor.dtype == trt.float32: + return tensor, None + return network.add_cast(tensor, trt.float32).get_output(0), tensor.dtype + + +def _restore_dtype(network, tensor, original): + if original is None: + return tensor + return network.add_cast(tensor, original).get_output(0) + + +def add_layer_norm(network, inp, gamma, beta, eps): + source, original = _as_float32(network, inp) + axis = len(inp.shape) - 1 + mean = network.add_reduce(source, trt.ReduceOperation.AVG, 1 << axis, True).get_output(0) + centred = network.add_elementwise(source, mean, trt.ElementWiseOperation.SUB).get_output(0) + square = network.add_elementwise(centred, centred, trt.ElementWiseOperation.PROD).get_output(0) + variance = network.add_reduce(square, trt.ReduceOperation.AVG, 1 << axis, True).get_output(0) + width = int(inp.shape[-1]) + epsilon = add_constant(network, tuple([1] * len(inp.shape)), np.full((1,), eps)) + shifted = network.add_elementwise(variance, epsilon, trt.ElementWiseOperation.SUM).get_output(0) + deviation = network.add_unary(shifted, trt.UnaryOperation.SQRT).get_output(0) + normed = network.add_elementwise(centred, deviation, trt.ElementWiseOperation.DIV).get_output(0) + shape = tuple([1] * (len(inp.shape) - 1) + [width]) + scaled = network.add_elementwise( + normed, add_constant(network, shape, gamma), trt.ElementWiseOperation.PROD + ).get_output(0) + affine = network.add_elementwise( + scaled, add_constant(network, shape, beta), trt.ElementWiseOperation.SUM + ).get_output(0) + return _restore_dtype(network, affine, original) + + +def add_linear(network, inp, weight, bias=None, dtype=np.float32, *, matmul=None): + """y = x @ W^T + b, matching torch.nn.Linear's weight layout. + + ``matmul`` (``(network, input) -> output``) replaces the matrix product, which is how + a quantized projection takes its place; the bias is added the same way either way. + """ + rank = len(inp.shape) + if matmul is not None: + out = matmul(network, inp) + else: + weight = np.ascontiguousarray(np.asarray(weight, dtype=dtype)) + shape = (1,) * (rank - 2) + tuple(weight.shape) + constant = add_constant(network, shape, weight.reshape(shape), dtype=dtype) + out = network.add_matrix_multiply( + inp, trt.MatrixOperation.NONE, constant, trt.MatrixOperation.TRANSPOSE + ).get_output(0) + if bias is None: + return out + bias_shape = (1,) * (rank - 1) + (-1,) + bias = np.asarray(bias, dtype=dtype).reshape(bias_shape) + return network.add_elementwise( + out, add_constant(network, bias.shape, bias, dtype=dtype), trt.ElementWiseOperation.SUM + ).get_output(0) diff --git a/families/luke/model.py b/families/luke/model.py new file mode 100644 index 0000000000..4243c0a036 --- /dev/null +++ b/families/luke/model.py @@ -0,0 +1,221 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +"""LUKE word/entity embeddings, four entity-aware query paths and relation head.""" + +import json +from pathlib import Path + +import numpy as np +import tensorrt as trt + +from . import graph as g + + +def build(request, writer): + if request.task != "text_entity_pair_to_relation_scores" or request.backend != "trt": + raise ValueError("LUKE requires text_entity_pair_to_relation_scores with backend=trt") + if request.dynamic_kv_cache: + raise NotImplementedError("luke does not support dynamic_kv_cache") + if ( + request.precision != "fp32" + or request.tensor_parallel_size != 1 + or request.context_parallel_size != 1 + or request.max_batch_size != 1 + or request.quantization not in (None, "none") + or request.fp32_layers + or request.dynamic_kv_cache + or request.image_height is not None + or request.image_width is not None + or request.video_num_frames is not None + or request.mtp_seq_len is not None + ): + raise NotImplementedError("LUKE supports one fp32 text and ordered entity pair") + directory = Path(request.model_dir) + cfg = json.loads((directory / "config.json").read_text()) + if ( + cfg["model_type"] != "luke" + or cfg["architectures"] != ["LukeForEntityPairClassification"] + or not cfg["use_entity_aware_attention"] + or cfg["hidden_act"] != "gelu" + ): + raise ValueError("Expected LUKE entity-aware relation classification") + length = request.max_sequence_length or 128 + max_length = min(512, cfg["max_position_embeddings"] - cfg["pad_token_id"] - 1) + if not 8 <= length <= max_length: + raise ValueError(f"LUKE word profile must be between 8 and {max_length} tokens") + import torch + from transformers import LukeTokenizer + + tokenizer = LukeTokenizer.from_pretrained(directory, task="entity_pair_classification") + mention = tokenizer.max_mention_length + if not 1 <= mention <= 512: + raise ValueError("LUKE mention profile must be between 1 and 512") + entity_ids = [tokenizer.entity_mask_token_id, tokenizer.entity_mask2_token_id] + state = torch.load( + directory / "pytorch_model.bin", map_location="cpu", weights_only=True, mmap=True + ) + weights = {name: tensor.float().numpy() for name, tensor in state.items()} + # This Task uses role-specific masked entities, never arbitrary named IDs. + weights["luke.entity_embeddings.entity_embeddings.weight"] = weights[ + "luke.entity_embeddings.entity_embeddings.weight" + ][entity_ids] + width, heads = cfg["hidden_size"], cfg["num_attention_heads"] + dim, total = width // heads, length + 2 + labels = [cfg["id2label"][str(index)] for index in range(len(cfg["id2label"]))] + logger = trt.Logger(trt.Logger.VERBOSE if request.verbose else trt.Logger.WARNING) + builder = trt.Builder(logger) + net = 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) + + def const(value, dtype=np.float32): + value = np.ascontiguousarray(value, dtype=dtype) + return net.add_constant(value.shape, value).get_output(0) + + def shuf(x, shape, perm=None): + layer = net.add_shuffle(x) + if perm is not None: + layer.first_transpose = perm + layer.reshape_dims = shape + return layer.get_output(0) + + def add(a, b): + return net.add_elementwise(a, b, trt.ElementWiseOperation.SUM).get_output(0) + + def mul(a, b): + return net.add_elementwise(a, b, trt.ElementWiseOperation.PROD).get_output(0) + + def linear(x, name): + return g.add_linear(net, x, weights[name + ".weight"], weights.get(name + ".bias")) + + def norm(x, name): + return g.add_layer_norm( + net, x, weights[name + ".weight"], weights[name + ".bias"], cfg["layer_norm_eps"] + ) + + def gather(name, ids): + return net.add_gather(const(weights[name + ".weight"]), ids, 0).get_output(0) + + def concat(values, axis): + layer = net.add_concatenation(values) + layer.axis = axis + return layer.get_output(0) + + def split(x, start, count): + return net.add_slice(x, (start, 0), (count, width), (1, 1)).get_output(0) + + def heads_view(x, count): + return shuf(shuf(x, (1, count, heads, dim)), (1, heads, count, dim), (0, 2, 1, 3)) + + ids = net.add_input("input_ids", trt.int32, (length,)) + valid = net.add_input("attention_mask", trt.int32, (length,)) + positions = net.add_input("position_ids", trt.int32, (length,)) + entity_positions = net.add_input("entity_position_ids", trt.int32, (2, mention)) + prefix = "luke.embeddings" + words = add( + add( + gather(prefix + ".word_embeddings", ids), + gather(prefix + ".position_embeddings", positions), + ), + const(weights[prefix + ".token_type_embeddings.weight"][:1]), + ) + words = norm(words, prefix + ".LayerNorm") + prefix = "luke.entity_embeddings" + entity = const(weights[prefix + ".entity_embeddings.weight"]) + if cfg["entity_emb_size"] != width: + entity = linear(entity, prefix + ".entity_embedding_dense") + clipped = net.add_elementwise( + entity_positions, const(np.zeros((1, 1)), np.int32), trt.ElementWiseOperation.MAX + ).get_output(0) + mask = net.add_elementwise( + entity_positions, const(np.full((1, 1), -1), np.int32), trt.ElementWiseOperation.GREATER + ).get_output(0) + mask = net.add_cast(mask, trt.float32).get_output(0) + positional = gather(prefix + ".position_embeddings", clipped) + positional = mul(positional, shuf(mask, (2, mention, 1))) + summed = net.add_reduce(positional, trt.ReduceOperation.SUM, 2, False).get_output(0) + counts = net.add_reduce(mask, trt.ReduceOperation.SUM, 2, True).get_output(0) + counts = net.add_elementwise( + counts, const(np.full((1, 1), 1e-7)), trt.ElementWiseOperation.MAX + ).get_output(0) + means = net.add_elementwise(summed, counts, trt.ElementWiseOperation.DIV).get_output(0) + entity = norm( + add(add(entity, means), const(weights[prefix + ".token_type_embeddings.weight"][:1])), + prefix + ".LayerNorm", + ) + hidden = concat([words, entity], 0) + full_valid = concat([valid, const(np.ones((2,)), np.int32)], 0) + blocked = net.add_elementwise( + full_valid, const(np.zeros((1,)), np.int32), trt.ElementWiseOperation.EQUAL + ).get_output(0) + mask = net.add_select( + shuf(blocked, (1, 1, 1, total)), + const(np.full((1, 1, 1, total), -np.inf)), + const(np.zeros((1, 1, 1, total))), + ).get_output(0) + scale = const(np.full((1, 1, 1, 1), dim**-0.5)) + for index in range(cfg["num_hidden_layers"]): + prefix = f"luke.encoder.layer.{index}" + attention = prefix + ".attention.self" + word, entity = split(hidden, 0, length), split(hidden, length, 2) + keys = heads_view(linear(hidden, attention + ".key"), total) + values = heads_view(linear(hidden, attention + ".value"), total) + word_key = net.add_slice( + keys, (0, 0, 0, 0), (1, heads, length, dim), (1, 1, 1, 1) + ).get_output(0) + entity_key = net.add_slice( + keys, (0, 0, length, 0), (1, heads, 2, dim), (1, 1, 1, 1) + ).get_output(0) + rows = [] + for source, count, query_names in [ + (word, length, ("query", "w2e_query")), + (entity, 2, ("e2w_query", "e2e_query")), + ]: + blocks = [] + for key, query_name in zip((word_key, entity_key), query_names): + query = heads_view(linear(source, attention + "." + query_name), count) + blocks.append( + net.add_matrix_multiply( + query, trt.MatrixOperation.NONE, key, trt.MatrixOperation.TRANSPOSE + ).get_output(0) + ) + rows.append(concat(blocks, 3)) + scores = add(mul(concat(rows, 2), scale), mask) + softmax = net.add_softmax(scores) + softmax.axes = 8 + context = net.add_matrix_multiply( + softmax.get_output(0), trt.MatrixOperation.NONE, values, trt.MatrixOperation.NONE + ).get_output(0) + context = shuf(context, (total, width), (0, 2, 1, 3)) + hidden = norm( + add(hidden, linear(context, prefix + ".attention.output.dense")), + prefix + ".attention.output.LayerNorm", + ) + inner = linear(hidden, prefix + ".intermediate.dense") + inner = net.add_activation(inner, trt.ActivationType.GELU_ERF).get_output(0) + hidden = norm( + add(hidden, linear(inner, prefix + ".output.dense")), prefix + ".output.LayerNorm" + ) + logits = linear(shuf(split(hidden, length, 2), (1, 2 * width)), "classifier") + logits.name = "relation_logits" + net.mark_output(logits) + plan = builder.build_serialized_network(net, options) + if plan is None: + raise RuntimeError("LUKE relation encoder engine build failed") + writer.set_header(family="luke", task=request.task, backend=request.backend) + writer.add_bytes("model.plan", bytes(plan)) + writer.add_bytes("tokenizer.json", tokenizer._tokenizer.to_str().encode()) + writer.add_json( + "runtime.json", + dict( + sequence_length=length, + max_mention_length=mention, + vocab_size=cfg["vocab_size"], + pad_token_id=tokenizer.pad_token_id, + bos_token_id=tokenizer.bos_token_id, + eos_token_id=tokenizer.eos_token_id, + entity_markers=list(tokenizer.extra_special_tokens_ids[:2]), + labels=labels, + ), + ) diff --git a/families/luke/requirements.txt b/families/luke/requirements.txt new file mode 100644 index 0000000000..15742c15e6 --- /dev/null +++ b/families/luke/requirements.txt @@ -0,0 +1,3 @@ +numpy +torch +transformers==5.2.0 diff --git a/families/luke/runtime/CMakeLists.txt b/families/luke/runtime/CMakeLists.txt new file mode 100644 index 0000000000..5b71f13f3a --- /dev/null +++ b/families/luke/runtime/CMakeLists.txt @@ -0,0 +1,31 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +find_package(ICU REQUIRED COMPONENTS uc i18n) +add_library(trtmc_model_luke SHARED bpe_tokenizer.cpp relation_input.cpp plugin.cpp) +target_include_directories(trtmc_model_luke PRIVATE ${PROJECT_SOURCE_DIR} + ${PROJECT_SOURCE_DIR}/core/runtime/include) +target_include_directories(trtmc_model_luke SYSTEM PRIVATE ${TRTMC_CUDA_INCLUDE_DIR}) +target_link_libraries(trtmc_model_luke PRIVATE trtmc_core nlohmann_json::nlohmann_json + ${TRTMC_CUDART_LIBRARY} ICU::uc ICU::i18n) +target_compile_options(trtmc_model_luke PRIVATE -Wall -Wextra -Wpedantic) +set_target_properties(trtmc_model_luke PROPERTIES + LIBRARY_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}" BUILD_RPATH "\$ORIGIN" INSTALL_RPATH "\$ORIGIN") +install(TARGETS trtmc_model_luke LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR}) + +if(TRTMC_BUILD_TESTS) + add_executable(test_luke_tokenizer + ${PROJECT_SOURCE_DIR}/families/luke/tests/cpp/test_tokenizer.cpp) + target_include_directories(test_luke_tokenizer PRIVATE ${PROJECT_SOURCE_DIR}) + target_link_libraries(test_luke_tokenizer PRIVATE + trtmc_model_luke nlohmann_json::nlohmann_json) + set_target_properties(test_luke_tokenizer PROPERTIES + RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}") +endif() + +if(TRTMC_BUILD_TESTS) + target_include_directories(test_luke_tokenizer PRIVATE ${PROJECT_SOURCE_DIR}/core/runtime/include) + add_executable(test_luke_runtime ${PROJECT_SOURCE_DIR}/families/luke/tests/cpp/test_runtime.cpp) + target_link_libraries(test_luke_runtime PRIVATE trtmc_c nlohmann_json::nlohmann_json) + set_target_properties(test_luke_runtime PROPERTIES RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}") +endif() diff --git a/families/luke/runtime/bpe_tokenizer.cpp b/families/luke/runtime/bpe_tokenizer.cpp new file mode 100644 index 0000000000..af37953e4e --- /dev/null +++ b/families/luke/runtime/bpe_tokenizer.cpp @@ -0,0 +1,1086 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + */ + +#include "families/luke/runtime/token_id.h" +#include "families/luke/runtime/tokenizer.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace trtmc { +namespace { + +// ─── UTF-8 helpers ─── + +// Decode one UTF-8 codepoint from s starting at pos, advance pos. +inline char32_t utf8_to_char32(const std::string& s, size_t& pos) { + unsigned char c = static_cast(s[pos]); + if (c < 0x80) { + ++pos; + return static_cast(c); + } + if ((c & 0xE0) == 0xC0 && pos + 1 < s.size()) { + char32_t cp = (static_cast(c & 0x1F) << 6) | + static_cast(static_cast(s[pos + 1]) & 0x3F); + pos += 2; + return cp; + } + if ((c & 0xF0) == 0xE0 && pos + 2 < s.size()) { + char32_t cp = (static_cast(c & 0x0F) << 12) | + (static_cast(static_cast(s[pos + 1]) & 0x3F) << 6) | + static_cast(static_cast(s[pos + 2]) & 0x3F); + pos += 3; + return cp; + } + if ((c & 0xF8) == 0xF0 && pos + 3 < s.size()) { + char32_t cp = (static_cast(c & 0x07) << 18) | + (static_cast(static_cast(s[pos + 1]) & 0x3F) << 12) | + (static_cast(static_cast(s[pos + 2]) & 0x3F) << 6) | + static_cast(static_cast(s[pos + 3]) & 0x3F); + pos += 4; + return cp; + } + ++pos; + return 0xFFFD; +} + +inline std::string utf32_to_utf8(char32_t cp) { + std::string r; + if (cp <= 0x7F) { + r.push_back(static_cast(cp)); + } else if (cp <= 0x7FF) { + r.push_back(static_cast(0xC0 | ((cp >> 6) & 0x1F))); + r.push_back(static_cast(0x80 | (cp & 0x3F))); + } else if (cp <= 0xFFFF) { + r.push_back(static_cast(0xE0 | ((cp >> 12) & 0x0F))); + r.push_back(static_cast(0x80 | ((cp >> 6) & 0x3F))); + r.push_back(static_cast(0x80 | (cp & 0x3F))); + } else if (cp <= 0x10FFFF) { + r.push_back(static_cast(0xF0 | ((cp >> 18) & 0x07))); + r.push_back(static_cast(0x80 | ((cp >> 12) & 0x3F))); + r.push_back(static_cast(0x80 | ((cp >> 6) & 0x3F))); + r.push_back(static_cast(0x80 | (cp & 0x3F))); + } + return r; +} + +// Read one UTF-8 codepoint from raw bytes, advance ptr. Returns 0xFFFD on error. +inline char32_t read_utf8(const char*& p, const char* end) { + if (p >= end) + return 0xFFFD; + unsigned char c = static_cast(*p); + if (c < 0x80) { + ++p; + return c; + } + if ((c & 0xE0) == 0xC0 && p + 1 < end) { + char32_t cp = + (static_cast(c & 0x1F) << 6) | (static_cast(p[1]) & 0x3F); + p += 2; + return cp; + } + if ((c & 0xF0) == 0xE0 && p + 2 < end) { + char32_t cp = (static_cast(c & 0x0F) << 12) | + (static_cast(static_cast(p[1]) & 0x3F) << 6) | + (static_cast(p[2]) & 0x3F); + p += 3; + return cp; + } + if ((c & 0xF8) == 0xF0 && p + 3 < end) { + char32_t cp = (static_cast(c & 0x07) << 18) | + (static_cast(static_cast(p[1]) & 0x3F) << 12) | + (static_cast(static_cast(p[2]) & 0x3F) << 6) | + (static_cast(p[3]) & 0x3F); + p += 4; + return cp; + } + ++p; + return 0xFFFD; +} + +// ─── GPT-2 byte encoder: byte value <-> Unicode codepoint ─── + +struct ByteEncoderTables { + // byte -> UTF-8 encoded string (precomputed for speed) + std::string byte_to_utf8[256]; + // Unicode codepoint -> byte value + std::unordered_map cp_to_byte; + + ByteEncoderTables() { + // GPT-2 byte encoder: printable bytes map to themselves, + // others map to 256+ to avoid control chars. + bool direct[256] = {}; + for (int b = 33; b <= 126; ++b) + direct[b] = true; // !"#$...~ + for (int b = 161; b <= 172; ++b) + direct[b] = true; // non-breaking space area + for (int b = 174; b <= 255; ++b) + direct[b] = true; // extended latin + + int n = 0; + for (int b = 0; b < 256; ++b) { + char32_t cp = direct[b] ? static_cast(b) : static_cast(256 + n++); + byte_to_utf8[b] = utf32_to_utf8(cp); + cp_to_byte[cp] = static_cast(b); + } + } +}; + +static const ByteEncoderTables& byte_tables() { + static ByteEncoderTables tables; + return tables; +} + +// ─── Hand-written BPE pre-tokenizer ─── +// +// Supports two regex variants: +// +// GPT-2 (used by GPT-2, Falcon, OPT): +// 'contractions| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+ +// +// Qwen3 (used by Qwen3, LLaMA-3, Mistral, Phi): +// (?i:contractions)|[^\r\n\p{L}\p{N}]?\p{L}+|\p{N}| +// ?[^\s\p{L}\p{N}]+[\r\n]*|\s*[\r\n]+|\s+(?!\S)|\s+ +// +// Key differences: Qwen3 allows any non-CR/LF/letter/digit as optional prefix before +// letters, matches single digits, and has explicit newline handling. + +inline bool is_unicode_whitespace(char32_t cp) { + return cp == ' ' || cp == '\t' || cp == '\n' || cp == '\r' || cp == 0x0B || cp == 0x0C // VT, FF + || cp == 0xA0 // non-breaking space + || cp == 0x2000 || cp == 0x200A // en space through hair space + || cp == 0x3000; // ideographic space +} + +// ─── BpeTokenizer implementation ─── + +class BpeTokenizer final : public ITokenizer { + public: + static std::unique_ptr Create(const char* tokenizer_json_data, + std::size_t tokenizer_json_size, + bool add_special_tokens) { + auto tokenizer = std::unique_ptr(new BpeTokenizer()); + tokenizer->mAddSpecialTokens = add_special_tokens; + tokenizer->parse_tokenizer_json(tokenizer_json_data, tokenizer_json_size); + return tokenizer; + } + + void encode_segment(const std::string& text, std::vector& result) const { + const auto normalized = normalize_text(text); + if (mIsSentencePiece) { + encode_sentencepiece(normalized, result); + } else if (mIsMetaspace) { + encode_metaspace(normalized, result); + } else { + encode_bytelevel(normalized, result); + } + } + + std::vector encode(const std::string& text) const override { + std::vector result; + if (mAddSpecialTokens) { + for (int32_t bos_id : mPostBosIds) + result.push_back(bos_id); + } + + auto segments = split_added_tokens(text); + for (const auto& seg : segments) { + if (seg.added_id >= 0) + result.push_back(seg.added_id); + else + encode_segment(seg.text, result); + } + + if (mAddSpecialTokens) { + for (int32_t eos_id : mPostEosIds) + result.push_back(eos_id); + } + + return result; + } + + std::string decode(const std::vector& ids) const override { + std::string joined = join_vocab_tokens(ids); + switch (mDecoderType) { + case DecoderType::kByteLevel: + return byte_decode(joined); + case DecoderType::kMetaspace: + return decode_metaspace(joined); + case DecoderType::kSequence: + return decode_sequence(joined); + } + return byte_decode(joined); + } + + int32_t id_for_token(std::string_view token) const override { + auto it = mTokenToId.find(std::string(token)); + return it != mTokenToId.end() ? it->second : -1; + } + + std::string token_for_id(int32_t id) const override { + if (const auto found = mAddedVocab.find(id); found != mAddedVocab.end()) + return found->second; + if (id >= 0 && static_cast(id) < mVocab.size()) { + return mVocab[id]; + } + return ""; + } + + private: + BpeTokenizer() = default; + + enum class DecoderType { kByteLevel, kMetaspace, kSequence }; + + std::string normalize_text(const std::string& source) const { + std::string text = source; + for (const auto& replacement : mLiteralReplacements) { + std::size_t offset = 0; + while ((offset = text.find(replacement.first, offset)) != std::string::npos) { + text.replace(offset, replacement.first.size(), replacement.second); + offset += replacement.second.size(); + } + } + if (!mNormalizeLowercase && !mNormalizeWhitespace) { + return text; + } + + std::string normalized; + normalized.reserve(text.size()); + const char* cursor = text.data(); + const char* end = cursor + text.size(); + bool previous_was_whitespace = false; + while (cursor < end) { + const char* char_start = cursor; + const char32_t cp = read_utf8(cursor, end); + if (mNormalizeWhitespace && is_unicode_whitespace(cp)) { + if (!previous_was_whitespace) { + normalized.push_back(' '); + } + previous_was_whitespace = true; + continue; + } + previous_was_whitespace = false; + if (mNormalizeLowercase && cp >= 'A' && cp <= 'Z') { + normalized.push_back(static_cast(cp - 'A' + 'a')); + } else { + normalized.append(char_start, cursor); + } + } + return normalized; + } + + // ─── Added token segmentation ─── + + struct Segment { + std::string text; + int32_t added_id; /* -1 = normal */ + }; + + std::pair find_longest_added_token(const std::string& text, size_t pos) const { + int32_t best_id = -1; + size_t best_len = 0; + for (const auto& [content, id] : mAddedTokenPatterns) { + if (pos + content.size() <= text.size() && content.size() > best_len && + text.compare(pos, content.size(), content) == 0) { + best_id = id; + best_len = content.size(); + } + } + return {best_id, best_len}; + } + + static void strip_added_token_left_space(std::string& text) { + const char* begin = text.data(); + const char* cursor = begin; + const char* end = begin + text.size(); + size_t content_end = 0; + while (cursor < end) { + const char32_t cp = read_utf8(cursor, end); + // AddedToken lstrip uses the Unicode White_Space property. + const bool whitespace = (cp >= 0x09 && cp <= 0x0D) || cp == 0x20 || cp == 0x85 || + cp == 0xA0 || cp == 0x1680 || (cp >= 0x2000 && cp <= 0x200A) || + cp == 0x2028 || cp == 0x2029 || cp == 0x202F || cp == 0x205F || + cp == 0x3000; + if (!whitespace) + content_end = static_cast(cursor - begin); + } + text.resize(content_end); + } + + std::vector split_added_tokens(const std::string& text) const { + std::vector segments; + if (mAddedTokenPatterns.empty()) { + segments.push_back({text, -1}); + return segments; + } + size_t pos = 0; + while (pos < text.size()) { + auto [best_id, best_len] = find_longest_added_token(text, pos); + if (best_id >= 0) { + if (mLstripAddedTokenIds.count(best_id) && !segments.empty() && + segments.back().added_id < 0) { + strip_added_token_left_space(segments.back().text); + } + segments.push_back({text.substr(pos, best_len), best_id}); + pos += best_len; + } else { + if (segments.empty() || segments.back().added_id >= 0) { + segments.push_back({"", -1}); + } + segments.back().text.push_back(text[pos]); + ++pos; + } + } + return segments; + } + + // ─── Encoding helpers ─── + + // Metaspace encode (DeepSeek style): raw UTF-8 char split, BPE merge. + // Spaces are dropped (not in vocab), Ġ (U+0120) used as separator. + void encode_metaspace(const std::string& text, std::vector& result) const { + std::vector chars; + const char* cp = text.data(); + const char* ce = cp + text.size(); + while (cp < ce) { + const char* cs = cp; + read_utf8(cp, ce); + std::string ch(cs, cp); + if (mTokenToId.count(ch)) { + chars.push_back(std::move(ch)); + } + } + auto tokens = apply_merges(std::move(chars)); + for (const auto& token : tokens) { + auto it = mTokenToId.find(token); + if (it != mTokenToId.end()) { + result.push_back(it->second); + } + } + } + + // SentencePiece-style encode: replace spaces with ▁, split to chars, BPE merge. + // Used for Metaspace pre-tokenizer and Sequence decoder models (LLaMA, Mistral, Phi-3). + // Normalize text for SentencePiece: replace spaces with ▁, handle prepend + std::string normalize_sentencepiece(const std::string& text) const { + static const std::string sp = "\xe2\x96\x81"; // U+2581 + std::string out; + if (mSentencePiecePrependAlways) { + out = sp; + } + for (char c : text) { + out += (c == ' ') ? sp : std::string(1, c); + } + // Metaspace prepend_scheme=first: prepend if not already starting with ▁ + if (!mSentencePiecePrependAlways && mSentencePiecePrependIfMissing && + (out.empty() || out.compare(0, sp.size(), sp) != 0)) { + out = sp + out; + } + return out; + } + + void encode_sentencepiece(const std::string& text, std::vector& result) const { + std::string normalized = normalize_sentencepiece(text); + + // Split into UTF-8 characters + std::vector chars; + const char* cp = normalized.data(); + const char* ce = cp + normalized.size(); + while (cp < ce) { + const char* cs = cp; + read_utf8(cp, ce); + chars.emplace_back(cs, cp); + } + + // byte_fallback: replace unknown chars with <0xXX> + if (mByteFallback) { + chars = apply_byte_fallback_encode(std::move(chars)); + } + + // BPE merge and lookup + auto tokens = apply_merges(std::move(chars)); + for (const auto& token : tokens) { + auto it = mTokenToId.find(token); + if (it != mTokenToId.end()) { + result.push_back(it->second); + } + } + } + + // For byte_fallback: replace chars not in vocab with <0xXX> byte tokens + std::vector apply_byte_fallback_encode(std::vector chars) const { + std::vector result; + for (auto& ch : chars) { + if (mTokenToId.count(ch)) { + result.push_back(std::move(ch)); + } else { + // Split into individual bytes as <0xXX> + for (unsigned char byte : ch) { + char buf[8]; + std::snprintf(buf, sizeof(buf), "<0x%02X>", byte); + result.push_back(std::string(buf)); + } + } + } + return result; + } + + void encode_bytelevel(const std::string& text, std::vector& result) const { + std::vector words; + if (mRegex) { + UErrorCode status = U_ZERO_ERROR; + const std::string prepared = + mAddPrefixSpace && !text.empty() && text.front() != ' ' ? " " + text : text; + const auto unicode = icu::UnicodeString::fromUTF8(prepared); + std::unique_ptr matcher(mRegex->matcher(unicode, status)); + if (U_FAILURE(status)) + throw std::runtime_error("LUKE tokenizer regex matcher failed"); + int32_t previous = 0; + while (matcher->find(status)) { + const int32_t start = matcher->start(status), end = matcher->end(status); + if (start > previous) { + std::string gap; + unicode.tempSubStringBetween(previous, start).toUTF8String(gap); + words.push_back(std::move(gap)); + } + if (end > start) { + std::string match; + unicode.tempSubStringBetween(start, end).toUTF8String(match); + words.push_back(std::move(match)); + } + previous = end; + } + if (U_FAILURE(status)) + throw std::runtime_error("LUKE tokenizer regex matching failed"); + if (previous < unicode.length()) { + std::string tail; + unicode.tempSubString(previous).toUTF8String(tail); + words.push_back(std::move(tail)); + } + } + + for (const auto& word : words) { + auto chars = byte_encode(word); + if (!chars.empty() && !mEndOfWordSuffix.empty()) { + chars.back() += mEndOfWordSuffix; + } + auto tokens = apply_merges(std::move(chars)); + for (const auto& token : tokens) { + auto it = mTokenToId.find(token); + if (it != mTokenToId.end()) { + result.push_back(it->second); + } + } + } + } + + // ─── Decoding helpers ─── + + std::string join_vocab_tokens(const std::vector& ids) const { + std::string joined; + for (int32_t id : ids) { + if (mSpecialIds.count(id)) + continue; + joined += token_for_id(id); + } + return joined; + } + + std::string decode_metaspace(const std::string& joined) const { + std::string result; + const std::string g_char = utf32_to_utf8(0x0120); + const std::string spiece_char = "\xe2\x96\x81"; // U+2581 + size_t pos = 0; + while (pos < joined.size()) { + if (pos + g_char.size() <= joined.size() && + joined.compare(pos, g_char.size(), g_char) == 0) { + result.push_back(' '); + pos += g_char.size(); + } else if (pos + spiece_char.size() <= joined.size() && + joined.compare(pos, spiece_char.size(), spiece_char) == 0) { + result.push_back(' '); + pos += spiece_char.size(); + } else { + result.push_back(joined[pos]); + ++pos; + } + } + if (!result.empty() && result[0] == ' ') { + result.erase(0, 1); + } + return result; + } + + // ─── Sequence decoder (SentencePiece BPE models: LLaMA, Mistral, Phi-3) ─── + + std::string decode_sequence(const std::string& joined) const { + std::string text = joined; + // Step 1: Apply Replace operations (e.g. ▁ → space) + for (const auto& rep : mSeqDecoderReplaces) { + text = string_replace_all(text, rep.pattern, rep.content); + } + // Step 2: ByteFallback — convert <0xXX> tokens to raw bytes + if (mSeqDecoderByteFallback) { + text = apply_byte_fallback(text); + } + // Step 3: Fuse is implicit (tokens already joined) + // Step 4: Strip leading space + if (mSeqDecoderStripLeft && !text.empty() && text[0] == ' ') { + text.erase(0, 1); + } + return text; + } + + static std::string string_replace_all(const std::string& input, const std::string& from, + const std::string& to) { + if (from.empty()) + return input; + std::string result; + result.reserve(input.size()); + size_t pos = 0; + while (pos < input.size()) { + if (pos + from.size() <= input.size() && input.compare(pos, from.size(), from) == 0) { + result += to; + pos += from.size(); + } else { + result.push_back(input[pos]); + ++pos; + } + } + return result; + } + + static int hex_char_value(char c) { + if (c >= '0' && c <= '9') + return c - '0'; + if (c >= 'a' && c <= 'f') + return c - 'a' + 10; + if (c >= 'A' && c <= 'F') + return c - 'A' + 10; + return -1; + } + + // Try to parse <0xXX> at position pos. Returns parsed byte or -1. + static int try_parse_byte_token(const std::string& text, size_t pos) { + if (pos + 6 > text.size()) + return -1; + if (text[pos] != '<' || text[pos + 1] != '0' || text[pos + 2] != 'x' || + text[pos + 5] != '>') + return -1; + int h = hex_char_value(text[pos + 3]); + int l = hex_char_value(text[pos + 4]); + if (h < 0 || l < 0) + return -1; + return (h << 4) | l; + } + + static std::string apply_byte_fallback(const std::string& text) { + std::string result; + result.reserve(text.size()); + size_t pos = 0; + while (pos < text.size()) { + int byte_val = try_parse_byte_token(text, pos); + if (byte_val >= 0) { + result.push_back(static_cast(byte_val)); + pos += 6; + } else { + result.push_back(text[pos]); + ++pos; + } + } + return result; + } + + // ─── Byte-level encoding ─── + + static std::vector byte_encode(const std::string& text) { + const auto& tables = byte_tables(); + std::vector result; + result.reserve(text.size()); + for (unsigned char byte : text) { + result.push_back(tables.byte_to_utf8[byte]); + } + return result; + } + + static std::string byte_decode(const std::string& text) { + const auto& tables = byte_tables(); + std::string result; + result.reserve(text.size()); + size_t pos = 0; + while (pos < text.size()) { + size_t start = pos; + char32_t cp = utf8_to_char32(text, pos); + auto it = tables.cp_to_byte.find(cp); + if (it != tables.cp_to_byte.end()) { + result.push_back(static_cast(it->second)); + } else { + // Not a GPT-2 byte-encoded codepoint — pass through raw UTF-8 + result.append(text, start, pos - start); + } + } + return result; + } + + // ─── BPE merge algorithm ─── + + struct MergeCandidate { + int rank; + std::string first; + std::string second; + }; + + MergeCandidate find_best_merge(const std::vector& tokens) const { + MergeCandidate best{INT_MAX, "", ""}; + for (size_t i = 0; i + 1 < tokens.size(); ++i) { + auto it = + mMergeRank.find(std::make_pair(std::cref(tokens[i]), std::cref(tokens[i + 1]))); + if (it != mMergeRank.end() && it->second < best.rank) { + best = {it->second, tokens[i], tokens[i + 1]}; + } + } + return best; + } + + static std::vector merge_all_pairs(std::vector tokens, + const std::string& first, + const std::string& second) { + std::string merged = first + second; + std::vector result; + result.reserve(tokens.size()); + for (size_t i = 0; i < tokens.size(); ++i) { + if (i + 1 < tokens.size() && tokens[i] == first && tokens[i + 1] == second) { + result.push_back(merged); + ++i; // skip next + } else { + result.push_back(std::move(tokens[i])); + } + } + return result; + } + + // Optimized: merge ALL occurrences of the best pair per pass. + std::vector apply_merges(std::vector tokens) const { + if (tokens.size() <= 1) + return tokens; + + while (true) { + auto best = find_best_merge(tokens); + if (best.rank == INT_MAX) + break; + tokens = merge_all_pairs(std::move(tokens), best.first, best.second); + if (tokens.size() <= 1) + break; + } + + return tokens; + } + + // ─── JSON parsing helpers ─── + + static bool is_eos_content(const std::string& s) { + return s == "<|endoftext|>" || s == "" || s == "<|end_of_text|>"; + } + + void parse_vocab(const nlohmann::json& j) { + auto& vocab_obj = j["model"]["vocab"]; + size_t vocab_size = vocab_obj.size(); + mVocab.resize(vocab_size); + + for (auto& [token, id] : vocab_obj.items()) { + const auto token_id = + luke::checked_token_id(id, vocab_size, "Invalid LUKE base vocabulary ID"); + mVocab[token_id] = token; + mTokenToId[token] = token_id; + } + } + + void parse_merges(const nlohmann::json& j) { + if (!j["model"].contains("merges")) + throw std::runtime_error("Invalid tokenizer.json: missing model.merges"); + + auto& merges_arr = j["model"]["merges"]; + mMergeRank.reserve(merges_arr.size()); + + for (size_t i = 0; i < merges_arr.size(); ++i) { + std::string first, second; + + if (merges_arr[i].is_array()) { + auto arr = merges_arr[i].get>(); + if (arr.size() != 2) + continue; + first = std::move(arr[0]); + second = std::move(arr[1]); + } else if (merges_arr[i].is_string()) { + std::string merge_str = merges_arr[i].get(); + auto space_pos = merge_str.find(' '); + if (space_pos == std::string::npos) + continue; + first = merge_str.substr(0, space_pos); + second = merge_str.substr(space_pos + 1); + } else { + continue; + } + + auto pair = std::make_pair(std::move(first), std::move(second)); + mMergeRank[pair] = static_cast(i); + } + } + + void parse_added_tokens(const nlohmann::json& j) { + if (!j.contains("added_tokens")) + return; + for (auto& tok : j["added_tokens"]) { + std::string content = tok.at("content").get(); + const auto id = + luke::checked_token_id(tok.at("id"), uint64_t{INT32_MAX} + 1, + "LUKE added-token ID must be a nonnegative int32"); + + // Added IDs can be sparse and need not extend the base vocabulary. + // Keep storage proportional to token count, never to an untrusted ID. + mAddedVocab[id] = content; + mTokenToId[content] = id; + + if (tok.value("special", false)) { + mSpecialTokens[content] = id; + mSpecialIds.insert(id); + if (is_eos_content(content)) + mEosId = id; + } + // All added tokens (special and non-special) participate in pre-split + // matching during encode, matching HuggingFace's AddedToken behavior. + // The special flag only controls decode filtering (mSpecialIds) and + // post_processor BOS/EOS insertion. + mAddedTokenPatterns.push_back({content, id}); + if (tok.value("lstrip", false)) + mLstripAddedTokenIds.insert(id); + } + // Sort by length descending for longest-match-first + std::sort(mAddedTokenPatterns.begin(), mAddedTokenPatterns.end(), + [](const auto& a, const auto& b) { return a.first.size() > b.first.size(); }); + } + + DecoderType classify_decoder_type(const nlohmann::json& j) const { + if (!j.contains("decoder") || j["decoder"].is_null()) { + return mIsMetaspace ? DecoderType::kMetaspace : DecoderType::kByteLevel; + } + std::string dt = j["decoder"].value("type", ""); + if (dt == "ByteLevel") + return DecoderType::kByteLevel; + if (dt == "Metaspace") + return DecoderType::kMetaspace; + if (dt == "Sequence") + return DecoderType::kSequence; + return mIsMetaspace ? DecoderType::kMetaspace : DecoderType::kByteLevel; + } + + void detect_decoder(const nlohmann::json& j) { + mDecoderType = classify_decoder_type(j); + if (mDecoderType == DecoderType::kSequence) { + parse_sequence_decoder(j["decoder"]); + } + // SentencePiece encode: vocab uses ▁ (U+2581) for spaces. + // Detect by: (1) ▁ in vocabulary, or (2) normalizer prepends ▁. + static const std::string spiece_marker = "\xe2\x96\x81"; // U+2581 + mIsSentencePiece = mTokenToId.count(spiece_marker) > 0 || mSentencePiecePrependAlways; + } + + void parse_seq_decoder_replace(const nlohmann::json& sub) { + SeqDecoderReplace rep; + if (sub.contains("pattern") && sub["pattern"].contains("String")) { + rep.pattern = sub["pattern"]["String"].get(); + } + rep.content = sub.value("content", ""); + if (!rep.pattern.empty()) { + mSeqDecoderReplaces.push_back(std::move(rep)); + } + } + + void parse_sequence_decoder(const nlohmann::json& dec) { + if (!dec.contains("decoders")) + return; + for (auto& sub : dec["decoders"]) { + std::string sub_type = sub.value("type", ""); + if (sub_type == "Replace") { + parse_seq_decoder_replace(sub); + } else if (sub_type == "ByteFallback") { + mSeqDecoderByteFallback = true; + } else if (sub_type == "Strip") { + if (sub.value("content", " ") == " " && sub.value("start", 0) > 0) { + mSeqDecoderStripLeft = true; + } + } + // Fuse is implicit (tokens already joined) + } + } + + static std::string optional_model_string(const nlohmann::json& model, const char* key) { + auto it = model.find(key); + if (it != model.end() && it->is_string()) + return it->get(); + return {}; + } + + void parse_tokenizer_json(const char* json_data, std::size_t json_size) { + nlohmann::json j; + try { + j = nlohmann::json::parse(json_data, json_data + json_size); + } catch (const std::exception& e) { + throw std::runtime_error(std::string("Failed to parse tokenizer.json: ") + e.what()); + } + + if (!j.contains("model")) + throw std::runtime_error("Invalid tokenizer.json: missing model"); + auto& model = j["model"]; + if (!model.contains("vocab") || !model["vocab"].is_object()) + throw std::runtime_error("Invalid tokenizer.json: model.vocab must be an object"); + if (!model.contains("merges") || !model["merges"].is_array()) + throw std::runtime_error("Invalid tokenizer.json: model.merges must be an array"); + + mByteFallback = model.value("byte_fallback", false); + mEndOfWordSuffix = optional_model_string(model, "end_of_word_suffix"); + parse_vocab(j); + parse_merges(j); + parse_added_tokens(j); + parse_post_processor(j); + detect_normalizer(j); + const auto& pretokenizer = j.at("pre_tokenizer"); + if (pretokenizer.value("type", "") != "ByteLevel" || + !pretokenizer.value("use_regex", false)) + throw std::runtime_error("Unsupported LUKE ByteLevel pre-tokenizer"); + mAddPrefixSpace = pretokenizer.value("add_prefix_space", true); + const std::string pattern = + R"('s|'t|'re|'ve|'m|'ll|'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+)"; + UErrorCode regex_status = U_ZERO_ERROR; + mRegex.reset( + icu::RegexPattern::compile(icu::UnicodeString::fromUTF8(pattern), 0, regex_status)); + if (U_FAILURE(regex_status)) + throw std::runtime_error("LUKE tokenizer regex compilation failed"); + detect_decoder(j); + } + + // Detect normalizer: check for Prepend (always prepend ▁) vs none + static bool normalizer_sequence_prepends(const nlohmann::json& norm, + const std::string& norm_type) { + if (norm_type != "Sequence" || !norm.contains("normalizers")) + return false; + for (auto& sub : norm["normalizers"]) { + if (sub.value("type", "") == "Prepend") + return true; + } + return false; + } + + static bool normalizer_replaces_space_with_sentence_piece(const nlohmann::json& norm, + const std::string& norm_type) { + if (norm_type == "Sequence" && norm.contains("normalizers")) { + for (const auto& sub : norm["normalizers"]) { + if (normalizer_replaces_space_with_sentence_piece(sub, sub.value("type", ""))) { + return true; + } + } + return false; + } + if (norm_type != "Replace") + return false; + if (!norm.contains("pattern") || !norm["pattern"].contains("String")) + return false; + if (norm["pattern"]["String"].get() != " ") + return false; + return norm.value("content", "") == "\xe2\x96\x81"; + } + + void detect_normalizer(const nlohmann::json& j) { + if (!j.contains("normalizer") || j["normalizer"].is_null()) + return; + auto& norm = j["normalizer"]; + std::string norm_type = norm.value("type", ""); + detect_text_normalizers(norm); + if (normalizer_sequence_prepends(norm, norm_type)) { + mSentencePiecePrependAlways = true; + } else if (normalizer_replaces_space_with_sentence_piece(norm, norm_type)) { + // Gemma replaces spaces with ▁ but does not prepend ▁ to the + // first token. Preserve the old prepend-if-missing behavior for + // Metaspace-style SentencePiece models. + mSentencePiecePrependIfMissing = false; + } + } + + void detect_text_normalizers(const nlohmann::json& normalizer) { + const std::string type = normalizer.value("type", ""); + if (type == "Sequence" && normalizer.contains("normalizers")) { + for (const auto& child : normalizer["normalizers"]) { + detect_text_normalizers(child); + } + return; + } + if (type == "Replace" && normalizer.contains("pattern") && + normalizer["pattern"].contains("String")) { + const auto pattern = normalizer["pattern"]["String"].get(); + if (pattern.empty()) + throw std::runtime_error("LUKE tokenizer replacement cannot be empty"); + mLiteralReplacements.emplace_back(pattern, normalizer.at("content").get()); + return; + } + if (type == "Lowercase") { + mNormalizeLowercase = true; + return; + } + if (type == "Replace" && normalizer.contains("pattern") && + normalizer["pattern"].contains("Regex") && + normalizer["pattern"]["Regex"].get() == "\\s+" && + normalizer.value("content", "") == " ") { + mNormalizeWhitespace = true; + } + } + + // Parse post_processor to extract BOS/EOS tokens for add_special_tokens + void parse_post_processor(const nlohmann::json& j) { + if (!j.contains("post_processor") || j["post_processor"].is_null()) + return; + auto& pp = j["post_processor"]; + std::string pp_type = pp.value("type", ""); + + if (pp_type == "TemplateProcessing") { + parse_template_post_processor(pp); + } else if (pp_type == "Sequence") { + parse_sequence_post_processor(pp); + } else if (pp_type == "RobertaProcessing") { + parse_roberta_post_processor(pp); + } + // ByteLevel post_processor doesn't add tokens, nothing to do + } + + // Iterate Sequence post_processor's processors array to find TemplateProcessing + void parse_sequence_post_processor(const nlohmann::json& pp) { + if (!pp.contains("processors")) + return; + for (auto& sub : pp["processors"]) { + if (sub.value("type", "") == "TemplateProcessing") { + parse_template_post_processor(sub); + return; // first TemplateProcessing wins + } + } + } + + // RobertaProcessing: {"type":"RobertaProcessing","cls":["",0],"sep":["",2],...} + void parse_roberta_post_processor(const nlohmann::json& pp) { + if (pp.contains("cls") && pp["cls"].is_array() && pp["cls"].size() >= 2) { + int32_t cls_id = pp["cls"][1].get(); + mPostBosIds.push_back(cls_id); + } + if (pp.contains("sep") && pp["sep"].is_array() && pp["sep"].size() >= 2) { + int32_t sep_id = pp["sep"][1].get(); + mPostEosIds.push_back(sep_id); + } + } + + int32_t resolve_special_token_id(const nlohmann::json& entry) const { + if (!entry.contains("SpecialToken")) + return -1; + std::string token_id = entry["SpecialToken"].value("id", ""); + if (token_id.empty()) + return -1; + auto it = mSpecialTokens.find(token_id); + return it != mSpecialTokens.end() ? it->second : -1; + } + + void parse_template_post_processor(const nlohmann::json& pp) { + if (!pp.contains("single")) + return; + bool seen_sequence = false; + for (auto& entry : pp["single"]) { + if (entry.contains("Sequence")) { + seen_sequence = true; + continue; + } + int32_t id = resolve_special_token_id(entry); + if (id < 0) + continue; + if (seen_sequence) { + mPostEosIds.push_back(id); + } else { + mPostBosIds.push_back(id); + } + } + } + + // ─── Data members ─── + + std::unordered_map mAddedVocab; + std::vector mVocab; + std::unordered_map mTokenToId; + + struct PairHash { + size_t operator()(const std::pair& p) const { + size_t h1 = std::hash{}(p.first); + size_t h2 = std::hash{}(p.second); + return h1 ^ (h2 * 0x9e3779b97f4a7c15ULL + 0x9e3779b9 + (h1 << 6) + (h1 >> 2)); + } + }; + + std::unordered_map, int, PairHash> mMergeRank; + + std::unordered_map mSpecialTokens; + std::unordered_set mSpecialIds; // O(1) lookup in decode() + int32_t mEosId = -1; + + // Non-special added tokens: matched before pre-tokenization (longest first) + std::vector> mAddedTokenPatterns; + std::unordered_set mLstripAddedTokenIds; + + bool mAddSpecialTokens = false; + bool mIsMetaspace = false; + bool mIsSentencePiece = false; + bool mSentencePiecePrependAlways = + false; // true for Normalizer Prepend, false for Metaspace first + bool mSentencePiecePrependIfMissing = true; + bool mByteFallback = false; + bool mAddPrefixSpace{false}; + std::unique_ptr mRegex; + std::vector> mLiteralReplacements; + bool mNormalizeLowercase = false; + bool mNormalizeWhitespace = false; + std::string mEndOfWordSuffix; + + // Post-processor: BOS/EOS token IDs to add when add_special_tokens=true + // Vectors to support multiple BOS/EOS tokens (e.g. GLM-4: [gMASK] + ) + std::vector mPostBosIds; + std::vector mPostEosIds; + + DecoderType mDecoderType = DecoderType::kByteLevel; + + // Sequence decoder config (parsed from tokenizer.json decoder field) + struct SeqDecoderReplace { + std::string pattern; + std::string content; + }; + std::vector mSeqDecoderReplaces; + bool mSeqDecoderByteFallback = false; + bool mSeqDecoderStripLeft = false; +}; + +} // namespace + +std::unique_ptr CreateBpeTokenizer(const char* tokenizer_json_data, + std::size_t tokenizer_json_size, + bool add_special_tokens) { + return BpeTokenizer::Create(tokenizer_json_data, tokenizer_json_size, add_special_tokens); +} + +} // namespace trtmc diff --git a/families/luke/runtime/plugin.cpp b/families/luke/runtime/plugin.cpp new file mode 100644 index 0000000000..08aa53c162 --- /dev/null +++ b/families/luke/runtime/plugin.cpp @@ -0,0 +1,98 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + */ +#include "families/luke/runtime/relation_input.h" +#include "families/luke/runtime/token_id.h" +#include "trtmc/internal/model.h" +#include "trtmc/runtime/family_factory.h" +#include "trtmc/runtime/trt_backend.h" + +#include +namespace trtmc::luke { +namespace { +class Pipeline final : public internal::IModel, public internal::ITextEntityPairToRelationScores { + public: + Pipeline(std::unique_ptr engine, std::unique_ptr tokenizer, + nlohmann::json cfg) + : engine_(std::move(engine)), tokenizer_(std::move(tokenizer)), cfg_(std::move(cfg)) {} + const char* task() const noexcept override { return "text_entity_pair_to_relation_scores"; } + std::vector task_bindings() override { + return {internal::bind(*this)}; + } + internal::LabelScoresResult run(const internal::TextEntityPairToRelationScoresRequest& input, + internal::ConfigView config) override { + internal::validate_config({}, config); + auto encoded = encode_relation(*tokenizer_, input, cfg_); + const int64_t length = cfg_.at("sequence_length"), mention = cfg_.at("max_mention_length"); + const auto tensor = [](std::vector& values, std::vector shape) { + Tensor result; + result.data = values.data(); + result.shape = std::move(shape); + result.dtype = DType::kInt32; + return result; + }; + const auto outputs = engine_->forward( + {{"input_ids", tensor(encoded.ids, {length})}, + {"attention_mask", tensor(encoded.valid, {length})}, + {"position_ids", tensor(encoded.positions, {length})}, + {"entity_position_ids", tensor(encoded.entity_positions, {2, mention})}}); + const auto found = outputs.find("relation_logits"); + const auto labels = cfg_.at("labels").get>(); + if (found == outputs.end() || found->second.dtype != DType::kFloat32 || + found->second.numel() != labels.size() || !found->second.data) + throw std::runtime_error("Invalid LUKE relation score output"); + const auto* data = static_cast(found->second.data); + internal::LabelScoresResult result; + result.scores.assign(data, data + labels.size()); + result.labels = labels; + result.kind = internal::ScoreKind::Logit; + for (const float score : result.scores) + if (!std::isfinite(score)) + throw std::runtime_error("Nonfinite LUKE relation score"); + return result; + } + + private: + std::unique_ptr engine_; + std::unique_ptr tokenizer_; + nlohmann::json cfg_; +}; +std::vector section(const BundleReader& reader, const char* name) { + const auto* found = reader.find_section(name); + if (!found || !found->length) + throw std::runtime_error(std::string("LUKE bundle lacks ") + name); + return reader.read_section(name); +} +} // namespace +} // namespace trtmc::luke +extern "C" trtmc::ITask* trtmc_create_family(const trtmc::FamilyContext& context) { + if (context.kv_cache_size_bytes != 0) + throw std::invalid_argument("luke does not support --kv-cache-size"); + using namespace trtmc; + if (context.kv_cache_size_bytes || + context.reader.info().task != "text_entity_pair_to_relation_scores") + throw std::invalid_argument( + "LUKE requires entity relation scores without an external cache"); + const auto raw = luke::section(context.reader, "runtime.json"); + const auto cfg = nlohmann::json::parse(raw.begin(), raw.end()); + const int64_t length = cfg.at("sequence_length"), mention = cfg.at("max_mention_length"), + vocab = cfg.at("vocab_size"); + if (length < 8 || length > 512 || mention < 1 || mention > 512 || vocab <= 0 || + vocab > INT32_MAX || cfg.at("labels").empty()) + throw std::runtime_error("Invalid LUKE relation profile"); + const auto& markers = cfg.at("entity_markers"); + if (!markers.is_array() || markers.size() != 2) + throw std::runtime_error("LUKE entity_markers must be an array of two token IDs"); + for (const auto& marker : markers) + luke::checked_token_id(marker, vocab, "Invalid LUKE entity marker ID"); + for (const auto field : {"bos_token_id", "eos_token_id", "pad_token_id"}) + luke::checked_token_id(cfg.at(field), vocab, "Invalid LUKE special token"); + const auto plan = luke::section(context.reader, "model.plan"); + auto engine = context.backend.create_module(plan.data(), plan.size(), {}); + if (!engine || !engine->ok()) + throw std::runtime_error("LUKE engine failed to load"); + const auto data = luke::section(context.reader, "tokenizer.json"); + auto tokenizer = CreateBpeTokenizer(data.data(), data.size(), false); + return new luke::Pipeline(std::move(engine), std::move(tokenizer), cfg); +} diff --git a/families/luke/runtime/relation_input.cpp b/families/luke/runtime/relation_input.cpp new file mode 100644 index 0000000000..24f10db838 --- /dev/null +++ b/families/luke/runtime/relation_input.cpp @@ -0,0 +1,95 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + */ +#include "families/luke/runtime/relation_input.h" + +#include +#include +#include +#include +#include +namespace trtmc::luke { +EncodedRelation encode_relation(const ITokenizer& tokenizer, + const internal::TextEntityPairToRelationScoresRequest& input, + const nlohmann::json& cfg) { + const std::string text(input.text); + const std::array entities{input.subject, input.object}; + std::set boundaries; + for (const auto span : entities) { + if (span.begin >= span.end || span.end > text.size()) + throw std::invalid_argument("Invalid LUKE entity byte span"); + boundaries.insert(span.begin); + boundaries.insert(span.end); + } + if (!(input.subject.end <= input.object.begin || input.object.end <= input.subject.begin)) + throw std::invalid_argument("LUKE entity pair spans must be disjoint"); + std::vector body; + std::map mapping; + size_t current = 0; + for (const auto original : boundaries) { + auto boundary = original; + // The published tokenizer leaves a preceding ASCII space with the next + // segment, then independently runs ByteLevel BPE on each segment. + if (boundary && text[boundary - 1] == ' ') + --boundary; + if (current != boundary) { + const auto chunk = tokenizer.encode(text.substr(current, boundary - current)); + body.insert(body.end(), chunk.begin(), chunk.end()); + current = boundary; + } + mapping[original] = body.size(); + } + const auto tail = tokenizer.encode(text.substr(current)); + body.insert(body.end(), tail.begin(), tail.end()); + std::array, 2> spans; + for (size_t i = 0; i < 2; ++i) + spans[i] = {mapping.at(entities[i].begin), mapping.at(entities[i].end)}; + for (const auto span : spans) + if (span.first == span.second) + throw std::invalid_argument("LUKE entity spans must contain at least one token"); + // Emit closing markers before opening markers at a shared token boundary. + // Compute positions from the final sequence, including its leading BOS. + const auto original = spans; + std::vector marked; + for (size_t position = 0; position <= body.size(); ++position) { + for (size_t i = 0; i < 2; ++i) + if (original[i].second == position) { + marked.push_back(cfg.at("entity_markers").at(i)); + spans[i].second = marked.size() + 1; + } + for (size_t i = 0; i < 2; ++i) + if (original[i].first == position) { + spans[i].first = marked.size() + 1; + marked.push_back(cfg.at("entity_markers").at(i)); + } + if (position < body.size()) + marked.push_back(body[position]); + } + body = std::move(marked); + EncodedRelation result; + result.ids.push_back(cfg.at("bos_token_id")); + result.ids.insert(result.ids.end(), body.begin(), body.end()); + result.ids.push_back(cfg.at("eos_token_id")); + const size_t length = cfg.at("sequence_length"), mention = cfg.at("max_mention_length"); + if (result.ids.size() > length) + throw std::invalid_argument("LUKE text exceeds its built word profile"); + const int32_t vocab = cfg.at("vocab_size"), pad = cfg.at("pad_token_id"); + for (const auto id : result.ids) + if (id < 0 || id >= vocab) + throw std::runtime_error("Invalid LUKE tokenizer ID"); + result.valid.assign(length, 0); + std::fill(result.valid.begin(), result.valid.begin() + result.ids.size(), 1); + result.ids.resize(length, pad); + result.positions.assign(length, pad); + int32_t position = pad; + for (size_t i = 0; i < length; ++i) + if (result.ids[i] != pad) + result.positions[i] = ++position; + result.entity_positions.assign(2 * mention, -1); + for (size_t i = 0; i < 2; ++i) + for (size_t j = 0; j < std::min(mention, spans[i].second - spans[i].first); ++j) + result.entity_positions[i * mention + j] = spans[i].first + j; + return result; +} +} // namespace trtmc::luke diff --git a/families/luke/runtime/relation_input.h b/families/luke/runtime/relation_input.h new file mode 100644 index 0000000000..7e67151dee --- /dev/null +++ b/families/luke/runtime/relation_input.h @@ -0,0 +1,17 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + */ +#pragma once +#include "families/luke/runtime/tokenizer.h" +#include "trtmc/internal/features.h" + +#include +namespace trtmc::luke { +struct EncodedRelation { + std::vector ids, valid, positions, entity_positions; +}; +EncodedRelation encode_relation(const ITokenizer&, + const internal::TextEntityPairToRelationScoresRequest&, + const nlohmann::json&); +} // namespace trtmc::luke diff --git a/families/luke/runtime/token_id.h b/families/luke/runtime/token_id.h new file mode 100644 index 0000000000..11dadc8247 --- /dev/null +++ b/families/luke/runtime/token_id.h @@ -0,0 +1,22 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + */ +#pragma once + +#include +#include +#include + +namespace trtmc::luke { + +inline int32_t checked_token_id(const nlohmann::json& value, uint64_t limit, const char* error) { + if (!value.is_number_integer() || (!value.is_number_unsigned() && value.get() < 0)) + throw std::runtime_error(error); + const auto id = value.get(); + if (id >= limit || id > INT32_MAX) + throw std::runtime_error(error); + return static_cast(id); +} + +} // namespace trtmc::luke diff --git a/families/luke/runtime/tokenizer.h b/families/luke/runtime/tokenizer.h new file mode 100644 index 0000000000..a315433c25 --- /dev/null +++ b/families/luke/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 { + +class ITokenizer { + public: + virtual ~ITokenizer() = default; + virtual std::vector encode(const std::string& text) const = 0; + virtual std::string decode(const std::vector& ids) const = 0; + virtual std::int32_t id_for_token(std::string_view token) const = 0; + virtual std::string token_for_id(std::int32_t id) const = 0; +}; + +std::unique_ptr CreateBpeTokenizer(const char* tokenizer_json_data, + std::size_t tokenizer_json_size, + bool add_special_tokens = false); + +} // namespace trtmc diff --git a/families/luke/support.py b/families/luke/support.py new file mode 100644 index 0000000000..0427c57e16 --- /dev/null +++ b/families/luke/support.py @@ -0,0 +1,11 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +from tensorrt_model_connect.model_support import family_support + +describe = family_support( + model_types=("luke",), + architectures=("LukeForEntityPairClassification",), + tasks=("text_entity_pair_to_relation_scores",), + default_task="text_entity_pair_to_relation_scores", + default_precision="fp32", +) diff --git a/families/luke/tests/__init__.py b/families/luke/tests/__init__.py new file mode 100644 index 0000000000..04e3e120ff --- /dev/null +++ b/families/luke/tests/__init__.py @@ -0,0 +1,4 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""luke package.""" diff --git a/families/luke/tests/checkpoint_identity.py b/families/luke/tests/checkpoint_identity.py new file mode 100644 index 0000000000..0d9de7ec4f --- /dev/null +++ b/families/luke/tests/checkpoint_identity.py @@ -0,0 +1,35 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +"""Verify the exact local checkpoint inputs before claiming a pinned comparison.""" + +from pathlib import Path + + +def verify_pinned_copy(candidate: Path, cached: Path) -> Path: + def inputs(directory): + return { + p.relative_to(directory): p + for p in directory.rglob("*") + if p.is_file() + and p.suffix in {".json", ".txt", ".bin", ".safetensors", ".model"} + and ".cache" not in p.relative_to(directory).parts + } + + expected, actual = inputs(cached), inputs(candidate) + if not expected or actual.keys() != expected.keys(): + raise AssertionError("checkpoint inputs differ from the pinned cached snapshot") + # The offline asset boundary supplies the trusted pinned snapshot. Compare + # every input byte, including verified local copies, without hashing family + # sources, plans, or bundles. + for name, source in expected.items(): + path = actual[name] + if path.stat().st_size != source.stat().st_size: + raise AssertionError(f"checkpoint input differs from pinned content: {name}") + with path.open("rb") as candidate_stream, source.open("rb") as pinned_stream: + while True: + chunk = pinned_stream.read(1024 * 1024) + if candidate_stream.read(len(chunk)) != chunk: + raise AssertionError(f"checkpoint input differs from pinned content: {name}") + if not chunk: + break + return candidate diff --git a/families/luke/tests/cpp/test_runtime.cpp b/families/luke/tests/cpp/test_runtime.cpp new file mode 100644 index 0000000000..fcf677052d --- /dev/null +++ b/families/luke/tests/cpp/test_runtime.cpp @@ -0,0 +1,30 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + */ +#include "trtmc/features.hpp" + +#include +#include +int main(int argc, char** argv) { + if (argc != 3) + return 2; + trtmc::LoadOptions options; + options.runtime_root = argv[2]; + nlohmann::json request; + std::cin >> request; + const auto result = trtmc::Model::load(argv[1], options) + .task() + .run({request.at("text"), + {request.at("subject")[0], request.at("subject")[1]}, + {request.at("object")[0], request.at("object")[1]}}); + std::vector labels; + for (auto label : result.labels()) + labels.emplace_back(label); + std::cout << nlohmann::json{{"labels", labels}, + {"scores", std::vector(result.scores().begin(), + result.scores().end())}, + {"kind", result.kind()}} + .dump() + << '\n'; +} diff --git a/families/luke/tests/cpp/test_tokenizer.cpp b/families/luke/tests/cpp/test_tokenizer.cpp new file mode 100644 index 0000000000..7375631956 --- /dev/null +++ b/families/luke/tests/cpp/test_tokenizer.cpp @@ -0,0 +1,30 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + */ +#include "families/luke/runtime/relation_input.h" + +#include +#include +int main() try { + nlohmann::json request; + std::cin >> request; + std::ifstream file(request.at("tokenizer_path").get(), std::ios::binary); + const std::string data((std::istreambuf_iterator(file)), {}); + auto tokenizer = trtmc::CreateBpeTokenizer(data.data(), data.size(), false); + const std::string text = request.at("text"); + const trtmc::internal::TextEntityPairToRelationScoresRequest input{ + text, + {request.at("subject")[0], request.at("subject")[1]}, + {request.at("object")[0], request.at("object")[1]}}; + const auto result = trtmc::luke::encode_relation(*tokenizer, input, request.at("config")); + std::cout << nlohmann::json{{"input_ids", result.ids}, + {"attention_mask", result.valid}, + {"position_ids", result.positions}, + {"entity_position_ids", result.entity_positions}} + .dump() + << '\n'; +} catch (const std::exception& error) { + std::cerr << error.what() << '\n'; + return 1; +} diff --git a/families/luke/tests/manifests/luke-large-tacred.json b/families/luke/tests/manifests/luke-large-tacred.json new file mode 100644 index 0000000000..e5003db66d --- /dev/null +++ b/families/luke/tests/manifests/luke-large-tacred.json @@ -0,0 +1,45 @@ +{ + "name": "luke-large-finetuned-tacred", + "hf_id": "studio-ousia/luke-large-finetuned-tacred", + "hf_revision": "ba3d02d7791d738d6bd480592ed814525124fbbc", + "family": "luke", + "bundle": "luke-large-tacred.bundle", + "task": "text_entity_pair_to_relation_scores", + "precision": "fp32", + "max_sequence_length": 128, + "tensor_parallel_size": 1, + "testcases": [ + { + "name": "luke-large-tacred-relations", + "premerge": true, + "max_abs_error": 0.0003, + "examples": [ + { + "text": "Barack Obama was born in Honolulu.", + "subject": "Barack Obama", + "object": "Honolulu" + }, + { + "text": "The Beatles were founded in Liverpool.", + "subject": "The Beatles", + "object": "Liverpool" + }, + { + "text": "Alice lives in Paris.", + "subject": "Paris", + "object": "Alice" + }, + { + "text": "Éva works for Microsoft in Zürich.", + "subject": "Éva", + "object": "Microsoft" + }, + { + "text": "The headquarters of Microsoft are in Redmond", + "subject": "Microsoft", + "object": "Redmond" + } + ] + } + ] +} diff --git a/families/luke/tests/test_checkpoint_identity.py b/families/luke/tests/test_checkpoint_identity.py new file mode 100644 index 0000000000..6ac97682b8 --- /dev/null +++ b/families/luke/tests/test_checkpoint_identity.py @@ -0,0 +1,27 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +import shutil + +import pytest + +from .checkpoint_identity import verify_pinned_copy + + +@pytest.mark.parametrize("mutation", [None, "changed", "missing", "alternate_weights"]) +def test_pinned_checkpoint_copy(tmp_path, mutation): + cached, copy = tmp_path / "snapshots" / "revision", tmp_path / "copy" + cached.mkdir(parents=True) + for name, content in [("config.json", b"{}"), ("pytorch_model.bin", b"weights")]: + (cached / name).write_bytes(content) + shutil.copytree(cached, copy) + if mutation == "changed": + (copy / "pytorch_model.bin").write_bytes(b"altered") + elif mutation == "missing": + (copy / "config.json").unlink() + elif mutation == "alternate_weights": + (copy / "model.safetensors").write_bytes(b"other") + if mutation: + with pytest.raises(AssertionError, match="checkpoint input"): + verify_pinned_copy(copy, cached) + else: + assert verify_pinned_copy(copy, cached) == copy diff --git a/families/luke/tests/test_e2e.py b/families/luke/tests/test_e2e.py new file mode 100644 index 0000000000..db1431291b --- /dev/null +++ b/families/luke/tests/test_e2e.py @@ -0,0 +1,436 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Pinned LUKE entity-aware tokenizer and relation score parity through the public Task API.""" + +from __future__ import annotations + +import json +import os +import subprocess +from functools import cache +from pathlib import Path + +import pytest + +from tensorrt_model_connect import BuildRequest, build +from tools.e2e_evidence import evidence_enabled, evidence_stage, record_evidence + +FAMILY = "luke" +TASKS = frozenset({"text_entity_pair_to_relation_scores"}) +TEST_ROOT = Path(__file__).resolve().parent +MANIFEST_ROOT = TEST_ROOT / "manifests" + + +def _case_index() -> dict[str, tuple[Path, dict, dict]]: + result = {} + for path in sorted(MANIFEST_ROOT.glob("*.json")): + manifest = json.loads(path.read_text(encoding="utf-8")) + assert manifest["family"] == FAMILY + assert manifest["task"] in TASKS + for case in manifest["testcases"]: + name = str(case["name"]) + assert name not in result + result[name] = (path, manifest, case) + return result + + +CASES = _case_index() + + +def _selected_cases(config) -> tuple[list[str], bool]: + model_filters = set() + for raw in config.getoption("--e2e-model") or []: + model_filters.update((item.strip() for item in str(raw).split(",") if item.strip())) + models_file = config.getoption("--e2e-models-file") + if models_file: + model_filters.update( + ( + line.strip() + for line in Path(models_file).read_text(encoding="utf-8").splitlines() + if line.strip() and (not line.lstrip().startswith("#")) + ) + ) + testcase_filters = set() + for raw in config.getoption("--e2e-testcase") or []: + testcase_filters.update((item.strip() for item in str(raw).split(",") if item.strip())) + if not model_filters and (not testcase_filters): + return (sorted(CASES), False) + selected = [] + for name, (_, manifest, _) in CASES.items(): + model_match = ( + not model_filters + or FAMILY in model_filters + or name in model_filters + or (manifest["name"] in model_filters) + ) + testcase_match = not testcase_filters or name in testcase_filters + if model_match and testcase_match: + selected.append(name) + return (sorted(selected), True) + + +def pytest_generate_tests(metafunc) -> None: + if "case_name" in metafunc.fixturenames: + names, enabled = _selected_cases(metafunc.config) + parameters = names + if not enabled: + parameters = [ + pytest.param( + name, + marks=pytest.mark.skip( + reason="direct E2E requires one of the three explicit E2E selectors" + ), + ) + for name in names + ] + metafunc.parametrize("case_name", parameters, ids=names) + + +def _required_path(value: str | None, label: str) -> Path: + assert value, f"selected {FAMILY} E2E requires {label}" + path = Path(value) + assert path.exists(), f"selected {FAMILY} E2E {label} does not exist: {path}" + return path + + +@cache +def _native_test_binary(name: str) -> Path: + """Build source-only helpers in the configured native test tree.""" + build_dir = _required_path(os.environ.get("TRTMC_NATIVE_BUILD_DIR"), "TRTMC_NATIVE_BUILD_DIR") + subprocess.run( + ["cmake", "--build", str(build_dir), "--parallel", "2", "--target", name], + check=True, + timeout=600, + ) + return _required_path(str(build_dir / name), name) + + +def _record_comparison(tmp_path, label, native, reference, checks): + """Retain the output pair and the result of already enforced comparisons.""" + if not evidence_enabled(): + return + import numpy as np + + paths = [] + for role, value in (("native", native), ("reference", reference)): + if isinstance(value, np.ndarray): + path = tmp_path / f"{label}-{role}.npz" + np.savez_compressed(path, output=value) + else: + path = tmp_path / f"{label}-{role}.json" + path.write_text(json.dumps(value, ensure_ascii=False) + "\n", encoding="utf-8") + paths.append(path) + record_evidence( + "reference_comparison", + { + "label": label, + "scope": "independent_reference", + "enforced": True, + "native": paths[0], + "reference": paths[1], + "checks": [dict(check, scope="independent_reference") for check in checks], + }, + ) + + +def _model_dir(manifest: dict) -> Path: + explicit = os.environ.get(f"TRTMC_{FAMILY.upper()}_MODEL_DIR") + from huggingface_hub import snapshot_download + + try: + snapshot = snapshot_download( + repo_id=manifest["hf_id"], revision=manifest.get("hf_revision"), local_files_only=True + ) + except Exception as error: + raise AssertionError( + f"selected {FAMILY} E2E requires the exact cached checkpoint {manifest['hf_id']}" + ) from error + from .checkpoint_identity import verify_pinned_copy + + candidate = ( + _required_path(explicit, f"TRTMC_{FAMILY.upper()}_MODEL_DIR") + if explicit + else Path(snapshot) + ) + return verify_pinned_copy(candidate, Path(snapshot)) + + +def _runtime() -> tuple[Path, Path]: + binary = _required_path(os.environ.get("TRTMC_BINARY"), "TRTMC_BINARY") + runtime_root = _required_path(os.environ.get("TRTMC_RUNTIME_ROOT"), "TRTMC_RUNTIME_ROOT") + assert (runtime_root / "libtrtmc_backend_trt.so").is_file() + assert (runtime_root / f"libtrtmc_model_{FAMILY}.so").is_file() + import torch + + assert torch.cuda.is_available(), f"selected {FAMILY} E2E requires CUDA" + assert torch.cuda.device_count() >= 1, f"selected {FAMILY} E2E requires one GPU" + return (binary, runtime_root) + + +def _build(model_dir: Path, bundle: Path, manifest: dict) -> None: + build( + BuildRequest( + model_dir=model_dir, + output_path=bundle, + family=FAMILY, + task=manifest["task"], + precision=manifest["precision"], + max_sequence_length=manifest.get("max_sequence_length"), + image_height=manifest.get("image_height"), + image_width=manifest.get("image_width"), + video_num_frames=manifest.get("video_num_frames"), + max_batch_size=int(manifest.get("max_batch_size", 1)), + tensor_parallel_size=int(manifest["tensor_parallel_size"]), + quantization=manifest.get("quantization"), + fp32_layers=tuple((int(layer) for layer in manifest.get("fp32_layers", ()))), + ) + ) + + +def _run_json( + binary: Path, + runtime_root: Path, + bundle: Path, + case: dict, + command: str, + *arguments: str, +) -> dict: + with evidence_stage("runtime"): + invocation = [ + str(binary), + command, + str(bundle), + "--runtime-root", + str(runtime_root), + *arguments, + ] + env = os.environ.copy() + env["LD_LIBRARY_PATH"] = ":".join( + (value for value in (str(runtime_root), env.get("LD_LIBRARY_PATH", "")) if value) + ) + completed = subprocess.run( + invocation, + check=False, + capture_output=True, + text=True, + env=env, + timeout=int(case.get("runtime_timeout_s", 3600)), + ) + record_evidence( + "native_process", + { + "argv": completed.args, + "stdout": (completed.stdout or "")[-4096:], + "stderr": (completed.stderr or "")[-16384:], + "returncode": completed.returncode, + }, + ) + assert completed.returncode == 0, completed.stderr + completed.stdout + payloads = [] + for line in completed.stdout.splitlines(): + start = line.find("{") + if start >= 0: + try: + payloads.append(json.loads(line[start:])) + except json.JSONDecodeError: + pass + assert payloads, f"native {command} returned no JSON: {completed.stdout[-1000:]}" + assert all((payload == payloads[0] for payload in payloads)) + return payloads[0] + + +def _examples(case): + for example in case["examples"]: + text = example["text"] + spans = [] + for role in ("subject", "object"): + begin = text.index(example[role]) + spans.append((begin, begin + len(example[role]))) + byte_spans = [ + (len(text[:begin].encode()), len(text[:end].encode())) for begin, end in spans + ] + yield text, spans, dict(text=text, subject=byte_spans[0], object=byte_spans[1]) + + +def test_native_entity_tokenization(case_name, tmp_path): + import numpy as np + from transformers import LukeTokenizer + + _, manifest, case = CASES[case_name] + directory = _model_dir(manifest) + _required_path(os.environ.get("TRTMC_RUNTIME_ROOT"), "TRTMC_RUNTIME_ROOT") + tokenizer = LukeTokenizer.from_pretrained(directory, task="entity_pair_classification") + tokenizer_path = tmp_path / "tokenizer.json" + tokenizer_path.write_text(tokenizer._tokenizer.to_str()) + config = dict( + sequence_length=manifest["max_sequence_length"], + max_mention_length=tokenizer.max_mention_length, + vocab_size=len(tokenizer), + pad_token_id=tokenizer.pad_token_id, + bos_token_id=tokenizer.bos_token_id, + eos_token_id=tokenizer.eos_token_id, + entity_markers=list(tokenizer.extra_special_tokens_ids[:2]), + ) + for text, spans, request in _examples(case): + expected = tokenizer( + text, + entity_spans=spans, + padding="max_length", + max_length=manifest["max_sequence_length"], + max_entity_length=2, + return_token_type_ids=True, + ) + completed = subprocess.run( + [str(_native_test_binary("test_luke_tokenizer"))], + input=json.dumps( + dict(**request, tokenizer_path=str(tokenizer_path), config=config), + ensure_ascii=False, + ), + capture_output=True, + text=True, + check=False, + ) + assert completed.returncode == 0, completed.stderr + actual = json.loads(completed.stdout) + assert actual["input_ids"] == expected["input_ids"] + assert actual["attention_mask"] == expected["attention_mask"] + assert ( + actual["entity_position_ids"] + == np.asarray(expected["entity_position_ids"]).reshape(-1).tolist() + ) + valid = np.asarray(expected["input_ids"]) != tokenizer.pad_token_id + positions = np.where(valid, valid.cumsum() + tokenizer.pad_token_id, tokenizer.pad_token_id) + assert actual["position_ids"] == positions.tolist() + + +def test_official_checkpoint_e2e(case_name, tmp_path): + _, manifest, case = CASES[case_name] + record_evidence("inputs", {"manifest": manifest, "case": case}) + record_evidence( + "checkpoint", + { + "repo_id": manifest["hf_id"], + "revision": manifest["hf_revision"], + "precision": manifest["precision"], + }, + ) + record_evidence( + "thresholds", + { + key: value + for key, value in case.items() + if any( + word in key + for word in ("error", "cosine", "atol", "rtol", "snr", "rmse", "max_abs") + ) + }, + ) + for asset_key in ("image", "test_image", "audio"): + if asset_key in case: + for asset_path in (TEST_ROOT / case[asset_key], TEST_ROOT / "data" / case[asset_key]): + if asset_path.is_file(): + record_evidence("inputs", {asset_key: asset_path}) + break + import numpy as np + import torch + from transformers import LukeTokenizer, LukeForEntityPairClassification + + _, manifest, case = CASES[case_name] + with evidence_stage("checkpoint"): + directory = _model_dir(manifest) + _, runtime_root = _runtime() + bundle = tmp_path / manifest["bundle"] + with evidence_stage("build"): + _build(directory, bundle, manifest) + record_evidence("bundle", {"path": str(bundle), "manifest": manifest}) + torch.backends.cuda.matmul.allow_tf32 = False + torch.backends.cudnn.allow_tf32 = False + with evidence_stage("reference"): + tokenizer = LukeTokenizer.from_pretrained(directory, task="entity_pair_classification") + with evidence_stage("reference"): + reference = ( + LukeForEntityPairClassification.from_pretrained(directory, dtype=torch.float32) + .eval() + .to("cuda") + ) + labels = [reference.config.id2label[index] for index in range(reference.config.num_labels)] + for text, spans, request in _examples(case): + inputs = tokenizer( + text, + entity_spans=spans, + padding="max_length", + max_length=manifest["max_sequence_length"], + max_entity_length=2, + return_token_type_ids=True, + return_tensors="pt", + ).to("cuda") + with evidence_stage("reference"), torch.no_grad(): + expected = reference(**inputs).logits[0].cpu().numpy() + with evidence_stage("runtime"): + completed = subprocess.run( + [str(_native_test_binary("test_luke_runtime")), str(bundle), str(runtime_root)], + input=json.dumps(request, ensure_ascii=False), + capture_output=True, + text=True, + check=False, + timeout=600, + ) + record_evidence( + "runtime_process", + { + "argv": completed.args, + "returncode": completed.returncode, + "stdout": (completed.stdout or "")[-4096:], + "stderr": (completed.stderr or "")[-16384:], + }, + ) + with evidence_stage("comparison"): + assert completed.returncode == 0, completed.stderr + completed.stdout + payload = json.loads(completed.stdout.splitlines()[-1]) + with evidence_stage("comparison"): + assert payload["labels"] == labels and payload["kind"] == 1 + actual = np.asarray(payload["scores"], dtype=np.float32) + with evidence_stage("comparison"): + assert actual.shape == expected.shape and np.isfinite(actual).all() + record_evidence("inputs", {"text": text, "entity_spans": spans, "request": request}) + record_evidence("native", {"labels": labels, "scores": actual}) + record_evidence( + "reference", {"mode": "hf_transformers", "labels": labels, "scores": expected} + ) + maximum = float(np.max(np.abs(actual - expected))) + record_evidence( + "metrics", + { + "max_abs_error": maximum, + "native_top_class": int(np.argmax(actual)), + "reference_top_class": int(np.argmax(expected)), + }, + ) + with evidence_stage("comparison"): + assert maximum <= case["max_abs_error"] + with evidence_stage("comparison"): + assert np.argmax(actual) == np.argmax(expected) + _record_comparison( + tmp_path, + f"relation-{len(text)}-{int(np.argmax(actual))}", + actual, + expected, + [ + { + "name": "max_abs_error", + "actual": maximum, + "operator": "<=", + "expected": case["max_abs_error"], + "passed": maximum <= case["max_abs_error"], + }, + { + "name": "top_class", + "actual": int(np.argmax(actual)), + "operator": "==", + "expected": int(np.argmax(expected)), + "passed": bool(np.argmax(actual) == np.argmax(expected)), + }, + ], + ) + print(f"LUKE {text!r}: max_abs={maximum:.8g}, relation={labels[np.argmax(actual)]}") diff --git a/families/luke/tests/test_support.py b/families/luke/tests/test_support.py new file mode 100644 index 0000000000..26047fb4fa --- /dev/null +++ b/families/luke/tests/test_support.py @@ -0,0 +1,39 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +import json + +import pytest +from tensorrt_model_connect.model_support import ModelMetadata, resolve_family + + +def test_luke_checkpoint_has_one_owner(): + family, support = resolve_family(ModelMetadata({"model_type": "luke"}, {})) + assert family == "luke" + assert support.tasks == ("text_entity_pair_to_relation_scores",) + assert support.default_task == "text_entity_pair_to_relation_scores" + + +def test_builder_rejects_word_profile_above_runtime_limit(tmp_path): + from tensorrt_model_connect import BuildRequest + + from families.luke.model import build + + config = { + "architectures": ["LukeForEntityPairClassification"], + "model_type": "luke", + "hidden_act": "gelu", + "use_entity_aware_attention": True, + "max_position_embeddings": 1024, + "pad_token_id": 1, + } + (tmp_path / "config.json").write_text(json.dumps(config)) + request = BuildRequest( + model_dir=tmp_path, + output_path=tmp_path / "luke.bundle", + family="luke", + precision="fp32", + task="text_entity_pair_to_relation_scores", + max_sequence_length=513, + ) + with pytest.raises(ValueError, match="between 8 and 512 tokens"): + build(request, None) diff --git a/families/luke/tests/test_tokenizer.py b/families/luke/tests/test_tokenizer.py new file mode 100644 index 0000000000..1fe8ad3422 --- /dev/null +++ b/families/luke/tests/test_tokenizer.py @@ -0,0 +1,107 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +import json +import os +from pathlib import Path +import subprocess + +import pytest +from tokenizers import Tokenizer, models, pre_tokenizers + + +@pytest.fixture(scope="module") +def tokenizer_binary(): + build = Path(os.environ["TRTMC_NATIVE_BUILD_DIR"]) + subprocess.run( + ["cmake", "--build", str(build), "--parallel", "2", "--target", "test_luke_tokenizer"], + check=True, + timeout=600, + ) + binary = build / "test_luke_tokenizer" + assert binary.is_file(), "native tokenizer consumer was not built" + return binary + + +@pytest.fixture +def invoke(tmp_path, tokenizer_binary): + alphabet = sorted(pre_tokenizers.ByteLevel.alphabet()) + tokenizer = Tokenizer( + models.BPE(vocab={token: i for i, token in enumerate(alphabet)}, merges=[]) + ) + tokenizer.pre_tokenizer = pre_tokenizers.ByteLevel(add_prefix_space=False) + tokenizer.add_special_tokens(["", ""]) + source = json.loads(tokenizer.to_str()) + config = dict( + sequence_length=8, + max_mention_length=30, + vocab_size=258, + pad_token_id=0, + bos_token_id=1, + eos_token_id=2, + entity_markers=[256, 257], + ) + + def run(mutation=None, text="AB", subject=(0, 1), object=(1, 2)): + if mutation: + mutation(source) + path = tmp_path / "tokenizer.json" + path.write_text(json.dumps(source)) + request = dict( + tokenizer_path=str(path), config=config, text=text, subject=subject, object=object + ) + return subprocess.run( + [str(tokenizer_binary)], input=json.dumps(request), text=True, capture_output=True + ) + + return run + + +def test_added_tokens_beyond_base_and_short_word_profile(invoke): + process = invoke() + assert process.returncode == 0, process.stderr + result = json.loads(process.stdout) + assert len(result["input_ids"]) == 8 + assert result["entity_position_ids"][:30] == [1, 2, 3] + [-1] * 27 + assert result["entity_position_ids"][30:] == [4, 5, 6] + [-1] * 27 + + +def test_added_token_is_matched_inside_entity_text(invoke): + process = invoke(text="B", subject=(0, 5), object=(5, 6)) + assert process.returncode == 0, process.stderr + assert json.loads(process.stdout)["input_ids"][1:4] == [256, 256, 256] + + +@pytest.mark.parametrize("identifier", [42.5, -1, 256, 2**32 + 42, 2**64 - 1]) +def test_invalid_base_vocabulary_id_is_rejected(invoke, identifier): + process = invoke(lambda source: source["model"]["vocab"].update(A=identifier)) + assert process.returncode == 1 + assert "Invalid LUKE base vocabulary ID" in process.stderr + + +@pytest.mark.parametrize("field", ["id", "content"]) +def test_missing_added_token_field_is_rejected(invoke, field): + process = invoke(lambda source: source["added_tokens"][0].pop(field)) + assert process.returncode == 1 + assert field in process.stderr + + +@pytest.mark.parametrize("identifier", [-1, 2147483648, 18446744073709551615, 1.5]) +def test_invalid_added_token_id_is_rejected(invoke, identifier): + process = invoke(lambda source: source["added_tokens"][0].update(id=identifier)) + assert process.returncode == 1 + assert "nonnegative" in process.stderr + + +def test_sparse_unused_added_id_does_not_expand_vocabulary(invoke): + process = invoke( + lambda source: source["added_tokens"].append( + dict(id=2000000000, content="", special=False) + ) + ) + assert process.returncode == 0, process.stderr + + +def test_empty_token_entity_is_rejected(invoke): + process = invoke(text=" A", subject=(0, 1), object=(1, 2)) + assert process.returncode == 1 + assert "at least one token" in process.stderr diff --git a/website/plugins/model-support-inventory/index.js b/website/plugins/model-support-inventory/index.js index 7b0e2f4a76..aa08e1c3fb 100644 --- a/website/plugins/model-support-inventory/index.js +++ b/website/plugins/model-support-inventory/index.js @@ -67,6 +67,7 @@ const TASKS = { title_body_to_embedding: ['Title and body embedding', 'Natural Language Processing', 'feature-extraction', 'embed'], masked_text_to_token_scores: ['Masked text token scores', 'Natural Language Processing', 'fill-mask', 'encode'], text_pair_to_pretraining_relation_scores: ['Text-pair pretraining relation scores', 'Natural Language Processing', null, 'encode'], + text_entity_pair_to_relation_scores: ['Entity-pair relation scores', 'Natural Language Processing', null, null], text_to_replaced_token_scores: ['Replaced-token scores', 'Natural Language Processing', null, 'encode'], text_prediction_positions_to_token_scores: ['Selected-position token scores', 'Natural Language Processing', null, 'encode'], image_to_token_features: ['Image token features', 'Computer Vision', 'image-feature-extraction', 'extract-features'], diff --git a/website/plugins/model-support-inventory/index.test.js b/website/plugins/model-support-inventory/index.test.js index 1520cc8aed..c838ea52ac 100644 --- a/website/plugins/model-support-inventory/index.test.js +++ b/website/plugins/model-support-inventory/index.test.js @@ -179,6 +179,7 @@ test('SDK-only Tasks do not invent CLI workloads or taxonomy links', (context) = 'pose_hypotheses_crops_to_refined_poses', 'batch_series_to_point_forecast', 'recurrent_tokens_to_logits', + 'text_entity_pair_to_relation_scores', 'text_to_audio_video', ]) addTaskManifest(root, task); const inventory = collectModelSupportInventory(root);