From 683c47cec34887251384fc2bac0386d2aa099bd3 Mon Sep 17 00:00:00 2001 From: Will Guo Date: Thu, 12 Nov 2026 20:55:14 -0800 Subject: [PATCH 1/3] feat(jina_embeddings_v3): add native embeddings Build the rotary encoder and select the published query or passage LoRA adapter inside one TensorRT graph. Default embeddings retain the unadapted base model; all roles use masked mean pooling and L2 normalization. Cover native SentencePiece normalization, pinned checkpoint parity against Transformers and PEFT, multilingual inputs and role-dependent embeddings through the text embedding Task API. Signed-off-by: Will Guo --- families/jina_embeddings_v3/__init__.py | 0 families/jina_embeddings_v3/model.py | 228 +++++++ families/jina_embeddings_v3/requirements.txt | 3 + .../jina_embeddings_v3/runtime/CMakeLists.txt | 23 + .../jina_embeddings_v3/runtime/charsmap.h | 103 ++++ .../jina_embeddings_v3/runtime/plugin.cpp | 103 ++++ .../jina_embeddings_v3/runtime/tokenizer.h | 29 + .../runtime/unigram_tokenizer.cpp | 577 ++++++++++++++++++ families/jina_embeddings_v3/support.py | 10 + families/jina_embeddings_v3/tests/__init__.py | 0 .../tests/cpp/test_tokenizer.cpp | 17 + .../manifests/jina-embeddings-v3-hf.json | 35 ++ families/jina_embeddings_v3/tests/test_e2e.py | 271 ++++++++ .../jina_embeddings_v3/tests/test_support.py | 9 + 14 files changed, 1408 insertions(+) create mode 100644 families/jina_embeddings_v3/__init__.py create mode 100644 families/jina_embeddings_v3/model.py create mode 100644 families/jina_embeddings_v3/requirements.txt create mode 100644 families/jina_embeddings_v3/runtime/CMakeLists.txt create mode 100644 families/jina_embeddings_v3/runtime/charsmap.h create mode 100644 families/jina_embeddings_v3/runtime/plugin.cpp create mode 100644 families/jina_embeddings_v3/runtime/tokenizer.h create mode 100644 families/jina_embeddings_v3/runtime/unigram_tokenizer.cpp create mode 100644 families/jina_embeddings_v3/support.py create mode 100644 families/jina_embeddings_v3/tests/__init__.py create mode 100644 families/jina_embeddings_v3/tests/cpp/test_tokenizer.cpp create mode 100644 families/jina_embeddings_v3/tests/manifests/jina-embeddings-v3-hf.json create mode 100644 families/jina_embeddings_v3/tests/test_e2e.py create mode 100644 families/jina_embeddings_v3/tests/test_support.py diff --git a/families/jina_embeddings_v3/__init__.py b/families/jina_embeddings_v3/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/families/jina_embeddings_v3/model.py b/families/jina_embeddings_v3/model.py new file mode 100644 index 0000000000..3e2c6b6448 --- /dev/null +++ b/families/jina_embeddings_v3/model.py @@ -0,0 +1,228 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +"""Bidirectional rotary encoder with native query and passage LoRA selection.""" + +import json +from pathlib import Path + +import numpy as np +import tensorrt as trt + + +def build_engine(weights, adapters, cfg, length, verbose=False): + logger = trt.Logger(trt.Logger.VERBOSE if 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) + width = cfg["hidden_size"] + heads = cfg["num_attention_heads"] + dim = width // heads + + def const(value): + value = np.ascontiguousarray(value, dtype=np.float32) + return net.add_constant(value.shape, value).get_output(0) + + def op(a, b, kind): + return net.add_elementwise(a, b, kind).get_output(0) + + def add(a, b): + return op(a, b, trt.ElementWiseOperation.SUM) + + def mul(a, b): + return op(a, b, trt.ElementWiseOperation.PROD) + + def reshape(x, shape): + layer = net.add_shuffle(x) + layer.reshape_dims = shape + return layer.get_output(0) + + def mm(x, w, transpose=False): + return net.add_matrix_multiply( + x, + trt.MatrixOperation.NONE, + w, + trt.MatrixOperation.TRANSPOSE if transpose else trt.MatrixOperation.NONE, + ).get_output(0) + + adapter_id = net.add_input("adapter_id", trt.int32, (1,)) + + def selected(key): + query, passage = (adapter[key] for adapter in adapters) + table = const(np.stack([np.zeros_like(query), query, passage])) + return reshape(net.add_gather(table, adapter_id, 0).get_output(0), query.shape) + + def lora(x, key): + return mul( + mm( + mm(x, selected(key + ".lora_A.weight"), True), + selected(key + ".lora_B.weight"), + True, + ), + const(np.array([[0.25]])), + ) + + def linear(x, key, adapter_key=None, rows=None): + weight, bias = weights[key + ".weight"], weights[key + ".bias"] + if rows is not None: + weight, bias = weight[rows], bias[rows] + output = add(mm(x, const(weight), True), const(bias.reshape(1, -1))) + return add(output, lora(x, adapter_key or key)) + + def norm(x, key): + layer = net.add_normalization( + x, + const(weights[key + ".weight"].reshape(1, -1)), + const(weights[key + ".bias"].reshape(1, -1)), + 2, + ) + layer.epsilon = cfg["layer_norm_eps"] + return layer.get_output(0) + + ids = net.add_input("input_ids", trt.int32, (length,)) + valid = net.add_input("attention_mask", trt.int32, (length,)) + + def embeddings(key, token_ids): + output = net.add_gather(const(weights[key + ".weight"]), token_ids, 0).get_output(0) + a = selected(key + ".lora_embedding_A") + b = selected(key + ".lora_embedding_B") + transpose = net.add_shuffle(a) + transpose.first_transpose = (1, 0) + low = net.add_gather(transpose.get_output(0), token_ids, 0).get_output(0) + return add(output, mul(mm(low, b, True), const(np.array([[0.25]])))) + + hidden = embeddings("roberta.embeddings.word_embeddings", ids) + zero = net.add_constant((1,), np.zeros(1, dtype=np.int32)).get_output(0) + hidden = norm( + add(hidden, embeddings("roberta.embeddings.token_type_embeddings", zero)), "roberta.emb_ln" + ) + valid_float = net.add_cast(valid, trt.float32).get_output(0) + mask = reshape( + mul( + op(const(np.ones(1)), valid_float, trt.ElementWiseOperation.SUB), + const(np.array([-1e9])), + ), + (1, 1, 1, length), + ) + frequency = 1 / (cfg["rotary_emb_base"] ** (np.arange(0, dim, 2, dtype=np.float32) / dim)) + angles = np.arange(length, dtype=np.float32)[:, None] * frequency + angles = np.concatenate([angles, angles], axis=-1) + cosine = const(np.cos(angles).reshape(1, 1, length, dim)) + sine = const(np.sin(angles).reshape(1, 1, length, dim)) + + def split(x): + layer = net.add_shuffle(x) + layer.reshape_dims = (1, length, heads, dim) + layer.second_transpose = (0, 2, 1, 3) + return layer.get_output(0) + + def rope(x): + first = net.add_slice( + x, (0, 0, 0, 0), (1, heads, length, dim // 2), (1, 1, 1, 1) + ).get_output(0) + second = net.add_slice( + x, (0, 0, 0, dim // 2), (1, heads, length, dim // 2), (1, 1, 1, 1) + ).get_output(0) + negative = net.add_unary(second, trt.UnaryOperation.NEG).get_output(0) + layer = net.add_concatenation([negative, first]) + layer.axis = 3 + return add(mul(x, cosine), mul(layer.get_output(0), sine)) + + for index in range(cfg["num_hidden_layers"]): + prefix = f"roberta.encoder.layers.{index}" + q, k, v = [ + split( + linear( + hidden, + prefix + ".mixer.Wqkv", + prefix + ".self_attn." + name + "_proj", + slice(i * width, (i + 1) * width), + ) + ) + for i, name in enumerate(("q", "k", "v")) + ] + scores = mm(rope(q), rope(k), True) + scores = add(mul(scores, const(np.array([[[[dim**-0.5]]]]))), mask) + softmax = net.add_softmax(scores) + softmax.axes = 8 + context = mm(softmax.get_output(0), v) + layer = net.add_shuffle(context) + layer.first_transpose = (0, 2, 1, 3) + layer.reshape_dims = (length, width) + hidden = norm( + add(hidden, linear(layer.get_output(0), prefix + ".mixer.out_proj")), prefix + ".norm1" + ) + mlp = linear(hidden, prefix + ".mlp.fc1") + mlp = net.add_activation(mlp, trt.ActivationType.GELU_ERF).get_output(0) + hidden = norm(add(hidden, linear(mlp, prefix + ".mlp.fc2")), prefix + ".norm2") + total = net.add_reduce( + mul(hidden, reshape(valid_float, (length, 1))), trt.ReduceOperation.SUM, 1, True + ).get_output(0) + count = reshape( + net.add_reduce(valid_float, trt.ReduceOperation.SUM, 1, True).get_output(0), (1, 1) + ) + mean = op(total, count, trt.ElementWiseOperation.DIV) + norm2 = net.add_reduce(mul(mean, mean), trt.ReduceOperation.SUM, 2, True).get_output(0) + output = op( + mean, + net.add_unary(norm2, trt.UnaryOperation.SQRT).get_output(0), + trt.ElementWiseOperation.DIV, + ) + output.name = "embedding" + net.mark_output(output) + plan = builder.build_serialized_network(net, options) + if plan is None: + raise RuntimeError("Jina embedding engine build failed") + return bytes(plan) + + +def build(request, writer): + if request.task != "text_to_embedding" or request.backend != "trt": + raise ValueError("Jina embeddings requires text_to_embedding and backend=trt") + 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("Jina embedding supports a single fp32 text input") + directory = Path(request.model_dir) + cfg = json.loads((directory / "config.json").read_text()) + length = request.max_sequence_length or 256 + if cfg["model_type"] != "jina_embeddings_v3" or cfg["hidden_act"] != "gelu": + raise ValueError("Expected Jina embeddings v3 GELU encoder") + if not 2 <= length <= min(8192, cfg["max_position_embeddings"]): + raise ValueError("Jina embedding requires a sequence profile in [2, 8192]") + from safetensors import safe_open + + def load(filename): + with safe_open(str(directory / filename), framework="pt", device="cpu") as handle: + return {key: handle.get_tensor(key).float().numpy() for key in handle.keys()} + + weights = load("model.safetensors") + adapters = [] + for name in ("retrieval_query", "retrieval_passage"): + config = json.loads((directory / name / "adapter_config.json").read_text()) + if config["r"] != 4 or config["lora_alpha"] != 1: + raise ValueError("Jina retrieval adapter scaling must be alpha=1, rank=4") + adapters.append(load(name + "/adapter_model.safetensors")) + writer.set_header(family="jina_embeddings_v3", task=request.task, backend=request.backend) + writer.add_bytes("model.plan", build_engine(weights, adapters, cfg, length, request.verbose)) + writer.add_bytes("tokenizer.json", (directory / "tokenizer.json").read_bytes()) + writer.add_json( + "runtime.json", + dict( + sequence_length=length, + hidden_size=cfg["hidden_size"], + pad_token_id=cfg["pad_token_id"], + vocab_size=cfg["vocab_size"], + ), + ) diff --git a/families/jina_embeddings_v3/requirements.txt b/families/jina_embeddings_v3/requirements.txt new file mode 100644 index 0000000000..739a2abf86 --- /dev/null +++ b/families/jina_embeddings_v3/requirements.txt @@ -0,0 +1,3 @@ +torch>=2.6 +transformers==5.20.0 +peft==0.21.2 diff --git a/families/jina_embeddings_v3/runtime/CMakeLists.txt b/families/jina_embeddings_v3/runtime/CMakeLists.txt new file mode 100644 index 0000000000..ff477579ef --- /dev/null +++ b/families/jina_embeddings_v3/runtime/CMakeLists.txt @@ -0,0 +1,23 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +add_library(trtmc_model_jina_embeddings_v3 SHARED unigram_tokenizer.cpp plugin.cpp) +target_include_directories(trtmc_model_jina_embeddings_v3 PRIVATE ${PROJECT_SOURCE_DIR} + ${PROJECT_SOURCE_DIR}/core/runtime/include) +target_include_directories(trtmc_model_jina_embeddings_v3 SYSTEM PRIVATE ${TRTMC_CUDA_INCLUDE_DIR}) +target_link_libraries(trtmc_model_jina_embeddings_v3 PRIVATE trtmc_core nlohmann_json::nlohmann_json + ${TRTMC_CUDART_LIBRARY}) +target_compile_options(trtmc_model_jina_embeddings_v3 PRIVATE -Wall -Wextra -Wpedantic) +set_target_properties(trtmc_model_jina_embeddings_v3 PROPERTIES + LIBRARY_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}" BUILD_RPATH "\$ORIGIN" INSTALL_RPATH "\$ORIGIN") +install(TARGETS trtmc_model_jina_embeddings_v3 LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR}) + +if(TRTMC_BUILD_TESTS) + add_executable(test_jina_embeddings_v3_tokenizer + ${PROJECT_SOURCE_DIR}/families/jina_embeddings_v3/tests/cpp/test_tokenizer.cpp) + target_include_directories(test_jina_embeddings_v3_tokenizer PRIVATE ${PROJECT_SOURCE_DIR}) + target_link_libraries(test_jina_embeddings_v3_tokenizer PRIVATE + trtmc_model_jina_embeddings_v3 nlohmann_json::nlohmann_json) + set_target_properties(test_jina_embeddings_v3_tokenizer PROPERTIES + RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}") +endif() diff --git a/families/jina_embeddings_v3/runtime/charsmap.h b/families/jina_embeddings_v3/runtime/charsmap.h new file mode 100644 index 0000000000..bbec61dd5f --- /dev/null +++ b/families/jina_embeddings_v3/runtime/charsmap.h @@ -0,0 +1,103 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + */ +#pragma once + +#include +#include +#include +#include + +namespace trtmc::mt5 { + +// SentencePiece's serialized normalization map: a little-endian Darts trie +// followed by NUL-terminated UTF-8 replacements. It belongs to the checkpoint; +// substituting a generic Unicode normalization algorithm changes token IDs. +class CharsMap { + public: + void load(const std::string& encoded) { + std::vector bytes; + unsigned value = 0; + int bits = 0; + const std::string alphabet = + "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; + for (const unsigned char c : encoded) { + if (c == '=') break; + const auto position = alphabet.find(c); + if (position == std::string::npos) + throw std::runtime_error("mt5 invalid normalization map encoding"); + value = (value << 6) | static_cast(position); + bits += 6; + if (bits >= 8) { + bits -= 8; + bytes.push_back(static_cast((value >> bits) & 255U)); + } + } + auto word = [&bytes](std::size_t index) -> std::uint32_t { + if (index > bytes.size() || bytes.size() - index < 4) + throw std::runtime_error("mt5 truncated normalization map"); + return std::uint32_t(bytes[index]) | (std::uint32_t(bytes[index+1]) << 8) + | (std::uint32_t(bytes[index+2]) << 16) | (std::uint32_t(bytes[index+3]) << 24); + }; + const auto size = word(0); + if (size == 0 || size % 4 || size > bytes.size() - 4) + throw std::runtime_error("mt5 invalid normalization trie size"); + units_.clear(); + for (std::size_t index = 4; index < size + 4U; index += 4) + units_.push_back(word(index)); + replacements_.assign(bytes.begin() + size + 4U, bytes.end()); + } + + std::string normalize(const std::string& input) const { + if (units_.empty()) return input; + std::string result; + for (std::size_t start = 0; start < input.size();) { + std::uint32_t node = offset(units_[0]); + std::size_t matched = 0; + std::uint32_t replacement = 0; + for (std::size_t end = start; end < input.size(); ++end) { + const auto c = static_cast(input[end]); + if (c == 0) break; + node ^= c; + if (node >= units_.size()) break; + const auto unit = units_[node]; + if ((unit & 0x800000FFU) != c) break; + node ^= offset(unit); + if (unit & 0x100U) { + if (node >= units_.size()) + throw std::runtime_error("mt5 invalid normalization leaf"); + replacement = units_[node] & 0x7FFFFFFFU; + matched = end - start + 1; + } + } + if (matched) { + if (replacement >= replacements_.size()) + throw std::runtime_error("mt5 invalid normalization replacement"); + const auto end = replacements_.find('\0', replacement); + if (end == std::string::npos) + throw std::runtime_error("mt5 unterminated normalization replacement"); + result.append(replacements_, replacement, end - replacement); + start += matched; + } else { + // Preserve one UTF-8 codepoint when the trie has no replacement. + const auto c = static_cast(input[start]); + const std::size_t size = c < 0x80 ? 1 : c < 0xE0 ? 2 : c < 0xF0 ? 3 : 4; + if (size > input.size() - start) + throw std::invalid_argument("mt5 input contains truncated UTF-8"); + result.append(input, start, size); + start += size; + } + } + return result; + } + + private: + static std::uint32_t offset(std::uint32_t unit) { + return (unit >> 10) << ((unit & 0x200U) >> 6); + } + std::vector units_; + std::string replacements_; +}; + +} // namespace trtmc::mt5 diff --git a/families/jina_embeddings_v3/runtime/plugin.cpp b/families/jina_embeddings_v3/runtime/plugin.cpp new file mode 100644 index 0000000000..0724e7efab --- /dev/null +++ b/families/jina_embeddings_v3/runtime/plugin.cpp @@ -0,0 +1,103 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + */ +#include "families/jina_embeddings_v3/runtime/tokenizer.h" +#include "trtmc/internal/features.h" +#include "trtmc/internal/model.h" +#include "trtmc/runtime/family_factory.h" +#include "trtmc/runtime/trt_backend.h" +#include +#include +#include +#include + +namespace trtmc::jina_embeddings_v3 { +namespace { +std::vector section(const BundleReader& reader, const char* name) { + const auto* found = reader.find_section(name); + if (!found || found->length == 0) + throw std::runtime_error(std::string("Jina embedding bundle is missing ") + name); + return reader.read_section(name); +} + +class Pipeline final : public internal::IModel, public internal::ITextToEmbedding { + public: + Pipeline(std::unique_ptr engine, std::unique_ptr tokenizer, + int32_t length, int32_t width, int32_t vocab, int32_t pad) + : engine_(std::move(engine)), tokenizer_(std::move(tokenizer)), length_(length), + width_(width), vocab_(vocab), pad_(pad) {} + const char* task() const noexcept override { return "text_to_embedding"; } + std::vector task_bindings() override { + return {internal::bind(*this)}; + } + internal::SemanticEmbeddingResult run(const internal::TextToEmbeddingRequest& request, + internal::ConfigView config) override { + if (!config.empty()) throw internal::ConfigError("Jina embedding has no runtime config"); + int32_t adapter_id = 0; + switch (request.role) { + case internal::EmbeddingRole::Default: break; + case internal::EmbeddingRole::Query: adapter_id = 1; break; + case internal::EmbeddingRole::Document: adapter_id = 2; break; + default: throw std::invalid_argument("Unknown Jina embedding role"); + } + auto ids = tokenizer_->encode(std::string(request.text)); + if (ids.empty() || ids.size() > static_cast(length_)) + throw std::invalid_argument("Jina embedding requires a nonempty input within the built profile"); + for (const auto id : ids) { + if (id < 0 || id >= vocab_) + throw std::invalid_argument("Jina tokenizer returned an invalid token ID"); + } + const auto count = ids.size(); + ids.resize(length_, pad_); + std::vector valid(length_, 0); + std::fill(valid.begin(), valid.begin() + count, 1); + Tensor input, mask; + input.data = ids.data(); input.shape = {length_}; input.dtype = DType::kInt32; + mask.data = valid.data(); mask.shape = {length_}; mask.dtype = DType::kInt32; + Tensor adapter; + adapter.data = &adapter_id; adapter.shape = {1}; adapter.dtype = DType::kInt32; + auto outputs = engine_->forward({{"input_ids", input}, {"attention_mask", mask}, + {"adapter_id", adapter}}); + const auto found = outputs.find("embedding"); + if (found == outputs.end() || !found->second.data || + found->second.dtype != DType::kFloat32 || + found->second.shape != std::vector{1, width_}) + throw std::runtime_error("Jina engine returned an invalid embedding"); + const auto* values = static_cast(found->second.data); + internal::SemanticEmbeddingResult result; + result.values.assign(values, values + width_); + for (const auto value : result.values) { + if (!std::isfinite(value)) throw std::runtime_error("Jina embedding is nonfinite"); + } + result.embedding_space = "jina_embeddings_v3"; + result.pooling = "mean"; + result.normalization = "l2"; + return result; + } + private: + std::unique_ptr engine_; + std::unique_ptr tokenizer_; + int32_t length_, width_, vocab_, pad_; +}; +} // namespace +} // namespace trtmc::jina_embeddings_v3 + +extern "C" trtmc::ITask* trtmc_create_family(const trtmc::FamilyContext& context) { + using namespace trtmc; + if (context.kv_cache_size_bytes != 0 || context.reader.info().task != "text_to_embedding") + throw std::invalid_argument("Jina requires text embedding without a KV cache"); + const auto data = jina_embeddings_v3::section(context.reader, "runtime.json"); + const auto cfg = nlohmann::json::parse(data.begin(), data.end()); + const int32_t length = cfg.at("sequence_length"), width = cfg.at("hidden_size"); + const int32_t vocab = cfg.at("vocab_size"), pad = cfg.at("pad_token_id"); + if (length <= 0 || length > 8192 || width <= 0 || vocab <= 0 || pad < 0 || pad >= vocab) + throw std::runtime_error("Invalid Jina embedding runtime dimensions"); + const auto plan = jina_embeddings_v3::section(context.reader, "model.plan"); + auto engine = context.backend.create_module(plan.data(), plan.size(), {}); + if (!engine || !engine->ok()) throw std::runtime_error("Jina engine failed to load"); + const auto tokenizer_json = jina_embeddings_v3::section(context.reader, "tokenizer.json"); + auto tokenizer = CreateUnigramTokenizer(tokenizer_json.data(), tokenizer_json.size(), true); + return new jina_embeddings_v3::Pipeline(std::move(engine), std::move(tokenizer), length, width, + vocab, pad); +} diff --git a/families/jina_embeddings_v3/runtime/tokenizer.h b/families/jina_embeddings_v3/runtime/tokenizer.h new file mode 100644 index 0000000000..80d3e26bc3 --- /dev/null +++ b/families/jina_embeddings_v3/runtime/tokenizer.h @@ -0,0 +1,29 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + */ + +#pragma once + +#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 CreateUnigramTokenizer(const char* tokenizer_json_data, + std::size_t tokenizer_json_size, + bool add_special_tokens = false); + +} // namespace trtmc diff --git a/families/jina_embeddings_v3/runtime/unigram_tokenizer.cpp b/families/jina_embeddings_v3/runtime/unigram_tokenizer.cpp new file mode 100644 index 0000000000..cdcfcd4b73 --- /dev/null +++ b/families/jina_embeddings_v3/runtime/unigram_tokenizer.cpp @@ -0,0 +1,577 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + */ + +#include "families/jina_embeddings_v3/runtime/tokenizer.h" +#include "families/jina_embeddings_v3/runtime/charsmap.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace trtmc { +namespace { + +// ─── UTF-8 helpers ─── + +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 char32_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; +} + +// Return the byte length of the UTF-8 codepoint starting at s[pos]. +inline size_t utf8_char_len(const std::string& s, size_t pos) { + unsigned char c = static_cast(s[pos]); + if (c < 0x80) + return 1; + if ((c & 0xE0) == 0xC0) + return 2; + if ((c & 0xF0) == 0xE0) + return 3; + if ((c & 0xF8) == 0xF0) + return 4; + return 1; +} + +std::string lowercase_ascii(std::string text) { + std::transform(text.begin(), text.end(), text.begin(), + [](unsigned char c) { return static_cast(std::tolower(c)); }); + return text; +} + +// ─── Metaspace Pre-tokenizer ─── +// Replaces spaces with ▁ (U+2581) and optionally adds prefix space. + +static const std::string kMetaspaceChar = "\xe2\x96\x81"; // ▁ U+2581 + +inline bool is_ws(char c) { + return c == ' ' || c == '\t' || c == '\n' || c == '\r'; +} + +std::vector whitespace_split(const std::string& text) { + std::vector words; + size_t i = 0; + while (i < text.size()) { + while (i < text.size() && is_ws(text[i])) + ++i; + if (i >= text.size()) + break; + size_t start = i; + while (i < text.size() && !is_ws(text[i])) + ++i; + words.push_back(text.substr(start, i - start)); + } + return words; +} + +[[maybe_unused]] std::string metaspace_pre_tokenize(const std::string& text, + bool add_prefix_space) { + std::string result; + result.reserve(text.size() + 8); + if (add_prefix_space && !text.empty() && text[0] != ' ') { + result += kMetaspaceChar; + } + for (size_t i = 0; i < text.size(); ++i) { + if (text[i] == ' ') { + result += kMetaspaceChar; + } else { + result += text[i]; + } + } + return result; +} + +// ─── Trie for efficient vocab prefix lookup ─── + +struct TrieNode { + std::unordered_map children; + int token_id = -1; // -1 = not a token end + float score = 0.0f; +}; + +class Trie { + public: + Trie() { mNodes.emplace_back(); } // root node + + void insert(const std::string& token, int id, float score) { + int node = 0; + for (char c : token) { + auto it = mNodes[node].children.find(c); + if (it == mNodes[node].children.end()) { + int next = static_cast(mNodes.size()); + mNodes.emplace_back(); + mNodes[node].children[c] = next; + node = next; + } else { + node = it->second; + } + } + mNodes[node].token_id = id; + mNodes[node].score = score; + } + + // Find all tokens that match a prefix of text starting at offset. + // Returns vector of (token_id, byte_length, score). + struct Match { + int token_id; + size_t length; + float score; + }; + + void find_prefixes(const std::string& text, size_t offset, std::vector& out) const { + out.clear(); + int node = 0; + for (size_t i = offset; i < text.size(); ++i) { + char c = text[i]; + auto it = mNodes[node].children.find(c); + if (it == mNodes[node].children.end()) + break; + node = it->second; + if (mNodes[node].token_id >= 0) { + out.push_back({mNodes[node].token_id, i - offset + 1, mNodes[node].score}); + } + } + } + + private: + std::vector mNodes; +}; + +// ─── Viterbi algorithm for Unigram tokenization ─── + +struct ViterbiNode { + float score; + int token_id; + size_t prev_pos; // byte position of previous node +}; + +std::vector viterbi_encode(const std::string& text, const Trie& trie, int32_t unk_id, + float unk_score) { + if (text.empty()) + return {}; + + size_t n = text.size(); + // best[i] = best path score to reach byte position i + std::vector best(n + 1, {-std::numeric_limits::infinity(), -1, 0}); + best[0].score = 0.0f; + + std::vector matches; + + for (size_t i = 0; i < n; ++i) { + if (best[i].score == -std::numeric_limits::infinity()) + continue; + + trie.find_prefixes(text, i, matches); + + for (const auto& m : matches) { + size_t end = i + m.length; + float new_score = best[i].score + m.score; + if (new_score > best[end].score) { + best[end].score = new_score; + best[end].token_id = m.token_id; + best[end].prev_pos = i; + } + } + + // Advance by one UTF-8 codepoint after emitting UNK. + size_t char_len = utf8_char_len(text, i); + size_t end = i + char_len; + if (end <= n) { + float new_score = best[i].score + unk_score; + if (new_score > best[end].score) { + best[end].score = new_score; + best[end].token_id = unk_id; + best[end].prev_pos = i; + } + } + } + + // Backtrack to find the best path + std::vector ids; + size_t pos = n; + while (pos > 0) { + if (best[pos].token_id < 0) { + // Unreachable after emitting UNK. + ids.push_back(unk_id); + break; + } + ids.push_back(best[pos].token_id); + pos = best[pos].prev_pos; + } + + std::reverse(ids.begin(), ids.end()); + return ids; +} + +// ─── UnigramTokenizer ─── + +class UnigramTokenizer final : public ITokenizer { + public: + static std::unique_ptr Create(const char* json_data, std::size_t json_size, + bool add_special_tokens) { + auto tok = std::unique_ptr(new UnigramTokenizer()); + tok->mAddSpecialTokens = add_special_tokens; + tok->parse_tokenizer_json(json_data, json_size); + return tok; + } + + std::vector encode(const std::string& text) const override { + if (text.empty()) { + return mAddSpecialTokens ? make_special_frame({}) : std::vector{}; + } + + // Normalize + std::string normalized = mCharsMap.normalize(text); + if (mLowercase) + normalized = lowercase_ascii(std::move(normalized)); + + // Pre-tokenize: WhitespaceSplit → Metaspace + auto words = whitespace_split(normalized); + std::vector ids; + for (size_t i = 0; i < words.size(); ++i) { + // Metaspace: prepend ▁ to each word + std::string processed = kMetaspaceChar + words[i]; + auto word_ids = viterbi_encode(processed, mTrie, mUnkId, mUnkScore); + ids.insert(ids.end(), word_ids.begin(), word_ids.end()); + } + + if (mAddSpecialTokens) + ids = make_special_frame(ids); + return ids; + } + + std::string decode(const std::vector& ids) const override { + std::string result; + for (int32_t id : ids) { + if (mDecodeSkipIds.count(id)) + continue; + std::string token = token_for_id(id); + result += token; + } + // Remove metaspace characters and clean up + return decode_metaspace(result); + } + + int32_t id_for_token(std::string_view token) const override { + auto it = mTokenToId.find(std::string(token)); + return it != mTokenToId.end() ? it->second : -1; + } + + std::string token_for_id(int32_t id) const override { + if (id >= 0 && static_cast(id) < mIdToToken.size()) { + return mIdToToken[id]; + } + return ""; + } + + private: + UnigramTokenizer() = default; + + static std::string decode_metaspace(const std::string& text) { + std::string result; + size_t pos = 0; + while (pos < text.size()) { + if (pos + kMetaspaceChar.size() <= text.size() && + text.compare(pos, kMetaspaceChar.size(), kMetaspaceChar) == 0) { + if (!result.empty()) + result += ' '; + pos += kMetaspaceChar.size(); + } else { + result += text[pos]; + ++pos; + } + } + return result; + } + + std::vector make_special_frame(std::vector ids) const { + std::vector result; + if (mBosId >= 0) + result.push_back(mBosId); + result.insert(result.end(), ids.begin(), ids.end()); + if (mEosId >= 0) + result.push_back(mEosId); + return result; + } + + // ─── JSON parsing ─── + + void parse_tokenizer_json(const char* json_data, std::size_t json_size) { + nlohmann::json j; + try { + j = nlohmann::json::parse(json_data, json_data + json_size); + } catch (const std::exception& e) { + throw std::runtime_error(std::string("Failed to parse tokenizer.json: ") + e.what()); + } + + validate_model(j); + parse_vocab(j); + build_trie(); + parse_normalizer(j); + parse_pre_tokenizer(j); + parse_added_tokens(j); + parse_post_processor(j); + resolve_special_ids(); + } + + static void validate_model(const nlohmann::json& j) { + if (!j.contains("model")) + throw std::runtime_error("Invalid tokenizer.json: missing model"); + + auto& model = j["model"]; + + if (!model.contains("vocab") || !model["vocab"].is_array()) + throw std::runtime_error("Invalid tokenizer.json: model.vocab must be an array"); + } + + void parse_vocab(const nlohmann::json& j) { + auto& vocab = j["model"]["vocab"]; + mIdToToken.resize(vocab.size()); + mUnkId = j["model"].value("unk_id", 0); + + for (size_t i = 0; i < vocab.size(); ++i) { + auto& entry = vocab[i]; + std::string token = entry[0].get(); + float score = entry[1].get(); + + mIdToToken[i] = token; + mTokenToId[token] = static_cast(i); + mScores.push_back(score); + } + + // UNK score: must be worse than ANY real vocab token for Viterbi + float min_score = 0.0f; + for (float s : mScores) { + if (s < min_score) + min_score = s; + } + mUnkScore = min_score - 10.0f; + } + + void build_trie() { + for (size_t i = 0; i < mIdToToken.size(); ++i) { + const auto& token = mIdToToken[i]; + if (!token.empty()) { + mTrie.insert(token, static_cast(i), mScores[i]); + } + } + } + + void apply_normalizer_config(const nlohmann::json& norm) { + const std::string ntype = norm.value("type", ""); + if (ntype == "Precompiled") { + mCharsMap.load(norm.at("precompiled_charsmap").get()); + return; + } + if (ntype == "Lowercase") { + mLowercase = true; + return; + } + if (ntype == "Prepend") { + // MT5-style: prepend a string (e.g., "▁") to input + mAddPrefixSpace = true; + } + } + + void parse_normalizer(const nlohmann::json& j) { + if (!j.contains("normalizer") || j["normalizer"].is_null()) + return; + const auto& norm = j["normalizer"]; + if (norm.value("type", "") == "Sequence" && norm.contains("normalizers")) { + for (const auto& sub : norm["normalizers"]) + apply_normalizer_config(sub); + return; + } + apply_normalizer_config(norm); + } + + void parse_pre_tokenizer(const nlohmann::json& j) { + if (!j.contains("pre_tokenizer") || j["pre_tokenizer"].is_null()) + return; + auto& pt = j["pre_tokenizer"]; + std::string ptype = pt.value("type", ""); + + if (ptype == "Metaspace") { + mAddPrefixSpace = pt.value("add_prefix_space", true); + } else if (ptype == "Sequence") { + // Look for Metaspace inside the sequence + if (pt.contains("pretokenizers")) { + for (auto& sub : pt["pretokenizers"]) { + if (sub.value("type", "") == "Metaspace") { + mAddPrefixSpace = sub.value("add_prefix_space", true); + break; + } + } + } + } + } + + void parse_added_tokens(const nlohmann::json& j) { + if (!j.contains("added_tokens")) + return; + for (auto& tok : j["added_tokens"]) { + int32_t tok_id = tok.value("id", -1); + std::string content = tok.value("content", ""); + if (tok_id >= 0 && !content.empty()) { + if (static_cast(tok_id) >= mIdToToken.size()) { + mIdToToken.resize(static_cast(tok_id) + 1); + mScores.resize(static_cast(tok_id) + 1, 0.0f); + } + mIdToToken[tok_id] = content; + mTokenToId[content] = tok_id; + } + } + } + + // Extract BOS/EOS from TemplateProcessing "single" array + void extract_template_bos_eos(const nlohmann::json& pp) { + if (!pp.contains("single") || !pp["single"].is_array()) + return; + bool seen_sequence = false; + for (auto& item : pp["single"]) { + if (item.contains("Sequence")) { + seen_sequence = true; + continue; + } + if (!item.contains("SpecialToken")) + continue; + std::string tok_str = item["SpecialToken"].value("id", ""); + auto it = mTokenToId.find(tok_str); + if (it == mTokenToId.end()) + continue; + if (!seen_sequence && mBosId < 0) + mBosId = it->second; + else + mEosId = it->second; + } + } + + // Extract BOS/EOS from RobertaProcessing cls/sep arrays + static int32_t extract_pp_id(const nlohmann::json& pp, const char* key) { + if (pp.contains(key) && pp[key].is_array() && pp[key].size() >= 2) + return pp[key][1].get(); + return -1; + } + + void parse_post_processor(const nlohmann::json& j) { + if (!j.contains("post_processor") || j["post_processor"].is_null()) + return; + auto& pp = j["post_processor"]; + std::string ptype = pp.value("type", ""); + + if (ptype == "TemplateProcessing") + extract_template_bos_eos(pp); + if (ptype == "RobertaProcessing") { + mBosId = extract_pp_id(pp, "cls"); + mEosId = extract_pp_id(pp, "sep"); + } + } + + void resolve_special_ids() { + // Try common special-token names. + auto find_id = [this](const std::string& a, const std::string& b) -> int32_t { + auto it = mTokenToId.find(a); + if (it != mTokenToId.end()) + return it->second; + it = mTokenToId.find(b); + return it != mTokenToId.end() ? it->second : -1; + }; + + if (mBosId < 0) + mBosId = find_id("", "[CLS]"); + if (mEosId < 0) + mEosId = find_id("", "[SEP]"); + int32_t padId = find_id("", "[PAD]"); + + // Build decode skip set + for (int32_t id : {mBosId, mEosId, padId}) { + if (id >= 0) + mDecodeSkipIds.insert(id); + } + } + + // ─── Data members ─── + + std::vector mIdToToken; + std::vector mScores; + std::unordered_map mTokenToId; + std::unordered_set mDecodeSkipIds; + Trie mTrie; + + int32_t mUnkId = 0; + float mUnkScore = -100.0f; + bool mAddSpecialTokens = true; + mt5::CharsMap mCharsMap; + bool mLowercase = false; + bool mAddPrefixSpace = true; + + int32_t mBosId = -1; + int32_t mEosId = -1; +}; + +} // namespace + +std::unique_ptr CreateUnigramTokenizer(const char* tokenizer_json_data, + std::size_t tokenizer_json_size, + bool add_special_tokens) { + return UnigramTokenizer::Create(tokenizer_json_data, tokenizer_json_size, add_special_tokens); +} + +} // namespace trtmc diff --git a/families/jina_embeddings_v3/support.py b/families/jina_embeddings_v3/support.py new file mode 100644 index 0000000000..79de6298b0 --- /dev/null +++ b/families/jina_embeddings_v3/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 family_support + +describe = family_support( + model_types=("jina_embeddings_v3",), + tasks=("text_to_embedding",), + default_task="text_to_embedding", + default_precision="fp32", +) diff --git a/families/jina_embeddings_v3/tests/__init__.py b/families/jina_embeddings_v3/tests/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/families/jina_embeddings_v3/tests/cpp/test_tokenizer.cpp b/families/jina_embeddings_v3/tests/cpp/test_tokenizer.cpp new file mode 100644 index 0000000000..bc74290bab --- /dev/null +++ b/families/jina_embeddings_v3/tests/cpp/test_tokenizer.cpp @@ -0,0 +1,17 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + */ +#include "families/jina_embeddings_v3/runtime/tokenizer.h" +#include +#include +#include +#include + +int main(int argc, char** argv) { + if (argc != 3) return 2; + std::ifstream file(argv[1]); + const std::string data((std::istreambuf_iterator(file)), {}); + const auto tokenizer = trtmc::CreateUnigramTokenizer(data.data(), data.size(), true); + std::cout << nlohmann::json(tokenizer->encode(argv[2])).dump() << '\n'; +} diff --git a/families/jina_embeddings_v3/tests/manifests/jina-embeddings-v3-hf.json b/families/jina_embeddings_v3/tests/manifests/jina-embeddings-v3-hf.json new file mode 100644 index 0000000000..595ff468f9 --- /dev/null +++ b/families/jina_embeddings_v3/tests/manifests/jina-embeddings-v3-hf.json @@ -0,0 +1,35 @@ +{ + "name": "jina-embeddings-v3-hf", + "hf_id": "jinaai/jina-embeddings-v3-hf", + "hf_revision": "d18862d9a48706220815554fac3ebb4dfa46fc28", + "bundle": "jina-embeddings-v3-hf.bundle", + "family": "jina_embeddings_v3", + "task": "text_to_embedding", + "precision": "fp32", + "max_sequence_length": 256, + "tensor_parallel_size": 1, + "testcases": [ + { + "name": "jina-embeddings-v3-hf", + "premerge": true, + "inputs": [ + { + "text": "How do plants absorb sunlight?", + "role": "default" + }, + { + "text": "How do plants absorb sunlight?", + "role": "query" + }, + { + "text": "How do plants absorb sunlight?", + "role": "document" + }, + { + "text": "多言語の文章と café 123.", + "role": "document" + } + ] + } + ] +} diff --git a/families/jina_embeddings_v3/tests/test_e2e.py b/families/jina_embeddings_v3/tests/test_e2e.py new file mode 100644 index 0000000000..aec0189ecc --- /dev/null +++ b/families/jina_embeddings_v3/tests/test_e2e.py @@ -0,0 +1,271 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Pinned official-reference parity through the native text-embedding Task API.""" + +from __future__ import annotations + +import json +import math +import os +import subprocess +from pathlib import Path + +import pytest + +from tensorrt_model_connect import BuildRequest, build + +FAMILY = "jina_embeddings_v3" +TASKS = frozenset({"text_to_embedding"}) +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 + + +def _model_dir(manifest: dict) -> Path: + explicit = os.environ.get(f"TRTMC_{FAMILY.upper()}_MODEL_DIR") + if explicit: + return _required_path(explicit, 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 + return 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: + 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)), + ) + 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 test_official_checkpoint_e2e(case_name, tmp_path): + import numpy as np + import torch + from transformers import AutoModel, AutoTokenizer + + _, manifest, case = CASES[case_name] + directory = _model_dir(manifest) + binary, runtime_root = _runtime() + tokenizer = AutoTokenizer.from_pretrained(directory) + for text in [ + "A small test.", + "日本語の文章 中文 한국어", + "café e\u0301 123\n test", + "", + " trailing spaces ", + ]: + completed = subprocess.run( + [ + str(runtime_root / "test_jina_embeddings_v3_tokenizer"), + str(directory / "tokenizer.json"), + text, + ], + check=False, + capture_output=True, + text=True, + ) + assert completed.returncode == 0, completed.stderr + assert json.loads(completed.stdout) == tokenizer.encode(text), repr(text) + + bundle = tmp_path / manifest["bundle"] + _build(directory, bundle, manifest) + torch.backends.cuda.matmul.allow_tf32 = False + torch.backends.cudnn.allow_tf32 = False + model = ( + AutoModel.from_pretrained(directory, dtype=torch.float32, attn_implementation="eager") + .eval() + .to("cuda") + ) + for name in ("retrieval_query", "retrieval_passage"): + model.load_adapter(str(directory / name), adapter_name=name) + model.eval() + roles = {} + for item in case["inputs"]: + if item["role"] == "default": + model.disable_adapters() + else: + model.enable_adapters() + model.set_adapter( + {"query": "retrieval_query", "document": "retrieval_passage"}[item["role"]] + ) + inputs = tokenizer(item["text"], return_tensors="pt").to("cuda") + with torch.no_grad(): + hidden = model(**inputs).last_hidden_state + valid = inputs["attention_mask"].unsqueeze(-1) + mean = (hidden * valid).sum(dim=1) / valid.sum(dim=1) + expected = torch.nn.functional.normalize(mean, dim=-1)[0].cpu().numpy() + payload = _run_json( + binary, + runtime_root, + bundle, + case, + "embed", + "--task", + manifest["task"], + "--text", + item["text"], + "--role", + item["role"], + ) + assert payload["embedding_space"] == "jina_embeddings_v3" + assert payload["pooling"] == "mean" and payload["normalization"] == "l2" + actual = np.asarray(payload["values"], dtype=np.float32) + assert actual.shape == expected.shape == (1024,) + assert np.isfinite(actual).all() + assert abs(np.linalg.norm(actual) - 1) <= 1e-5 + cosine = np.dot(actual, expected) / (np.linalg.norm(actual) * np.linalg.norm(expected)) + assert cosine >= 0.99999 + np.testing.assert_allclose(actual, expected, atol=1e-4, rtol=0) + roles.setdefault(item["role"], actual) + print( + f"Jina role={item['role']}, cosine={cosine:.8f}, maxabs={np.max(np.abs(actual - expected)):.6g}" + ) + # The adapters must affect the embedding even with identical input text. + assert np.linalg.norm(roles["default"] - roles["query"]) > 0.01 + assert np.linalg.norm(roles["query"] - roles["document"]) > 0.01 diff --git a/families/jina_embeddings_v3/tests/test_support.py b/families/jina_embeddings_v3/tests/test_support.py new file mode 100644 index 0000000000..cd6abaf6d4 --- /dev/null +++ b/families/jina_embeddings_v3/tests/test_support.py @@ -0,0 +1,9 @@ +# 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 + + +def test_embedding_checkpoint_has_one_owner(): + family, support = resolve_family(ModelMetadata({"model_type": "jina_embeddings_v3"}, {})) + assert family == "jina_embeddings_v3" + assert support.tasks == ("text_to_embedding",) From 591719d68b8e940a0b894a4a933d57b100feac0b Mon Sep 17 00:00:00 2001 From: Will Guo Date: Fri, 13 Nov 2026 06:04:46 -0800 Subject: [PATCH 2/3] chore(jina-embeddings-v3): satisfy source checks Signed-off-by: Will Guo --- .../jina_embeddings_v3/runtime/charsmap.h | 20 +++++--- .../jina_embeddings_v3/runtime/plugin.cpp | 46 +++++++++++++------ .../runtime/unigram_tokenizer.cpp | 2 +- .../tests/cpp/test_tokenizer.cpp | 4 +- families/jina_embeddings_v3/tests/test_e2e.py | 1 - 5 files changed, 49 insertions(+), 24 deletions(-) diff --git a/families/jina_embeddings_v3/runtime/charsmap.h b/families/jina_embeddings_v3/runtime/charsmap.h index bbec61dd5f..23b27afe53 100644 --- a/families/jina_embeddings_v3/runtime/charsmap.h +++ b/families/jina_embeddings_v3/runtime/charsmap.h @@ -23,7 +23,8 @@ class CharsMap { const std::string alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; for (const unsigned char c : encoded) { - if (c == '=') break; + if (c == '=') + break; const auto position = alphabet.find(c); if (position == std::string::npos) throw std::runtime_error("mt5 invalid normalization map encoding"); @@ -37,8 +38,9 @@ class CharsMap { auto word = [&bytes](std::size_t index) -> std::uint32_t { if (index > bytes.size() || bytes.size() - index < 4) throw std::runtime_error("mt5 truncated normalization map"); - return std::uint32_t(bytes[index]) | (std::uint32_t(bytes[index+1]) << 8) - | (std::uint32_t(bytes[index+2]) << 16) | (std::uint32_t(bytes[index+3]) << 24); + return std::uint32_t(bytes[index]) | (std::uint32_t(bytes[index + 1]) << 8) | + (std::uint32_t(bytes[index + 2]) << 16) | + (std::uint32_t(bytes[index + 3]) << 24); }; const auto size = word(0); if (size == 0 || size % 4 || size > bytes.size() - 4) @@ -50,7 +52,8 @@ class CharsMap { } std::string normalize(const std::string& input) const { - if (units_.empty()) return input; + if (units_.empty()) + return input; std::string result; for (std::size_t start = 0; start < input.size();) { std::uint32_t node = offset(units_[0]); @@ -58,11 +61,14 @@ class CharsMap { std::uint32_t replacement = 0; for (std::size_t end = start; end < input.size(); ++end) { const auto c = static_cast(input[end]); - if (c == 0) break; + if (c == 0) + break; node ^= c; - if (node >= units_.size()) break; + if (node >= units_.size()) + break; const auto unit = units_[node]; - if ((unit & 0x800000FFU) != c) break; + if ((unit & 0x800000FFU) != c) + break; node ^= offset(unit); if (unit & 0x100U) { if (node >= units_.size()) diff --git a/families/jina_embeddings_v3/runtime/plugin.cpp b/families/jina_embeddings_v3/runtime/plugin.cpp index 0724e7efab..8e86831b45 100644 --- a/families/jina_embeddings_v3/runtime/plugin.cpp +++ b/families/jina_embeddings_v3/runtime/plugin.cpp @@ -7,6 +7,7 @@ #include "trtmc/internal/model.h" #include "trtmc/runtime/family_factory.h" #include "trtmc/runtime/trt_backend.h" + #include #include #include @@ -33,17 +34,25 @@ class Pipeline final : public internal::IModel, public internal::ITextToEmbeddin } internal::SemanticEmbeddingResult run(const internal::TextToEmbeddingRequest& request, internal::ConfigView config) override { - if (!config.empty()) throw internal::ConfigError("Jina embedding has no runtime config"); + if (!config.empty()) + throw internal::ConfigError("Jina embedding has no runtime config"); int32_t adapter_id = 0; switch (request.role) { - case internal::EmbeddingRole::Default: break; - case internal::EmbeddingRole::Query: adapter_id = 1; break; - case internal::EmbeddingRole::Document: adapter_id = 2; break; - default: throw std::invalid_argument("Unknown Jina embedding role"); + case internal::EmbeddingRole::Default: + break; + case internal::EmbeddingRole::Query: + adapter_id = 1; + break; + case internal::EmbeddingRole::Document: + adapter_id = 2; + break; + default: + throw std::invalid_argument("Unknown Jina embedding role"); } auto ids = tokenizer_->encode(std::string(request.text)); if (ids.empty() || ids.size() > static_cast(length_)) - throw std::invalid_argument("Jina embedding requires a nonempty input within the built profile"); + throw std::invalid_argument( + "Jina embedding requires a nonempty input within the built profile"); for (const auto id : ids) { if (id < 0 || id >= vocab_) throw std::invalid_argument("Jina tokenizer returned an invalid token ID"); @@ -53,12 +62,18 @@ class Pipeline final : public internal::IModel, public internal::ITextToEmbeddin std::vector valid(length_, 0); std::fill(valid.begin(), valid.begin() + count, 1); Tensor input, mask; - input.data = ids.data(); input.shape = {length_}; input.dtype = DType::kInt32; - mask.data = valid.data(); mask.shape = {length_}; mask.dtype = DType::kInt32; + input.data = ids.data(); + input.shape = {length_}; + input.dtype = DType::kInt32; + mask.data = valid.data(); + mask.shape = {length_}; + mask.dtype = DType::kInt32; Tensor adapter; - adapter.data = &adapter_id; adapter.shape = {1}; adapter.dtype = DType::kInt32; - auto outputs = engine_->forward({{"input_ids", input}, {"attention_mask", mask}, - {"adapter_id", adapter}}); + adapter.data = &adapter_id; + adapter.shape = {1}; + adapter.dtype = DType::kInt32; + auto outputs = engine_->forward( + {{"input_ids", input}, {"attention_mask", mask}, {"adapter_id", adapter}}); const auto found = outputs.find("embedding"); if (found == outputs.end() || !found->second.data || found->second.dtype != DType::kFloat32 || @@ -68,13 +83,15 @@ class Pipeline final : public internal::IModel, public internal::ITextToEmbeddin internal::SemanticEmbeddingResult result; result.values.assign(values, values + width_); for (const auto value : result.values) { - if (!std::isfinite(value)) throw std::runtime_error("Jina embedding is nonfinite"); + if (!std::isfinite(value)) + throw std::runtime_error("Jina embedding is nonfinite"); } result.embedding_space = "jina_embeddings_v3"; result.pooling = "mean"; result.normalization = "l2"; return result; } + private: std::unique_ptr engine_; std::unique_ptr tokenizer_; @@ -95,9 +112,10 @@ extern "C" trtmc::ITask* trtmc_create_family(const trtmc::FamilyContext& context throw std::runtime_error("Invalid Jina embedding runtime dimensions"); const auto plan = jina_embeddings_v3::section(context.reader, "model.plan"); auto engine = context.backend.create_module(plan.data(), plan.size(), {}); - if (!engine || !engine->ok()) throw std::runtime_error("Jina engine failed to load"); + if (!engine || !engine->ok()) + throw std::runtime_error("Jina engine failed to load"); const auto tokenizer_json = jina_embeddings_v3::section(context.reader, "tokenizer.json"); auto tokenizer = CreateUnigramTokenizer(tokenizer_json.data(), tokenizer_json.size(), true); return new jina_embeddings_v3::Pipeline(std::move(engine), std::move(tokenizer), length, width, - vocab, pad); + vocab, pad); } diff --git a/families/jina_embeddings_v3/runtime/unigram_tokenizer.cpp b/families/jina_embeddings_v3/runtime/unigram_tokenizer.cpp index cdcfcd4b73..484743cb3b 100644 --- a/families/jina_embeddings_v3/runtime/unigram_tokenizer.cpp +++ b/families/jina_embeddings_v3/runtime/unigram_tokenizer.cpp @@ -3,8 +3,8 @@ * SPDX-License-Identifier: Apache-2.0 */ -#include "families/jina_embeddings_v3/runtime/tokenizer.h" #include "families/jina_embeddings_v3/runtime/charsmap.h" +#include "families/jina_embeddings_v3/runtime/tokenizer.h" #include #include diff --git a/families/jina_embeddings_v3/tests/cpp/test_tokenizer.cpp b/families/jina_embeddings_v3/tests/cpp/test_tokenizer.cpp index bc74290bab..3bcc1e76e5 100644 --- a/families/jina_embeddings_v3/tests/cpp/test_tokenizer.cpp +++ b/families/jina_embeddings_v3/tests/cpp/test_tokenizer.cpp @@ -3,13 +3,15 @@ * SPDX-License-Identifier: Apache-2.0 */ #include "families/jina_embeddings_v3/runtime/tokenizer.h" + #include #include #include #include int main(int argc, char** argv) { - if (argc != 3) return 2; + if (argc != 3) + return 2; std::ifstream file(argv[1]); const std::string data((std::istreambuf_iterator(file)), {}); const auto tokenizer = trtmc::CreateUnigramTokenizer(data.data(), data.size(), true); diff --git a/families/jina_embeddings_v3/tests/test_e2e.py b/families/jina_embeddings_v3/tests/test_e2e.py index aec0189ecc..e67aa50907 100644 --- a/families/jina_embeddings_v3/tests/test_e2e.py +++ b/families/jina_embeddings_v3/tests/test_e2e.py @@ -6,7 +6,6 @@ from __future__ import annotations import json -import math import os import subprocess from pathlib import Path From e5fb9dedcc4def80fd3554ea708731bddb14fba3 Mon Sep 17 00:00:00 2001 From: Will Guo Date: Thu, 19 Nov 2026 01:44:56 -0800 Subject: [PATCH 3/3] fix(jina_embeddings_v3): preserve native validation outputs and own static runtime contracts Signed-off-by: Will Guo --- families/jina_embeddings_v3/__init__.py | 4 + families/jina_embeddings_v3/model.py | 2 + .../jina_embeddings_v3/runtime/plugin.cpp | 4 +- families/jina_embeddings_v3/tests/__init__.py | 4 + families/jina_embeddings_v3/tests/test_e2e.py | 247 ++++++++++++++---- .../jina_embeddings_v3/tests/test_support.py | 1 + 6 files changed, 208 insertions(+), 54 deletions(-) diff --git a/families/jina_embeddings_v3/__init__.py b/families/jina_embeddings_v3/__init__.py index e69de29bb2..2fd2b9ac94 100644 --- a/families/jina_embeddings_v3/__init__.py +++ b/families/jina_embeddings_v3/__init__.py @@ -0,0 +1,4 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""jina embeddings v3 family package.""" diff --git a/families/jina_embeddings_v3/model.py b/families/jina_embeddings_v3/model.py index 3e2c6b6448..1bf25ac1d9 100644 --- a/families/jina_embeddings_v3/model.py +++ b/families/jina_embeddings_v3/model.py @@ -180,6 +180,8 @@ def rope(x): def build(request, writer): if request.task != "text_to_embedding" or request.backend != "trt": raise ValueError("Jina embeddings requires text_to_embedding and backend=trt") + if request.dynamic_kv_cache: + raise NotImplementedError("jina_embeddings_v3 does not support dynamic_kv_cache") if ( request.precision != "fp32" or request.tensor_parallel_size != 1 diff --git a/families/jina_embeddings_v3/runtime/plugin.cpp b/families/jina_embeddings_v3/runtime/plugin.cpp index 8e86831b45..2ff425c373 100644 --- a/families/jina_embeddings_v3/runtime/plugin.cpp +++ b/families/jina_embeddings_v3/runtime/plugin.cpp @@ -101,8 +101,10 @@ class Pipeline final : public internal::IModel, public internal::ITextToEmbeddin } // namespace trtmc::jina_embeddings_v3 extern "C" trtmc::ITask* trtmc_create_family(const trtmc::FamilyContext& context) { + if (context.kv_cache_size_bytes != 0) + throw std::invalid_argument("jina_embeddings_v3 does not support --kv-cache-size"); using namespace trtmc; - if (context.kv_cache_size_bytes != 0 || context.reader.info().task != "text_to_embedding") + if (context.reader.info().task != "text_to_embedding") throw std::invalid_argument("Jina requires text embedding without a KV cache"); const auto data = jina_embeddings_v3::section(context.reader, "runtime.json"); const auto cfg = nlohmann::json::parse(data.begin(), data.end()); diff --git a/families/jina_embeddings_v3/tests/__init__.py b/families/jina_embeddings_v3/tests/__init__.py index e69de29bb2..458fd3a235 100644 --- a/families/jina_embeddings_v3/tests/__init__.py +++ b/families/jina_embeddings_v3/tests/__init__.py @@ -0,0 +1,4 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""jina embeddings v3 package.""" diff --git a/families/jina_embeddings_v3/tests/test_e2e.py b/families/jina_embeddings_v3/tests/test_e2e.py index e67aa50907..d472624f67 100644 --- a/families/jina_embeddings_v3/tests/test_e2e.py +++ b/families/jina_embeddings_v3/tests/test_e2e.py @@ -8,11 +8,13 @@ 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 = "jina_embeddings_v3" TASKS = frozenset({"text_to_embedding"}) @@ -92,6 +94,46 @@ def _required_path(value: str | None, label: str) -> 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") if explicit: @@ -149,49 +191,88 @@ def _run_json( command: str, *arguments: str, ) -> dict: - 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)), - ) - 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] + 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 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 AutoModel, AutoTokenizer _, manifest, case = CASES[case_name] - directory = _model_dir(manifest) + with evidence_stage("checkpoint"): + directory = _model_dir(manifest) binary, runtime_root = _runtime() - tokenizer = AutoTokenizer.from_pretrained(directory) + with evidence_stage("reference"): + tokenizer = AutoTokenizer.from_pretrained(directory) for text in [ "A small test.", "日本語の文章 中文 한국어", @@ -201,7 +282,7 @@ def test_official_checkpoint_e2e(case_name, tmp_path): ]: completed = subprocess.run( [ - str(runtime_root / "test_jina_embeddings_v3_tokenizer"), + str(_native_test_binary("test_jina_embeddings_v3_tokenizer")), str(directory / "tokenizer.json"), text, ], @@ -209,18 +290,23 @@ def test_official_checkpoint_e2e(case_name, tmp_path): capture_output=True, text=True, ) - assert completed.returncode == 0, completed.stderr - assert json.loads(completed.stdout) == tokenizer.encode(text), repr(text) + with evidence_stage("comparison"): + assert completed.returncode == 0, completed.stderr + with evidence_stage("comparison"): + assert json.loads(completed.stdout) == tokenizer.encode(text), repr(text) bundle = tmp_path / manifest["bundle"] - _build(directory, bundle, manifest) + 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 - model = ( - AutoModel.from_pretrained(directory, dtype=torch.float32, attn_implementation="eager") - .eval() - .to("cuda") - ) + with evidence_stage("reference"): + model = ( + AutoModel.from_pretrained(directory, dtype=torch.float32, attn_implementation="eager") + .eval() + .to("cuda") + ) for name in ("retrieval_query", "retrieval_passage"): model.load_adapter(str(directory / name), adapter_name=name) model.eval() @@ -234,7 +320,7 @@ def test_official_checkpoint_e2e(case_name, tmp_path): {"query": "retrieval_query", "document": "retrieval_passage"}[item["role"]] ) inputs = tokenizer(item["text"], return_tensors="pt").to("cuda") - with torch.no_grad(): + with evidence_stage("reference"), torch.no_grad(): hidden = model(**inputs).last_hidden_state valid = inputs["attention_mask"].unsqueeze(-1) mean = (hidden * valid).sum(dim=1) / valid.sum(dim=1) @@ -252,19 +338,74 @@ def test_official_checkpoint_e2e(case_name, tmp_path): "--role", item["role"], ) - assert payload["embedding_space"] == "jina_embeddings_v3" - assert payload["pooling"] == "mean" and payload["normalization"] == "l2" + with evidence_stage("comparison"): + assert payload["embedding_space"] == "jina_embeddings_v3" + with evidence_stage("comparison"): + assert payload["pooling"] == "mean" and payload["normalization"] == "l2" actual = np.asarray(payload["values"], dtype=np.float32) - assert actual.shape == expected.shape == (1024,) - assert np.isfinite(actual).all() - assert abs(np.linalg.norm(actual) - 1) <= 1e-5 + record_evidence("inputs", {"input": item, "token_ids": inputs["input_ids"].cpu().numpy()}) + record_evidence( + "thresholds", + {"cosine_min": 0.99999, "embedding_atol": 1e-4, "embedding_rtol": 0, "norm_atol": 1e-5}, + ) + record_evidence("native", {"role": item["role"], "text": item["text"], "values": actual}) + record_evidence( + "reference", + { + "mode": "hf_transformers", + "role": item["role"], + "text": item["text"], + "values": expected, + }, + ) + with evidence_stage("comparison"): + assert actual.shape == expected.shape == (1024,) + with evidence_stage("comparison"): + assert np.isfinite(actual).all() + with evidence_stage("comparison"): + assert abs(np.linalg.norm(actual) - 1) <= 1e-5 cosine = np.dot(actual, expected) / (np.linalg.norm(actual) * np.linalg.norm(expected)) - assert cosine >= 0.99999 - np.testing.assert_allclose(actual, expected, atol=1e-4, rtol=0) + with evidence_stage("comparison"): + assert cosine >= 0.99999 + with evidence_stage("comparison"): + np.testing.assert_allclose(actual, expected, atol=1e-4, rtol=0) + mismatch = int(np.count_nonzero(~np.isclose(actual, expected, atol=1e-4, rtol=0))) + record_evidence( + "metrics", + { + "role": item["role"], + "cosine": float(cosine), + "max_abs_error": float(np.max(np.abs(actual - expected))), + }, + ) + _record_comparison( + tmp_path, + f"embedding-{item['role']}-{len(item['text'])}", + actual, + expected, + [ + { + "name": "cosine", + "actual": float(cosine), + "operator": ">=", + "expected": 0.99999, + "passed": bool(cosine >= 0.99999), + }, + { + "name": "values_outside_tolerance", + "actual": mismatch, + "operator": "==", + "expected": 0, + "passed": mismatch == 0, + }, + ], + ) roles.setdefault(item["role"], actual) print( f"Jina role={item['role']}, cosine={cosine:.8f}, maxabs={np.max(np.abs(actual - expected)):.6g}" ) # The adapters must affect the embedding even with identical input text. - assert np.linalg.norm(roles["default"] - roles["query"]) > 0.01 - assert np.linalg.norm(roles["query"] - roles["document"]) > 0.01 + with evidence_stage("comparison"): + assert np.linalg.norm(roles["default"] - roles["query"]) > 0.01 + with evidence_stage("comparison"): + assert np.linalg.norm(roles["query"] - roles["document"]) > 0.01 diff --git a/families/jina_embeddings_v3/tests/test_support.py b/families/jina_embeddings_v3/tests/test_support.py index cd6abaf6d4..a0226f7840 100644 --- a/families/jina_embeddings_v3/tests/test_support.py +++ b/families/jina_embeddings_v3/tests/test_support.py @@ -7,3 +7,4 @@ def test_embedding_checkpoint_has_one_owner(): family, support = resolve_family(ModelMetadata({"model_type": "jina_embeddings_v3"}, {})) assert family == "jina_embeddings_v3" assert support.tasks == ("text_to_embedding",) + assert support.default_task == "text_to_embedding"