From 94f115b476e7ed55aecf37efcd90078b8beed578 Mon Sep 17 00:00:00 2001 From: Will Guo Date: Fri, 13 Nov 2026 08:40:01 -0800 Subject: [PATCH 1/2] feat(bros): add native document encoding Build the pinned BROS base checkpoint as an FP32 TensorRT encoder for up to 128 tokens with normalized page rectangles, attention masks and segment IDs. Keep relative geometry, encoder topology and orchestration in the family. Add the document encoding Task and structured-input CLI. Validate every token and pooled feature against the upstream checkpoint, including its legacy box-module weight names, plus intermediate tensors, geometry sensitivity, capacity boundary, invalid-request recovery, CLI execution, ownership, architecture and public documentation locally. Signed-off-by: Will Guo --- CMakeLists.txt | 8 + apps/cli/cli.cpp | 34 ++- apps/cli/cli.h | 1 + apps/cli/tests/test_document_encoding_cli.cpp | 56 ++++ apps/task_runtime.h | 1 + core/runtime/include/trtmc/task.h | 24 ++ families/bros/README.md | 44 +++ families/bros/__init__.py | 3 + families/bros/model.py | 275 ++++++++++++++++++ families/bros/requirements.txt | 3 + families/bros/runtime/CMakeLists.txt | 15 + families/bros/runtime/pipeline.cpp | 61 ++++ families/bros/runtime/pipeline.h | 19 ++ families/bros/runtime/plugin.cpp | 24 ++ families/bros/support.py | 11 + families/bros/tests/__init__.py | 2 + families/bros/tests/cpp/e2e_consumer.cpp | 55 ++++ .../tests/manifests/bros-base-uncased.json | 19 ++ families/bros/tests/math_check.py | 86 ++++++ families/bros/tests/requirements.txt | 1 + families/bros/tests/test_e2e.py | 262 +++++++++++++++++ families/bros/tests/test_model.py | 44 +++ families/bros/tests/test_support.py | 10 + website/docs/api/cli-reference.md | 8 +- website/docs/api/cpp-api.md | 9 + .../plugins/model-support-inventory/index.js | 1 + .../model-support-inventory/index.test.js | 11 + 27 files changed, 1085 insertions(+), 2 deletions(-) create mode 100644 apps/cli/tests/test_document_encoding_cli.cpp create mode 100644 families/bros/README.md create mode 100644 families/bros/__init__.py create mode 100644 families/bros/model.py create mode 100644 families/bros/requirements.txt create mode 100644 families/bros/runtime/CMakeLists.txt create mode 100644 families/bros/runtime/pipeline.cpp create mode 100644 families/bros/runtime/pipeline.h create mode 100644 families/bros/runtime/plugin.cpp create mode 100644 families/bros/support.py create mode 100644 families/bros/tests/__init__.py create mode 100644 families/bros/tests/cpp/e2e_consumer.cpp create mode 100644 families/bros/tests/manifests/bros-base-uncased.json create mode 100644 families/bros/tests/math_check.py create mode 100644 families/bros/tests/requirements.txt create mode 100644 families/bros/tests/test_e2e.py create mode 100644 families/bros/tests/test_model.py create mode 100644 families/bros/tests/test_support.py diff --git a/CMakeLists.txt b/CMakeLists.txt index a6e4f0377c..ef4363e995 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -515,6 +515,14 @@ if(TRTMC_BUILD_TESTS) target_compile_options(test_cli PRIVATE -Wall -Wextra -Wpedantic) add_test(NAME cli COMMAND test_cli) + add_executable(test_document_encoding_cli apps/cli/tests/test_document_encoding_cli.cpp) + target_include_directories(test_document_encoding_cli PRIVATE ${PROJECT_SOURCE_DIR}/apps) + target_link_libraries(test_document_encoding_cli PRIVATE trtmc_cli nlohmann_json::nlohmann_json) + target_compile_options(test_document_encoding_cli PRIVATE -Wall -Wextra -Wpedantic) + add_test(NAME document_encoding_cli COMMAND test_document_encoding_cli + ${CMAKE_BINARY_DIR}/document-encoding-cli-test) + + if(TRTMC_BUILD_SERVER) add_executable(test_server_worker apps/server/tests/test_native_worker.cpp) target_include_directories(test_server_worker PRIVATE diff --git a/apps/cli/cli.cpp b/apps/cli/cli.cpp index 6835558982..aeda567d4e 100644 --- a/apps/cli/cli.cpp +++ b/apps/cli/cli.cpp @@ -93,6 +93,7 @@ const std::unordered_map& command_specs() { {CommandKind::kEncode, {"--text", "--text-pair", "--token-ids", "--segment-ids", "--attention-mask", "--blocked-attention", "--prediction-positions"}}}, + {"encode-document", {CommandKind::kEncodeDocument, {"--input"}}}, {"embed", {CommandKind::kEmbed, {"--text", "--token-ids", "--image", "--title", "--body", "--role"}}}, @@ -880,6 +881,36 @@ int dispatch(const Command& command, ITask& task, std::ostream& output) { write_json(output, {{"score", score}}); return EXIT_SUCCESS; } + case CommandKind::kEncodeDocument: { + std::ifstream file(require_option(command, "--input")); + if (!file) throw std::invalid_argument("cannot read document JSON"); + const auto input = nlohmann::json::parse(file); + auto integers = [&](const char* name, bool required) { + std::vector values; + if (!input.contains(name) && !required) return values; + const auto& array = input.at(name); + if (!array.is_array()) throw std::invalid_argument(std::string(name) + " must be an integer array"); + for (const auto& value : array) { + if (!value.is_number_integer() || + (value.is_number_unsigned() && value.get() > 2147483647ULL) || + (!value.is_number_unsigned() && (value.get() < -2147483648LL || value.get() > 2147483647LL))) + throw std::invalid_argument(std::string(name) + " requires signed 32-bit integers"); + values.push_back(value.get()); + } + return values; + }; + DocumentEncodingRequest request; + request.token_ids = integers("token_ids", true); + request.attention_mask = integers("attention_mask", false); + request.token_type_ids = integers("token_type_ids", false); + request.boxes = input.at("boxes").get>>(); + const auto result = require_interface(task).encode(request); + require_finite(result.token_features, "document token features"); + require_finite(result.pooled_features, "document pooled features"); + write_json(output, {{"token_features", result.token_features}, {"pooled_features", result.pooled_features}, + {"tokens", result.tokens}, {"dim", result.dim}}); + return EXIT_SUCCESS; + } case CommandKind::kClassify: { const io::LoadedImage image = read_image(require_option(command, "--image")); const auto result = require_interface(task).classify( @@ -1614,7 +1645,7 @@ void print_usage(std::ostream& output) { " trtmc inspect BUNDLE\n" " trtmc COMMAND BUNDLE [--runtime-root DIR] [OPTIONS]\n\n" "Execution commands:\n" - " run, encode, embed, rerank, classify, detect, extract-features,\n" + " run, encode, encode-document, embed, rerank, classify, detect, extract-features,\n" " predict-structure, disparity, depth, geometry,\n" " segment,\n" " segment-prompted, video-segment, generate-audio, transcribe,\n" @@ -1639,6 +1670,7 @@ void print_usage(std::ostream& output) { " .yaml/.yml, .json and .b2rq select their declared encodings.\n" " SDK output defaults to prediction.cif or prediction.pdb.\n\n" "Audio classification input:\n" + " encode-document BUNDLE --input JSON encodes token IDs and page rectangles.\n" " classify BUNDLE --audio WAV scores an audio model's own classes;\n" " classify BUNDLE --image FILE stays the image path.\n\n" "BYOK options:\n" diff --git a/apps/cli/cli.h b/apps/cli/cli.h index e430056b24..0e175ecaf4 100644 --- a/apps/cli/cli.h +++ b/apps/cli/cli.h @@ -27,6 +27,7 @@ enum class CommandKind { kInspect, kRun, kEncode, + kEncodeDocument, kEmbed, kRerank, kClassify, diff --git a/apps/cli/tests/test_document_encoding_cli.cpp b/apps/cli/tests/test_document_encoding_cli.cpp new file mode 100644 index 0000000000..d074bfd4f5 --- /dev/null +++ b/apps/cli/tests/test_document_encoding_cli.cpp @@ -0,0 +1,56 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + */ +#include "cli/cli.h" +#include "task_runtime.h" +#include +#include +#include +#include +#include +#include +#include +static_assert(std::is_abstract_v); +namespace { +void check(bool x,const char* message) {if (!x) throw std::runtime_error(message);} +class Document final : public trtmc::IDocumentEncoding { + public: + int calls{0}; + trtmc::DocumentEncodingResult encode(const trtmc::DocumentEncodingRequest& r) override { + ++calls; + check(r.token_ids==std::vector{7,11} && r.attention_mask==std::vector{1,0} && + r.token_type_ids==std::vector{0,1},"token metadata changed"); + check(r.boxes==std::vector>{{0,0,0.5F,1},{0.5F,0,1,1}},"page rectangles changed"); + return {{1,2,3,4},{5,6},2,2}; + } +}; +} +int main(int argc,char** argv) { + try { + if (argc!=2) throw std::invalid_argument("usage: test_document_encoding_cli TEMP_DIR"); + const std::filesystem::path root(argv[1]);std::filesystem::create_directories(root);const auto path=root/"input.json"; + nlohmann::json input={{"token_ids",{7,11}},{"attention_mask",{1,0}},{"token_type_ids",{0,1}}, + {"boxes",{{0,0,0.5,1},{0.5,0,1,1}}}}; + {std::ofstream file(path);file< args={"trtmc","encode-document","fixture.bundle","--input",path.string()}; + std::vector pointers;for (auto& a:args) pointers.push_back(a.data()); + const auto command=trtmc::cli::parse_args(static_cast(pointers.size()),pointers.data()); + check(command.kind==trtmc::cli::CommandKind::kEncodeDocument,"document command missing"); + Document task;check(trtmc::app::uses_existing_task_runtime(task.task()),"document Task loader selection missing"); + std::ostringstream output;check(trtmc::cli::dispatch(command,task,output)==0,"document dispatch failed"); + const auto result=nlohmann::json::parse(output.str()); + check(result.at("tokens")==2 && result.at("dim")==2 && result.at("token_features")==std::vector{1,2,3,4},"feature dimensions changed"); + for (int mode=0;mode<3;++mode) { + auto invalid=input; + if (mode==0) invalid["token_ids"][0]=4294967303ULL; + if (mode==1) invalid["attention_mask"][0]=1.5; + if (mode==2) invalid["token_type_ids"][0]=-2147483649LL; + {std::ofstream file(path);file< token_ids; + std::vector> boxes; + std::vector attention_mask; + std::vector token_type_ids; +}; + +struct DocumentEncodingResult { + std::vector token_features; // token-major, tokens x dim + std::vector pooled_features; + std::int32_t tokens{0}; + std::int32_t dim{0}; +}; + struct SegmentResult { std::vector mask; std::int32_t height{0}; @@ -704,6 +721,13 @@ class IEncoding : public virtual ITask { virtual EmbeddingResult encode(const std::string& text) = 0; }; +class IDocumentEncoding : public virtual ITask { + public: + static constexpr const char* kTask = "document_encoding"; + const char* task() const noexcept override { return kTask; } + virtual DocumentEncodingResult encode(const DocumentEncodingRequest& request) = 0; +}; + class IReranking : public virtual ITask { public: static constexpr const char* kTask = "reranking"; diff --git a/families/bros/README.md b/families/bros/README.md new file mode 100644 index 0000000000..a8b446dbd8 --- /dev/null +++ b/families/bros/README.md @@ -0,0 +1,44 @@ +# BROS + +This family builds `naver-clova-ocr/bros-base-uncased` at revision +`0f0e83a58cde75af72e331e6a018cd5bc7ccab31` as an FP32 TensorRT document encoder. +The native `IDocumentEncoding` Task accepts 1 to 128 token IDs, one normalized +`[left, top, right, bottom]` page rectangle per token, and optional binary +attention masks and segment IDs. It returns each token's 768 features and the +768-element pooled vector. This base checkpoint has no entity-classification head. + +Callers tokenize using the checkpoint's BERT vocabulary and repeat each word's +box for its WordPiece tokens. Special-token boxes may be zero rectangles. No +special tokens are inserted by the runtime. The family pads internally with +masked tokens, validates the complete request before execution, and removes +padding rows from returned features. + +```bash +trtmc encode-document model.bundle --input page.json +``` + +For example, `page.json` may contain: + +```json +{"token_ids":[101,7592,102],"boxes":[[0,0,0,0],[0.1,0.1,0.3,0.2],[0,0,0,0]]} +``` + +The family owns learned text embeddings, sinusoidal relative box features, +attention geometry, all twelve encoder layers and pooling. It reads the legacy +checkpoint box-module names directly; the upstream test loader explicitly maps +those three names to its current module names and verifies every loaded tensor. +The obsolete unused one-dimensional frequency buffer is not part of execution. +The PyTorch state dictionary is read with `weights_only=True`. + +Batch size is one. Other capacities, FP16, quantization, parallel execution, +image/video options and KV caches are rejected. GPU computation uses TensorRT +operators throughout. Select validation with: + +```bash +python -m pytest families/bros/tests --e2e-model bros -q +``` + +Tests compare upstream intermediate tensors, every token and pooled feature on +invoice and paragraph fixtures, sensitivity to changed geometry, masks and +segments, the 128-token boundary, repeated requests, rejection recovery and the +CLI. Runtime plans and validation artifacts stay outside the source branch. diff --git a/families/bros/__init__.py b/families/bros/__init__.py new file mode 100644 index 0000000000..d05e6f4f26 --- /dev/null +++ b/families/bros/__init__.py @@ -0,0 +1,3 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +"""BROS document encoder family.""" diff --git a/families/bros/model.py b/families/bros/model.py new file mode 100644 index 0000000000..8f202a8c2b --- /dev/null +++ b/families/bros/model.py @@ -0,0 +1,275 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +"""BROS text embeddings, relative page geometry and encoder in TensorRT.""" + +import json +from pathlib import Path +import numpy as np +import tensorrt as trt + + +def validate_config(raw): + from transformers import BrosConfig + + c = BrosConfig.from_dict(raw).to_dict() + if ( + c["model_type"] != "bros" + or c["hidden_act"] != "gelu" + or c["is_decoder"] + or c["add_cross_attention"] + ): + raise ValueError("bros requires the bidirectional GELU document encoder") + if ( + c["dim_bbox"] != 8 + or c["dim_bbox_sinusoid_emb_1d"] % 2 + or c["dim_bbox_sinusoid_emb_1d"] <= 0 + ): + raise ValueError("bros requires eight coordinates with even sinusoidal width") + if ( + c["hidden_size"] % c["num_attention_heads"] + or c["num_hidden_layers"] <= 0 + or c["max_position_embeddings"] < 128 + ): + raise ValueError("bros invalid encoder or position dimensions") + return c + + +class Graph: + def __init__(self, network, config, weights, cap=128, debug=False): + self.n, self.c, self.w, self.cap, self.debug = network, config, weights, cap, debug + self.storage = [] + + def weight(self, name): + key = name + if key not in self.w and key.startswith("bbox_embeddings."): + key = "embeddings." + key[len("bbox_embeddings.") :] + if key not in self.w: + raise ValueError(f"bros missing checkpoint tensor {name}") + value = np.ascontiguousarray(self.w[key], dtype=np.float32) + if not np.isfinite(value).all(): + raise ValueError(f"bros nonfinite tensor {name}") + self.storage.append(value) + return value + + def constant(self, value, dtype=np.float32): + value = np.ascontiguousarray(value, dtype=dtype) + self.storage.append(value) + return self.n.add_constant(value.shape, trt.Weights(value)).get_output(0) + + def reshape(self, x, shape, transpose=None): + layer = self.n.add_shuffle(x) + layer.reshape_dims = shape + if transpose is not None: + layer.second_transpose = transpose + return layer.get_output(0) + + def binary(self, x, y, op): + return self.n.add_elementwise(x, y, op).get_output(0) + + def add(self, x, y): + return self.binary(x, y, trt.ElementWiseOperation.SUM) + + def mul(self, x, y): + return self.binary(x, y, trt.ElementWiseOperation.PROD) + + def linear(self, x, name): + w = self.weight(name + ".weight") + rank = len(x.shape) + rhs = self.constant(w.T.reshape((1,) * (rank - 2) + w.T.shape)) + y = self.n.add_matrix_multiply( + x, trt.MatrixOperation.NONE, rhs, trt.MatrixOperation.NONE + ).get_output(0) + if name + ".bias" in self.w: + y = self.add( + y, self.constant(self.weight(name + ".bias").reshape((1,) * (rank - 1) + (-1,))) + ) + return y + + def norm(self, x, name): + rank = len(x.shape) + shape = (1,) * (rank - 1) + (-1,) + layer = self.n.add_normalization( + x, + self.constant(self.weight(name + ".weight").reshape(shape)), + self.constant(self.weight(name + ".bias").reshape(shape)), + 1 << (rank - 1), + ) + layer.epsilon = self.c["layer_norm_eps"] + return layer.get_output(0) + + def output(self, x, name): + x = self.n.add_identity(x).get_output(0) + x.name = name + self.n.mark_output(x) + + def geometry(self, boxes): + cap = self.cap + boxes = self.n.add_gather( + boxes, self.constant([0, 1, 2, 1, 2, 3, 0, 3], np.int32), 2 + ).get_output(0) + boxes = self.mul(boxes, self.constant([[[self.c["bbox_scale"]]]])) + difference = self.binary( + self.reshape(boxes, (1, cap, 8)), + self.reshape(boxes, (cap, 1, 8)), + trt.ElementWiseOperation.SUB, + ) + values = [] + for i in range(8): + positions = self.n.add_slice( + difference, (0, 0, i), (cap, cap, 1), (1, 1, 1) + ).get_output(0) + freq = self.weight( + "bbox_embeddings.bbox_sinusoid_emb." + + ("x" if i % 2 == 0 else "y") + + "_pos_emb.inv_freq" + ) + angles = self.mul(positions, self.constant(freq.reshape(1, 1, -1))) + parts = [ + self.n.add_unary(angles, op).get_output(0) + for op in (trt.UnaryOperation.SIN, trt.UnaryOperation.COS) + ] + concat = self.n.add_concatenation(parts) + concat.axis = 2 + values.append(concat.get_output(0)) + concat = self.n.add_concatenation(values) + concat.axis = 2 + projected = self.linear( + self.reshape(concat.get_output(0), (cap * cap, self.c["dim_bbox_sinusoid_emb_2d"])), + "bbox_embeddings.bbox_projection", + ) + return self.reshape( + projected, (1, cap, cap, self.c["hidden_size"] // self.c["num_attention_heads"]) + ) + + def attention(self, x, bbox, mask, name): + cap, h = self.cap, self.c["hidden_size"] + heads = self.c["num_attention_heads"] + d = h // heads + q, k, v = [ + self.reshape(self.linear(x, name + ".self." + p), (1, cap, heads, d), (0, 2, 1, 3)) + for p in ("query", "key", "value") + ] + scores = self.n.add_matrix_multiply( + q, trt.MatrixOperation.NONE, k, trt.MatrixOperation.TRANSPOSE + ).get_output(0) + # One batched matrix product per query position, with all heads sharing + # its relative-box table. This expresses the geometry contraction directly. + queries = self.n.add_shuffle(q) + queries.first_transpose = (0, 2, 1, 3) + queries.reshape_dims = (cap, heads, d) + spatial = self.n.add_matrix_multiply( + queries.get_output(0), + trt.MatrixOperation.NONE, + self.reshape(bbox, (cap, cap, d)), + trt.MatrixOperation.TRANSPOSE, + ).get_output(0) + spatial = self.reshape(spatial, (1, cap, heads, cap), (0, 2, 1, 3)) + scores = self.mul(self.add(scores, spatial), self.constant([[[[d**-0.5]]]])) + scores = self.add(scores, mask) + probs = self.n.add_softmax(scores) + probs.axes = 1 << 3 + context = self.n.add_matrix_multiply( + probs.get_output(0), trt.MatrixOperation.NONE, v, trt.MatrixOperation.NONE + ).get_output(0) + merge = self.n.add_shuffle(context) + merge.first_transpose = (0, 2, 1, 3) + merge.reshape_dims = (1, cap, h) + return self.norm( + self.add(x, self.linear(merge.get_output(0), name + ".output.dense")), + name + ".output.LayerNorm", + ) + + def build(self): + cap, h = self.cap, self.c["hidden_size"] + ids = self.n.add_input("input_ids", trt.int32, (1, cap)) + segments = self.n.add_input("token_type_ids", trt.int32, (1, cap)) + boxes = self.n.add_input("bbox", trt.float32, (1, cap, 4)) + mask = self.n.add_input("attention_mask", trt.float32, (1, 1, 1, cap)) + x = self.n.add_gather( + self.constant(self.weight("embeddings.word_embeddings.weight")), ids, 0 + ).get_output(0) + segment_emb = self.n.add_gather( + self.constant(self.weight("embeddings.token_type_embeddings.weight")), segments, 0 + ).get_output(0) + positions = self.constant(self.weight("embeddings.position_embeddings.weight")[:cap][None]) + x = self.norm(self.add(self.add(x, segment_emb), positions), "embeddings.LayerNorm") + bbox = self.geometry(boxes) + if self.debug: + self.output(x, "embeddings") + self.output(bbox, "geometry") + for i in range(self.c["num_hidden_layers"]): + p = f"encoder.layer.{i}" + x = self.attention(x, bbox, mask, p + ".attention") + y = self.n.add_activation( + self.linear(x, p + ".intermediate.dense"), trt.ActivationType.GELU_ERF + ).get_output(0) + x = self.norm(self.add(x, self.linear(y, p + ".output.dense")), p + ".output.LayerNorm") + if self.debug: + self.output(x, f"layer_{i}") + self.output(x, "token_features") + cls = self.n.add_slice(x, (0, 0, 0), (1, 1, h), (1, 1, 1)).get_output(0) + pooled = self.n.add_activation( + self.linear(self.reshape(cls, (1, h)), "pooler.dense"), trt.ActivationType.TANH + ).get_output(0) + self.output(pooled, "pooled_features") + + +def compile_engine(config, weights, verbose=False, cap=128, debug=False): + logger = trt.Logger(trt.Logger.VERBOSE if verbose else trt.Logger.WARNING) + builder = trt.Builder(logger) + network = builder.create_network(1 << int(trt.NetworkDefinitionCreationFlag.STRONGLY_TYPED)) + options = builder.create_builder_config() + options.builder_optimization_level = 3 + options.clear_flag(trt.BuilderFlag.TF32) + graph = Graph(network, config, weights, cap, debug) + graph.build() + plan = builder.build_serialized_network(network, options) + if plan is None: + raise RuntimeError("bros TensorRT document encoder build failed") + return bytes(plan) + + +def build(request, writer): + if request.dynamic_kv_cache: + raise NotImplementedError("bros does not support dynamic_kv_cache") + if ( + request.task != "document_encoding" + or request.precision != "fp32" + or request.backend != "trt" + ): + raise ValueError("bros requires document_encoding, FP32 and backend=trt") + for field, value, default in ( + ("max_batch_size", request.max_batch_size, 1), + ("tensor_parallel_size", request.tensor_parallel_size, 1), + ("context_parallel_size", request.context_parallel_size, 1), + ("video_num_frames", request.video_num_frames, None), + ("image_height", request.image_height, None), + ("image_width", request.image_width, None), + ("mtp_seq_len", request.mtp_seq_len, None), + ("fp32_layers", request.fp32_layers, ()), + ): + if value != default: + raise NotImplementedError(f"bros does not support {field}") + if request.max_sequence_length not in (None, 128): + raise ValueError("bros supports a 128-token capacity") + if request.quantization not in (None, "none"): + raise NotImplementedError("bros does not support quantization") + root = Path(request.model_dir) + c = validate_config(json.loads((root / "config.json").read_text())) + import torch + + raw = torch.load(root / "pytorch_model.bin", map_location="cpu", weights_only=True) + weights = {k: v.detach().float().numpy() for k, v in raw.items()} + writer.set_header(family="bros", task=request.task, backend=request.backend) + writer.add_bytes("encoder.plan", compile_engine(c, weights, request.verbose)) + writer.add_json( + "runtime.json", + dict( + schema_version=1, + capacity=128, + hidden_size=c["hidden_size"], + vocab_size=c["vocab_size"], + type_vocab_size=c["type_vocab_size"], + pad_token_id=c["pad_token_id"], + ), + ) diff --git a/families/bros/requirements.txt b/families/bros/requirements.txt new file mode 100644 index 0000000000..ef3b8264f6 --- /dev/null +++ b/families/bros/requirements.txt @@ -0,0 +1,3 @@ +numpy>=1.26 +torch>=2.6 +transformers==5.3.0 diff --git a/families/bros/runtime/CMakeLists.txt b/families/bros/runtime/CMakeLists.txt new file mode 100644 index 0000000000..2394f8e148 --- /dev/null +++ b/families/bros/runtime/CMakeLists.txt @@ -0,0 +1,15 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +add_library(trtmc_model_bros SHARED pipeline.cpp plugin.cpp) +target_include_directories(trtmc_model_bros PRIVATE ${PROJECT_SOURCE_DIR} ${PROJECT_SOURCE_DIR}/core/runtime/include) +target_include_directories(trtmc_model_bros SYSTEM PRIVATE ${TRTMC_CUDA_INCLUDE_DIR}) +target_link_libraries(trtmc_model_bros PRIVATE trtmc_core nlohmann_json::nlohmann_json ${TRTMC_CUDART_LIBRARY}) +target_compile_options(trtmc_model_bros PRIVATE -Wall -Wextra -Wpedantic) +set_target_properties(trtmc_model_bros PROPERTIES LIBRARY_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}" + BUILD_RPATH "\$ORIGIN" INSTALL_RPATH "\$ORIGIN") +install(TARGETS trtmc_model_bros LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR}) +if(TRTMC_BUILD_TESTS) + add_executable(bros_e2e ${PROJECT_SOURCE_DIR}/families/bros/tests/cpp/e2e_consumer.cpp) + target_link_libraries(bros_e2e PRIVATE trtmc_runtime nlohmann_json::nlohmann_json) + set_target_properties(bros_e2e PROPERTIES RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}") +endif() diff --git a/families/bros/runtime/pipeline.cpp b/families/bros/runtime/pipeline.cpp new file mode 100644 index 0000000000..cdb76f8e82 --- /dev/null +++ b/families/bros/runtime/pipeline.cpp @@ -0,0 +1,61 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + */ +#include "families/bros/runtime/pipeline.h" +#include +#include +#include +#include +namespace trtmc::bros { +namespace { +Tensor tensor(void* data,std::vector shape,DType dtype) { + Tensor result;result.data=data;result.shape=std::move(shape);result.dtype=dtype;return result; +} +} +Pipeline::Pipeline(std::unique_ptr engine,Config config):engine_(std::move(engine)),c_(config) { + if (!engine_ || !engine_->ok() || c_.capacity!=128 || c_.hidden!=768 || c_.vocab!=30522 || c_.types!=2 || c_.pad!=0) + throw std::invalid_argument("bros unsupported engine or document profile"); +} +DocumentEncodingResult Pipeline::encode(const DocumentEncodingRequest& request) { + const auto count=request.token_ids.size(); + if (count<1 || count>static_cast(c_.capacity) || request.boxes.size()!=count || + (!request.attention_mask.empty() && request.attention_mask.size()!=count) || + (!request.token_type_ids.empty() && request.token_type_ids.size()!=count)) + throw std::invalid_argument("bros requires 1..128 tokens with matching boxes, masks and segments"); + std::vector ids(c_.capacity,c_.pad),segments(c_.capacity,0); + std::vector boxes(c_.capacity*4,0),mask(c_.capacity,-std::numeric_limits::max()); + bool attended=false; + for (std::size_t i=0;i=c_.vocab || type<0 || type>=c_.types || (active!=0 && active!=1)) + throw std::invalid_argument("bros invalid token, segment or attention mask value"); + if (!std::all_of(box.begin(),box.end(),[](float x) { return std::isfinite(x) && x>=0 && x<=1; }) || box[0]>box[2] || box[1]>box[3]) + throw std::invalid_argument("bros page boxes must be finite normalized corner rectangles"); + ids[i]=id;segments[i]=type;std::copy(box.begin(),box.end(),boxes.begin()+i*4); + if (active) {mask[i]=0;attended=true;} + } + if (!attended) throw std::invalid_argument("bros requires at least one attended token"); + const auto outputs=engine_->forward({ + {"input_ids",tensor(ids.data(),{1,c_.capacity},DType::kInt32)}, + {"token_type_ids",tensor(segments.data(),{1,c_.capacity},DType::kInt32)}, + {"bbox",tensor(boxes.data(),{1,c_.capacity,4},DType::kFloat32)}, + {"attention_mask",tensor(mask.data(),{1,1,1,c_.capacity},DType::kFloat32)}}); + auto read=[&](const char* name,std::vector shape,std::size_t size) { + const auto found=outputs.find(name); + if (found==outputs.end() || !found->second.data || found->second.dtype!=DType::kFloat32 || found->second.shape!=shape) + throw std::runtime_error(std::string("bros invalid engine output: ")+name); + const auto* values=static_cast(found->second.data); + if (!std::all_of(values,values+size,[](float x) { return std::isfinite(x); })) + throw std::runtime_error("bros returned nonfinite features"); + return std::vector(values,values+size); + }; + DocumentEncodingResult result; + result.tokens=static_cast(count);result.dim=c_.hidden; + result.token_features=read("token_features",{1,c_.capacity,c_.hidden},count*c_.hidden); + result.pooled_features=read("pooled_features",{1,c_.hidden},c_.hidden); + return result; +} +} diff --git a/families/bros/runtime/pipeline.h b/families/bros/runtime/pipeline.h new file mode 100644 index 0000000000..3c2e27a453 --- /dev/null +++ b/families/bros/runtime/pipeline.h @@ -0,0 +1,19 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + */ +#pragma once +#include "trtmc/task.h" +#include "trtmc/runtime/trt_module.h" +#include +namespace trtmc::bros { +struct Config { int capacity{128}; int hidden{768}; int vocab{30522}; int types{2}; int pad{0}; }; +class Pipeline final : public IDocumentEncoding { + public: + Pipeline(std::unique_ptr engine,Config config); + DocumentEncodingResult encode(const DocumentEncodingRequest& request) override; + private: + std::unique_ptr engine_; + Config c_; +}; +} diff --git a/families/bros/runtime/plugin.cpp b/families/bros/runtime/plugin.cpp new file mode 100644 index 0000000000..37a7fc0daa --- /dev/null +++ b/families/bros/runtime/plugin.cpp @@ -0,0 +1,24 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + */ +#include "families/bros/runtime/pipeline.h" +#include "trtmc/runtime/family_factory.h" +#include "trtmc/runtime/trt_backend.h" +#include +#include +extern "C" trtmc::ITask* trtmc_create_family(const trtmc::FamilyContext& context) { + if (context.kv_cache_size_bytes!=0) throw std::invalid_argument("bros does not support --kv-cache-size"); + auto section=[&](const char* name) { + const auto* value=context.reader.find_section(name); + if (!value || value->length==0) throw std::runtime_error(std::string("bros missing section: ")+name); + return context.reader.read_section(name); + }; + const auto data=section("runtime.json");const auto json=nlohmann::json::parse(data.begin(),data.end()); + if (json.at("schema_version").get()!=1) throw std::invalid_argument("bros unsupported runtime schema"); + trtmc::bros::Config c; + c.capacity=json.at("capacity");c.hidden=json.at("hidden_size");c.vocab=json.at("vocab_size"); + c.types=json.at("type_vocab_size");c.pad=json.at("pad_token_id"); + const auto plan=section("encoder.plan"); + return new trtmc::bros::Pipeline(context.backend.create_module(plan.data(),plan.size(),{}),c); +} diff --git a/families/bros/support.py b/families/bros/support.py new file mode 100644 index 0000000000..0a0db5fa9c --- /dev/null +++ b/families/bros/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=("bros",), + architectures=("BrosModel",), + tasks=("document_encoding",), + default_task="document_encoding", + default_precision="fp32", +) diff --git a/families/bros/tests/__init__.py b/families/bros/tests/__init__.py new file mode 100644 index 0000000000..52a7a9daf0 --- /dev/null +++ b/families/bros/tests/__init__.py @@ -0,0 +1,2 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 diff --git a/families/bros/tests/cpp/e2e_consumer.cpp b/families/bros/tests/cpp/e2e_consumer.cpp new file mode 100644 index 0000000000..8345727900 --- /dev/null +++ b/families/bros/tests/cpp/e2e_consumer.cpp @@ -0,0 +1,55 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + */ +#include "trtmc/runtime/family_loader.h" +#include +#include +#include +#include +#include +int main(int argc,char** argv) { + try { + if (argc!=4) throw std::invalid_argument("usage: bros_e2e BUNDLE RUNTIME REQUESTS"); + auto loaded=trtmc::load_task(argv[1],argv[2]); + auto* task=dynamic_cast(loaded.get()); + if (!task || std::string(task->task())!="document_encoding") throw std::runtime_error("BROS document Task missing"); + std::ifstream file(argv[3]);const auto requests=nlohmann::json::parse(file); + nlohmann::json results=nlohmann::json::array();trtmc::DocumentEncodingRequest first;trtmc::DocumentEncodingResult expected; + for (const auto& input:requests) { + trtmc::DocumentEncodingRequest request; + request.token_ids=input.at("token_ids").get>(); + request.boxes=input.at("boxes").get>>(); + request.attention_mask=input.value("attention_mask",std::vector{}); + request.token_type_ids=input.value("token_type_ids",std::vector{}); + const auto result=task->encode(request); + if (results.empty()) {first=request;expected=result;} + results.push_back({{"token_features",result.token_features},{"pooled_features",result.pooled_features},{"tokens",result.tokens},{"dim",result.dim}}); + } + for (int mode=0;mode<13;++mode) { + auto bad=first; + switch (mode) { + case 0: bad.token_ids.clear();break; + case 1: bad.token_ids.resize(129);bad.boxes.resize(129);break; + case 2: bad.boxes.pop_back();break; + case 3: bad.attention_mask={1};break; + case 4: bad.token_type_ids={0};break; + case 5: bad.token_ids[0]=-1;break; + case 6: bad.token_ids[0]=30522;break; + case 7: bad.token_type_ids.assign(first.token_ids.size(),2);break; + case 8: bad.attention_mask.assign(first.token_ids.size(),2);break; + case 9: bad.attention_mask.assign(first.token_ids.size(),0);break; + case 10: bad.boxes[0][0]=std::numeric_limits::quiet_NaN();break; + case 11: bad.boxes[0][0]=-0.1F;break; + case 12: bad.boxes[0]={0.9F,0.2F,0.1F,0.3F};break; + } + bool rejected=false; + try {(void)task->encode(bad);} catch (const std::invalid_argument&) {rejected=true;} + if (!rejected) throw std::runtime_error("BROS accepted malformed document"); + const auto result=task->encode(first); + if (result.token_features!=expected.token_features || result.pooled_features!=expected.pooled_features || result.tokens!=expected.tokens || result.dim!=expected.dim) + throw std::runtime_error("BROS state leaked after invalid document"); + } + std::cout< len(word_ids) // 2) for i in range(len(word_ids))] + return result + + words = [ + "Invoice", + "Number", + "INV-0042", + "Date", + "2026-11-13", + "Subtotal", + "$120.00", + "Tax", + "$9.60", + "Total", + "$129.60", + ] + locations = [ + [ + 0.05 + (i % 2) * 0.45, + 0.04 + (i // 2) * 0.13, + 0.42 + (i % 2) * 0.45, + 0.12 + (i // 2) * 0.13, + ] + for i in range(len(words)) + ] + first = page(words, locations) + shifted = page(words, [[x0, 1 - y1, x1, 1 - y0] for x0, y0, x1, y1 in locations]) + words2 = "Please send the updated invoice to the accounting department before the end of November. Include the customer reference and the complete shipping address. Café receipt total: 129.60 dollars.".split() + locations2 = [ + [ + 0.03 + (i % 6) * 0.15, + 0.03 + (i // 6) * 0.12, + 0.16 + (i % 6) * 0.15, + 0.11 + (i // 6) * 0.12, + ] + for i in range(len(words2)) + ] + third = page(words2, locations2, mask=True) + long_words = ["invoice", "total", "amount", "paid"] * 40 + positions = [ + [ + 0.02 + (i % 10) * 0.095, + 0.02 + (i // 10) * 0.05, + 0.10 + (i % 10) * 0.095, + 0.06 + (i // 10) * 0.05, + ] + for i in range(len(long_words)) + ] + boundary = page(long_words, positions) + assert len(boundary["token_ids"]) == 128 + return [first, shifted, third, boundary, first] + + +def reference(root, requests, tmp_path): + import torch + from transformers import BrosModel + + torch.set_num_threads(8) + torch.backends.cuda.matmul.allow_tf32 = False + torch.backends.cudnn.allow_tf32 = False + # The published checkpoint predates the upstream bbox-module rename. + mapping = { + "embeddings.bbox_projection.weight": "bbox_embeddings.bbox_projection.weight", + "embeddings.bbox_sinusoid_emb.x_pos_emb.inv_freq": "bbox_embeddings.bbox_sinusoid_emb.x_pos_emb.inv_freq", + "embeddings.bbox_sinusoid_emb.y_pos_emb.inv_freq": "bbox_embeddings.bbox_sinusoid_emb.y_pos_emb.inv_freq", + } + model, info = BrosModel.from_pretrained( + root, + dtype=torch.float32, + trust_remote_code=MANIFEST["trust_remote_code"], + key_mapping=mapping, + output_loading_info=True, + ) + assert not info["missing_keys"] and not info["mismatched_keys"] and not info["error_msgs"] + assert set(info["unexpected_keys"]) == {"embeddings.bbox_sinusoid_emb.inv_freq"} + raw = torch.load(root / "pytorch_model.bin", map_location="cpu", weights_only=True) + loaded = model.state_dict() + for name, value in raw.items(): + if name == "embeddings.bbox_sinusoid_emb.inv_freq": + continue + assert torch.equal(value, loaded[mapping.get(name, name)]), name + model = model.cuda().eval() + results = [] + with torch.inference_mode(): + for i, request in enumerate(requests): + inputs = dict( + input_ids=torch.tensor([request["token_ids"]], device="cuda"), + bbox=torch.tensor([request["boxes"]], device="cuda", dtype=torch.float32), + ) + for key in ("attention_mask", "token_type_ids"): + if key in request: + inputs[key] = torch.tensor([request[key]], device="cuda") + output = model(**inputs) + tokens = output.last_hidden_state.cpu().numpy()[0] + pooled = output.pooler_output.cpu().numpy()[0] + np.savez(tmp_path / f"reference-{i}.npz", token_features=tokens, pooled_features=pooled) + results.append( + dict( + token_features=tokens.reshape(-1).tolist(), + pooled_features=pooled.tolist(), + tokens=len(request["token_ids"]), + dim=768, + ) + ) + assert not np.allclose( + results[0]["token_features"], results[1]["token_features"], atol=1e-4, rtol=0 + ) + del model, loaded, raw, inputs, output + gc.collect() + torch.cuda.empty_cache() + return results + + +def test_official_checkpoint_e2e(case_name, tmp_path): + from families.bros.tests.math_check import check_stages + + case = next(c for c in MANIFEST["testcases"] if c["name"] == case_name) + assert case["reference_precision"] == "fp32" + check_stages() + root = checkpoint() + runtime = Path(os.environ["TRTMC_RUNTIME_ROOT"]) + assert resolve_family(load_model_metadata(root))[0] == MANIFEST["family"] + assert (runtime / "libtrtmc_model_bros.so").is_file() + requests = fixtures(root) + record_evidence("inputs", dict(manifest=MANIFEST, case=case, requests=requests)) + record_evidence( + "checkpoint", + dict(model_dir=str(root), hf_id=MANIFEST["hf_id"], hf_revision=MANIFEST["hf_revision"]), + ) + with evidence_stage("reference"): + expected = reference(root, requests, tmp_path) + record_evidence("reference", expected) + assert expected[0] == expected[-1] + bundle = tmp_path / MANIFEST["bundle"] + with evidence_stage("build"): + build( + BuildRequest( + root, + bundle, + MANIFEST["family"], + MANIFEST["task"], + MANIFEST["precision"], + tensor_parallel_size=MANIFEST["tensor_parallel_size"], + ) + ) + path = tmp_path / "requests.json" + path.write_text(json.dumps(requests)) + with evidence_stage("native"): + command = [str(runtime / "bros_e2e"), str(bundle), str(runtime), str(path)] + completed = subprocess.run(command, check=True, capture_output=True, text=True, timeout=300) + actual = json.loads(completed.stdout.strip().splitlines()[-1]) + record_evidence("commands", dict(argv=command)) + assert len(actual) == len(expected) and actual[0] == actual[-1] + for observed, wanted in zip(actual, expected): + assert observed["tokens"] == wanted["tokens"] and observed["dim"] == wanted["dim"] + np.testing.assert_allclose( + observed["token_features"], + wanted["token_features"], + atol=case["features_atol"], + rtol=case["features_rtol"], + ) + np.testing.assert_allclose( + observed["pooled_features"], + wanted["pooled_features"], + atol=case["pooled_atol"], + rtol=case["features_rtol"], + ) + path = tmp_path / "document.json" + path.write_text(json.dumps(requests[0])) + with evidence_stage("cli"): + command = [ + str(runtime / "trtmc"), + "encode-document", + str(bundle), + "--runtime-root", + str(runtime), + "--input", + str(path), + ] + completed = subprocess.run(command, check=True, capture_output=True, text=True, timeout=180) + observed = json.loads(completed.stdout.strip().splitlines()[-1]) + record_evidence("commands", dict(argv=command)) + assert observed["tokens"] == expected[0]["tokens"] and observed["dim"] == 768 + np.testing.assert_allclose( + observed["token_features"], + expected[0]["token_features"], + atol=case["features_atol"], + rtol=case["features_rtol"], + ) + np.testing.assert_allclose( + observed["pooled_features"], + expected[0]["pooled_features"], + atol=case["pooled_atol"], + rtol=case["features_rtol"], + ) + record_evidence("native", actual) diff --git a/families/bros/tests/test_model.py b/families/bros/tests/test_model.py new file mode 100644 index 0000000000..2e9f7d73b2 --- /dev/null +++ b/families/bros/tests/test_model.py @@ -0,0 +1,44 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +import pytest +from tensorrt_model_connect import BuildRequest +from families.bros.model import Graph, build, validate_config + + +def test_profile_rejections(tmp_path): + with pytest.raises(ValueError, match="FP32"): + build( + BuildRequest(tmp_path, tmp_path / "test.bundle", "bros", "document_encoding", "fp16"), + None, + ) + with pytest.raises(NotImplementedError, match="dynamic_kv_cache"): + build( + BuildRequest( + tmp_path, + tmp_path / "test.bundle", + "bros", + "document_encoding", + "fp32", + dynamic_kv_cache=True, + ), + None, + ) + with pytest.raises(ValueError, match="128-token"): + build( + BuildRequest( + tmp_path, + tmp_path / "test.bundle", + "bros", + "document_encoding", + "fp32", + max_sequence_length=512, + ), + None, + ) + + +def test_no_missing_or_unsupported_geometry(): + with pytest.raises(ValueError, match="missing checkpoint tensor"): + Graph(None, {}, {}).weight("embeddings.word_embeddings.weight") + with pytest.raises(ValueError, match="eight coordinates"): + validate_config(dict(model_type="bros", dim_bbox=4)) diff --git a/families/bros/tests/test_support.py b/families/bros/tests/test_support.py new file mode 100644 index 0000000000..5f3a8ad51b --- /dev/null +++ b/families/bros/tests/test_support.py @@ -0,0 +1,10 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +from tensorrt_model_connect.model_support import ModelMetadata, resolve_family +from families.bros.support import describe + + +def test_document_owner(): + family, support = resolve_family(ModelMetadata(config={"model_type": "bros"}, model_index={})) + assert family == "bros" and support.default_task == "document_encoding" + assert describe(ModelMetadata(config={"model_type": "bert"}, model_index={})) is None diff --git a/website/docs/api/cli-reference.md b/website/docs/api/cli-reference.md index ef5294b71b..a68976a04f 100644 --- a/website/docs/api/cli-reference.md +++ b/website/docs/api/cli-reference.md @@ -104,7 +104,7 @@ Common load options are: | Task | Command and primary inputs | | --- | --- | | Text or vision-language generation | `run` with `--prompt`, and optional `--image` | -| Encoding and embedding | `encode --text TEXT`, `embed --text TEXT` | +| Encoding and embedding | `encode --text TEXT`, `encode-document --input JSON`, `embed --text TEXT` | | Reranking | `rerank --query TEXT --document TEXT` | | Classification and features | `classify --image PATH`, `extract-features --image PATH` | | Stereo and geometry | `disparity --left PATH --right PATH`, `geometry --image PATH --output DIR` | @@ -152,3 +152,9 @@ Unknown commands, unknown command-specific options, duplicate options, task interface mismatches, invalid values, and missing DSOs fail with a nonzero exit status. Run `trtmc help` for the compiled executable's concise synopsis and `python -m tensorrt_model_connect build --help` for the exact build parser. + +`encode-document BUNDLE --input page.json` accepts `token_ids`, one normalized +`[left, top, right, bottom]` rectangle per token in `boxes`, and optional +`attention_mask` and `token_type_ids` integer arrays. The family owns token +vocabulary, length and mask validation. The output contains token-major +`token_features`, `pooled_features`, `tokens`, and feature width `dim`. diff --git a/website/docs/api/cpp-api.md b/website/docs/api/cpp-api.md index b2fb192347..72bda99d0a 100644 --- a/website/docs/api/cpp-api.md +++ b/website/docs/api/cpp-api.md @@ -228,3 +228,12 @@ primitives live in `libtrtmc_core.so`. A family factory receives a The reader exposes immutable metadata and on-demand section reads only. The factory must copy the lightweight reader into its pipeline if it will read a section after the factory returns; it must never retain the context reference. + +### Document encoding bundles + +The release-coupled `IDocumentEncoding` Task accepts a `DocumentEncodingRequest` +with token IDs, normalized page rectangles, and optional attention and segment +IDs. `DocumentEncodingResult` returns token-major features, a pooled vector, +and explicit token and feature dimensions. The family owns vocabulary, +geometry and supported-length validation. Keep a loaded Task alive while using +it, as with the other `load_task()` interfaces. diff --git a/website/plugins/model-support-inventory/index.js b/website/plugins/model-support-inventory/index.js index 16f8c83e7c..57188fad51 100644 --- a/website/plugins/model-support-inventory/index.js +++ b/website/plugins/model-support-inventory/index.js @@ -9,6 +9,7 @@ const path = require('path'); const TASKS = { audio_generation: ['Text to speech', 'Audio', 'text-to-speech', 'generate-audio'], classification: ['Image classification', 'Computer Vision', 'image-classification', 'classify'], + document_encoding: ['Document encoding', 'Multimodal', null, 'encode-document'], embedding: ['Embedding', 'Natural Language Processing', 'feature-extraction', 'embed'], encoding: ['Encoding', 'Natural Language Processing', 'feature-extraction', 'encode'], image_edit: ['Image editing', 'Computer Vision', 'image-to-image', 'generate-image'], diff --git a/website/plugins/model-support-inventory/index.test.js b/website/plugins/model-support-inventory/index.test.js index aa558e237f..afb508326a 100644 --- a/website/plugins/model-support-inventory/index.test.js +++ b/website/plugins/model-support-inventory/index.test.js @@ -282,3 +282,14 @@ test('requires the complete family shape', () => { fs.rmSync(path.join(root, 'families', 'beta', 'runtime', 'CMakeLists.txt')); assert.throws(() => collectModelSupportInventory(root), /missing families\/beta\/runtime/); }); + + +test('maps document encoding to its structured-input CLI', () => { + const root = repository(); + const manifest = path.join(root, 'families', 'alpha', 'tests', 'manifests', 'small.json'); + const payload = JSON.parse(fs.readFileSync(manifest)); + payload.task = 'document_encoding'; + fs.writeFileSync(manifest, JSON.stringify(payload)); + const [profile] = collectModelSupportInventory(root).modelProfiles; + assert.deepEqual(profile.cliCommands, ['encode-document']); +}); From be9adc1ce792ad54742261f9e42301d23013c294 Mon Sep 17 00:00:00 2001 From: Will Guo Date: Wed, 2 Dec 2026 20:22:53 -0800 Subject: [PATCH 2/2] fix(bros): validate document boxes and checkpoint geometry Signed-off-by: Will Guo --- apps/cli/cli.cpp | 9 ++++++++- apps/cli/tests/test_document_encoding_cli.cpp | 5 +++-- families/bros/model.py | 2 ++ families/bros/runtime/pipeline.cpp | 1 + families/bros/runtime/pipeline.h | 2 ++ families/bros/tests/test_model.py | 9 +++++++++ 6 files changed, 25 insertions(+), 3 deletions(-) diff --git a/apps/cli/cli.cpp b/apps/cli/cli.cpp index aeda567d4e..fc8919b07c 100644 --- a/apps/cli/cli.cpp +++ b/apps/cli/cli.cpp @@ -903,7 +903,14 @@ int dispatch(const Command& command, ITask& task, std::ostream& output) { request.token_ids = integers("token_ids", true); request.attention_mask = integers("attention_mask", false); request.token_type_ids = integers("token_type_ids", false); - request.boxes = input.at("boxes").get>>(); + const auto& boxes = input.at("boxes"); + if (!boxes.is_array()) + throw std::invalid_argument("boxes must be an array of rectangles"); + for (const auto& box : boxes) { + if (!box.is_array() || box.size() != 4) + throw std::invalid_argument("boxes must contain exactly four coordinates per rectangle"); + request.boxes.push_back(box.get>()); + } const auto result = require_interface(task).encode(request); require_finite(result.token_features, "document token features"); require_finite(result.pooled_features, "document pooled features"); diff --git a/apps/cli/tests/test_document_encoding_cli.cpp b/apps/cli/tests/test_document_encoding_cli.cpp index d074bfd4f5..4fdb52fade 100644 --- a/apps/cli/tests/test_document_encoding_cli.cpp +++ b/apps/cli/tests/test_document_encoding_cli.cpp @@ -41,15 +41,16 @@ int main(int argc,char** argv) { std::ostringstream output;check(trtmc::cli::dispatch(command,task,output)==0,"document dispatch failed"); const auto result=nlohmann::json::parse(output.str()); check(result.at("tokens")==2 && result.at("dim")==2 && result.at("token_features")==std::vector{1,2,3,4},"feature dimensions changed"); - for (int mode=0;mode<3;++mode) { + for (int mode=0;mode<4;++mode) { auto invalid=input; if (mode==0) invalid["token_ids"][0]=4294967303ULL; if (mode==1) invalid["attention_mask"][0]=1.5; if (mode==2) invalid["token_type_ids"][0]=-2147483649LL; + if (mode==3) invalid["boxes"][0]={0,0,0.5,1,0.5,0,0,1}; {std::ofstream file(path);file< engine,Config config):engine_(std throw std::invalid_argument("bros unsupported engine or document profile"); } DocumentEncodingResult Pipeline::encode(const DocumentEncodingRequest& request) { + const std::lock_guard lock(execution_); const auto count=request.token_ids.size(); if (count<1 || count>static_cast(c_.capacity) || request.boxes.size()!=count || (!request.attention_mask.empty() && request.attention_mask.size()!=count) || diff --git a/families/bros/runtime/pipeline.h b/families/bros/runtime/pipeline.h index 3c2e27a453..5937f00e98 100644 --- a/families/bros/runtime/pipeline.h +++ b/families/bros/runtime/pipeline.h @@ -6,6 +6,7 @@ #include "trtmc/task.h" #include "trtmc/runtime/trt_module.h" #include +#include namespace trtmc::bros { struct Config { int capacity{128}; int hidden{768}; int vocab{30522}; int types{2}; int pad{0}; }; class Pipeline final : public IDocumentEncoding { @@ -13,6 +14,7 @@ class Pipeline final : public IDocumentEncoding { Pipeline(std::unique_ptr engine,Config config); DocumentEncodingResult encode(const DocumentEncodingRequest& request) override; private: + std::mutex execution_; std::unique_ptr engine_; Config c_; }; diff --git a/families/bros/tests/test_model.py b/families/bros/tests/test_model.py index 2e9f7d73b2..cb7ace6ccc 100644 --- a/families/bros/tests/test_model.py +++ b/families/bros/tests/test_model.py @@ -42,3 +42,12 @@ def test_no_missing_or_unsupported_geometry(): Graph(None, {}, {}).weight("embeddings.word_embeddings.weight") with pytest.raises(ValueError, match="eight coordinates"): validate_config(dict(model_type="bros", dim_bbox=4)) + + +def test_rejects_checkpoint_geometry_that_runtime_cannot_load(tmp_path): + from transformers import BrosConfig + + BrosConfig(hidden_size=64, num_attention_heads=4, vocab_size=127).save_pretrained(tmp_path) + request = BuildRequest(tmp_path, tmp_path / "out.bundle", "bros", "document_encoding", "fp32") + with pytest.raises(ValueError, match="runtime requires"): + build(request, None)