# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 """LUKE word/entity embeddings, four entity-aware query paths and relation head.""" import json from pathlib import Path import numpy as np import tensorrt as trt from . import graph as g def build(request, writer): if request.task != "text_entity_pair_to_relation_scores" or request.backend != "trt": raise ValueError("LUKE requires text_entity_pair_to_relation_scores with backend=trt") if request.dynamic_kv_cache: raise NotImplementedError("luke does not support dynamic_kv_cache") 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("LUKE supports one fp32 text and ordered entity pair") directory = Path(request.model_dir) cfg = json.loads((directory / "config.json").read_text()) if ( cfg["model_type"] != "luke" or cfg["architectures"] != ["LukeForEntityPairClassification"] or not cfg["use_entity_aware_attention"] or cfg["hidden_act"] != "gelu" ): raise ValueError("Expected LUKE entity-aware relation classification") length = request.max_sequence_length or 128 if not 8 <= length <= cfg["max_position_embeddings"] - cfg["pad_token_id"] - 1: raise ValueError("LUKE word profile exceeds its position table") import torch from transformers import LukeTokenizer tokenizer = LukeTokenizer.from_pretrained(directory, task="entity_pair_classification") mention = tokenizer.max_mention_length entity_ids = [tokenizer.entity_mask_token_id, tokenizer.entity_mask2_token_id] state = torch.load( directory / "pytorch_model.bin", map_location="cpu", weights_only=True, mmap=True ) weights = {name: tensor.float().numpy() for name, tensor in state.items()} # This Task uses role-specific masked entities, never arbitrary named IDs. weights["luke.entity_embeddings.entity_embeddings.weight"] = weights[ "luke.entity_embeddings.entity_embeddings.weight" ][entity_ids] width, heads = cfg["hidden_size"], cfg["num_attention_heads"] dim, total = width // heads, length + 2 labels = [cfg["id2label"][str(index)] for index in range(len(cfg["id2label"]))] logger = trt.Logger(trt.Logger.VERBOSE if request.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) def const(value, dtype=np.float32): value = np.ascontiguousarray(value, dtype=dtype) return net.add_constant(value.shape, value).get_output(0) def shuf(x, shape, perm=None): layer = net.add_shuffle(x) if perm is not None: layer.first_transpose = perm layer.reshape_dims = shape return layer.get_output(0) def add(a, b): return net.add_elementwise(a, b, trt.ElementWiseOperation.SUM).get_output(0) def mul(a, b): return net.add_elementwise(a, b, trt.ElementWiseOperation.PROD).get_output(0) def linear(x, name): return g.add_linear(net, x, weights[name + ".weight"], weights.get(name + ".bias")) def norm(x, name): return g.add_layer_norm( net, x, weights[name + ".weight"], weights[name + ".bias"], cfg["layer_norm_eps"] ) def gather(name, ids): return net.add_gather(const(weights[name + ".weight"]), ids, 0).get_output(0) def concat(values, axis): layer = net.add_concatenation(values) layer.axis = axis return layer.get_output(0) def split(x, start, count): return net.add_slice(x, (start, 0), (count, width), (1, 1)).get_output(0) def heads_view(x, count): return shuf(shuf(x, (1, count, heads, dim)), (1, heads, count, dim), (0, 2, 1, 3)) ids = net.add_input("input_ids", trt.int32, (length,)) valid = net.add_input("attention_mask", trt.int32, (length,)) positions = net.add_input("position_ids", trt.int32, (length,)) entity_positions = net.add_input("entity_position_ids", trt.int32, (2, mention)) prefix = "luke.embeddings" words = add( add( gather(prefix + ".word_embeddings", ids), gather(prefix + ".position_embeddings", positions), ), const(weights[prefix + ".token_type_embeddings.weight"][:1]), ) words = norm(words, prefix + ".LayerNorm") prefix = "luke.entity_embeddings" entity = const(weights[prefix + ".entity_embeddings.weight"]) if cfg["entity_emb_size"] != width: entity = linear(entity, prefix + ".entity_embedding_dense") clipped = net.add_elementwise( entity_positions, const(np.zeros((1, 1)), np.int32), trt.ElementWiseOperation.MAX ).get_output(0) mask = net.add_elementwise( entity_positions, const(np.full((1, 1), -1), np.int32), trt.ElementWiseOperation.GREATER ).get_output(0) mask = net.add_cast(mask, trt.float32).get_output(0) positional = gather(prefix + ".position_embeddings", clipped) positional = mul(positional, shuf(mask, (2, mention, 1))) summed = net.add_reduce(positional, trt.ReduceOperation.SUM, 2, False).get_output(0) counts = net.add_reduce(mask, trt.ReduceOperation.SUM, 2, True).get_output(0) counts = net.add_elementwise( counts, const(np.full((1, 1), 1e-7)), trt.ElementWiseOperation.MAX ).get_output(0) means = net.add_elementwise(summed, counts, trt.ElementWiseOperation.DIV).get_output(0) entity = norm( add(add(entity, means), const(weights[prefix + ".token_type_embeddings.weight"][:1])), prefix + ".LayerNorm", ) hidden = concat([words, entity], 0) full_valid = concat([valid, const(np.ones((2,)), np.int32)], 0) blocked = net.add_elementwise( full_valid, const(np.zeros((1,)), np.int32), trt.ElementWiseOperation.EQUAL ).get_output(0) mask = net.add_select( shuf(blocked, (1, 1, 1, total)), const(np.full((1, 1, 1, total), -np.inf)), const(np.zeros((1, 1, 1, total))), ).get_output(0) scale = const(np.full((1, 1, 1, 1), dim**-0.5)) for index in range(cfg["num_hidden_layers"]): prefix = f"luke.encoder.layer.{index}" attention = prefix + ".attention.self" word, entity = split(hidden, 0, length), split(hidden, length, 2) keys = heads_view(linear(hidden, attention + ".key"), total) values = heads_view(linear(hidden, attention + ".value"), total) word_key = net.add_slice( keys, (0, 0, 0, 0), (1, heads, length, dim), (1, 1, 1, 1) ).get_output(0) entity_key = net.add_slice( keys, (0, 0, length, 0), (1, heads, 2, dim), (1, 1, 1, 1) ).get_output(0) rows = [] for source, count, query_names in [ (word, length, ("query", "w2e_query")), (entity, 2, ("e2w_query", "e2e_query")), ]: blocks = [] for key, query_name in zip((word_key, entity_key), query_names): query = heads_view(linear(source, attention + "." + query_name), count) blocks.append( net.add_matrix_multiply( query, trt.MatrixOperation.NONE, key, trt.MatrixOperation.TRANSPOSE ).get_output(0) ) rows.append(concat(blocks, 3)) scores = add(mul(concat(rows, 2), scale), mask) softmax = net.add_softmax(scores) softmax.axes = 8 context = net.add_matrix_multiply( softmax.get_output(0), trt.MatrixOperation.NONE, values, trt.MatrixOperation.NONE ).get_output(0) context = shuf(context, (total, width), (0, 2, 1, 3)) hidden = norm( add(hidden, linear(context, prefix + ".attention.output.dense")), prefix + ".attention.output.LayerNorm", ) inner = linear(hidden, prefix + ".intermediate.dense") inner = net.add_activation(inner, trt.ActivationType.GELU_ERF).get_output(0) hidden = norm( add(hidden, linear(inner, prefix + ".output.dense")), prefix + ".output.LayerNorm" ) logits = linear(shuf(split(hidden, length, 2), (1, 2 * width)), "classifier") logits.name = "relation_logits" net.mark_output(logits) plan = builder.build_serialized_network(net, options) if plan is None: raise RuntimeError("LUKE relation encoder engine build failed") writer.set_header(family="luke", task=request.task, backend=request.backend) writer.add_bytes("model.plan", bytes(plan)) writer.add_bytes("tokenizer.json", tokenizer._tokenizer.to_str().encode()) writer.add_json( "runtime.json", dict( sequence_length=length, max_mention_length=mention, vocab_size=cfg["vocab_size"], pad_token_id=tokenizer.pad_token_id, bos_token_id=tokenizer.bos_token_id, eos_token_id=tokenizer.eos_token_id, entity_markers=list(tokenizer.extra_special_tokens_ids[:2]), labels=labels, ), )