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

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions core/api/include/trtmc/features.h
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
17 changes: 17 additions & 0 deletions core/api/include/trtmc/features.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -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;
};
Expand Down Expand Up @@ -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 Traits>
class FeatureTask {
public:
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -764,6 +779,8 @@ using TitleBodyToEmbedding = detail::FeatureTask<detail::TitleBodyToEmbeddingTra
using MaskedTextToTokenScores = detail::FeatureTask<detail::MaskedTextToTokenScoresTraits>;
using TextPairToPretrainingRelationScores =
detail::FeatureTask<detail::TextPairToPretrainingRelationScoresTraits>;
using TextEntityPairToRelationScores =
detail::FeatureTask<detail::TextEntityPairToRelationScoresTraits>;
using TextToReplacedTokenScores = detail::FeatureTask<detail::TextToReplacedTokenScoresTraits>;
using TextPredictionPositionsToTokenScores =
detail::FeatureTask<detail::TextPredictionPositionsToTokenScoresTraits>;
Expand Down
33 changes: 33 additions & 0 deletions core/api/runtime/features.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -545,6 +545,26 @@ const trtmc_document_words_to_token_features_api_v1 document_features_api{
document_features_run,
result_view<DocumentTokenFeaturesStorage, trtmc_document_token_features_view_v1>};

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<unsigned char>(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 <class Interface, class Request, class Storage>
trtmc_status TRTMC_CALL run(trtmc_model* model, const Request* input,
const trtmc_config_view_v1* config, trtmc_result** out,
Expand All @@ -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<Interface, internal::IImageToClassScores>)
require_class_identity(result);
if constexpr (std::is_same_v<Interface, internal::ITextEntityPairToRelationScores>) {
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<Storage>(std::move(result));
});
}
Expand Down Expand Up @@ -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<internal::ITextEntityPairToRelationScores,
trtmc_text_entity_pair_to_relation_scores_request_v1, LabelScoresStorage>,
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},
Expand Down Expand Up @@ -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},
Expand Down
32 changes: 32 additions & 0 deletions core/api/tests/features_family.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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<TaskInstance> task_bindings() override {
return {bind<ITextEntityPairToRelationScores>(*this)};
}
LabelScoresResult run(const TextEntityPairToRelationScoresRequest& input,
ConfigView config) override {
validate_config({}, config);
LabelScoresResult result;
result.scores = {-1,
2,
static_cast<float>(input.subject.begin),
static_cast<float>(input.subject.end),
static_cast<float>(input.object.begin),
static_cast<float>(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"; }
Expand Down Expand Up @@ -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)
Expand Down
57 changes: 57 additions & 0 deletions core/api/tests/features_test.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
#include "trtmc/features.hpp"

#include <algorithm>
#include <array>
#include <cmath>
#include <filesystem>
#include <fstream>
Expand Down Expand Up @@ -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<TextEntityPairToRelationScores>();
auto result =
Model::load(path.string(), options).task<TextEntityPairToRelationScores>().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<float, 6>& 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<TextPairToPretrainingRelationScores>(),
"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<TextEntityPairToRelationScores>().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 <class Function>
void rejects_index(Function function, trtmc_status code, size_t index, const char* message) {
bool matched = false;
Expand Down Expand Up @@ -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",
Expand Down
17 changes: 17 additions & 0 deletions core/runtime/include/trtmc/internal/features.h
Original file line number Diff line number Diff line change
Expand Up @@ -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
4 changes: 4 additions & 0 deletions families/luke/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0

"""luke family package."""
78 changes: 78 additions & 0 deletions families/luke/graph.py
Original file line number Diff line number Diff line change
@@ -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)
Loading
Loading