Skip to content
Draft
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
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0

# Imagenette's class prompts are English: the Chinese text tower still ranks them, and the benchmark compares TRTMC
# with the native model on the same prompts (its gate is the regression against native, not an absolute accuracy).
reference:
adapter: families/chinese_clip/reference/adapter.py # the runtime's relevance logit (scale x cosine)
10 changes: 10 additions & 0 deletions apps/aiperf_qual/config/models/svd-xt-fp32.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0

# An image-only model: the catalog request's prompt is empty and its size is the bundle's. Its guidance is a per-frame
# range, stated here at the pipeline's defaults (the runtime's too) so neither side falls back on its own.
reference:
adapter: families/stable_video_diffusion/reference/adapter.py # Diffusers StableVideoDiffusionPipeline
requirements: families/stable_video_diffusion/requirements.txt
options: {num_frames: 14} # the manifest's video_num_frames
request: {min_guidance_scale: 1.0, max_guidance_scale: 3.0}
10 changes: 10 additions & 0 deletions apps/aiperf_qual/config/models/svd-xt.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0

# An image-only model: the catalog request's prompt is empty and its size is the bundle's. Its guidance is a per-frame
# range, stated here at the pipeline's defaults (the runtime's too) so neither side falls back on its own.
reference:
adapter: families/stable_video_diffusion/reference/adapter.py # Diffusers StableVideoDiffusionPipeline
requirements: families/stable_video_diffusion/requirements.txt
options: {num_frames: 25} # the manifest's video_num_frames
request: {min_guidance_scale: 1.0, max_guidance_scale: 3.0}
4 changes: 4 additions & 0 deletions apps/aiperf_qual/tests/test_request_contract.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,10 @@ def test_image_video_controls_must_be_present_but_do_not_apply_to_text_or_speech
assert unstated_defaults(image, "generate_image") == []
assert unstated_defaults({**image, "media_type": "video"}, "generate_image") == ["num_frames"]
assert unstated_defaults({**image, "num_steps": -1}, "generate_image") == ["num_steps"]
# a per-frame guidance range (Stable Video Diffusion) states the guidance; one end alone does not
ranged = {"num_steps": 25, "min_guidance_scale": 1.0, "max_guidance_scale": 3.0, "height": 576, "width": 1024}
assert unstated_defaults(ranged, "generate_image") == []
assert unstated_defaults({**ranged, "max_guidance_scale": None}, "generate_image") == ["guidance_scale"]
assert unstated_defaults({"prompt": "cat"}, "generate") == []
assert unstated_defaults({"text": "hello"}, "generate_audio") == []

Expand Down
2 changes: 2 additions & 0 deletions apps/aiperf_qual/trtmc_aiperf_qual/suites.py
Original file line number Diff line number Diff line change
Expand Up @@ -597,6 +597,8 @@ def unstated_defaults(request: Mapping[str, Any], operation: str | None = None)
required = ["num_steps", "guidance_scale", "height", "width"]
if request.get("media_type") == "video":
required.append("num_frames")
if all(request.get(name) not in (None, "") for name in ("min_guidance_scale", "max_guidance_scale")):
required.remove("guidance_scale") # a per-frame guidance range (Stable Video Diffusion) states it
problems += [field for field in required if request.get(field) in (None, "") and field not in problems]
problems += [field for field in ("num_steps", "height", "width", "num_frames")
if field in request and (not isinstance(request[field], (int, float))
Expand Down
27 changes: 22 additions & 5 deletions apps/benchmark/native/benchmark_worker.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -2896,10 +2896,25 @@ Json run_generate_image(const trtmc::Model& model, const Json& request, const Ti
observe_video);
}
if (initial) {
// The frame count is fixed by the bundle; a stated one must be what it produced.
const auto expected = request.value("num_frames", std::int64_t{0});
// The frame count is fixed by the bundle; a stated one must be what it produced. So is the
// frame size of a Task that declares no height or width config (Stable Video Diffusion).
const auto task = task_for_operation<trtmc::InitialImageTextToVideo>(model, task_id);
const auto config = sdk_config(request, task.config_fields(),
const auto fields = task.config_fields();
const auto declares = [&](std::string_view name) {
return std::any_of(fields.begin(), fields.end(),
[&](const auto& field) { return field.name == name; });
};
const bool fixed_size = !declares("height") && !declares("width");
Json inputs = request;
std::vector<std::pair<std::string, std::int64_t>> expected{
{"num_frames", request.value("num_frames", std::int64_t{0})}};
if (fixed_size)
for (const char* name : {"height", "width"})
if (inputs.contains(name)) {
expected.emplace_back(name, inputs.at(name).get<std::int64_t>());
inputs.erase(name);
}
const auto config = sdk_config(inputs, fields,
{"prompt", "image_path", "image_paths", "num_frames",
"batch_size", "media_type", "_artifact_prefix"});
return run(
Expand All @@ -2910,8 +2925,10 @@ Json run_generate_image(const trtmc::Model& model, const Json& request, const Ti
},
[&](const trtmc::VideoGenerationResult& result) {
auto output = observe_video(result);
if (expected > 0 && output.at("num_frames").get<std::int64_t>() != expected)
throw std::runtime_error("generated video does not have the stated num_frames");
for (const auto& [name, value] : expected)
if (value > 0 && output.at(name).get<std::int64_t>() != value)
throw std::runtime_error("generated video does not have the stated " +
name);
return output;
});
}
Expand Down
16 changes: 12 additions & 4 deletions apps/benchmark/trtmc_benchmark/task_adapters.py
Original file line number Diff line number Diff line change
Expand Up @@ -977,12 +977,20 @@ def _image_generation_request(task: str, case: Mapping[str, Any], root: Path) ->
def _initial_image_video_request(case: Mapping[str, Any], root: Path) -> dict[str, Any]:
"""The Task's inputs (prompt, initial image) and only the generation controls the testcase states; the
image is optional here because a testcase may only flag ``initial_image`` and leave the picture to the
benchmark (an AIPerf suite supplies one of the bundle's size)."""
base = _image_generation_request("image_generation", case, root)
request: dict[str, Any] = {"prompt": base["prompt"]}
benchmark (an AIPerf suite supplies one of the bundle's size). An image-only model (Stable Video Diffusion)
states no prompt: its request carries the empty prompt its Task requires."""
stated = any(case.get(key) for key in ("prompt", "test_prompt", "prompt_file", "prompt_repeat")) or any(
_inputs(case).get(key) for key in ("prompt", "source_text"))
base = _image_generation_request("image_generation", case if stated else {**case, "prompt": "unused"}, root)
request: dict[str, Any] = {"prompt": base["prompt"] if stated else ""}
if base["negative_prompt"]:
request["negative_prompt"] = base["negative_prompt"]
for name in ("seed", "num_steps", "height", "width"):
steps = _explicit(case, "num_inference_steps", "num_steps")
if steps is not _MISSING and int(steps) > 0:
request["num_steps"] = int(steps)
elif base["num_steps"] > 0: # inputs.num_sampling_steps
request["num_steps"] = base["num_steps"]
for name in ("seed", "height", "width"):
if base[name] > 0 or (name == "seed" and base[name] == 0):
request[name] = base[name]
if base["guidance_scale"] >= 0:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,12 @@ def test_image_to_video_requests_send_only_the_stated_controls_and_an_optional_i
assert flagged.request == {"prompt": "waves", "seed": 42, "num_steps": 50, "guidance_scale": 5.0}
pictured = resolve_task_case("initial_image_text_to_video", {**case, "image": "start.png"}, tmp_path)
assert pictured.request["image_path"] == str(tmp_path / "start.png")
# an image-only model's testcase (Stable Video Diffusion): no prompt, its steps named num_steps
image_only = resolve_task_case("initial_image_text_to_video", {"image": "start.png", "seed": 42, "num_steps": 25},
tmp_path)
assert image_only.request == {"prompt": "", "seed": 42, "num_steps": 25, "image_path": str(tmp_path / "start.png")}
with pytest.raises(BenchmarkError):
resolve_task_case("initial_image_text_to_video", {**case, "num_steps": 25}, tmp_path)


def test_structure_requests_name_the_document_and_only_stated_sampling_controls(tmp_path):
Expand Down
51 changes: 51 additions & 0 deletions families/chinese_clip/reference/adapter.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0

"""Chinese-CLIP's Transformers model for ``relevance``, as tests/test_e2e.py runs it: the Python processor
(``use_fast=False``), lowercasing as the runtime does, every query of the request against the one image with the
text padded to the 64-token window, and each pair scored as the logit scale times the cosine of the projected
embeddings (the runtime's logit)."""

from pathlib import Path
from typing import Any, Mapping


class Adapter:
def __init__(self, spec: Any, host: Any) -> None:
from transformers import ChineseCLIPModel, ChineseCLIPProcessor

self.spec, self.host = spec, host
# The checkpoint ships no tokenizer config, and Transformers' BertTokenizer does not lowercase by default:
# its vocabulary is lowercase, so a capital such as "English" would become [UNK]. The runtime lowercases.
self.processor = ChineseCLIPProcessor.from_pretrained(spec.model, **{**spec.pretrained_kwargs(),
"use_fast": False, "do_lower_case": True})
self.model = host.maybe_compile(ChineseCLIPModel.from_pretrained(
spec.model, **spec.model_kwargs()).to(spec.device, spec.dtype).eval(), spec)

def invoke(self, request: Mapping[str, Any], artifact_base: Path) -> Any:
import torch

image = self.host.load_image(str(self.host.required(request, "image_path")))
queries = [str(query) for query in self.host.required(request, "queries")]
batch = self.processor(text=queries, images=image, padding="max_length", max_length=64, truncation=True,
return_tensors="pt")
pixels = batch["pixel_values"].to(self.spec.device, self.spec.dtype)
tokens = {key: batch[key].to(self.spec.device) for key in ("input_ids", "attention_mask")}

def score() -> Any:
def embedded(output: Any, name: str) -> Any:
if torch.is_tensor(output):
return output
vector = getattr(output, name, None)
return output.pooler_output if vector is None else vector

image_vector = embedded(self.model.get_image_features(pixel_values=pixels), "image_embeds")[0].float()
texts = embedded(self.model.get_text_features(**tokens), "text_embeds").float()
image_unit = image_vector / image_vector.norm()
texts = texts / texts.norm(dim=-1, keepdim=True)
return float(self.model.logit_scale.exp()) * (texts @ image_unit)

scores, model_ms = self.host.timed(score)
values = scores.cpu().tolist()
return self.host.invocation({"scored_pairs": len(values), "scores": values, "queries": queries,
"top_class": max(range(len(values)), key=values.__getitem__)}, model_ms)
59 changes: 59 additions & 0 deletions families/stable_video_diffusion/reference/adapter.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0

"""Stable Video Diffusion's native pipeline for ``generate_image``, as tests/test_e2e.py runs it: Diffusers'
``StableVideoDiffusionPipeline`` on the initial image alone (an image-only model: a stated prompt is refused, as the
runtime does), at the image's size and the bundle's frame count, with the request's steps, seed and conditioning
controls. The noise follows the runtime's stream: a CPU generator seeded with ``seed`` draws the float32
conditioning-image noise and then the float32 latents, cast to the pipeline dtype. Frames THWC in 0-1."""

from __future__ import annotations

from pathlib import Path
from typing import Any, Mapping

import numpy as np

# The runtime's conditioning controls (its Task config) that the pipeline also takes.
CONTROLS = {"min_guidance_scale": float, "max_guidance_scale": float, "fps": int, "motion_bucket_id": int,
"noise_aug_strength": float}


class Adapter:
def __init__(self, spec: Any, host: Any) -> None:
import torch
from diffusers import StableVideoDiffusionPipeline

self.spec, self.host, self.torch = spec, host, torch
kwargs = {"revision": spec.revision} if spec.revision else {}
self.pipe = StableVideoDiffusionPipeline.from_pretrained(spec.model, torch_dtype=spec.dtype,
**kwargs).to(spec.device)
self.pipe.set_progress_bar_config(disable=True)
host.maybe_compile(self.pipe.unet, spec)
self.frames = int(spec.options["num_frames"]) # the bundle's frame count (its manifest's video_num_frames)

def invoke(self, request: Mapping[str, Any], artifact_base: Path) -> Any:
torch, host = self.torch, self.host
if str(request.get("prompt") or ""):
raise host.Error("Stable Video Diffusion is conditioned on the initial image only; pass an empty prompt")
image = host.load_image(str(host.required(request, "image_path"))).convert("RGB")
width, height = image.size
seed = int(request.get("seed", 0))
generator = torch.Generator("cpu").manual_seed(seed)
torch.randn((1, 3, height, width), generator=generator) # the conditioning-image noise draw
factor = self.pipe.vae_scale_factor
latents = torch.randn((1, self.frames, self.pipe.unet.config.in_channels // 2, height // factor,
width // factor), generator=generator).to(self.spec.dtype)
kwargs: dict[str, Any] = {
"image": image, "height": height, "width": width, "num_frames": self.frames,
"decode_chunk_size": self.frames, "generator": torch.Generator("cpu").manual_seed(seed),
"latents": latents, "output_type": "np"}
if int(request.get("num_steps", -1)) > 0:
kwargs["num_inference_steps"] = int(request["num_steps"])
kwargs.update({name: convert(request[name]) for name, convert in CONTROLS.items() if name in request})
with torch.no_grad():
result, model_ms = host.timed(lambda: self.pipe(**kwargs))
video = np.asarray(result.frames[0], dtype=np.float32)
return host.invocation({**host.tensor_observation(video, artifact_base), "media_type": "video",
"num_frames": int(video.shape[0]), "height": int(video.shape[1]),
"width": int(video.shape[2])}, model_ms)
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
{
"name": "svd-xt-fp16-l0",
"premerge": true,
"image": "test_img.jpeg",
"image": "data/test_img.jpeg",
"seed": 7,
"num_steps": 25,
"reference_precisions": [
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
{
"name": "svd-xt-fp32",
"premerge": true,
"image": "test_img.jpeg",
"image": "data/test_img.jpeg",
"seed": 7,
"num_steps": 25,
"reference_precisions": [
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
{
"name": "svd-xt-fp16",
"premerge": false,
"image": "test_img.jpeg",
"image": "data/test_img.jpeg",
"seed": 42,
"num_steps": 25,
"reference_precisions": [
Expand Down
2 changes: 1 addition & 1 deletion families/stable_video_diffusion/tests/test_e2e.py
Original file line number Diff line number Diff line change
Expand Up @@ -158,7 +158,7 @@ def _initial_image(manifest: dict, case: dict, tmp_path: Path) -> tuple[Path, np
from PIL import Image

height, width = int(manifest["image_height"]), int(manifest["image_width"])
source = Image.open(TEST_ROOT / "data" / case["image"]).convert("RGB")
source = Image.open(TEST_ROOT / case["image"]).convert("RGB")
crop_width = min(source.width, round(source.height * width / height))
crop_height = min(source.height, round(crop_width * height / width))
left = (source.width - crop_width) // 2
Expand Down
Loading