diff --git a/CMakeLists.txt b/CMakeLists.txt index 10c8152eab..6e5461b115 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -537,6 +537,14 @@ if(TRTMC_BUILD_TESTS) target_compile_options(test_cli PRIVATE -Wall -Wextra -Wpedantic) add_test(NAME cli COMMAND test_cli) + add_executable(test_video_classification_cli apps/cli/tests/test_video_classification_cli.cpp) + target_include_directories(test_video_classification_cli PRIVATE ${PROJECT_SOURCE_DIR}/apps) + target_link_libraries(test_video_classification_cli PRIVATE trtmc_cli nlohmann_json::nlohmann_json) + target_compile_options(test_video_classification_cli PRIVATE -Wall -Wextra -Wpedantic) + add_test(NAME video_classification_cli COMMAND test_video_classification_cli + ${CMAKE_BINARY_DIR}/video-classification-cli-test) + + if(TRTMC_BUILD_SERVER) add_executable(test_server_worker apps/server/tests/test_native_worker.cpp) target_include_directories(test_server_worker PRIVATE diff --git a/apps/cli/cli.cpp b/apps/cli/cli.cpp index fffa13eb8a..4e813d34f4 100644 --- a/apps/cli/cli.cpp +++ b/apps/cli/cli.cpp @@ -98,6 +98,7 @@ const std::unordered_map& command_specs() { {"--text", "--token-ids", "--image", "--title", "--body", "--role"}}}, {"rerank", {CommandKind::kRerank, {"--query", "--document", "--image", "--documents"}}}, {"classify", {CommandKind::kClassify, {"--image", "--audio"}}}, + {"classify-video", {CommandKind::kClassifyVideo, {"--frame"}}}, {"detect", {CommandKind::kDetect, {"--image", "--prompt"}}}, {"layout", {CommandKind::kLayout, {"--image"}}}, {"extract-features", {CommandKind::kExtractFeatures, {"--image"}}}, @@ -893,6 +894,26 @@ int dispatch(const Command& command, ITask& task, std::ostream& output) { {"top_score", result.top_score}}); return EXIT_SUCCESS; } + case CommandKind::kClassifyVideo: { + if (command.frames.empty()) + throw std::invalid_argument("classify-video requires at least one --frame"); + std::vector images; + images.reserve(command.frames.size()); + for (const auto& path : command.frames) + images.push_back(read_image(path)); + VideoClassificationRequest request; + for (const auto& image : images) + request.frames.push_back({image.pixels.data(), image.pixels.size(), image.height, + image.width, VideoFrameFormat::kRgbFloat32}); + const auto result = require_interface(task).classify(request); + require_finite(result.logits, "video classification logits"); + if (!std::isfinite(result.top_score)) + throw std::runtime_error("video classification returned a non-finite top score"); + write_json(output, {{"logits", result.logits}, + {"top_class", result.top_class}, + {"top_score", result.top_score}}); + return EXIT_SUCCESS; + } case CommandKind::kDetect: { const io::LoadedImage image = read_image(require_option(command, "--image")); const auto result = require_interface(task).detect( @@ -1631,46 +1652,49 @@ int dispatch(const Command& command, const Model& model, std::ostream& output) { } void print_usage(std::ostream& output) { - output << "Usage:\n" - " trtmc version\n" - " trtmc inspect BUNDLE\n" - " trtmc COMMAND BUNDLE [--runtime-root DIR] [OPTIONS]\n\n" - "Execution commands:\n" - " run, encode, embed, rerank, classify, detect, layout, extract-features,\n" - " predict-structure, disparity, depth, geometry,\n" - " segment,\n" - " segment-prompted, video-segment, generate-audio, transcribe,\n" - " transcribe-batch, transcribe-streaming, speak, speech-session, generate-image,\n" - " generate-image-batch, generate-video,\n" - " solve, forecast, control, generate-world\n\n" - "Text diffusion replay options:\n" - " [--generation-mode MODE] [--block-length N] [--threshold S]\n" - " --initial-latents-raw PATH [--condition-latents-raw PATH\n" - " --condition-mask-raw PATH] [--sampling-steps-raw PATH]\n" - " [--sde-noise-raw PATH] [--num-steps N] [--guidance-scale S]\n" - " [--cfg-scale S] [--sde-gamma S]\n\n" - "Text generation options:\n" - " [--source-language-token-id N] [--forced-bos-token-id N]\n\n" - "Offline transcription options:\n" - " [--beam-size N] [--length-penalty F] [--punctuation true|false]\n" - " [--max-input-seconds F] [--segment-length-seconds F]\n" - " [--segment-min-seconds F] [--segment-overlap-seconds F]\n" - " [--lcs-merge true|false]\n\n" - "Molecular structure input:\n" - " predict-structure BUNDLE --input REQUEST [--input-encoding ENCODING]\n" - " .yaml/.yml, .json and .b2rq select their declared encodings.\n" - " SDK output defaults to prediction.cif or prediction.pdb.\n\n" - "Audio classification input:\n" - " classify BUNDLE --audio WAV scores an audio model's own classes;\n" - " classify BUNDLE --image FILE stays the image path.\n\n" - "BYOK options:\n" - " --byok-library DSO --byok-function FUNCTION --byok-name KERNEL\n\n" - "Runtime-sized KV cache:\n" - " [--kv-cache-size BYTES|GB|GiB]\n\n" - "TensorRT-RTX runtime options:\n" - " [--runtime-cache PATH] [--cuda-graphs]\n\n" - "Task SDK options: [--task TASK_ID] [--set NAME=VALUE]...\n" - "Without --runtime-root, plugins load from the installed runtime directory.\n"; + output + << "Usage:\n" + " trtmc version\n" + " trtmc inspect BUNDLE\n" + " trtmc COMMAND BUNDLE [--runtime-root DIR] [OPTIONS]\n\n" + "Execution commands:\n" + " run, encode, embed, rerank, classify, classify-video, detect, layout, " + "extract-features,\n" + " predict-structure, disparity, depth, geometry,\n" + " segment,\n" + " segment-prompted, video-segment, generate-audio, transcribe,\n" + " transcribe-batch, transcribe-streaming, speak, speech-session, generate-image,\n" + " generate-image-batch, generate-video,\n" + " solve, forecast, control, generate-world\n\n" + "Text diffusion replay options:\n" + " [--generation-mode MODE] [--block-length N] [--threshold S]\n" + " --initial-latents-raw PATH [--condition-latents-raw PATH\n" + " --condition-mask-raw PATH] [--sampling-steps-raw PATH]\n" + " [--sde-noise-raw PATH] [--num-steps N] [--guidance-scale S]\n" + " [--cfg-scale S] [--sde-gamma S]\n\n" + "Text generation options:\n" + " [--source-language-token-id N] [--forced-bos-token-id N]\n\n" + "Offline transcription options:\n" + " [--beam-size N] [--length-penalty F] [--punctuation true|false]\n" + " [--max-input-seconds F] [--segment-length-seconds F]\n" + " [--segment-min-seconds F] [--segment-overlap-seconds F]\n" + " [--lcs-merge true|false]\n\n" + "Molecular structure input:\n" + " predict-structure BUNDLE --input REQUEST [--input-encoding ENCODING]\n" + " .yaml/.yml, .json and .b2rq select their declared encodings.\n" + " SDK output defaults to prediction.cif or prediction.pdb.\n\n" + "Audio classification input:\n" + " classify BUNDLE --audio WAV scores an audio model's own classes;\n" + " classify BUNDLE --image FILE stays the image path.\n" + " classify-video BUNDLE --frame FILE [--frame FILE ...] scores ordered RGB frames.\n\n" + "BYOK options:\n" + " --byok-library DSO --byok-function FUNCTION --byok-name KERNEL\n\n" + "Runtime-sized KV cache:\n" + " [--kv-cache-size BYTES|GB|GiB]\n\n" + "TensorRT-RTX runtime options:\n" + " [--runtime-cache PATH] [--cuda-graphs]\n\n" + "Task SDK options: [--task TASK_ID] [--set NAME=VALUE]...\n" + "Without --runtime-root, plugins load from the installed runtime directory.\n"; } int run(int argc, char** argv, std::ostream& output, std::ostream& error) { diff --git a/apps/cli/cli.h b/apps/cli/cli.h index 0c1728cdb6..ddacf89a8b 100644 --- a/apps/cli/cli.h +++ b/apps/cli/cli.h @@ -30,6 +30,7 @@ enum class CommandKind { kEmbed, kRerank, kClassify, + kClassifyVideo, kDetect, kLayout, kExtractFeatures, diff --git a/apps/cli/tests/test_video_classification_cli.cpp b/apps/cli/tests/test_video_classification_cli.cpp new file mode 100644 index 0000000000..0cdba33d7a --- /dev/null +++ b/apps/cli/tests/test_video_classification_cli.cpp @@ -0,0 +1,85 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + */ +#include "cli/cli.h" +#include "cli/io.h" +#include "task_runtime.h" + +#include +#include +#include +#include +#include +#include +static_assert(std::is_abstract_v); +namespace { +void check(bool x, const char* message) { + if (!x) + throw std::runtime_error(message); +} +trtmc::cli::Command parse(std::vector args) { + std::vector argv; + for (auto& s : args) + argv.push_back(s.data()); + return trtmc::cli::parse_args(static_cast(argv.size()), argv.data()); +} +class Video final : public trtmc::IVideoClassification { + public: + int calls{0}; + trtmc::ClassificationResult + classify(const trtmc::VideoClassificationRequest& request) override { + ++calls; + check(request.frames.size() == 2, "frame sequence size changed"); + const auto& a = request.frames[0]; + const auto& b = request.frames[1]; + check(a.height == 1 && a.width == 1 && a.element_count == 3 && + a.format == trtmc::VideoFrameFormat::kRgbFloat32, + "frame format changed"); + check(static_cast(a.pixels)[0] == 1 && + static_cast(a.pixels)[2] == 0 && + static_cast(b.pixels)[0] == 0 && + static_cast(b.pixels)[2] == 1, + "frame order or RGB values changed"); + return {{-2, 3}, 1, 0.9F}; + } +}; +} // namespace +int main(int argc, char** argv) { + try { + if (argc != 2) + throw std::invalid_argument("usage: test_video_classification_cli TEMP_DIR"); + const std::filesystem::path root(argv[1]); + std::filesystem::create_directories(root); + const auto a = (root / "first.png").string(), b = (root / "second.png").string(); + trtmc::cli::io::save_png(a, {1, 0, 0}, 1, 1); + trtmc::cli::io::save_png(b, {0, 0, 1}, 1, 1); + Video task; + check(trtmc::app::uses_existing_task_runtime(task.task()), + "video Task loader selection missing"); + const auto command = + parse({"trtmc", "classify-video", "fixture.bundle", "--frame", a, "--frame", b}); + check(command.kind == trtmc::cli::CommandKind::kClassifyVideo && + command.frames == std::vector{a, b}, + "frame arguments reordered"); + std::ostringstream output; + check(trtmc::cli::dispatch(command, task, output) == 0, "dispatch failed"); + const auto result = nlohmann::json::parse(output.str()); + check(result.at("logits") == std::vector{-2, 3} && result.at("top_class") == 1, + "class scores changed"); + bool rejected = false; + try { + std::ostringstream ignored; + (void)trtmc::cli::dispatch(parse({"trtmc", "classify-video", "fixture.bundle"}), task, + ignored); + } catch (const std::invalid_argument&) { + rejected = true; + } + check(rejected && task.calls == 1, "empty clip reached the family"); + std::cout << "Ordered RGB frames and video classification CLI passed\n"; + return 0; + } catch (const std::exception& e) { + std::cerr << e.what() << '\n'; + return 1; + } +} diff --git a/apps/task_runtime.h b/apps/task_runtime.h index 0e0f484642..f6081eb4bc 100644 --- a/apps/task_runtime.h +++ b/apps/task_runtime.h @@ -42,6 +42,7 @@ inline bool uses_existing_task_runtime(std::string_view primary_task) noexcept { IMonocularDepth::kTask, IMonocularGeometry::kTask, IImageClassification::kTask, + IVideoClassification::kTask, IObjectDetection::kTask, IDocumentLayout::kTask, IPoseHypothesisRefinement::kTask, diff --git a/core/runtime/include/trtmc/task.h b/core/runtime/include/trtmc/task.h index c6d1dffa2c..caafa634d5 100644 --- a/core/runtime/include/trtmc/task.h +++ b/core/runtime/include/trtmc/task.h @@ -327,6 +327,12 @@ struct VideoFrameView { VideoFrameFormat format{VideoFrameFormat::kRgb8}; }; +// Frames are ordered in time. RGB8 uses scalar byte count; RGB float uses +// scalar float count and values in [0,1]. The caller retains storage during classify(). +struct VideoClassificationRequest { + std::vector frames; +}; + struct VideoSegmentationRequest { std::vector frames; std::string text_prompt; @@ -785,6 +791,13 @@ class IImageClassification : public virtual ITask { std::int32_t width) = 0; }; +class IVideoClassification : public virtual ITask { + public: + static constexpr const char* kTask = "video_classification"; + const char* task() const noexcept override { return kTask; } + virtual ClassificationResult classify(const VideoClassificationRequest& request) = 0; +}; + class IObjectDetection : public virtual ITask { public: static constexpr const char* kTask = "object_detection"; diff --git a/families/vivit/README.md b/families/vivit/README.md new file mode 100644 index 0000000000..383ac7872b --- /dev/null +++ b/families/vivit/README.md @@ -0,0 +1,37 @@ +# ViViT + +This family runs `google/vivit-b-16x2` at revision +`fc341053d36b42d446b3ffccdbd52452712a23f3` as FP32 TensorRT video classification. +The profile takes exactly 32 ordered RGB frames, uses the published bilinear +shortest-edge resize to 256 and center crop to 224, and returns all 400 Kinetics +class logits, the top class index, and its softmax probability. + +The native `IVideoClassification` Task accepts interleaved RGB bytes or finite +RGB floats in [0,1]. Frames may have different source dimensions. The caller +selects and orders frames; the family does not decode or sample video files. +The CLI accepts the same sequence through repeated `--frame` arguments: + +```bash +frames=() +for frame in frames/frame-{00..31}.png; do frames+=(--frame "$frame"); done +trtmc classify-video model.bundle "${frames[@]}" +``` + +The family owns Conv3D tubelets, positional embeddings, all twelve encoder +layers, the classification head, preprocessing and native orchestration. All +GPU computation uses TensorRT operators. Batch size is one; FP16, quantization, +parallel execution, other frame counts, resolution changes and KV caches are +explicitly rejected. The published PyTorch state dictionary is loaded with +`weights_only=True`. + +Select the pinned E2E with: + +```bash +python -m pytest families/vivit/tests --e2e-model vivit -q +``` + +The test compares upstream intermediate tensors on a nondegenerate small +model, all logits and probabilities on natural-image and moving-pattern clips, +Pillow preprocessing, both public frame formats, the CLI, repeated requests, +and recovery after malformed clips. Plans and validation artifacts are external +to the source branch. diff --git a/families/vivit/__init__.py b/families/vivit/__init__.py new file mode 100644 index 0000000000..64b6c6cbd2 --- /dev/null +++ b/families/vivit/__init__.py @@ -0,0 +1,3 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +"""ViViT video classification family.""" diff --git a/families/vivit/model.py b/families/vivit/model.py new file mode 100644 index 0000000000..acea2e469c --- /dev/null +++ b/families/vivit/model.py @@ -0,0 +1,249 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +"""ViViT tubelet projection, full spatiotemporal attention and class head.""" + +import json +from pathlib import Path +import numpy as np +import tensorrt as trt + + +def validate_config(raw): + from transformers import VivitConfig + + c = VivitConfig.from_dict(raw).to_dict() + if c["model_type"] != "vivit" or c["num_channels"] != 3 or c["hidden_act"] != "gelu_fast": + raise ValueError("vivit requires RGB ViViT with gelu_fast") + if c["hidden_size"] % c["num_attention_heads"] or c["num_hidden_layers"] <= 0: + raise ValueError("vivit invalid encoder dimensions") + if any(x <= 0 for x in c["tubelet_size"]) or len(c["tubelet_size"]) != 3: + raise ValueError("vivit requires three positive tubelet dimensions") + for n, p in zip((c["num_frames"], c["image_size"], c["image_size"]), c["tubelet_size"]): + if n <= 0 or n % p: + raise ValueError("vivit tubelets must divide the clip dimensions") + return c + + +class Graph: + def __init__(self, network, config, weights, debug=False): + self.n, self.c, self.w, self.debug = network, config, weights, debug + self.storage = [] + + def weight(self, name): + if name not in self.w: + raise ValueError(f"vivit missing checkpoint tensor {name}") + value = np.ascontiguousarray(self.w[name], dtype=np.float32) + if not np.isfinite(value).all(): + raise ValueError(f"vivit nonfinite checkpoint tensor {name}") + self.storage.append(value) + return value + + def constant(self, value): + value = np.ascontiguousarray(value, dtype=np.float32) + 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 add(self, x, y): + return self.n.add_elementwise(x, y, trt.ElementWiseOperation.SUM).get_output(0) + + def mul(self, x, value): + c = self.constant(np.full((1,) * len(x.shape), value, np.float32)) + return self.n.add_elementwise(x, c, trt.ElementWiseOperation.PROD).get_output(0) + + def linear(self, x, name, *, bias=True): + w = self.weight(name + ".weight") + offset = self.weight(name + ".bias") if bias else None + rank = len(x.shape) + rhs = self.constant(w.T.reshape((1,) * (rank - 2) + tuple(w.T.shape))) + y = self.n.add_matrix_multiply( + x, trt.MatrixOperation.NONE, rhs, trt.MatrixOperation.NONE + ).get_output(0) + if offset is not None: + y = self.add(y, self.constant(offset.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 attention(self, x, name): + tokens, channels = x.shape[1:] + heads = self.c["num_attention_heads"] + dim = channels // heads + q, k, v = [ + self.reshape( + self.linear(x, name + ".attention." + part, bias=self.c["qkv_bias"]), + (1, tokens, heads, dim), + (0, 2, 1, 3), + ) + for part in ("query", "key", "value") + ] + scores = self.n.add_matrix_multiply( + q, trt.MatrixOperation.NONE, k, trt.MatrixOperation.TRANSPOSE + ).get_output(0) + probs = self.n.add_softmax(self.mul(scores, dim**-0.5)) + 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, tokens, channels) + return self.linear(merge.get_output(0), name + ".output.dense") + + def build(self): + c = self.c + frames, size, hidden = c["num_frames"], c["image_size"], c["hidden_size"] + x = self.n.add_input("pixel_values", trt.float32, (1, 3, frames, size, size)) + w = self.weight("vivit.embeddings.patch_embeddings.projection.weight") + layer = self.n.add_convolution_nd( + x, + hidden, + tuple(c["tubelet_size"]), + trt.Weights(w), + trt.Weights(self.weight("vivit.embeddings.patch_embeddings.projection.bias")), + ) + layer.stride_nd = tuple(c["tubelet_size"]) + x = layer.get_output(0) + tokens = int(np.prod(x.shape[2:])) + x = self.reshape(x, (1, hidden, tokens), (0, 2, 1)) + if self.debug: + self.output(x, "tubelets") + concat = self.n.add_concatenation( + [self.constant(self.weight("vivit.embeddings.cls_token")), x] + ) + concat.axis = 1 + x = self.add( + concat.get_output(0), self.constant(self.weight("vivit.embeddings.position_embeddings")) + ) + if self.debug: + self.output(x, "embeddings") + for i in range(c["num_hidden_layers"]): + p = f"vivit.encoder.layer.{i}" + x = self.add(x, self.attention(self.norm(x, p + ".layernorm_before"), p + ".attention")) + y = self.linear(self.norm(x, p + ".layernorm_after"), p + ".intermediate.dense") + # Match GELU-fast's published tanh formula and operation order. + square = self.n.add_elementwise(y, y, trt.ElementWiseOperation.PROD).get_output(0) + inner = self.add( + self.constant(np.ones((1, 1, 1), np.float32)), self.mul(square, 0.044715) + ) + scaled = self.mul(y, 0.7978845608) + t = self.n.add_activation( + self.n.add_elementwise(scaled, inner, trt.ElementWiseOperation.PROD).get_output(0), + trt.ActivationType.TANH, + ).get_output(0) + y = self.n.add_elementwise( + self.mul(y, 0.5), + self.add(t, self.constant(np.ones((1, 1, 1), np.float32))), + trt.ElementWiseOperation.PROD, + ).get_output(0) + x = self.add(x, self.linear(y, p + ".output.dense")) + if self.debug: + self.output(x, f"layer_{i}") + x = self.norm(x, "vivit.layernorm") + if self.debug: + self.output(x, "hidden") + x = self.n.add_slice(x, (0, 0, 0), (1, 1, hidden), (1, 1, 1)).get_output(0) + self.output(self.linear(self.reshape(x, (1, hidden)), "classifier"), "logits") + + +def compile_engine(config, weights, verbose=False, 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, debug) + graph.build() + plan = builder.build_serialized_network(network, options) + if plan is None: + raise RuntimeError("vivit TensorRT build failed") + return bytes(plan) + + +def build(request, writer): + if request.dynamic_kv_cache: + raise NotImplementedError("vivit does not support dynamic_kv_cache") + if ( + request.task != "video_classification" + or request.precision != "fp32" + or request.backend != "trt" + ): + raise ValueError("vivit requires video_classification, 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), + ("max_sequence_length", request.max_sequence_length, None), + ("mtp_seq_len", request.mtp_seq_len, None), + ("fp32_layers", request.fp32_layers, ()), + ): + if value != default: + raise NotImplementedError(f"vivit does not support {field}") + if request.quantization not in (None, "none"): + raise NotImplementedError("vivit does not support quantization") + root = Path(request.model_dir) + c = validate_config(json.loads((root / "config.json").read_text())) + if c["num_frames"] != 32 or c["image_size"] != 224 or c["tubelet_size"] != [2, 16, 16]: + raise ValueError("vivit supports 32 frames at 224x224 with 2x16x16 tubelets") + if len(c["id2label"]) != 400: + raise ValueError("vivit requires the 400-class Kinetics head") + if ( + request.video_num_frames not in (None, 32) + or request.image_height not in (None, 224) + or request.image_width not in (None, 224) + ): + raise ValueError("vivit clip dimensions are fixed by the checkpoint") + p = json.loads((root / "preprocessor_config.json").read_text()) + if ( + p.get("size") != {"shortest_edge": 256} + or p.get("crop_size") != {"height": 224, "width": 224} + or p.get("resample", 2) != 2 + or p.get("do_normalize", True) + or p.get("rescale_factor", 1 / 127.5) != 1 / 127.5 + or not all(p.get(k, True) for k in ("do_resize", "do_center_crop", "do_rescale")) + or not p.get("offset", True) + ): + raise ValueError("vivit requires the published bilinear resize, crop and offset rescaling") + import torch + from packaging.version import Version + + # GHSA-63cw-57p8-fm3p also affects the weights-only loader. + if Version(torch.__version__) < Version("2.10.0"): + raise RuntimeError("vivit legacy checkpoint loading requires torch>=2.10.0") + + 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="vivit", task=request.task, backend=request.backend) + writer.add_bytes("classifier.plan", compile_engine(c, weights, request.verbose)) + writer.add_json( + "runtime.json", + dict( + schema_version=1, + frames=32, + image_size=224, + num_classes=len(c["id2label"]), + labels=c["id2label"], + ), + ) diff --git a/families/vivit/requirements.txt b/families/vivit/requirements.txt new file mode 100644 index 0000000000..ad6ad446e6 --- /dev/null +++ b/families/vivit/requirements.txt @@ -0,0 +1,3 @@ +numpy>=1.26 +torch>=2.10.0 +transformers==5.3.0 diff --git a/families/vivit/runtime/CMakeLists.txt b/families/vivit/runtime/CMakeLists.txt new file mode 100644 index 0000000000..f7ae5ecc42 --- /dev/null +++ b/families/vivit/runtime/CMakeLists.txt @@ -0,0 +1,18 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +add_library(trtmc_model_vivit SHARED pipeline.cpp plugin.cpp image_preprocess.cpp) +target_include_directories(trtmc_model_vivit PRIVATE + ${PROJECT_SOURCE_DIR} ${PROJECT_SOURCE_DIR}/core/runtime/include) +target_include_directories(trtmc_model_vivit SYSTEM PRIVATE ${TRTMC_CUDA_INCLUDE_DIR}) +target_link_libraries(trtmc_model_vivit PRIVATE trtmc_core nlohmann_json::nlohmann_json ${TRTMC_CUDART_LIBRARY}) +target_compile_options(trtmc_model_vivit PRIVATE -Wall -Wextra -Wpedantic) +set_target_properties(trtmc_model_vivit PROPERTIES LIBRARY_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}" + BUILD_RPATH "\$ORIGIN" INSTALL_RPATH "\$ORIGIN") +install(TARGETS trtmc_model_vivit LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR}) +if(TRTMC_BUILD_TESTS) + add_executable(vivit_e2e ${PROJECT_SOURCE_DIR}/families/vivit/tests/cpp/e2e_consumer.cpp) + target_sources(vivit_e2e PRIVATE image_preprocess.cpp) + target_include_directories(vivit_e2e PRIVATE ${PROJECT_SOURCE_DIR}) + target_link_libraries(vivit_e2e PRIVATE trtmc_runtime nlohmann_json::nlohmann_json) + set_target_properties(vivit_e2e PROPERTIES RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}") +endif() diff --git a/families/vivit/runtime/image_preprocess.cpp b/families/vivit/runtime/image_preprocess.cpp new file mode 100644 index 0000000000..c48416e320 --- /dev/null +++ b/families/vivit/runtime/image_preprocess.cpp @@ -0,0 +1,184 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + */ + +#include "families/vivit/runtime/image_preprocess.h" + +#include +#include +#include +#include +#include +#include +#include + +namespace trtmc { + +namespace { + +// Pillow's resampler, reproduced coefficient for coefficient. The reference +// processor resamples with PIL, and a float resize or a differently +// normalised kernel lands a few least-significant bits away on every pixel. +// +// This checkpoint asks for **bilinear** (resample=2), where the other image +// families in this repo reproduce bicubic. Only two things differ between +// them - the kernel and its support radius - so both are built from the same +// plan here rather than keeping a second, silently divergent copy. +constexpr std::int32_t kPillowPrecisionBits = 22; +constexpr std::int64_t kPillowScale = std::int64_t{1} << kPillowPrecisionBits; +constexpr std::int64_t kPillowRounding = std::int64_t{1} << (kPillowPrecisionBits - 1); + +struct PillowSpan { + std::int32_t first{0}; + std::vector weights; +}; + +double pillow_bilinear(double value) { + value = std::abs(value); + return value < 1.0 ? 1.0 - value : 0.0; +} + +double pillow_bicubic(double value) { + constexpr double kA = -0.5; + value = std::abs(value); + if (value < 1.0) + return ((kA + 2.0) * value - (kA + 3.0)) * value * value + 1.0; + if (value < 2.0) + return ((kA * value - 5.0 * kA) * value + 8.0 * kA) * value - 4.0 * kA; + return 0.0; +} + +double filter_support(VivitResample resample) { + return resample == VivitResample::kBicubic ? 2.0 : 1.0; +} + +double apply_filter(VivitResample resample, double value) { + return resample == VivitResample::kBicubic ? pillow_bicubic(value) : pillow_bilinear(value); +} + +std::vector make_pillow_plan(std::int32_t input_size, std::int32_t output_size, + VivitResample resample) { + const double scale = static_cast(input_size) / output_size; + const double filter_scale = std::max(scale, 1.0); + const double support = filter_support(resample) * filter_scale; + const double inverse_filter_scale = 1.0 / filter_scale; + std::vector plan(static_cast(output_size)); + for (std::int32_t output_index = 0; output_index < output_size; ++output_index) { + const double center = (static_cast(output_index) + 0.5) * scale; + const auto first = + std::max(0, static_cast(center - support + 0.5)); + const auto end = + std::min(input_size, static_cast(center + support + 0.5)); + if (end <= first) + throw std::runtime_error("vivit Pillow resize produced empty support"); + + auto& span = plan[static_cast(output_index)]; + span.first = first; + std::vector floating(static_cast(end - first)); + double total = 0.0; + for (std::int32_t index = first; index < end; ++index) { + const double weight = apply_filter( + resample, (static_cast(index) - center + 0.5) * inverse_filter_scale); + floating[static_cast(index - first)] = weight; + total += weight; + } + if (!std::isfinite(total) || total == 0.0) + throw std::runtime_error("vivit Pillow resize has invalid coefficients"); + span.weights.reserve(floating.size()); + for (double weight : floating) { + const double scaled = weight / total * static_cast(kPillowScale); + if (!std::isfinite(scaled) || + scaled < static_cast(std::numeric_limits::min()) || + scaled > static_cast(std::numeric_limits::max())) { + throw std::runtime_error("vivit Pillow resize coefficient overflowed"); + } + span.weights.push_back( + static_cast(scaled < 0.0 ? scaled - 0.5 : scaled + 0.5)); + } + } + return plan; +} + +std::uint8_t apply_pillow_span(const std::uint8_t* source, std::int32_t stride, + const PillowSpan& span) { + std::int64_t sum = kPillowRounding; + for (std::size_t index = 0; index < span.weights.size(); ++index) { + sum += static_cast( + source[(span.first + static_cast(index)) * stride]) * + span.weights[index]; + } + if (sum <= 0) + return 0; + return static_cast(std::min(sum >> kPillowPrecisionBits, 255)); +} + +std::vector resize_pillow(const float* source, std::int32_t input_h, std::int32_t input_w, + std::int32_t output_h, std::int32_t output_w, + VivitResample resample) { + std::vector input(static_cast(input_h) * input_w * 3U); + std::transform(source, source + input.size(), input.begin(), [](float value) { + return static_cast(std::lround(std::clamp(value, 0.0F, 1.0F) * 255.0F)); + }); + + const auto horizontal_plan = make_pillow_plan(input_w, output_w, resample); + std::vector horizontal(static_cast(input_h) * output_w * 3U); + for (std::int32_t y = 0; y < input_h; ++y) { + for (std::int32_t x = 0; x < output_w; ++x) { + const auto& span = horizontal_plan[static_cast(x)]; + for (std::int32_t channel = 0; channel < 3; ++channel) { + const auto source_offset = static_cast(y) * input_w * 3U + channel; + const auto target = (static_cast(y) * output_w + x) * 3U + channel; + horizontal[target] = apply_pillow_span(input.data() + source_offset, 3, span); + } + } + } + + const auto vertical_plan = make_pillow_plan(input_h, output_h, resample); + std::vector output(static_cast(output_h) * output_w * 3U); + for (std::int32_t y = 0; y < output_h; ++y) { + const auto& span = vertical_plan[static_cast(y)]; + for (std::int32_t x = 0; x < output_w; ++x) { + for (std::int32_t channel = 0; channel < 3; ++channel) { + const auto source_offset = static_cast(x) * 3U + channel; + const auto target = (static_cast(y) * output_w + x) * 3U + channel; + output[target] = static_cast(apply_pillow_span( + horizontal.data() + source_offset, output_w * 3, span)) / + 255.0F; + } + } + } + return output; +} + +} // namespace + +std::vector preprocess_vivit_image(const float* pixels, std::int32_t height, + std::int32_t width) { + if (!pixels || height <= 0 || width <= 0 || height > 8192 || width > 8192) + throw std::invalid_argument("vivit frames must have dimensions in [1,8192]"); + const auto count = static_cast(height) * width * 3; + if (!std::all_of(pixels, pixels + count, + [](float x) { return std::isfinite(x) && x >= 0 && x <= 1; })) + throw std::invalid_argument("vivit RGB float pixels must be finite and in [0,1]"); + const auto shortest = std::min(height, width); + const auto resized_h = height <= width ? 256 : static_cast(256LL * height / shortest); + const auto resized_w = width <= height ? 256 : static_cast(256LL * width / shortest); + if (resized_h > 16384 || resized_w > 16384) + throw std::invalid_argument("vivit frame aspect ratio exceeds the supported resize extent"); + const auto resized = + resize_pillow(pixels, height, width, resized_h, resized_w, VivitResample::kBilinear); + const int top = (resized_h - 224) / 2, left = (resized_w - 224) / 2; + std::vector result(3 * 224 * 224); + for (int c = 0; c < 3; ++c) + for (int y = 0; y < 224; ++y) + for (int x = 0; x < 224; ++x) { + const float byte = + std::round(resized[((y + top) * resized_w + x + left) * 3 + c] * 255.F); + result[(c * 224 + y) * 224 + x] = + static_cast(static_cast(byte) * (1.0 / 127.5)) - 1.F; + } + return result; +} + +} // namespace trtmc diff --git a/families/vivit/runtime/image_preprocess.h b/families/vivit/runtime/image_preprocess.h new file mode 100644 index 0000000000..4e877feb39 --- /dev/null +++ b/families/vivit/runtime/image_preprocess.h @@ -0,0 +1,21 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + */ + +#pragma once + +#include +#include + +namespace trtmc { + +// Pillow's filter numbers, as a preprocessor config spells them. +enum class VivitResample : std::int32_t { kBilinear = 2, kBicubic = 3 }; + +// Interleaved RGB float input in [0,1], Pillow bilinear shortest-edge resize, +// center crop, then the checkpoint's offset rescaling to [-1,1]. +std::vector preprocess_vivit_image(const float* image_pixels, std::int32_t image_height, + std::int32_t image_width); + +} // namespace trtmc diff --git a/families/vivit/runtime/pipeline.cpp b/families/vivit/runtime/pipeline.cpp new file mode 100644 index 0000000000..30c4ff2661 --- /dev/null +++ b/families/vivit/runtime/pipeline.cpp @@ -0,0 +1,70 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + */ +#include "families/vivit/runtime/pipeline.h" + +#include "families/vivit/runtime/image_preprocess.h" + +#include +#include +#include +namespace trtmc::vivit { +Pipeline::Pipeline(std::unique_ptr classifier, std::int32_t classes) + : classifier_(std::move(classifier)), classes_(classes) { + if (!classifier_ || !classifier_->ok() || classes_ != 400) + throw std::invalid_argument("vivit requires a loaded 400-class classifier"); +} +ClassificationResult Pipeline::classify(const VideoClassificationRequest& request) { + const std::lock_guard lock(execution_); + if (request.frames.size() != 32) + throw std::invalid_argument("vivit requires exactly 32 ordered RGB frames"); + // Preprocess every frame before execution, so malformed clips never partially run. + constexpr std::size_t plane = 224 * 224; + std::vector input(3 * 32 * plane); + for (std::size_t i = 0; i < request.frames.size(); ++i) { + const auto& f = request.frames[i]; + if (!f.pixels || f.height < 1 || f.width < 1 || f.height > 8192 || f.width > 8192 || + f.element_count != static_cast(f.height) * f.width * 3) + throw std::invalid_argument("vivit invalid frame storage or geometry"); + std::vector converted; + const float* pixels = nullptr; + if (f.format == VideoFrameFormat::kRgbFloat32) { + pixels = static_cast(f.pixels); + } else if (f.format == VideoFrameFormat::kRgb8) { + const auto* bytes = static_cast(f.pixels); + converted.resize(f.element_count); + std::transform(bytes, bytes + f.element_count, converted.begin(), + [](std::uint8_t x) { return x / 255.F; }); + pixels = converted.data(); + } else { + throw std::invalid_argument("vivit unsupported frame format"); + } + const auto frame = preprocess_vivit_image(pixels, f.height, f.width); + for (std::size_t c = 0; c < 3; ++c) + std::copy_n(frame.data() + c * plane, plane, input.data() + (c * 32 + i) * plane); + } + Tensor tensor; + tensor.data = input.data(); + tensor.shape = {1, 3, 32, 224, 224}; + tensor.dtype = DType::kFloat32; + const auto outputs = classifier_->forward({{"pixel_values", tensor}}); + const auto found = outputs.find("logits"); + if (found == outputs.end() || !found->second.data || found->second.dtype != DType::kFloat32 || + found->second.shape != std::vector{1, classes_}) + throw std::runtime_error("vivit classifier returned invalid logits"); + const auto* values = static_cast(found->second.data); + ClassificationResult result; + result.logits.assign(values, values + classes_); + if (!std::all_of(result.logits.begin(), result.logits.end(), + [](float x) { return std::isfinite(x); })) + throw std::runtime_error("vivit classifier returned nonfinite logits"); + const auto top = std::max_element(result.logits.begin(), result.logits.end()); + result.top_class = static_cast(top - result.logits.begin()); + double denominator = 0; + for (float x : result.logits) + denominator += std::exp(static_cast(x) - *top); + result.top_score = static_cast(1 / denominator); + return result; +} +} // namespace trtmc::vivit diff --git a/families/vivit/runtime/pipeline.h b/families/vivit/runtime/pipeline.h new file mode 100644 index 0000000000..3cafe237ab --- /dev/null +++ b/families/vivit/runtime/pipeline.h @@ -0,0 +1,22 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + */ +#pragma once +#include "trtmc/runtime/trt_module.h" +#include "trtmc/task.h" + +#include +#include +namespace trtmc::vivit { +class Pipeline final : public IVideoClassification { + public: + Pipeline(std::unique_ptr classifier, std::int32_t classes); + ClassificationResult classify(const VideoClassificationRequest& request) override; + + private: + std::mutex execution_; + std::unique_ptr classifier_; + std::int32_t classes_; +}; +} // namespace trtmc::vivit diff --git a/families/vivit/runtime/plugin.cpp b/families/vivit/runtime/plugin.cpp new file mode 100644 index 0000000000..7ed2455df3 --- /dev/null +++ b/families/vivit/runtime/plugin.cpp @@ -0,0 +1,28 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + */ +#include "families/vivit/runtime/pipeline.h" +#include "trtmc/runtime/family_factory.h" +#include "trtmc/runtime/trt_backend.h" + +#include +#include +extern "C" trtmc::ITask* trtmc_create_family(const trtmc::FamilyContext& context) { + if (context.kv_cache_size_bytes != 0) + throw std::invalid_argument("vivit does not support --kv-cache-size"); + auto section = [&](const char* name) { + const auto* found = context.reader.find_section(name); + if (!found || found->length == 0) + throw std::runtime_error(std::string("vivit missing section: ") + name); + return context.reader.read_section(name); + }; + const auto data = section("runtime.json"); + const auto config = nlohmann::json::parse(data.begin(), data.end()); + if (config.at("schema_version").get() != 1 || config.at("frames").get() != 32 || + config.at("image_size").get() != 224 || config.at("num_classes").get() != 400) + throw std::invalid_argument("vivit unsupported runtime schema or geometry"); + const auto plan = section("classifier.plan"); + return new trtmc::vivit::Pipeline(context.backend.create_module(plan.data(), plan.size(), {}), + 400); +} diff --git a/families/vivit/support.py b/families/vivit/support.py new file mode 100644 index 0000000000..466ee6d542 --- /dev/null +++ b/families/vivit/support.py @@ -0,0 +1,12 @@ +# 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=("vivit",), + architectures=("VivitForVideoClassification",), + tasks=("video_classification",), + default_task="video_classification", + default_precision="fp32", +) diff --git a/families/vivit/tests/__init__.py b/families/vivit/tests/__init__.py new file mode 100644 index 0000000000..52a7a9daf0 --- /dev/null +++ b/families/vivit/tests/__init__.py @@ -0,0 +1,2 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 diff --git a/families/vivit/tests/cpp/e2e_consumer.cpp b/families/vivit/tests/cpp/e2e_consumer.cpp new file mode 100644 index 0000000000..86d2d94540 --- /dev/null +++ b/families/vivit/tests/cpp/e2e_consumer.cpp @@ -0,0 +1,119 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + */ +#include "families/vivit/runtime/image_preprocess.h" +#include "trtmc/runtime/family_loader.h" + +#include +#include +#include +#include +#include +int main(int argc, char** argv) { + try { + if (argc != 5) + throw std::invalid_argument("usage: vivit_e2e BUNDLE RUNTIME REQUESTS OUTPUT_DIR"); + auto loaded = trtmc::load_task(argv[1], argv[2]); + auto* task = dynamic_cast(loaded.get()); + if (!task || std::string(task->task()) != "video_classification") + throw std::runtime_error("ViViT does not expose video classification"); + std::ifstream file(argv[3]); + const auto requests = nlohmann::json::parse(file); + nlohmann::json results = nlohmann::json::array(); + std::vector> first; + trtmc::VideoClassificationRequest original; + trtmc::ClassificationResult first_result; + int index = 0; + for (const auto& input : requests) { + std::vector> bytes; + std::vector> pixels; + trtmc::VideoClassificationRequest request; + bytes.reserve(input.size()); + pixels.reserve(input.size()); + std::ofstream processed(std::string(argv[4]) + "/preprocess-" + std::to_string(index) + + ".bin", + std::ios::binary); + for (const auto& frame : input) { + const int h = frame.at("height"), w = frame.at("width"); + if (h < 1 || w < 1 || h > 8192 || w > 8192) + throw std::runtime_error("invalid frame fixture"); + bytes.emplace_back(static_cast(h) * w * 3); + std::ifstream source(frame.at("file").get(), std::ios::binary); + source.read(reinterpret_cast(bytes.back().data()), bytes.back().size()); + if (!source) + throw std::runtime_error("cannot read frame fixture"); + pixels.emplace_back(bytes.back().size()); + for (std::size_t i = 0; i < pixels.back().size(); ++i) + pixels.back()[i] = bytes.back()[i] / 255.F; + const auto values = trtmc::preprocess_vivit_image(pixels.back().data(), h, w); + processed.write(reinterpret_cast(values.data()), + values.size() * sizeof(float)); + // Exercise both supported public frame formats on the same clip. + const bool use_bytes = request.frames.size() % 2 == 0; + request.frames.push_back({use_bytes ? static_cast(bytes.back().data()) + : pixels.back().data(), + pixels.back().size(), h, w, + use_bytes ? trtmc::VideoFrameFormat::kRgb8 + : trtmc::VideoFrameFormat::kRgbFloat32}); + } + const auto result = task->classify(request); + if (index == 0) { + first = pixels; + original = request; + first_result = result; + for (std::size_t i = 0; i < first.size(); ++i) { + original.frames[i].pixels = first[i].data(); + original.frames[i].format = trtmc::VideoFrameFormat::kRgbFloat32; + } + } + results.push_back({{"logits", result.logits}, + {"top_class", result.top_class}, + {"top_score", result.top_score}}); + ++index; + } + auto recovery = [&] { + const auto result = task->classify(original); + if (result.logits != first_result.logits || + result.top_class != first_result.top_class || + result.top_score != first_result.top_score) + throw std::runtime_error("ViViT state leaked after rejection"); + }; + for (int mode = 0; mode < 9; ++mode) { + auto bad = original; + auto altered = first[0]; + if (mode == 0) + bad.frames.clear(); + if (mode == 1) + bad.frames.pop_back(); + if (mode == 2) + bad.frames.push_back(bad.frames[0]); + if (mode == 3) + bad.frames[0].pixels = nullptr; + if (mode == 4) + bad.frames[0].height = 0; + if (mode == 5) + --bad.frames[0].element_count; + if (mode == 6) + bad.frames[0].format = static_cast(99); + if (mode == 7 || mode == 8) { + altered[0] = mode == 7 ? std::numeric_limits::quiet_NaN() : 1.1F; + bad.frames[0].pixels = altered.data(); + } + bool rejected = false; + try { + (void)task->classify(bad); + } catch (const std::invalid_argument&) { + rejected = true; + } + if (!rejected) + throw std::runtime_error("ViViT accepted an invalid clip"); + recovery(); + } + std::cout << results.dump() << '\n'; + return 0; + } catch (const std::exception& error) { + std::cerr << error.what() << '\n'; + return 1; + } +} diff --git a/families/vivit/tests/data/test_img.jpeg b/families/vivit/tests/data/test_img.jpeg new file mode 100644 index 0000000000..095c03620f Binary files /dev/null and b/families/vivit/tests/data/test_img.jpeg differ diff --git a/families/vivit/tests/manifests/vivit-b-16x2.json b/families/vivit/tests/manifests/vivit-b-16x2.json new file mode 100644 index 0000000000..5ae7e0204e --- /dev/null +++ b/families/vivit/tests/manifests/vivit-b-16x2.json @@ -0,0 +1,21 @@ +{ + "name": "vivit-b-16x2", + "hf_id": "google/vivit-b-16x2", + "hf_revision": "fc341053d36b42d446b3ffccdbd52452712a23f3", + "family": "vivit", + "task": "video_classification", + "precision": "fp32", + "tensor_parallel_size": 1, + "trust_remote_code": false, + "bundle": "vivit-b-16x2.bundle", + "testcases": [{ + "name": "vivit-b-16x2-fp32", + "premerge": true, + "reference_precision": "fp32", + "frames": 32, + "max_preprocess_abs_error": 0.0000002, + "max_logits_abs_error": 0.0005, + "logits_rtol": 0.0001, + "max_probability_abs_error": 0.00001 + }] +} diff --git a/families/vivit/tests/math_check.py b/families/vivit/tests/math_check.py new file mode 100644 index 0000000000..357503f863 --- /dev/null +++ b/families/vivit/tests/math_check.py @@ -0,0 +1,67 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +"""Nondegenerate upstream tubelet, encoder and class-head comparisons.""" + + +def check_stages(): + import torch + import tensorrt as trt + from transformers import VivitConfig, VivitForVideoClassification + from families.vivit.model import compile_engine + + torch.set_num_threads(8) + torch.backends.cuda.matmul.allow_tf32 = False + torch.backends.cudnn.allow_tf32 = False + torch.manual_seed(357) + config = VivitConfig( + image_size=16, + num_frames=4, + tubelet_size=[2, 4, 4], + hidden_size=24, + intermediate_size=40, + num_hidden_layers=2, + num_attention_heads=3, + num_labels=7, + ) + config._attn_implementation = "eager" + model = VivitForVideoClassification(config).cuda().eval() + weights = {k: v.detach().cpu().numpy().copy() for k, v in model.state_dict().items()} + expected = {} + + def hook(name): + def capture(_m, _a, value): + expected[name] = value[0] if isinstance(value, tuple) else value + + return capture + + model.vivit.embeddings.patch_embeddings.register_forward_hook(hook("tubelets")) + model.vivit.embeddings.register_forward_hook(hook("embeddings")) + for i, layer in enumerate(model.vivit.encoder.layer): + layer.register_forward_hook(hook(f"layer_{i}")) + model.vivit.layernorm.register_forward_hook(hook("hidden")) + logger = trt.Logger(trt.Logger.WARNING) + runtime = trt.Runtime(logger) + engine = runtime.deserialize_cuda_engine(compile_engine(config.to_dict(), weights, debug=True)) + assert engine is not None + context = engine.create_execution_context() + for seed in (11, 13): + torch.manual_seed(seed) + pixels = torch.randn(1, 4, 3, 16, 16, device="cuda") + with torch.inference_mode(): + expected["logits"] = model(pixels).logits + source = pixels.permute(0, 2, 1, 3, 4).contiguous() + context.set_tensor_address("pixel_values", source.data_ptr()) + outputs = {} + for i in range(engine.num_io_tensors): + name = engine.get_tensor_name(i) + if engine.get_tensor_mode(name) == trt.TensorIOMode.OUTPUT: + outputs[name] = torch.empty( + tuple(engine.get_tensor_shape(name)), device="cuda", dtype=torch.float32 + ) + assert context.set_tensor_address(name, outputs[name].data_ptr()) + assert context.execute_async_v3(torch.cuda.current_stream().cuda_stream) + torch.cuda.synchronize() + assert outputs.keys() == expected.keys() + for name, value in outputs.items(): + print(name, seed, float((value - expected[name]).abs().max()), flush=True) + torch.testing.assert_close(value, expected[name], atol=5e-5, rtol=5e-5) diff --git a/families/vivit/tests/requirements.txt b/families/vivit/tests/requirements.txt new file mode 100644 index 0000000000..7e433514fa --- /dev/null +++ b/families/vivit/tests/requirements.txt @@ -0,0 +1,2 @@ +transformers==5.3.0 +Pillow==13.0.0 diff --git a/families/vivit/tests/test_e2e.py b/families/vivit/tests/test_e2e.py new file mode 100644 index 0000000000..cee01dbc9e --- /dev/null +++ b/families/vivit/tests/test_e2e.py @@ -0,0 +1,212 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +"""Pinned ViViT through the ordered-frame native Task and CLI.""" + +import gc +import json +import os +from pathlib import Path +import subprocess +import numpy as np +import pytest +from tensorrt_model_connect import BuildRequest, build +from tensorrt_model_connect.model_support import load_model_metadata, resolve_family +from tools.e2e_evidence import evidence_stage, record_evidence + +MANIFEST = json.loads((Path(__file__).parent / "manifests/vivit-b-16x2.json").read_text()) + + +def pytest_generate_tests(metafunc): + if "case_name" not in metafunc.fixturenames: + return + models, cases = set(), set() + for value in metafunc.config.getoption("--e2e-model"): + models.update(value.split(",")) + file = metafunc.config.getoption("--e2e-models-file") + if file: + models.update(Path(file).read_text().splitlines()) + for value in metafunc.config.getoption("--e2e-testcase"): + cases.update(value.split(",")) + selected = bool(models or cases) + parameters = [] + for case in MANIFEST["testcases"]: + if models and not models.intersection({"vivit", MANIFEST["name"], case["name"]}): + continue + if cases and case["name"] not in cases: + continue + marks = [] if selected else [pytest.mark.skip(reason="select VIVIT E2E explicitly")] + parameters.append(pytest.param(case["name"], id=case["name"], marks=marks)) + metafunc.parametrize("case_name", parameters) + + +def checkpoint(): + if path := os.environ.get("TRTMC_VIVIT_MODEL_DIR"): + return Path(path) + from huggingface_hub import snapshot_download + + return Path( + snapshot_download( + repo_id=MANIFEST["hf_id"], revision=MANIFEST["hf_revision"], local_files_only=True + ) + ) + + +def clips(): + from PIL import Image + + photo = np.asarray( + Image.open(Path(__file__).parent / "data/test_img.jpeg").convert("RGB").resize((160, 120)) + ) + natural = [np.roll(photo, 3 * i, axis=1).copy() for i in range(32)] + y, x = np.mgrid[:67, :101] + moving = [ + np.stack( + ((x * 3 + i * 7) % 256, (y * 5 - i * 9) % 256, ((x + y) * 2 + i * 11) % 256), axis=-1 + ).astype(np.uint8) + for i in range(32) + ] + return [natural, moving, list(reversed(natural)), natural] + + +def reference(root, video, case, tmp_path): + import torch + from transformers import VivitForVideoClassification, VivitImageProcessor + + torch.set_num_threads(8) + torch.backends.cuda.matmul.allow_tf32 = False + torch.backends.cudnn.allow_tf32 = False + processor = VivitImageProcessor.from_pretrained(root, local_files_only=True) + model, info = VivitForVideoClassification.from_pretrained( + root, dtype=torch.float32, trust_remote_code=MANIFEST["trust_remote_code"], output_loading_info=True + ) + assert not info["missing_keys"] and not info["mismatched_keys"] and not info["error_msgs"] + model = model.cuda().eval() + results = [] + with torch.inference_mode(): + for i, clip in enumerate(video): + inputs = processor(clip, return_tensors="pt") + assert inputs.pixel_values.shape == (1, case["frames"], 3, 224, 224) + logits = model(inputs.pixel_values.cuda()).logits[0] + result = dict( + logits=logits.cpu().numpy(), + top_class=int(logits.argmax()), + top_score=float(logits.softmax(-1).max()), + ) + np.savez( + tmp_path / f"reference-{i}.npz", + pixel_values=inputs.pixel_values.numpy(), + logits=result["logits"], + ) + results.append(result) + assert not np.array_equal(results[0]["logits"], results[1]["logits"]) + assert not np.array_equal(results[0]["logits"], results[2]["logits"]) + del model, inputs, logits + gc.collect() + torch.cuda.empty_cache() + return results + + +def test_official_checkpoint_e2e(case_name, tmp_path): + from families.vivit.tests.math_check import check_stages + from PIL import Image + + case = next(c for c in MANIFEST["testcases"] if c["name"] == case_name) + assert case["reference_precision"] == "fp32" + check_stages() + root = checkpoint() + runtime = Path(os.environ["TRTMC_RUNTIME_ROOT"]) + assert resolve_family(load_model_metadata(root))[0] == MANIFEST["family"] + assert (runtime / "libtrtmc_model_vivit.so").is_file() + video = clips() + record_evidence( + "inputs", + dict( + manifest=MANIFEST, + case=case, + fixtures=["panning photo", "moving RGB pattern", "reverse photo", "repeat photo"], + ), + ) + record_evidence( + "checkpoint", + dict(model_dir=str(root), hf_id=MANIFEST["hf_id"], hf_revision=MANIFEST["hf_revision"]), + ) + with evidence_stage("reference"): + expected = reference(root, video, case, tmp_path) + record_evidence( + "reference", + [ + dict(logits=r["logits"].tolist(), top_class=r["top_class"], top_score=r["top_score"]) + for r in expected + ], + ) + bundle = tmp_path / MANIFEST["bundle"] + with evidence_stage("build"): + build( + BuildRequest( + root, + bundle, + MANIFEST["family"], + MANIFEST["task"], + MANIFEST["precision"], + tensor_parallel_size=MANIFEST["tensor_parallel_size"], + ) + ) + requests = [] + for i, clip in enumerate(video): + frames = [] + for j, image in enumerate(clip): + path = tmp_path / f"frame-{i}-{j}.rgb" + image.tofile(path) + frames.append(dict(file=str(path), height=image.shape[0], width=image.shape[1])) + requests.append(frames) + path = tmp_path / "requests.json" + path.write_text(json.dumps(requests)) + with evidence_stage("native"): + command = [str(runtime / "vivit_e2e"), str(bundle), str(runtime), str(path), str(tmp_path)] + completed = subprocess.run(command, check=True, capture_output=True, text=True, timeout=300) + actual = json.loads(completed.stdout.strip().splitlines()[-1]) + record_evidence("commands", dict(argv=command)) + assert len(actual) == len(expected) and actual[0] == actual[-1] + for i, (observed, wanted) in enumerate(zip(actual, expected)): + pixels = np.fromfile(tmp_path / f"preprocess-{i}.bin", dtype=np.float32).reshape( + 1, case["frames"], 3, 224, 224 + ) + reference_pixels = np.load(tmp_path / f"reference-{i}.npz")["pixel_values"] + np.testing.assert_allclose( + pixels, reference_pixels, atol=case["max_preprocess_abs_error"], rtol=0 + ) + assert len(observed["logits"]) == 400 + np.testing.assert_allclose( + observed["logits"], + wanted["logits"], + atol=case["max_logits_abs_error"], + rtol=case["logits_rtol"], + ) + assert observed["top_class"] == wanted["top_class"] + assert abs(observed["top_score"] - wanted["top_score"]) <= case["max_probability_abs_error"] + with evidence_stage("cli"): + command = [ + str(runtime / "trtmc"), + "classify-video", + str(bundle), + "--runtime-root", + str(runtime), + ] + for j, image in enumerate(video[0]): + frame = tmp_path / f"cli-frame-{j}.png" + Image.fromarray(image).save(frame) + command.extend(["--frame", str(frame)]) + completed = subprocess.run(command, check=True, capture_output=True, text=True, timeout=180) + result = json.loads(completed.stdout.strip().splitlines()[-1]) + record_evidence("commands", dict(argv=command)) + np.testing.assert_allclose( + result["logits"], + expected[0]["logits"], + atol=case["max_logits_abs_error"], + rtol=case["logits_rtol"], + ) + assert result["top_class"] == expected[0]["top_class"] + assert ( + abs(result["top_score"] - expected[0]["top_score"]) <= case["max_probability_abs_error"] + ) + record_evidence("native", actual) diff --git a/families/vivit/tests/test_model.py b/families/vivit/tests/test_model.py new file mode 100644 index 0000000000..9a0d270374 --- /dev/null +++ b/families/vivit/tests/test_model.py @@ -0,0 +1,50 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +import numpy as np +import pytest +from tensorrt_model_connect import BuildRequest +from families.vivit.model import Graph, build, validate_config + + +def test_profile_rejections(tmp_path): + with pytest.raises(ValueError, match="FP32"): + build( + BuildRequest( + tmp_path, tmp_path / "test.bundle", "vivit", "video_classification", "fp16" + ), + None, + ) + with pytest.raises(NotImplementedError, match="dynamic_kv_cache"): + build( + BuildRequest( + tmp_path, + tmp_path / "test.bundle", + "vivit", + "video_classification", + "fp32", + dynamic_kv_cache=True, + ), + None, + ) + + +def test_missing_weight_and_invalid_tubelet(): + with pytest.raises(ValueError, match="missing checkpoint tensor"): + Graph(None, {}, {}).weight("vivit.embeddings.cls_token") + with pytest.raises(ValueError, match="tubelets must divide"): + validate_config(dict(model_type="vivit", num_frames=31)) + + +def test_classifier_requires_bias(): + graph = Graph(None, {}, {"classifier.weight": np.zeros((2, 4), dtype=np.float32)}) + with pytest.raises(ValueError, match=r"missing checkpoint tensor classifier\.bias"): + graph.linear(None, "classifier") + + +def test_rejects_nonkinetics_head_before_loading_weights(tmp_path): + from transformers import VivitConfig + + VivitConfig(num_labels=2).save_pretrained(tmp_path) + request = BuildRequest(tmp_path, tmp_path / "test.bundle", "vivit", "video_classification", "fp32") + with pytest.raises(ValueError, match="400-class"): + build(request, None) diff --git a/families/vivit/tests/test_support.py b/families/vivit/tests/test_support.py new file mode 100644 index 0000000000..62744edff0 --- /dev/null +++ b/families/vivit/tests/test_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 ModelMetadata, resolve_family +from families.vivit.support import describe + + +def test_video_owner(): + family, support = resolve_family(ModelMetadata(config={"model_type": "vivit"}, model_index={})) + assert family == "vivit" and support.default_task == "video_classification" + assert describe(ModelMetadata(config={"model_type": "vit"}, model_index={})) is None diff --git a/website/docs/api/cli-reference.md b/website/docs/api/cli-reference.md index ef5294b71b..64da4d0329 100644 --- a/website/docs/api/cli-reference.md +++ b/website/docs/api/cli-reference.md @@ -106,7 +106,7 @@ Common load options are: | Text or vision-language generation | `run` with `--prompt`, and optional `--image` | | Encoding and embedding | `encode --text TEXT`, `embed --text TEXT` | | Reranking | `rerank --query TEXT --document TEXT` | -| Classification and features | `classify --image PATH`, `extract-features --image PATH` | +| Classification and features | `classify --image PATH`, `classify-video --frame PATH` (repeat for each frame), `extract-features --image PATH` | | Stereo and geometry | `disparity --left PATH --right PATH`, `geometry --image PATH --output DIR` | | Segmentation | `segment --image PATH`, `segment-prompted --image PATH` with text or point prompt, `video-segment --frame PATH --prompt TEXT` | | Audio | `generate-audio --prompt TEXT --output PATH`, `speak --input WAV --output WAV`, `speech-session --input WAV` | @@ -152,3 +152,7 @@ Unknown commands, unknown command-specific options, duplicate options, task interface mismatches, invalid values, and missing DSOs fail with a nonzero exit status. Run `trtmc help` for the compiled executable's concise synopsis and `python -m tensorrt_model_connect build --help` for the exact build parser. + +`classify-video BUNDLE --frame first.png --frame second.png` preserves argument +order and returns `logits`, `top_class`, and `top_score` as JSON. Supply all +frames required by the family; each family owns its frame count and preprocessing. diff --git a/website/docs/api/cpp-api.md b/website/docs/api/cpp-api.md index 3f7e40f4d8..9e2228ff95 100644 --- a/website/docs/api/cpp-api.md +++ b/website/docs/api/cpp-api.md @@ -265,3 +265,13 @@ primitives live in `libtrtmc_core.so`. A family factory receives a The reader exposes immutable metadata and on-demand section reads only. The factory must copy the lightweight reader into its pipeline if it will read a section after the factory returns; it must never retain the context reference. + +### Video classification bundles + +The release-coupled `IVideoClassification` Task accepts an ordered +`VideoClassificationRequest::frames` sequence of `VideoFrameView` objects. +Frames carry interleaved RGB bytes or RGB floats in [0,1], explicit scalar +counts, and source dimensions. The caller owns storage throughout `classify()`. +The family validates supported clip geometry and returns `ClassificationResult` +with class logits, a top-class index and its score. The CLI equivalent uses +`classify-video` with repeated `--frame FILE` arguments in time order. diff --git a/website/plugins/model-support-inventory/index.js b/website/plugins/model-support-inventory/index.js index d833d344b7..448b005af9 100644 --- a/website/plugins/model-support-inventory/index.js +++ b/website/plugins/model-support-inventory/index.js @@ -36,6 +36,7 @@ const TASKS = { time_series_forecast: ['Time-series forecasting', 'Time Series', 'time-series-forecasting', 'forecast'], transcription: ['Speech recognition', 'Audio', 'automatic-speech-recognition', 'transcribe'], transcription_streaming: ['Streaming speech recognition', 'Audio', 'automatic-speech-recognition', 'transcribe'], + video_classification: ['Video classification', 'Computer Vision', 'video-classification', 'classify-video'], video_segmentation: ['Video segmentation', 'Computer Vision', 'image-segmentation', 'video-segment'], vision_language_generation: ['Vision-language generation', 'Multimodal', 'image-text-to-text', 'run'], world_model_generation: ['World-model generation', 'Computer Vision', 'image-to-video', 'generate-world'], diff --git a/website/plugins/model-support-inventory/index.test.js b/website/plugins/model-support-inventory/index.test.js index 82ea4c22e2..40e38d987d 100644 --- a/website/plugins/model-support-inventory/index.test.js +++ b/website/plugins/model-support-inventory/index.test.js @@ -308,3 +308,14 @@ test('requires the complete family shape', () => { fs.rmSync(path.join(root, 'families', 'beta', 'runtime', 'CMakeLists.txt')); assert.throws(() => collectModelSupportInventory(root), /missing families\/beta\/runtime/); }); + + +test('maps ordered video classification to its implemented command', () => { + const root = repository(); + const manifest = path.join(root, 'families', 'alpha', 'tests', 'manifests', 'small.json'); + const payload = JSON.parse(fs.readFileSync(manifest)); + payload.task = 'video_classification'; + fs.writeFileSync(manifest, JSON.stringify(payload)); + const [profile] = collectModelSupportInventory(root).modelProfiles; + assert.deepEqual(profile.cliCommands, ['classify-video']); +});