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
4 changes: 4 additions & 0 deletions families/pvt/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0

"""Pyramid Vision Transformer image classification."""
205 changes: 205 additions & 0 deletions families/pvt/model.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,205 @@
# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0

"""PVT patch stages, spatial-reduction attention, and classification in TensorRT."""

from __future__ import annotations

import json
from pathlib import Path

import numpy as np
from safetensors.numpy import load_file
import tensorrt as trt


def validate_config(config):
if config.get("model_type") != "pvt":
raise ValueError("pvt requires model_type=pvt")
if config.get("num_channels", 3) != 3 or config.get("hidden_act", "gelu") != "gelu":
raise NotImplementedError("pvt requires RGB input and exact GELU")
stages = config["num_encoder_blocks"]
for name in ("hidden_sizes", "depths", "num_attention_heads", "sequence_reduction_ratios",
"patch_sizes", "strides", "mlp_ratios"):
if len(config[name]) != stages or any(value <= 0 for value in config[name]):
raise ValueError(f"pvt {name} must contain one positive value per stage")
if config["patch_sizes"] != config["strides"]:
raise NotImplementedError("pvt requires matching patch sizes and strides")
if config["sequence_reduction_ratios"][-1] != 1:
raise ValueError("pvt class-token stage cannot spatially reduce its sequence")
for hidden, heads in zip(config["hidden_sizes"], config["num_attention_heads"]):
if hidden % heads:
raise ValueError("pvt attention heads must divide the stage width")
return config


class Graph:
def __init__(self, network, config, weights):
self.n, self.c, self.w = network, config, weights
self.constants = []

def constant(self, value):
value = np.ascontiguousarray(value, dtype=np.float32)
self.constants.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 add(self, x, y):
return self.n.add_elementwise(x, y, trt.ElementWiseOperation.SUM).get_output(0)

def linear(self, x, name):
weight = self.w[name + ".weight"]
rank = len(x.shape)
rhs = self.constant(weight.T.reshape((1,) * (rank - 2) + tuple(weight.T.shape)))
result = self.n.add_matrix_multiply(x, trt.MatrixOperation.NONE,
rhs, trt.MatrixOperation.NONE).get_output(0)
if name + ".bias" in self.w:
result = self.add(result, self.constant(self.w[name + ".bias"].reshape((1,) * (rank - 1) + (-1,))))
return result

def norm(self, x, name):
rank = len(x.shape)
shape = (1,) * (rank - 1) + (-1,)
layer = self.n.add_normalization(x, self.constant(self.w[name + ".weight"].reshape(shape)),
self.constant(self.w[name + ".bias"].reshape(shape)), 1 << (rank - 1))
layer.epsilon = self.c["layer_norm_eps"]
return layer.get_output(0)

def conv(self, x, name, stride):
weight = self.w[name + ".weight"]
layer = self.n.add_convolution_nd(x, weight.shape[0], tuple(weight.shape[-2:]),
trt.Weights(weight), trt.Weights(self.w[name + ".bias"]))
layer.stride_nd = (stride, stride)
return layer.get_output(0)

def to_tokens(self, x):
batch, channels, height, width = x.shape
layer = self.n.add_shuffle(x)
layer.first_transpose = (0, 2, 3, 1)
layer.reshape_dims = (batch, height * width, channels)
return layer.get_output(0)

def attention(self, x, name, heads, reduction, height, width):
tokens, channels = x.shape[1:]
dim = channels // heads
query = self.reshape(self.linear(x, name + ".self.query"), (1, tokens, heads, dim), (0, 2, 1, 3))
source = x
if reduction > 1:
spatial = self.reshape(x, (1, height, width, channels), (0, 3, 1, 2))
source = self.to_tokens(self.conv(spatial, name + ".self.sequence_reduction", reduction))
source = self.norm(source, name + ".self.layer_norm")
keys = source.shape[1]
key = self.reshape(self.linear(source, name + ".self.key"), (1, keys, heads, dim), (0, 2, 1, 3))
value = self.reshape(self.linear(source, name + ".self.value"), (1, keys, heads, dim), (0, 2, 1, 3))
scores = self.n.add_matrix_multiply(query, trt.MatrixOperation.NONE,
key, trt.MatrixOperation.TRANSPOSE).get_output(0)
scores = self.n.add_elementwise(scores, self.constant([[[[dim ** 0.5]]]]),
trt.ElementWiseOperation.DIV).get_output(0)
probabilities = self.n.add_softmax(scores)
probabilities.axes = 1 << 3
context = self.n.add_matrix_multiply(probabilities.get_output(0), trt.MatrixOperation.NONE,
value, trt.MatrixOperation.NONE).get_output(0)
merged = self.n.add_shuffle(context)
merged.first_transpose = (0, 2, 1, 3)
merged.reshape_dims = (1, tokens, channels)
return self.linear(merged.get_output(0), name + ".output.dense")

def build(self):
size = self.c["image_size"]
x = self.n.add_input("pixel_values", trt.float32, (1, 3, size, size))
for stage in range(self.c["num_encoder_blocks"]):
embedding = f"pvt.encoder.patch_embeddings.{stage}"
x = self.conv(x, embedding + ".projection", self.c["patch_sizes"][stage])
height, width = x.shape[-2:]
channels = x.shape[1]
x = self.norm(self.to_tokens(x), embedding + ".layer_norm")
if stage + 1 == self.c["num_encoder_blocks"]:
concat = self.n.add_concatenation([self.constant(self.w[embedding + ".cls_token"]), x])
concat.axis = 1
x = concat.get_output(0)
positions = self.w[embedding + ".position_embeddings"]
if tuple(x.shape) != positions.shape:
raise ValueError("pvt input resolution does not match checkpoint position embeddings")
x = self.add(x, self.constant(positions))
for layer in range(self.c["depths"][stage]):
prefix = f"pvt.encoder.block.{stage}.{layer}"
normalized = self.norm(x, prefix + ".layer_norm_1")
x = self.add(x, self.attention(normalized, prefix + ".attention",
self.c["num_attention_heads"][stage], self.c["sequence_reduction_ratios"][stage], height, width))
hidden = self.linear(self.norm(x, prefix + ".layer_norm_2"), prefix + ".mlp.dense1")
hidden = self.n.add_activation(hidden, trt.ActivationType.GELU_ERF).get_output(0)
x = self.add(x, self.linear(hidden, prefix + ".mlp.dense2"))
if stage + 1 < self.c["num_encoder_blocks"]:
x = self.reshape(x, (1, height, width, channels), (0, 3, 1, 2))
x = self.norm(x, "pvt.encoder.layer_norm")
cls = self.n.add_slice(x, (0, 0, 0), (1, 1, x.shape[-1]), (1, 1, 1)).get_output(0)
logits = self.linear(self.reshape(cls, (1, cls.shape[-1])), "classifier")
logits.name = "logits"
self.n.mark_output(logits)


def compile_engine(config, weights, verbose=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)
graph.build()
plan = builder.build_serialized_network(network, options)
if plan is None:
raise RuntimeError("pvt TensorRT classifier build failed")
return bytes(plan)


def build(request, writer):
if request.dynamic_kv_cache:
raise NotImplementedError("pvt does not support dynamic_kv_cache")
if request.task != "classification" or request.precision != "fp32" or request.backend != "trt":
raise ValueError("pvt requires classification, precision=fp32, 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),
("max_sequence_length", request.max_sequence_length, None),
("video_num_frames", request.video_num_frames, None), ("mtp_seq_len", request.mtp_seq_len, None),
("fp32_layers", request.fp32_layers, ()),
):
if value != default:
raise NotImplementedError(f"pvt does not support {field}")
if request.quantization not in (None, "none"):
raise NotImplementedError("pvt does not support quantization")
root = Path(request.model_dir)
config = validate_config(json.loads((root / "config.json").read_text()))
size = config["image_size"]
if request.image_height not in (None, size) or request.image_width not in (None, size):
raise ValueError("pvt image dimensions are fixed by the checkpoint")
processor = json.loads((root / "preprocessor_config.json").read_text())
if not all(processor.get(name, True) for name in ("do_resize", "do_rescale", "do_normalize")):
raise NotImplementedError("pvt requires resize, rescale, and normalization")
if processor.get("rescale_factor", 1 / 255) != 1 / 255 or processor.get("resample", 3) not in (2, 3):
raise NotImplementedError("pvt unsupported image rescaling or resampling")
normalization = {}
for name in ("image_mean", "image_std"):
value = processor[name]
values = [value] * 3 if type(value) in (int, float) else value
if (
not isinstance(values, list)
or len(values) != 3
or any(type(channel) not in (int, float) or not np.isfinite(channel) for channel in values)
or (name == "image_std" and min(values) <= 0)
):
raise ValueError(f"pvt requires valid {name} for three channels")
normalization[name] = values
weights = load_file(str(root / "model.safetensors"))
writer.set_header(family="pvt", task=request.task, backend=request.backend)
writer.add_bytes("classifier.plan", compile_engine(config, weights, request.verbose))
writer.add_json("runtime.json", {"schema_version": 1, "image_size": size,
"num_classes": int(weights["classifier.weight"].shape[0]),
"resample": processor.get("resample", 3), **normalization})
2 changes: 2 additions & 0 deletions families/pvt/requirements.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
torch>=2.6
Pillow>=10
27 changes: 27 additions & 0 deletions families/pvt/runtime/CMakeLists.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0

add_library(trtmc_model_pvt SHARED pipeline.cpp plugin.cpp image_preprocess.cpp)
target_include_directories(trtmc_model_pvt PRIVATE
${PROJECT_SOURCE_DIR} ${PROJECT_SOURCE_DIR}/core/runtime/include)
target_include_directories(trtmc_model_pvt SYSTEM PRIVATE ${TRTMC_CUDA_INCLUDE_DIR})
target_link_libraries(trtmc_model_pvt PRIVATE
trtmc_core nlohmann_json::nlohmann_json ${TRTMC_CUDART_LIBRARY})
target_compile_options(trtmc_model_pvt PRIVATE -Wall -Wextra -Wpedantic)
set_target_properties(trtmc_model_pvt PROPERTIES
LIBRARY_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}"
BUILD_RPATH "\$ORIGIN" INSTALL_RPATH "\$ORIGIN")
install(TARGETS trtmc_model_pvt LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR})

if(TRTMC_BUILD_TESTS)
add_executable(test_pvt_preprocess ${PROJECT_SOURCE_DIR}/families/pvt/tests/cpp/test_image_preprocess.cpp)
target_include_directories(test_pvt_preprocess PRIVATE ${PROJECT_SOURCE_DIR})
target_link_libraries(test_pvt_preprocess PRIVATE trtmc_model_pvt)
add_test(NAME pvt_preprocess COMMAND test_pvt_preprocess)

add_executable(pvt_e2e ${PROJECT_SOURCE_DIR}/families/pvt/tests/cpp/e2e_consumer.cpp)
target_include_directories(pvt_e2e PRIVATE
${PROJECT_SOURCE_DIR} ${PROJECT_SOURCE_DIR}/core/runtime/include)
target_link_libraries(pvt_e2e PRIVATE trtmc_runtime trtmc_core trtmc_model_pvt nlohmann_json::nlohmann_json)
set_target_properties(pvt_e2e PROPERTIES RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}")
endif()
Loading
Loading