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
8 changes: 8 additions & 0 deletions CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -537,6 +537,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
Expand Down
50 changes: 49 additions & 1 deletion apps/cli/cli.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,7 @@ const std::unordered_map<std::string, CommandSpec>& 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"}}},
Expand Down Expand Up @@ -881,6 +882,51 @@ 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<std::int32_t> 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<std::uint64_t>() > 2147483647ULL) ||
(!value.is_number_unsigned() && (value.get<std::int64_t>() < -2147483648LL ||
value.get<std::int64_t>() > 2147483647LL)))
throw std::invalid_argument(std::string(name) +
" requires signed 32-bit integers");
values.push_back(value.get<std::int32_t>());
}
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);
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<std::array<float, 4>>());
}
const auto result = require_interface<IDocumentEncoding>(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<IImageClassification>(task).classify(
Expand Down Expand Up @@ -1636,7 +1682,8 @@ 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, layout, extract-features,\n"
" run, encode, encode-document, embed, rerank, classify, detect, layout, "
"extract-features,\n"
" predict-structure, disparity, depth, geometry,\n"
" segment,\n"
" segment-prompted, video-segment, generate-audio, transcribe,\n"
Expand All @@ -1661,6 +1708,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"
Expand Down
1 change: 1 addition & 0 deletions apps/cli/cli.h
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ enum class CommandKind {
kInspect,
kRun,
kEncode,
kEncodeDocument,
kEmbed,
kRerank,
kClassify,
Expand Down
98 changes: 98 additions & 0 deletions apps/cli/tests/test_document_encoding_cli.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
/*
* 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 <filesystem>
#include <fstream>
#include <iostream>
#include <nlohmann/json.hpp>
#include <sstream>
#include <stdexcept>
#include <type_traits>
static_assert(std::is_abstract_v<trtmc::IDocumentEncoding>);
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<std::int32_t>{7, 11} &&
r.attention_mask == std::vector<std::int32_t>{1, 0} &&
r.token_type_ids == std::vector<std::int32_t>{0, 1},
"token metadata changed");
check(r.boxes == std::vector<std::array<float, 4>>{{0, 0, 0.5F, 1}, {0.5F, 0, 1, 1}},
"page rectangles changed");
return {{1, 2, 3, 4}, {5, 6}, 2, 2};
}
};
} // namespace
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 << input.dump();
}
std::vector<std::string> args = {"trtmc", "encode-document", "fixture.bundle", "--input",
path.string()};
std::vector<char*> pointers;
for (auto& a : args)
pointers.push_back(a.data());
const auto command =
trtmc::cli::parse_args(static_cast<int>(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<float>{1, 2, 3, 4},
"feature dimensions changed");
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 << invalid.dump();
}
bool rejected = false;
try {
std::ostringstream ignored;
(void)trtmc::cli::dispatch(command, task, ignored);
} catch (const std::invalid_argument&) {
rejected = true;
}
check(rejected && task.calls == 1, "invalid metadata reached document family");
}
std::cout << "Document token metadata, boxes, feature geometry and strict integer parsing "
"passed\n";
return 0;
} catch (const std::exception& e) {
std::cerr << e.what() << '\n';
return 1;
}
}
1 change: 1 addition & 0 deletions apps/task_runtime.h
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ inline bool uses_existing_task_runtime(std::string_view primary_task) noexcept {
ISpeechToolSessionProvider::kTask,
IEmbedding::kTask,
IEncoding::kTask,
IDocumentEncoding::kTask,
IReranking::kTask,
IStructuredDecision::kTask,
ISegmentation::kTask,
Expand Down
24 changes: 24 additions & 0 deletions core/runtime/include/trtmc/task.h
Original file line number Diff line number Diff line change
Expand Up @@ -120,6 +120,23 @@ struct EmbeddingResult {
std::int32_t dim{0};
};

// Token IDs and corresponding page rectangles in normalized coordinates.
// Each box is [left, top, right, bottom], one per token including special tokens.
// Optional masks and segment IDs default according to the owning family.
struct DocumentEncodingRequest {
std::vector<std::int32_t> token_ids;
std::vector<std::array<float, 4>> boxes;
std::vector<std::int32_t> attention_mask;
std::vector<std::int32_t> token_type_ids;
};

struct DocumentEncodingResult {
std::vector<float> token_features; // token-major, tokens x dim
std::vector<float> pooled_features;
std::int32_t tokens{0};
std::int32_t dim{0};
};

struct SegmentResult {
std::vector<std::int32_t> mask;
std::int32_t height{0};
Expand Down Expand Up @@ -717,6 +734,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";
Expand Down
44 changes: 44 additions & 0 deletions families/bros/README.md
Original file line number Diff line number Diff line change
@@ -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.
3 changes: 3 additions & 0 deletions families/bros/__init__.py
Original file line number Diff line number Diff line change
@@ -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."""
Loading
Loading