diff --git a/CMakeLists.txt b/CMakeLists.txt index 10c8152eab..436736d794 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -537,6 +537,13 @@ if(TRTMC_BUILD_TESTS) target_compile_options(test_cli PRIVATE -Wall -Wextra -Wpedantic) add_test(NAME cli COMMAND test_cli) + add_executable(test_audio_codec_cli apps/cli/tests/test_audio_codec_cli.cpp) + target_include_directories(test_audio_codec_cli PRIVATE + ${PROJECT_SOURCE_DIR}/core/runtime/include ${PROJECT_SOURCE_DIR}/apps) + target_link_libraries(test_audio_codec_cli PRIVATE trtmc_cli nlohmann_json::nlohmann_json) + target_compile_options(test_audio_codec_cli PRIVATE -Wall -Wextra -Wpedantic) + add_test(NAME audio_codec_cli COMMAND test_audio_codec_cli ${CMAKE_BINARY_DIR}/audio-codec-cli-data) + 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..694e4642a4 100644 --- a/apps/cli/cli.cpp +++ b/apps/cli/cli.cpp @@ -112,6 +112,8 @@ const std::unordered_map& command_specs() { {CommandKind::kSegmentPrompted, {"--image", "--prompt", "--point-x", "--point-y", "--foreground"}}}, {"video-segment", {CommandKind::kVideoSegment, {"--frame", "--prompt"}}}, + {"encode-audio", {CommandKind::kEncodeAudio, {"--input", "--output", "--num-codebooks"}}}, + {"decode-audio", {CommandKind::kDecodeAudio, {"--input", "--output"}}}, {"generate-audio", {CommandKind::kGenerateAudio, {"--prompt", "--description", "--output", "--max-new-tokens", "--talker-max-new-tokens", @@ -1159,6 +1161,73 @@ int dispatch(const Command& command, ITask& task, std::ostream& output) { write_json(output, {{"frames", std::move(output_frames)}}); return EXIT_SUCCESS; } + case CommandKind::kEncodeAudio: { + auto& codec = require_interface(task); + const auto audio = io::read_wav_interleaved(require_option(command, "--input")); + const auto tokens = codec.encode({{audio.samples.data(), audio.samples.size()}, + audio.sample_rate, + audio.channels, + int_option(command, "--num-codebooks", 0, 0)}); + nlohmann::json encoded{{"codes", tokens.codes}, + {"codebooks", tokens.codebooks}, + {"frames", tokens.frames}, + {"audio_frames", tokens.audio_frames}, + {"sample_rate", tokens.sample_rate}, + {"channels", tokens.channels}, + {"codec_id", tokens.codec_id}}; + const auto path = require_option(command, "--output"); + std::ofstream file(path); + if (!file) + throw std::runtime_error("unable to open codec output: " + path); + file << encoded.dump() << '\n'; + file.close(); + if (!file) + throw std::runtime_error("unable to write codec output: " + path); + write_json(output, + {{"output", path}, {"codebooks", tokens.codebooks}, {"frames", tokens.frames}}); + return EXIT_SUCCESS; + } + case CommandKind::kDecodeAudio: { + auto& codec = require_interface(task); + std::ifstream file(require_option(command, "--input")); + if (!file) + throw std::runtime_error("unable to open codec input"); + const auto json = nlohmann::json::parse(file); + auto integer = [](const nlohmann::json& value) -> std::int64_t { + if (!value.is_number_integer() || + (value.is_number_unsigned() && + value.get() > + static_cast(std::numeric_limits::max()))) + throw std::invalid_argument("codec metadata requires signed-range integers"); + return value.get(); + }; + auto integer32 = [&](const nlohmann::json& value) -> std::int32_t { + const auto number = integer(value); + if (number < std::numeric_limits::min() || + number > std::numeric_limits::max()) + throw std::invalid_argument("codec integer exceeds int32 range"); + return static_cast(number); + }; + AudioCodecTokens tokens; + tokens.codebooks = integer32(json.at("codebooks")); + tokens.frames = integer(json.at("frames")); + tokens.audio_frames = integer(json.at("audio_frames")); + tokens.sample_rate = integer32(json.at("sample_rate")); + tokens.channels = integer32(json.at("channels")); + tokens.codec_id = json.at("codec_id").get(); + if (!json.at("codes").is_array()) + throw std::invalid_argument("codec codes must be an integer array"); + for (const auto& code : json.at("codes")) + tokens.codes.push_back(integer32(code)); + const auto audio = codec.decode(tokens); + const auto path = require_option(command, "--output"); + io::write_wav(audio, path); + write_json(output, {{"output", path}, + {"sample_rate", audio.sample_rate}, + {"channels", audio.num_channels}, + {"num_samples", audio.num_samples}}); + return EXIT_SUCCESS; + } case CommandKind::kGenerateAudio: { AudioGenerationConfig config; config.max_new_tokens = int_option(command, "--max-new-tokens", 128, 1); @@ -1640,6 +1709,7 @@ void print_usage(std::ostream& output) { " predict-structure, disparity, depth, geometry,\n" " segment,\n" " segment-prompted, video-segment, generate-audio, transcribe,\n" + " encode-audio, decode-audio,\n" " transcribe-batch, transcribe-streaming, speak, speech-session, generate-image,\n" " generate-image-batch, generate-video,\n" " solve, forecast, control, generate-world\n\n" @@ -1651,6 +1721,9 @@ void print_usage(std::ostream& output) { " [--cfg-scale S] [--sde-gamma S]\n\n" "Text generation options:\n" " [--source-language-token-id N] [--forced-bos-token-id N]\n\n" + "Audio codec input and output:\n" + " encode-audio --input WAV --output CODES.json [--num-codebooks N]\n" + " decode-audio --input CODES.json --output WAV\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" diff --git a/apps/cli/cli.h b/apps/cli/cli.h index 0c1728cdb6..bfffdec5f2 100644 --- a/apps/cli/cli.h +++ b/apps/cli/cli.h @@ -41,6 +41,8 @@ enum class CommandKind { kSegmentPrompted, kVideoSegment, kGenerateAudio, + kEncodeAudio, + kDecodeAudio, kTranscribe, kTranscribeBatch, kTranscribeStreaming, diff --git a/apps/cli/tests/test_audio_codec_cli.cpp b/apps/cli/tests/test_audio_codec_cli.cpp new file mode 100644 index 0000000000..af1f11b1a8 --- /dev/null +++ b/apps/cli/tests/test_audio_codec_cli.cpp @@ -0,0 +1,118 @@ +/* + * 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 +#include + +namespace { +void check(bool condition, const char* message) { + if (!condition) + throw std::runtime_error(message); +} +trtmc::cli::Command parse(std::vector args) { + std::vector argv; + for (auto& arg : args) + argv.push_back(arg.data()); + return trtmc::cli::parse_args(static_cast(argv.size()), argv.data()); +} +class Codec final : public trtmc::IAudioCodec { + public: + std::vector captured; + trtmc::AudioCodecTokens encoded; + int decodes{0}; + trtmc::AudioCodecTokens encode(const trtmc::AudioCodecRequest& request) override { + check(request.sample_rate == 8000 && request.channels == 2 && request.num_codebooks == 2, + "codec input format or codebook selection was changed"); + captured.assign(request.samples.begin(), request.samples.end()); + encoded = {{3, 7, 11, 13}, 2, 2, 3, 8000, 2, "test-checkpoint/profile"}; + return encoded; + } + trtmc::AudioResult decode(const trtmc::AudioCodecTokens& tokens) override { + ++decodes; + check(tokens.codes == encoded.codes && tokens.codebooks == 2 && tokens.frames == 2 && + tokens.audio_frames == 3 && tokens.sample_rate == 8000 && tokens.channels == 2 && + tokens.codec_id == "test-checkpoint/profile", + "codec metadata or integer tokens were changed"); + return {captured, static_cast(captured.size()), 8000, 2}; + } +}; +} // namespace + +int main(int argc, char** argv) { + try { + if (argc != 2) + throw std::invalid_argument("usage: test_audio_codec_cli TEMP_DIR"); + const std::filesystem::path root(argv[1]); + std::filesystem::create_directories(root); + const auto wav = root / "input.wav", json_path = root / "codes.json", + output = root / "output.wav"; + const std::vector samples{0.25F, -0.125F, 0.5F, -0.25F, 0.75F, -0.5F}; + trtmc::cli::io::write_wav({samples, 6, 8000, 2}, wav.string()); + Codec codec; + check(trtmc::app::uses_existing_task_runtime(codec.task()), + "codec Task is not selected by the native loader"); + std::ostringstream stream; + auto encode = parse({"trtmc", "encode-audio", "fixture.bundle", "--input", wav.string(), + "--output", json_path.string(), "--num-codebooks", "2"}); + check(encode.kind == trtmc::cli::CommandKind::kEncodeAudio, + "encode command parsed incorrectly"); + check(trtmc::cli::dispatch(encode, codec, stream) == 0 && codec.captured == samples, + "encode did not preserve interleaved PCM"); + if (std::filesystem::exists("/dev/full")) { + auto full = encode; + full.options.at("--output") = "/dev/full"; + std::ostringstream response; + bool write_failed = false; + try { + (void)trtmc::cli::dispatch(full, codec, response); + } catch (const std::runtime_error& error) { + write_failed = + std::string_view(error.what()).find("unable to write codec output:") == 0; + } + check(write_failed && response.str().empty(), "codec accepted a failed buffered write"); + } + auto decode = parse({"trtmc", "decode-audio", "fixture.bundle", "--input", + json_path.string(), "--output", output.string()}); + check(trtmc::cli::dispatch(decode, codec, stream) == 0, "decode command failed"); + const auto audio = trtmc::cli::io::read_wav_interleaved(output.string()); + check(audio.samples == samples && audio.sample_rate == 8000 && audio.channels == 2, + "decode did not preserve PCM geometry or values"); + std::ifstream file(json_path); + const auto valid = nlohmann::json::parse(file); + for (int mode = 0; mode < 3; ++mode) { + auto invalid = valid; + if (mode == 0) + invalid["codes"][0] = std::uint64_t{4294967299ULL}; + if (mode == 1) + invalid["frames"] = std::numeric_limits::max(); + if (mode == 2) + invalid["channels"] = 1.5; + { + std::ofstream bad(json_path); + bad << invalid.dump(); + } + bool rejected = false; + try { + (void)trtmc::cli::dispatch(decode, codec, stream); + } catch (const std::invalid_argument&) { + rejected = true; + } + check(rejected && codec.decodes == 1, "invalid codec integers reached the family"); + } + std::cout << "Audio codec PCM, integer payload, identity and metadata round trips passed\n"; + return 0; + } catch (const std::exception& error) { + std::cerr << error.what() << '\n'; + return 1; + } +} diff --git a/apps/task_runtime.h b/apps/task_runtime.h index 0e0f484642..753f3ecea2 100644 --- a/apps/task_runtime.h +++ b/apps/task_runtime.h @@ -24,6 +24,7 @@ inline bool uses_existing_task_runtime(std::string_view primary_task) noexcept { IImageBatchGeneration::kTask, IWorldModelGeneration::kTask, IAudioGeneration::kTask, + IAudioCodec::kTask, ITranscription::kTask, IBatchTranscription::kTask, IStreamingTranscription::kTask, diff --git a/core/runtime/include/trtmc/task.h b/core/runtime/include/trtmc/task.h index c6d1dffa2c..da4942ae2f 100644 --- a/core/runtime/include/trtmc/task.h +++ b/core/runtime/include/trtmc/task.h @@ -94,6 +94,37 @@ struct AudioResult { std::int32_t num_channels{1}; }; +// Borrowed interleaved PCM; samples counts scalar values. A codec owns its +// supported rates, channels, codebook counts, padding and numerical policy. +struct AudioCodecRequest { + Span samples; + std::int32_t sample_rate{0}; + std::int32_t channels{1}; + // Zero selects the codec's declared default. + std::int32_t num_codebooks{0}; +}; + +struct AudioCodecTokens { + // Contiguous codebook-major integer indices, codebooks x frames. + std::vector codes; + std::int32_t codebooks{0}; + std::int64_t frames{0}; + // Original PCM frames per channel, before codec padding. + std::int64_t audio_frames{0}; + std::int32_t sample_rate{0}; + std::int32_t channels{1}; + // Opaque owner-defined codebook/profile identity, checked by the decoder. + std::string codec_id; +}; + +class IAudioCodec : public virtual ITask { + public: + static constexpr const char* kTask = "audio_codec"; + const char* task() const noexcept override { return kTask; } + virtual AudioCodecTokens encode(const AudioCodecRequest& request) = 0; + virtual AudioResult decode(const AudioCodecTokens& tokens) = 0; +}; + struct TranscriptionStreamConfig { std::int32_t input_sample_rate{16000}; std::int32_t max_new_tokens{224}; diff --git a/families/dac/README.md b/families/dac/README.md new file mode 100644 index 0000000000..2a092f6887 --- /dev/null +++ b/families/dac/README.md @@ -0,0 +1,36 @@ +# Descript Audio Codec + +The FP32 profile targets `descript/dac_44khz` at revision +`c1bc521685adf9cfe247bc39a5ca58917eda1ac4`, using Transformers 5.3.0 as the +unmodified reference. It supports one mono waveform of 1..65536 samples at +44100 Hz with all nine 1024-entry codebooks. The native codec pads the right +edge with zeros to a multiple of 512, preserves the original audio length, and +trims decoded PCM to that length. It rejects other formats and codebook counts. + +Family-owned TensorRT graphs implement the dilated residual encoder, Snake +activations, factorized normalized residual quantizers, and transposed-convolution +decoder. Encoding preserves the upstream maximum-score expression and eval-mode +straight-through arithmetic. Decoding reconstructs the waveform from integer +codebooks. TensorRT executes all neural math, without custom GPU kernels or +Torch inference in the native runtime. + +The generic native `IAudioCodec` Task carries PCM format, codebook-major integer +indices, original audio frame count, and an opaque codec/profile identity. +The family validates identity, rate, channels, dimensions, length and every +index before decoding. Returned token and waveform vectors own their storage. + +``` +trtmc encode-audio dac.bundle --input input.wav --output codes.json +trtmc decode-audio dac.bundle --input codes.json --output decoded.wav +``` + +Tests require exact integer codes and full waveform agreement at `5e-4` absolute +and `1e-4` relative tolerance for speech, tones, a chirp, silence, and repetition. +Small nondegenerate model stages use `5e-5` absolute and relative tolerance. +Native checks cover rejection recovery, codebook identity and metadata; generic +CLI tests cover PCM channel preservation and integer parsing bounds. + +Build `trtmc`, `trtmc_backend_trt`, `trtmc_model_dac` and `dac_e2e`, then run +`pytest families/dac/tests --e2e-model dac -q` with `TRTMC_DAC_MODEL_DIR`, +`TRTMC_RUNTIME_ROOT` and `TRTMC_BINARY` configured. Quantization, mixed precision, +sharding, dynamic KV caches, text, image and video profiles are rejected. diff --git a/families/dac/__init__.py b/families/dac/__init__.py new file mode 100644 index 0000000000..ed45d8cb40 --- /dev/null +++ b/families/dac/__init__.py @@ -0,0 +1,3 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +"""Descript Audio Codec model ownership.""" diff --git a/families/dac/model.py b/families/dac/model.py new file mode 100644 index 0000000000..c85f5d2e1b --- /dev/null +++ b/families/dac/model.py @@ -0,0 +1,297 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +"""Pure TensorRT DAC encoder, residual vector quantizer and waveform decoder.""" + +import json +import math +from pathlib import Path + +import numpy as np +from safetensors.numpy import load_file +import tensorrt as trt + + +class Graph: + def __init__(self, network, weights, config, debug): + self.n, self.w, self.c, self.debug = network, weights, config, debug + self.storage = [] + + def weight(self, name): + if name not in self.w: + raise ValueError(f"dac checkpoint is missing {name}") + value = np.ascontiguousarray(self.w[name], dtype=np.float32) + if not np.isfinite(value).all(): + raise ValueError(f"dac checkpoint contains nonfinite {name}") + self.storage.append(value) + return value + + def constant(self, value, dtype=np.float32): + value = np.ascontiguousarray(value, dtype=dtype) + self.storage.append(value) + return self.n.add_constant(value.shape, value).get_output(0) + + def binary(self, a, b, op): + if not isinstance(b, trt.ITensor): + b = self.constant(np.full((1,) * len(a.shape), b, np.float32)) + return self.n.add_elementwise(a, b, op).get_output(0) + + def add(self, a, b): + return self.binary(a, b, trt.ElementWiseOperation.SUM) + + def sub(self, a, b): + return self.binary(a, b, trt.ElementWiseOperation.SUB) + + def mul(self, a, b): + return self.binary(a, b, trt.ElementWiseOperation.PROD) + + def div(self, a, b): + return self.binary(a, b, trt.ElementWiseOperation.DIV) + + def reshape(self, value, shape, transpose=None): + layer = self.n.add_shuffle(value) + layer.reshape_dims = shape + if transpose is not None: + layer.second_transpose = transpose + return layer.get_output(0) + + def output(self, value, name): + value = self.n.add_identity(value).get_output(0) + value.name = name + self.n.mark_output(value) + + def cat(self, values, axis): + layer = self.n.add_concatenation(values) + layer.axis = axis + return layer.get_output(0) + + def conv(self, x, name, stride=1, padding=0, dilation=1, deconv=False): + w = self.weight(name + ".weight") + create = self.n.add_deconvolution_nd if deconv else self.n.add_convolution_nd + layer = create( + x, + w.shape[1] if deconv else w.shape[0], + (w.shape[-1], 1), + trt.Weights(w[..., None]), + trt.Weights(self.weight(name + ".bias")), + ) + layer.stride_nd = (stride, 1) + layer.padding_nd = (padding, 0) + if not deconv: + layer.dilation_nd = (dilation, 1) + return layer.get_output(0) + + def snake(self, x, name): + alpha = self.constant(self.weight(name + ".alpha")[..., None]) + sine = self.n.add_unary(self.mul(x, alpha), trt.UnaryOperation.SIN).get_output(0) + reciprocal = self.n.add_unary(self.add(alpha, 1e-9), trt.UnaryOperation.RECIP).get_output(0) + return self.add(x, self.mul(reciprocal, self.mul(sine, sine))) + + def residual(self, x, name, dilation): + y = self.conv( + self.snake(x, name + ".snake1"), + name + ".conv1", + padding=3 * dilation, + dilation=dilation, + ) + y = self.conv(self.snake(y, name + ".snake2"), name + ".conv2") + return self.add(x, y) + + def block(self, x, name, stride, decoder): + if decoder: + x = self.conv( + self.snake(x, name + ".snake1"), + name + ".conv_t1", + stride, + math.ceil(stride / 2), + deconv=True, + ) + for i, dilation in enumerate((1, 3, 9), 1): + x = self.residual(x, name + f".res_unit{i}", dilation) + if not decoder: + x = self.conv( + self.snake(x, name + ".snake1"), name + ".conv1", stride, math.ceil(stride / 2) + ) + return x + + def normalize(self, x): + norm = self.n.add_reduce( + self.mul(x, x), trt.ReduceOperation.SUM, 1 << (len(x.shape) - 1), True + ).get_output(0) + norm = self.n.add_unary(norm, trt.UnaryOperation.SQRT).get_output(0) + norm = self.binary(norm, 1e-12, trt.ElementWiseOperation.MAX) + return self.div(x, norm) + + def code_vectors(self, indices, name): + table = self.constant(self.weight(name + ".codebook.weight")) + vectors = self.n.add_gather(table, indices, 0).get_output(0) + vectors = self.reshape(vectors, (1, -1, self.c["codebook_dim"]), (0, 2, 1)) + return self.reshape(vectors, (1, self.c["codebook_dim"], -1, 1)) + + def encode(self): + x = self.n.add_input("input_values", trt.float32, (1, 1, -1, 1)) + x = self.conv(x, "encoder.conv1", padding=3) + for i, stride in enumerate(self.c["downsampling_ratios"]): + x = self.block(x, f"encoder.block.{i}", stride, False) + if self.debug: + self.output(self.reshape(x, (1, x.shape[1], -1)), f"encoder_{i}") + x = self.conv(self.snake(x, "encoder.snake1"), "encoder.conv2", padding=1) + if self.debug: + self.output(self.reshape(x, (1, self.c["hidden_size"], -1)), "encoder_hidden") + codes = [] + for i in range(self.c["n_codebooks"]): + p = f"quantizer.quantizers.{i}" + projected = self.conv(x, p + ".in_proj") + if self.debug: + self.output( + self.reshape(projected, (1, self.c["codebook_dim"], -1)), f"projected_{i}" + ) + encodings = self.reshape(projected, (1, self.c["codebook_dim"], -1), (0, 2, 1)) + encodings = self.normalize(encodings) + table = self.normalize(self.constant(self.weight(p + ".codebook.weight")[None])) + dot = self.n.add_matrix_multiply( + encodings, trt.MatrixOperation.NONE, table, trt.MatrixOperation.TRANSPOSE + ).get_output(0) + query_norm = self.n.add_reduce( + self.mul(encodings, encodings), trt.ReduceOperation.SUM, 4, True + ).get_output(0) + table_norm = self.n.add_reduce( + self.mul(table, table), trt.ReduceOperation.SUM, 4, True + ).get_output(0) + table_norm = self.reshape(table_norm, (1, 1, self.c["codebook_size"])) + # Preserve the upstream expression and its order, including the + # positive normalized codebook norm in the maximum-score form. + score = self.add(self.mul(self.sub(query_norm, self.mul(dot, 2)), -1), table_norm) + maximum = self.n.add_topk(score, trt.TopKOperation.MAX, 1, 4) + indices = maximum.get_output(1) + codes.append(self.reshape(indices, (1, 1, -1))) + vectors = self.code_vectors(indices, p) + # Upstream retains this straight-through arithmetic in eval mode. + vectors = self.add(projected, self.sub(vectors, projected)) + contribution = self.conv(vectors, p + ".out_proj") + x = self.sub(x, contribution) + self.output(self.cat(codes, 1), "audio_codes") + + def decode(self): + codes = self.n.add_input("audio_codes", trt.int32, (1, self.c["n_codebooks"], -1)) + quantized = None + for i in range(self.c["n_codebooks"]): + indices = self.n.add_gather(codes, self.constant([i], np.int32), 1).get_output(0) + vectors = self.code_vectors(indices, f"quantizer.quantizers.{i}") + vectors = self.conv(vectors, f"quantizer.quantizers.{i}.out_proj") + quantized = vectors if quantized is None else self.add(quantized, vectors) + if self.debug: + self.output(self.reshape(quantized, (1, self.c["hidden_size"], -1)), "quantized") + x = self.conv(quantized, "decoder.conv1", padding=3) + for i, stride in enumerate(self.c["upsampling_ratios"]): + x = self.block(x, f"decoder.block.{i}", stride, True) + if self.debug: + self.output(self.reshape(x, (1, x.shape[1], -1)), f"decoder_{i}") + x = self.conv(self.snake(x, "decoder.snake1"), "decoder.conv2", padding=3) + x = self.n.add_activation(x, trt.ActivationType.TANH).get_output(0) + self.output(self.reshape(x, (1, -1)), "audio_values") + + +def compile_engine(weights, config, max_samples, mode, 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, weights, config, debug) + hop = math.prod(config["downsampling_ratios"]) + profile = builder.create_optimization_profile() + if mode == "encode": + graph.encode() + profile.set_shape( + "input_values", + (1, 1, hop, 1), + (1, 1, min(max_samples, 8 * hop), 1), + (1, 1, max_samples, 1), + ) + elif mode == "decode": + graph.decode() + profile.set_shape( + "audio_codes", + (1, config["n_codebooks"], 1), + (1, config["n_codebooks"], min(max_samples // hop, 8)), + (1, config["n_codebooks"], max_samples // hop), + ) + else: + raise ValueError("dac unknown engine") + options.add_optimization_profile(profile) + plan = builder.build_serialized_network(network, options) + if plan is None: + raise RuntimeError(f"dac {mode} TensorRT build failed") + return bytes(plan) + + +def validate(config, processor): + if config["model_type"] != "dac" or config["sampling_rate"] != 44100: + raise ValueError("dac supports the 44100 Hz checkpoint") + if config["n_codebooks"] != 9 or config["codebook_size"] != 1024 or config["codebook_dim"] != 8: + raise ValueError("dac unsupported codebook geometry") + if config["downsampling_ratios"] != [2, 4, 8, 8] or config["upsampling_ratios"] != [8, 8, 4, 2]: + raise ValueError("dac unsupported sampling topology") + expected = { + "feature_size": 1, + "hop_length": 512, + "padding_side": "right", + "padding_value": 0.0, + "sampling_rate": 44100, + } + if any(processor.get(k) != v for k, v in expected.items()): + raise ValueError("dac unsupported audio preprocessing") + + +def build(request, writer): + if request.dynamic_kv_cache: + raise NotImplementedError("dac does not support dynamic_kv_cache") + if ( + request.task != "audio_codec" + or request.backend not in {"trt", "trt_rtx"} + or request.precision != "fp32" + ): + raise ValueError("dac supports FP32 audio_codec on TensorRT") + if ( + request.max_batch_size != 1 + or request.tensor_parallel_size != 1 + or request.context_parallel_size != 1 + ): + raise ValueError("dac supports batch one without parallel sharding") + if ( + request.quantization not in {None, "none"} + or request.fp32_layers + or request.mtp_seq_len is not None + ): + raise ValueError("dac does not support quantization, mixed precision or MTP") + if ( + request.max_sequence_length is not None + or request.image_height is not None + or request.image_width is not None + or request.video_num_frames is not None + ): + raise ValueError("dac does not support text, image or video profiles") + root = Path(request.model_dir) + config = json.loads((root / "config.json").read_text()) + processor = json.loads((root / "preprocessor_config.json").read_text()) + validate(config, processor) + weights = load_file(root / "model.safetensors") + writer.set_header(family="dac", task=request.task, backend=request.backend) + for mode in ("encode", "decode"): + writer.add_bytes( + mode + ".plan", compile_engine(weights, config, 65536, mode, request.verbose) + ) + writer.add_json( + "runtime.json", + { + "schema_version": 1, + "sample_rate": 44100, + "channels": 1, + "codebooks": 9, + "codebook_size": 1024, + "hop_length": 512, + "max_samples": 65536, + "codec_id": "descript/dac_44khz@c1bc521685adf9cfe247bc39a5ca58917eda1ac4", + }, + ) diff --git a/families/dac/requirements.txt b/families/dac/requirements.txt new file mode 100644 index 0000000000..4230b4fe83 --- /dev/null +++ b/families/dac/requirements.txt @@ -0,0 +1,2 @@ +numpy>=2 +safetensors>=0.7 diff --git a/families/dac/runtime/CMakeLists.txt b/families/dac/runtime/CMakeLists.txt new file mode 100644 index 0000000000..de77c35961 --- /dev/null +++ b/families/dac/runtime/CMakeLists.txt @@ -0,0 +1,16 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +add_library(trtmc_model_dac SHARED pipeline.cpp plugin.cpp) +target_include_directories(trtmc_model_dac PRIVATE + ${PROJECT_SOURCE_DIR} ${PROJECT_SOURCE_DIR}/core/runtime/include) +target_include_directories(trtmc_model_dac SYSTEM PRIVATE ${TRTMC_CUDA_INCLUDE_DIR}) +target_link_libraries(trtmc_model_dac PRIVATE trtmc_core nlohmann_json::nlohmann_json ${TRTMC_CUDART_LIBRARY}) +target_compile_options(trtmc_model_dac PRIVATE -Wall -Wextra -Wpedantic) +set_target_properties(trtmc_model_dac PROPERTIES LIBRARY_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}" + BUILD_RPATH "\$ORIGIN" INSTALL_RPATH "\$ORIGIN") +install(TARGETS trtmc_model_dac LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR}) +if(TRTMC_BUILD_TESTS) + add_executable(dac_e2e ${PROJECT_SOURCE_DIR}/families/dac/tests/cpp/e2e_consumer.cpp) + target_link_libraries(dac_e2e PRIVATE trtmc_runtime nlohmann_json::nlohmann_json) + set_target_properties(dac_e2e PROPERTIES RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}") +endif() diff --git a/families/dac/runtime/pipeline.cpp b/families/dac/runtime/pipeline.cpp new file mode 100644 index 0000000000..9dd3890b46 --- /dev/null +++ b/families/dac/runtime/pipeline.cpp @@ -0,0 +1,99 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + */ +#include "families/dac/runtime/pipeline.h" + +#include +#include +#include + +namespace trtmc::dac { +namespace { +Tensor tensor(void* data, std::vector shape, DType dtype) { + Tensor t; + t.data = data; + t.shape = std::move(shape); + t.dtype = dtype; + return t; +} +const Tensor& output(const TensorMap& values, const char* name, + const std::vector& shape, DType dtype) { + const auto found = values.find(name); + if (found == values.end() || !found->second.data || found->second.shape != shape || + found->second.dtype != dtype) + throw std::runtime_error(std::string("dac invalid engine output: ") + name); + return found->second; +} +} // namespace +Pipeline::Pipeline(std::unique_ptr encoder, std::unique_ptr decoder, + Config config) + : encoder_(std::move(encoder)), decoder_(std::move(decoder)), config_(std::move(config)) { + if (!encoder_ || !decoder_ || !encoder_->ok() || !decoder_->ok() || + config_.sample_rate != 44100 || config_.codebooks != 9 || config_.codebook_size != 1024 || + config_.hop != 512 || config_.max_samples != 65536 || + config_.codec_id != "descript/dac_44khz@c1bc521685adf9cfe247bc39a5ca58917eda1ac4") + throw std::invalid_argument("dac unsupported engine, codec identity or geometry"); +} +AudioCodecTokens Pipeline::encode(const AudioCodecRequest& request) { + if (!request.samples.data() || request.samples.empty() || + request.samples.size() > static_cast(config_.max_samples) || + request.sample_rate != config_.sample_rate || request.channels != 1 || + (request.num_codebooks != 0 && request.num_codebooks != config_.codebooks)) + throw std::invalid_argument( + "dac requires 1..65536 mono samples at 44100 Hz and all nine codebooks"); + if (!std::all_of(request.samples.begin(), request.samples.end(), + [](float x) { return std::isfinite(x); })) + throw std::invalid_argument("dac requires finite PCM samples"); + const auto frames = + static_cast((request.samples.size() + config_.hop - 1) / config_.hop); + std::vector padded(static_cast(frames) * config_.hop); + std::copy(request.samples.begin(), request.samples.end(), padded.begin()); + const auto values = + encoder_->forward({{"input_values", tensor(padded.data(), {1, 1, frames * config_.hop, 1}, + DType::kFloat32)}}); + const auto& encoded = + output(values, "audio_codes", {1, config_.codebooks, frames}, DType::kInt32); + const auto* data = static_cast(encoded.data); + AudioCodecTokens result; + result.codes.assign(data, data + config_.codebooks * frames); + if (!std::all_of(result.codes.begin(), result.codes.end(), + [&](int x) { return x >= 0 && x < config_.codebook_size; })) + throw std::runtime_error("dac encoder returned an invalid codebook index"); + result.codebooks = config_.codebooks; + result.frames = frames; + result.audio_frames = static_cast(request.samples.size()); + result.sample_rate = config_.sample_rate; + result.channels = 1; + result.codec_id = config_.codec_id; + return result; +} +AudioResult Pipeline::decode(const AudioCodecTokens& tokens) { + if (tokens.codec_id != config_.codec_id || tokens.codebooks != config_.codebooks || + tokens.channels != 1 || tokens.sample_rate != config_.sample_rate || tokens.frames < 1 || + tokens.frames > config_.max_samples / config_.hop || + tokens.audio_frames <= (tokens.frames - 1) * config_.hop || + tokens.audio_frames > tokens.frames * config_.hop || + tokens.codes.size() != static_cast(tokens.frames) * config_.codebooks) + throw std::invalid_argument( + "dac codebooks, identity, audio length or format do not match the bundle"); + if (!std::all_of(tokens.codes.begin(), tokens.codes.end(), + [&](int x) { return x >= 0 && x < config_.codebook_size; })) + throw std::invalid_argument("dac codebook index is outside [0,1024)"); + auto codes = tokens.codes; + const auto values = decoder_->forward( + {{"audio_codes", + tensor(codes.data(), {1, config_.codebooks, tokens.frames}, DType::kInt32)}}); + const auto& decoded = + output(values, "audio_values", {1, tokens.frames * config_.hop}, DType::kFloat32); + const auto* data = static_cast(decoded.data); + if (!std::all_of(data, data + decoded.numel(), [](float x) { return std::isfinite(x); })) + throw std::runtime_error("dac decoder returned nonfinite PCM"); + AudioResult result; + result.samples.assign(data, data + tokens.audio_frames); + result.num_samples = static_cast(tokens.audio_frames); + result.sample_rate = config_.sample_rate; + result.num_channels = 1; + return result; +} +} // namespace trtmc::dac diff --git a/families/dac/runtime/pipeline.h b/families/dac/runtime/pipeline.h new file mode 100644 index 0000000000..914b27073f --- /dev/null +++ b/families/dac/runtime/pipeline.h @@ -0,0 +1,25 @@ +/* + * 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" + +namespace trtmc::dac { +struct Config { + int sample_rate{44100}, codebooks{9}, codebook_size{1024}, hop{512}, max_samples{65536}; + std::string codec_id; +}; +class Pipeline final : public IAudioCodec { + public: + Pipeline(std::unique_ptr encoder, std::unique_ptr decoder, + Config config); + AudioCodecTokens encode(const AudioCodecRequest&) override; + AudioResult decode(const AudioCodecTokens&) override; + + private: + std::unique_ptr encoder_, decoder_; + Config config_; +}; +} // namespace trtmc::dac diff --git a/families/dac/runtime/plugin.cpp b/families/dac/runtime/plugin.cpp new file mode 100644 index 0000000000..5e0dec7961 --- /dev/null +++ b/families/dac/runtime/plugin.cpp @@ -0,0 +1,38 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + */ +#include "families/dac/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("dac does not support --kv-cache-size"); + auto section = [&](const char* name) { + const auto* found = context.reader.find_section(name); + if (!found || !found->length) + throw std::runtime_error(std::string("dac missing ") + name); + return context.reader.read_section(name); + }; + const auto bytes = section("runtime.json"); + const auto json = nlohmann::json::parse(bytes.begin(), bytes.end()); + if (json.at("schema_version") != 1 || json.at("channels") != 1) + throw std::invalid_argument("dac unsupported runtime schema"); + trtmc::dac::Config config; + config.sample_rate = json.at("sample_rate"); + config.codebooks = json.at("codebooks"); + config.codebook_size = json.at("codebook_size"); + config.hop = json.at("hop_length"); + config.max_samples = json.at("max_samples"); + config.codec_id = json.at("codec_id"); + const auto encoder = section("encode.plan"); + auto encoder_module = context.backend.create_module(encoder.data(), encoder.size(), {}); + const auto decoder = section("decode.plan"); + auto decoder_module = context.backend.create_module(decoder.data(), decoder.size(), {}); + return new trtmc::dac::Pipeline(std::move(encoder_module), std::move(decoder_module), + std::move(config)); +} diff --git a/families/dac/support.py b/families/dac/support.py new file mode 100644 index 0000000000..2f789bb1bc --- /dev/null +++ b/families/dac/support.py @@ -0,0 +1,11 @@ +# 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=("dac",), + architectures=("DacModel",), + tasks=("audio_codec",), + default_task="audio_codec", + default_precision="fp32", +) diff --git a/families/dac/tests/__init__.py b/families/dac/tests/__init__.py new file mode 100644 index 0000000000..52a7a9daf0 --- /dev/null +++ b/families/dac/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/dac/tests/cpp/e2e_consumer.cpp b/families/dac/tests/cpp/e2e_consumer.cpp new file mode 100644 index 0000000000..8faa4c5d2c --- /dev/null +++ b/families/dac/tests/cpp/e2e_consumer.cpp @@ -0,0 +1,144 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + */ +#include "trtmc/runtime/family_loader.h" + +#include +#include +#include +#include +#include + +int main(int argc, char** argv) { + try { + if (argc != 4) + throw std::invalid_argument("usage: dac_e2e BUNDLE RUNTIME_ROOT REQUESTS"); + std::ifstream file(argv[3]); + const auto requests = nlohmann::json::parse(file); + auto loaded = trtmc::load_task(argv[1], argv[2]); + auto* task = dynamic_cast(loaded.get()); + if (!task || std::string(task->task()) != "audio_codec") + throw std::runtime_error("DAC does not expose IAudioCodec"); + nlohmann::json results = nlohmann::json::array(); + std::vector first; + trtmc::AudioCodecTokens first_codes; + trtmc::AudioResult first_audio; + for (const auto& request : requests) { + const int count = request.at("samples"); + if (count < 1 || count > 65536) + throw std::invalid_argument("invalid audio fixture size"); + std::vector samples(count); + std::ifstream input(request.at("file").get(), std::ios::binary); + input.read(reinterpret_cast(samples.data()), samples.size() * sizeof(float)); + if (!input) + throw std::runtime_error("cannot read PCM fixture"); + auto codes = task->encode({{samples.data(), samples.size()}, 44100, 1, 0}); + auto audio = task->decode(codes); + if (audio.num_samples != count || audio.samples.size() != samples.size() || + audio.num_channels != 1 || audio.sample_rate != 44100) + throw std::runtime_error("DAC did not preserve original PCM geometry"); + if (results.empty()) { + first = samples; + first_codes = codes; + first_audio = audio; + } + results.push_back({{"codes", codes.codes}, + {"codebooks", codes.codebooks}, + {"frames", codes.frames}, + {"audio_frames", codes.audio_frames}, + {"sample_rate", codes.sample_rate}, + {"channels", codes.channels}, + {"codec_id", codes.codec_id}, + {"pcm", audio.samples}}); + } + auto recovered = [&] { + auto codes = task->encode({{first.data(), first.size()}, 44100, 1, 9}); + if (codes.codes != first_codes.codes || + task->decode(codes).samples != first_audio.samples) + throw std::runtime_error("DAC request state leaked after rejection"); + }; + for (int mode = 0; mode < 7; ++mode) { + auto samples = first; + if (mode == 4) + samples.resize(65537); + if (mode == 5) + samples[0] = std::numeric_limits::quiet_NaN(); + trtmc::AudioCodecRequest request{{samples.data(), samples.size()}, 44100, 1, 0}; + if (mode == 0) + request.samples = {nullptr, samples.size()}; + if (mode == 1) + request.samples = {}; + if (mode == 2) + request.sample_rate = 24000; + if (mode == 3) + request.channels = 2; + if (mode == 6) + request.num_codebooks = 8; + bool rejected = false; + try { + (void)task->encode(request); + } catch (const std::invalid_argument&) { + rejected = true; + } + if (!rejected) + throw std::runtime_error("DAC accepted invalid PCM request"); + recovered(); + } + for (int mode = 0; mode < 12; ++mode) { + auto codes = first_codes; + switch (mode) { + case 0: + codes.codec_id = "different-checkpoint"; + break; + case 1: + codes.codebooks = 8; + break; + case 2: + codes.channels = 2; + break; + case 3: + codes.sample_rate = 24000; + break; + case 4: + codes.frames = 0; + break; + case 5: + codes.frames = 129; + break; + case 6: + codes.audio_frames = 0; + break; + case 7: + codes.audio_frames = codes.frames * 512 + 1; + break; + case 8: + codes.codes.pop_back(); + break; + case 9: + codes.codes[0] = -1; + break; + case 10: + codes.codes[0] = 1024; + break; + case 11: + codes.audio_frames = (codes.frames - 1) * 512; + break; + } + bool rejected = false; + try { + (void)task->decode(codes); + } catch (const std::invalid_argument&) { + rejected = true; + } + if (!rejected) + throw std::runtime_error("DAC accepted invalid codebook metadata"); + recovered(); + } + std::cout << results.dump() << '\n'; + return 0; + } catch (const std::exception& error) { + std::cerr << error.what() << '\n'; + return 1; + } +} diff --git a/families/dac/tests/data/speech_16k_mono.wav b/families/dac/tests/data/speech_16k_mono.wav new file mode 100644 index 0000000000..ba144817e6 Binary files /dev/null and b/families/dac/tests/data/speech_16k_mono.wav differ diff --git a/families/dac/tests/manifests/dac-44khz.json b/families/dac/tests/manifests/dac-44khz.json new file mode 100644 index 0000000000..bff46eef0d --- /dev/null +++ b/families/dac/tests/manifests/dac-44khz.json @@ -0,0 +1,22 @@ +{ + "name": "dac-44khz", + "hf_id": "descript/dac_44khz", + "hf_revision": "c1bc521685adf9cfe247bc39a5ca58917eda1ac4", + "family": "dac", + "task": "audio_codec", + "precision": "fp32", + "tensor_parallel_size": 1, + "trust_remote_code": false, + "bundle": "dac-44khz.bundle", + "testcases": [{ + "name": "dac-44khz-fp32", + "premerge": true, + "reference_precision": "fp32", + "sample_rate": 44100, + "codebooks": 9, + "hop_length": 512, + "waveform_atol": 0.0005, + "waveform_rtol": 0.0001, + "sample_lengths": [4410, 15435, 22050, 513, 4410] + }] +} diff --git a/families/dac/tests/math_check.py b/families/dac/tests/math_check.py new file mode 100644 index 0000000000..8469645d54 --- /dev/null +++ b/families/dac/tests/math_check.py @@ -0,0 +1,108 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +"""Compare dynamic DAC stages and exact residual codebooks with upstream forwards.""" + + +def check_stages(): + import torch + import tensorrt as trt + from transformers import DacConfig, DacModel + from families.dac.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(349) + config = DacConfig( + encoder_hidden_size=4, + hidden_size=16, + decoder_hidden_size=32, + downsampling_ratios=[2, 2], + upsampling_ratios=[2, 2], + n_codebooks=3, + codebook_dim=4, + codebook_size=16, + hop_length=4, + sampling_rate=44100, + ) + model = DacModel(config).eval() + with torch.no_grad(): + # Keep this unit fixture nondegenerate through the full codec depth. + for name, value in model.named_parameters(): + if name.endswith("weight"): + value.normal_(0, 0.15) + elif name.endswith("bias"): + value.normal_(0, 0.01) + weights = {k: v.detach().numpy().copy() for k, v in model.state_dict().items()} + logger = trt.Logger(trt.Logger.WARNING) + runtime = trt.Runtime(logger) + + def make(mode): + engine = runtime.deserialize_cuda_engine( + compile_engine(weights, config.to_dict(), 128, mode, debug=True) + ) + assert engine is not None + return engine, engine.create_execution_context() + + def run(pair, inputs): + engine, context = pair + tensors = {k: v.contiguous().cuda() for k, v in inputs.items()} + for name, value in tensors.items(): + assert context.set_input_shape(name, tuple(value.shape)) + outputs = {} + for i in range(engine.num_io_tensors): + name = engine.get_tensor_name(i) + if engine.get_tensor_mode(name) == trt.TensorIOMode.OUTPUT: + dtype = torch.int32 if engine.get_tensor_dtype(name) == trt.int32 else torch.float32 + outputs[name] = torch.empty( + tuple(context.get_tensor_shape(name)), device="cuda", dtype=dtype + ) + tensors.update(outputs) + for name, value in tensors.items(): + assert context.set_tensor_address(name, value.data_ptr()) + assert context.execute_async_v3(torch.cuda.current_stream().cuda_stream) + torch.cuda.synchronize() + return {k: v.cpu() for k, v in outputs.items()} + + def compare(a, b, name): + print(name, float((a - b.cpu()).abs().max()), flush=True) + torch.testing.assert_close(a, b.cpu(), atol=5e-5, rtol=5e-5) + + enc, dec = make("encode"), make("decode") + model.cuda() + captured = {} + + def hook(name): + def capture(_m, _a, value): + captured[name] = value + + return capture + + for i, block in enumerate(model.encoder.block): + block.register_forward_hook(hook(f"encoder_{i}")) + model.encoder.conv2.register_forward_hook(hook("encoder_hidden")) + for i, quantizer in enumerate(model.quantizer.quantizers): + quantizer.in_proj.register_forward_hook(hook(f"projected_{i}")) + with torch.inference_mode(): + for count in (8, 28, 64): + audio = torch.randn(1, 1, count, device="cuda") * 0.2 + expected = model.encode(audio) + actual = run(enc, {"input_values": audio[..., None]}) + for name, value in captured.items(): + compare(actual[name], value, f"{name}-{count}") + assert actual["audio_codes"].dtype == torch.int32 + torch.testing.assert_close( + actual["audio_codes"], expected.audio_codes.cpu().to(torch.int32), atol=0, rtol=0 + ) + captured.clear() + for i, block in enumerate(model.decoder.block): + block.register_forward_hook(hook(f"decoder_{i}")) + for frames in (2, 7, 16): + codes = torch.randint(16, (1, 3, frames), device="cuda") + quantized = model.quantizer.from_codes(codes)[0] + expected = model.decode(audio_codes=codes).audio_values + actual = run(dec, {"audio_codes": codes.to(torch.int32)}) + compare(actual["quantized"], quantized, f"quantized-{frames}") + for name, value in captured.items(): + compare(actual[name], value, f"{name}-{frames}") + compare(actual["audio_values"], expected, f"waveform-{frames}") diff --git a/families/dac/tests/requirements.txt b/families/dac/tests/requirements.txt new file mode 100644 index 0000000000..715f66eb6f --- /dev/null +++ b/families/dac/tests/requirements.txt @@ -0,0 +1,3 @@ +torch>=2.12 +transformers==5.3.0 +pytest>=8 diff --git a/families/dac/tests/test_e2e.py b/families/dac/tests/test_e2e.py new file mode 100644 index 0000000000..caf3f5acc7 --- /dev/null +++ b/families/dac/tests/test_e2e.py @@ -0,0 +1,257 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +"""Pinned DAC checkpoint through the native abstract multimodal Task.""" + +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/dac-44khz.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({"dac", MANIFEST["name"], case["name"]}): + continue + if cases and case["name"] not in cases: + continue + marks = [] if selected else [pytest.mark.skip(reason="select DAC 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_DAC_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 fixtures(case): + import wave + + lengths = case["sample_lengths"] + rate = case["sample_rate"] + t = np.arange(lengths[0], dtype=np.float64) / rate + tones = 0.2 * np.sin(2 * np.pi * 220 * t) + 0.07 * np.sin(2 * np.pi * 659 * t) + with wave.open(str(Path(__file__).parent / "data/speech_16k_mono.wav")) as file: + assert file.getsampwidth() == 2 and file.getnchannels() == 1 + source_rate = file.getframerate() + voice = ( + np.frombuffer(file.readframes(file.getnframes()), dtype=" 0.005 + return [ + np.rint(np.clip(x, -1, 1) * 32767).astype(" name.replaceAll('_', '-')), - cliCommands: [...new Set([...tasks].map((name) => TASKS[name][3]).filter(Boolean))].sort(), + cliCommands: [...new Set([...tasks].flatMap(taskCommands))].sort(), precision: manifest.precision, quantization: manifest.quantization || 'none', parallelMode, @@ -342,7 +348,7 @@ function taskRecipe(taskName, profiles) { slug: family.replaceAll('_', '-'), recipeCount: familyProfiles.length, hfIds: [...new Set(familyProfiles.map((profile) => profile.hfId))].sort(), - cliCommands: TASKS[taskName][3] ? [TASKS[taskName][3]] : [], + cliCommands: taskCommands(taskName), })).sort((left, right) => left.family.localeCompare(right.family)), }; } diff --git a/website/plugins/model-support-inventory/index.test.js b/website/plugins/model-support-inventory/index.test.js index 82ea4c22e2..aa77afbccb 100644 --- a/website/plugins/model-support-inventory/index.test.js +++ b/website/plugins/model-support-inventory/index.test.js @@ -230,6 +230,19 @@ test('document layout recipes use the implemented layout command', (context) => .cliCommands, ['layout']); }); +test('audio codec recipes advertise both integer encode and decode commands', (context) => { + const root = repository(); + context.after(() => fs.rmSync(root, {recursive: true, force: true})); + addTaskManifest(root, 'audio_codec', 'beta'); + const inventory = collectModelSupportInventory(root); + const profile = inventory.modelProfiles.find((item) => item.task === 'audio_codec'); + assert.deepEqual(profile.cliCommands, ['decode-audio', 'encode-audio']); + const recipe = inventory.taskRecipes.find((item) => item.task === 'audio_codec'); + assert.equal(recipe.category, 'Audio'); + assert.equal(recipe.hfUrl, null); + assert.deepEqual(recipe.families[0].cliCommands, ['encode-audio', 'decode-audio']); +}); + test('rejects unknown Tasks including inherited object property names', (context) => { const root = repository(); context.after(() => fs.rmSync(root, {recursive: true, force: true}));