# 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"], ), )