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/encodec/README.md b/families/encodec/README.md new file mode 100644 index 0000000000..406bf86f96 --- /dev/null +++ b/families/encodec/README.md @@ -0,0 +1,35 @@ +# EnCodec 24 kHz + +The FP32 profile targets `facebook/encodec_24khz` at revision +`c1dbe2ae3f1de713481a3b3e7c47f357092ee040`, using Transformers 5.3.0 as the +unmodified reference. It encodes one mono 6400-sample waveform at 24000 Hz into +two 1024-entry codebooks with 20 frames. This is the checkpoint's default +1.5 kbps setting. The first profile has a fixed input duration and rejects +other sample counts, formats, and codebook selections. + +The family owns causal reflection padding, weight-normalized SEANet convolutions, +residual blocks, both two-layer LSTMs, Euclidean residual quantization, and the +waveform decoder. TensorRT loops express recurrent state updates and reset +their initial states on each request. All neural math executes in TensorRT; +the native runtime requires no Python, Torch or custom GPU kernels. + +Native `IAudioCodec` requests and codebook payloads preserve integer indices, +PCM format, original audio length, and codec/profile identity. Decoding checks +all metadata and index bounds before execution. Returned vectors own storage. + +``` +trtmc encode-audio encodec.bundle --input input.wav --output codes.json +trtmc decode-audio encodec.bundle --input codes.json --output decoded.wav +``` + +Small model tests compare every encoder, recurrent and decoder stage at `5e-5` +absolute and relative tolerance. Real checkpoint tests require exact codebooks +and full PCM agreement at `5e-4` absolute / `1e-4` relative tolerance for speech, +tones, chirp, silence and repetition, plus recovery after invalid requests and +WAV/JSON CLI round trips. + +Build `trtmc`, `trtmc_backend_trt`, `trtmc_model_encodec` and `encodec_e2e`, then +run `pytest families/encodec/tests --e2e-model encodec -q` with +`TRTMC_ENCODEC_MODEL_DIR`, `TRTMC_RUNTIME_ROOT` and `TRTMC_BINARY` set. +Quantization, mixed precision, sharding, dynamic KV caching, text, image, video, +stereo, chunk overlap, and amplitude normalization are outside this profile. diff --git a/families/encodec/__init__.py b/families/encodec/__init__.py new file mode 100644 index 0000000000..c26533e3e5 --- /dev/null +++ b/families/encodec/__init__.py @@ -0,0 +1,3 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +"""EnCodec neural audio codec ownership.""" diff --git a/families/encodec/model.py b/families/encodec/model.py new file mode 100644 index 0000000000..1fb37ebde7 --- /dev/null +++ b/families/encodec/model.py @@ -0,0 +1,342 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +"""SEANet convolutions, recurrent LSTM and residual codebooks in TensorRT.""" + +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, samples, codebooks, debug): + self.n, self.w, self.c = network, weights, config + self.samples, self.books, self.debug = samples, codebooks, debug + self.storage, self.folded = [], {} + + def weight(self, name): + if name in self.folded: + return self.folded[name] + if name in self.w: + value = self.w[name] + elif name.endswith(".weight"): + p = name[:-7] + if p + ".weight_g" in self.w: + gain, vector = self.w[p + ".weight_g"], self.w[p + ".weight_v"] + elif p + ".parametrizations.weight.original0" in self.w: + gain, vector = ( + self.w[p + ".parametrizations.weight.original0"], + self.w[p + ".parametrizations.weight.original1"], + ) + else: + raise ValueError(f"encodec checkpoint is missing {name}") + norm = np.sqrt( + np.sum( + vector.astype(np.float64) ** 2, axis=tuple(range(1, vector.ndim)), keepdims=True + ) + ).astype(np.float32) + value = vector * (gain / norm) + else: + raise ValueError(f"encodec checkpoint is missing {name}") + value = np.ascontiguousarray(value, dtype=np.float32) + if not np.isfinite(value).all(): + raise ValueError(f"encodec nonfinite checkpoint tensor {name}") + self.storage.append(value) + self.folded[name] = 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 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 activate(self, x, kind): + layer = self.n.add_activation(x, kind) + if kind == trt.ActivationType.ELU: + layer.alpha = 1 + 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 slice(self, x, start, size): + return self.n.add_slice(x, start, size, (1,) * len(size)).get_output(0) + + def conv(self, x, name, stride=1, dilation=1, transpose=False): + w = self.weight(name + ".conv.weight") + bias = self.weight(name + ".conv.bias") + if not transpose: + length = x.shape[2] + left = (w.shape[-1] - 1) * dilation + 1 - stride + right = (-length) % stride + if length <= max(left, right): + raise ValueError( + "encodec fixed profile cannot reflect this short convolution input" + ) + positions = np.pad(np.arange(length, dtype=np.int32), (left, right), mode="reflect") + x = self.n.add_gather(x, self.constant(positions, np.int32), 2).get_output(0) + create = self.n.add_deconvolution_nd if transpose else self.n.add_convolution_nd + layer = create( + x, + w.shape[1] if transpose else w.shape[0], + (w.shape[-1], 1), + trt.Weights(w[..., None]), + trt.Weights(bias), + ) + layer.stride_nd = (stride, 1) + if not transpose: + layer.dilation_nd = (dilation, 1) + x = layer.get_output(0) + if transpose: + trim = w.shape[-1] - stride + x = self.slice(x, (0, 0, 0, 0), (1, x.shape[1], x.shape[2] - trim, 1)) + return x + + def residual(self, x, name): + y = self.conv(self.activate(x, trt.ActivationType.ELU), name + ".block.1", dilation=1) + y = self.conv(self.activate(y, trt.ActivationType.ELU), name + ".block.3") + return self.add(self.conv(x, name + ".shortcut"), y) + + def lstm(self, x, name): + channels, frames = x.shape[1:3] + sequence = self.reshape(x, (1, channels, frames)) + loop = self.n.add_loop() + count_data = np.array(frames, dtype=np.int32) + self.storage.append(count_data) + count = self.n.add_constant((), trt.Weights(count_data)).get_output(0) + loop.add_trip_limit(count, trt.TripLimit.COUNT) + value = loop.add_iterator(sequence, 2).get_output(0) + + def linear(v, weight, bias): + w = self.constant(self.weight(weight)) + v = self.n.add_matrix_multiply( + v, trt.MatrixOperation.NONE, w, trt.MatrixOperation.TRANSPOSE + ).get_output(0) + return self.add(v, self.constant(self.weight(bias)[None])) + + for layer in range(self.c["num_lstm_layers"]): + h = loop.add_recurrence(self.constant(np.zeros((1, channels), np.float32))) + c = loop.add_recurrence(self.constant(np.zeros((1, channels), np.float32))) + prefix = name + ".lstm." + gates = self.add( + linear(value, prefix + f"weight_ih_l{layer}", prefix + f"bias_ih_l{layer}"), + linear( + h.get_output(0), prefix + f"weight_hh_l{layer}", prefix + f"bias_hh_l{layer}" + ), + ) + chunks = [self.slice(gates, (0, i * channels), (1, channels)) for i in range(4)] + i, f, g, o = [ + self.activate( + v, trt.ActivationType.TANH if index == 2 else trt.ActivationType.SIGMOID + ) + for index, v in enumerate(chunks) + ] + cell = self.add(self.mul(f, c.get_output(0)), self.mul(i, g)) + value = self.mul(o, self.activate(cell, trt.ActivationType.TANH)) + h.set_input(1, value) + c.set_input(1, cell) + collected = loop.add_loop_output(value, trt.LoopOutput.CONCATENATE, 2) + collected.set_input(1, count) + return self.reshape(self.add(sequence, collected.get_output(0)), (1, channels, frames, 1)) + + def network(self, x, decoder): + p = "decoder.layers" if decoder else "encoder.layers" + index = 0 + + def emit(value): + nonlocal index + if self.debug: + self.output( + self.reshape(value, (1, value.shape[1], value.shape[2])), + f"{'decoder' if decoder else 'encoder'}_{index}", + ) + index += 1 + return value + + x = emit(self.conv(x, f"{p}.{index}")) + if decoder: + x = emit(self.lstm(x, f"{p}.{index}")) + ratios = ( + self.c["upsampling_ratios"] if decoder else list(reversed(self.c["upsampling_ratios"])) + ) + for ratio in ratios: + if decoder: + x = emit(self.activate(x, trt.ActivationType.ELU)) + x = emit(self.conv(x, f"{p}.{index}", stride=ratio, transpose=True)) + x = emit(self.residual(x, f"{p}.{index}")) + else: + x = emit(self.residual(x, f"{p}.{index}")) + x = emit(self.activate(x, trt.ActivationType.ELU)) + x = emit(self.conv(x, f"{p}.{index}", stride=ratio)) + if not decoder: + x = emit(self.lstm(x, f"{p}.{index}")) + x = emit(self.activate(x, trt.ActivationType.ELU)) + return emit(self.conv(x, f"{p}.{index}")) + + def code_vectors(self, indices, name, frames): + vectors = self.n.add_gather( + self.constant(self.weight(name + ".codebook.embed")), indices, 0 + ).get_output(0) + vectors = self.reshape(vectors, (1, frames, self.c["codebook_dim"]), (0, 2, 1)) + return self.reshape(vectors, (1, self.c["codebook_dim"], frames, 1)) + + def encode(self): + x = self.n.add_input("input_values", trt.float32, (1, 1, self.samples, 1)) + x = self.network(x, False) + frames = x.shape[2] + codes = [] + for i in range(self.books): + p = f"quantizer.layers.{i}" + values = self.reshape(x, (1, self.c["hidden_size"], frames), (0, 2, 1)) + table = self.constant(self.weight(p + ".codebook.embed")[None]) + dots = self.n.add_matrix_multiply( + values, trt.MatrixOperation.NONE, table, trt.MatrixOperation.TRANSPOSE + ).get_output(0) + values_norm = self.n.add_reduce( + self.mul(values, values), 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"])) + score = self.mul(self.add(self.sub(values_norm, self.mul(dots, 2)), table_norm), -1) + indices = self.n.add_topk(score, trt.TopKOperation.MAX, 1, 4).get_output(1) + codes.append(self.reshape(indices, (1, 1, frames))) + x = self.sub(x, self.code_vectors(indices, p, frames)) + concat = self.n.add_concatenation(codes) + concat.axis = 1 + self.output(concat.get_output(0), "audio_codes") + + def decode(self): + frames = self.samples // math.prod(self.c["upsampling_ratios"]) + codes = self.n.add_input("audio_codes", trt.int32, (1, self.books, frames)) + x = None + for i in range(self.books): + indices = self.n.add_gather(codes, self.constant([i], np.int32), 1).get_output(0) + vectors = self.code_vectors(indices, f"quantizer.layers.{i}", frames) + x = vectors if x is None else self.add(x, vectors) + if self.debug: + self.output(self.reshape(x, (1, self.c["hidden_size"], frames)), "quantized") + x = self.network(x, True) + self.output(self.reshape(x, (1, self.samples)), "audio_values") + + +def compile_engine(weights, config, samples, codebooks, 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, samples, codebooks, debug) + if mode == "encode": + graph.encode() + elif mode == "decode": + graph.decode() + else: + raise ValueError("encodec unknown engine") + plan = builder.build_serialized_network(network, options) + if plan is None: + raise RuntimeError(f"encodec {mode} TensorRT build failed") + return bytes(plan) + + +def build(request, writer): + if request.dynamic_kv_cache: + raise NotImplementedError("encodec 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("encodec 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("encodec 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("encodec 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("encodec does not support text, image or video profiles") + from transformers import EncodecConfig + + root = Path(request.model_dir) + config = EncodecConfig.from_pretrained(root, local_files_only=True).to_dict() + expected = dict( + model_type="encodec", + sampling_rate=24000, + audio_channels=1, + normalize=False, + chunk_length_s=None, + use_causal_conv=True, + pad_mode="reflect", + norm_type="weight_norm", + trim_right_ratio=1.0, + upsampling_ratios=[8, 5, 4, 2], + num_residual_layers=1, + use_conv_shortcut=True, + codebook_dim=128, + hidden_size=128, + codebook_size=1024, + ) + if any(config.get(k) != v for k, v in expected.items()): + raise ValueError("encodec unsupported 24 kHz codec topology") + if config["target_bandwidths"][0] != 1.5: + raise ValueError("encodec requires the published 1.5 kbps default") + weights = load_file(root / "model.safetensors") + writer.set_header(family="encodec", task=request.task, backend=request.backend) + for mode in ("encode", "decode"): + writer.add_bytes( + mode + ".plan", compile_engine(weights, config, 6400, 2, mode, request.verbose) + ) + writer.add_json( + "runtime.json", + dict( + schema_version=1, + sample_rate=24000, + channels=1, + samples=6400, + codebooks=2, + codebook_size=1024, + frames=20, + hop_length=320, + max_samples=6400, + codec_id="facebook/encodec_24khz@c1dbe2ae3f1de713481a3b3e7c47f357092ee040/1500bps", + ), + ) diff --git a/families/encodec/requirements.txt b/families/encodec/requirements.txt new file mode 100644 index 0000000000..7da547733e --- /dev/null +++ b/families/encodec/requirements.txt @@ -0,0 +1,3 @@ +numpy>=2 +safetensors>=0.7 +transformers==5.3.0 diff --git a/families/encodec/runtime/CMakeLists.txt b/families/encodec/runtime/CMakeLists.txt new file mode 100644 index 0000000000..d9e0d9ac0a --- /dev/null +++ b/families/encodec/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_encodec SHARED pipeline.cpp plugin.cpp) +target_include_directories(trtmc_model_encodec PRIVATE + ${PROJECT_SOURCE_DIR} ${PROJECT_SOURCE_DIR}/core/runtime/include) +target_include_directories(trtmc_model_encodec SYSTEM PRIVATE ${TRTMC_CUDA_INCLUDE_DIR}) +target_link_libraries(trtmc_model_encodec PRIVATE trtmc_core nlohmann_json::nlohmann_json ${TRTMC_CUDART_LIBRARY}) +target_compile_options(trtmc_model_encodec PRIVATE -Wall -Wextra -Wpedantic) +set_target_properties(trtmc_model_encodec PROPERTIES LIBRARY_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}" + BUILD_RPATH "\$ORIGIN" INSTALL_RPATH "\$ORIGIN") +install(TARGETS trtmc_model_encodec LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR}) +if(TRTMC_BUILD_TESTS) + add_executable(encodec_e2e ${PROJECT_SOURCE_DIR}/families/encodec/tests/cpp/e2e_consumer.cpp) + target_link_libraries(encodec_e2e PRIVATE trtmc_runtime nlohmann_json::nlohmann_json) + set_target_properties(encodec_e2e PROPERTIES RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}") +endif() diff --git a/families/encodec/runtime/pipeline.cpp b/families/encodec/runtime/pipeline.cpp new file mode 100644 index 0000000000..452600c443 --- /dev/null +++ b/families/encodec/runtime/pipeline.cpp @@ -0,0 +1,101 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + */ +#include "families/encodec/runtime/pipeline.h" + +#include +#include +#include + +namespace trtmc::encodec { +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("encodec 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 != 24000 || config_.codebooks != 2 || config_.codebook_size != 1024 || + config_.hop != 320 || config_.max_samples != 6400 || + config_.codec_id != + "facebook/encodec_24khz@c1dbe2ae3f1de713481a3b3e7c47f357092ee040/1500bps") + throw std::invalid_argument("encodec unsupported engine, codec identity or geometry"); +} +AudioCodecTokens Pipeline::encode(const AudioCodecRequest& request) { + if (!request.samples.data() || + 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( + "encodec requires exactly 6400 mono samples at 24000 Hz and two codebooks"); + if (!std::all_of(request.samples.begin(), request.samples.end(), + [](float x) { return std::isfinite(x); })) + throw std::invalid_argument("encodec 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("encodec 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 != config_.max_samples || + 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( + "encodec 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("encodec 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("encodec 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::encodec diff --git a/families/encodec/runtime/pipeline.h b/families/encodec/runtime/pipeline.h new file mode 100644 index 0000000000..ae00e5aba6 --- /dev/null +++ b/families/encodec/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::encodec { +struct Config { + int sample_rate{24000}, codebooks{2}, codebook_size{1024}, hop{320}, max_samples{6400}; + 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::encodec diff --git a/families/encodec/runtime/plugin.cpp b/families/encodec/runtime/plugin.cpp new file mode 100644 index 0000000000..7feb44f282 --- /dev/null +++ b/families/encodec/runtime/plugin.cpp @@ -0,0 +1,39 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + */ +#include "families/encodec/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("encodec 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("encodec 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 || json.at("samples") != 6400 || + json.at("frames") != 20) + throw std::invalid_argument("encodec unsupported runtime schema"); + trtmc::encodec::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::encodec::Pipeline(std::move(encoder_module), std::move(decoder_module), + std::move(config)); +} diff --git a/families/encodec/support.py b/families/encodec/support.py new file mode 100644 index 0000000000..5f3d0769e7 --- /dev/null +++ b/families/encodec/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=("encodec",), + architectures=("EncodecModel",), + tasks=("audio_codec",), + default_task="audio_codec", + default_precision="fp32", +) diff --git a/families/encodec/tests/__init__.py b/families/encodec/tests/__init__.py new file mode 100644 index 0000000000..52a7a9daf0 --- /dev/null +++ b/families/encodec/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/encodec/tests/cpp/e2e_consumer.cpp b/families/encodec/tests/cpp/e2e_consumer.cpp new file mode 100644 index 0000000000..23b595665c --- /dev/null +++ b/families/encodec/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: encodec_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("EnCodec 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 > 6400) + 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()}, 24000, 1, 0}); + auto audio = task->decode(codes); + if (audio.num_samples != count || audio.samples.size() != samples.size() || + audio.num_channels != 1 || audio.sample_rate != 24000) + throw std::runtime_error("EnCodec 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()}, 24000, 1, 2}); + if (codes.codes != first_codes.codes || + task->decode(codes).samples != first_audio.samples) + throw std::runtime_error("EnCodec request state leaked after rejection"); + }; + for (int mode = 0; mode < 7; ++mode) { + auto samples = first; + if (mode == 4) + samples.resize(6401); + if (mode == 5) + samples[0] = std::numeric_limits::quiet_NaN(); + trtmc::AudioCodecRequest request{{samples.data(), samples.size()}, 24000, 1, 0}; + if (mode == 0) + request.samples = {nullptr, samples.size()}; + if (mode == 1) + request.samples = {}; + if (mode == 2) + request.sample_rate = 8000; + 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("EnCodec 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 = 8000; + break; + case 4: + codes.frames = 0; + break; + case 5: + codes.frames = 21; + break; + case 6: + codes.audio_frames = 0; + break; + case 7: + codes.audio_frames = codes.frames * 320 + 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) * 320; + break; + } + bool rejected = false; + try { + (void)task->decode(codes); + } catch (const std::invalid_argument&) { + rejected = true; + } + if (!rejected) + throw std::runtime_error("EnCodec 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/encodec/tests/data/speech_16k_mono.wav b/families/encodec/tests/data/speech_16k_mono.wav new file mode 100644 index 0000000000..ba144817e6 Binary files /dev/null and b/families/encodec/tests/data/speech_16k_mono.wav differ diff --git a/families/encodec/tests/manifests/encodec-24khz.json b/families/encodec/tests/manifests/encodec-24khz.json new file mode 100644 index 0000000000..0827578100 --- /dev/null +++ b/families/encodec/tests/manifests/encodec-24khz.json @@ -0,0 +1,23 @@ +{ + "name": "encodec-24khz", + "hf_id": "facebook/encodec_24khz", + "hf_revision": "c1dbe2ae3f1de713481a3b3e7c47f357092ee040", + "family": "encodec", + "task": "audio_codec", + "precision": "fp32", + "tensor_parallel_size": 1, + "trust_remote_code": false, + "bundle": "encodec-24khz.bundle", + "testcases": [{ + "name": "encodec-24khz-fp32", + "premerge": true, + "reference_precision": "fp32", + "sample_rate": 24000, + "codebooks": 2, + "hop_length": 320, + "bandwidth": 1.5, + "waveform_atol": 0.0005, + "waveform_rtol": 0.0001, + "sample_lengths": [6400,6400,6400,6400,6400] + }] +} diff --git a/families/encodec/tests/math_check.py b/families/encodec/tests/math_check.py new file mode 100644 index 0000000000..604c97fa81 --- /dev/null +++ b/families/encodec/tests/math_check.py @@ -0,0 +1,104 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +"""Compare causal reflection, recurrent state, exact codebooks and decoder stages.""" + + +def check_stages(): + import torch + import tensorrt as trt + from transformers import EncodecConfig, EncodecModel + from families.encodec.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(367) + config = EncodecConfig( + hidden_size=8, + codebook_dim=8, + codebook_size=16, + num_filters=4, + num_lstm_layers=2, + upsampling_ratios=[2, 2], + kernel_size=3, + last_kernel_size=3, + residual_kernel_size=3, + target_bandwidths=[48.0], + sampling_rate=24000, + normalize=False, + chunk_length_s=None, + use_causal_conv=True, + norm_type="weight_norm", + ) + model = EncodecModel(config).eval() + with torch.no_grad(): + for layer in model.quantizer.layers: + layer.codebook.embed.normal_(0, 0.15) + 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(), 80, 2, mode, debug=True) + ) + assert engine is not None + return engine, engine.create_execution_context() + + def run(pair, inputs): + engine, context = pair + tensors = {k: v.cuda().contiguous() for k, v in inputs.items()} + 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(engine.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) + + encoder, decoder = make("encode"), make("decode") + model.cuda() + captured = {} + + def hook(name): + def capture(_m, _a, value): + captured[name] = value + + return capture + + for i, layer in enumerate(model.encoder.layers): + layer.register_forward_hook(hook(f"encoder_{i}")) + with torch.inference_mode(): + audio = torch.randn(1, 1, 80, device="cuda") * 0.2 + expected = model.encode(audio, bandwidth=48.0) + actual = run(encoder, {"input_values": audio[..., None]}) + for name, value in captured.items(): + compare(actual[name], value, name) + torch.testing.assert_close( + actual["audio_codes"], expected.audio_codes[0].cpu().to(torch.int32), atol=0, rtol=0 + ) + captured.clear() + for i, layer in enumerate(model.decoder.layers): + layer.register_forward_hook(hook(f"decoder_{i}")) + for seed in (42, 43): + codes = torch.randint( + 16, (1, 2, 20), generator=torch.Generator().manual_seed(seed) + ).cuda() + quantized = model.quantizer.decode(codes.transpose(0, 1)) + expected = model.decode(codes[None], audio_scales=[None]).audio_values[:, 0] + actual = run(decoder, {"audio_codes": codes.to(torch.int32)}) + compare(actual["quantized"], quantized, f"quantized-{seed}") + for name, value in captured.items(): + compare(actual[name], value, f"{name}-{seed}") + compare(actual["audio_values"], expected, f"waveform-{seed}") diff --git a/families/encodec/tests/requirements.txt b/families/encodec/tests/requirements.txt new file mode 100644 index 0000000000..715f66eb6f --- /dev/null +++ b/families/encodec/tests/requirements.txt @@ -0,0 +1,3 @@ +torch>=2.12 +transformers==5.3.0 +pytest>=8 diff --git a/families/encodec/tests/test_e2e.py b/families/encodec/tests/test_e2e.py new file mode 100644 index 0000000000..e2a80b4c32 --- /dev/null +++ b/families/encodec/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 ENCODEC 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/encodec-24khz.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({"encodec", MANIFEST["name"], case["name"]}): + continue + if cases and case["name"] not in cases: + continue + marks = [] if selected else [pytest.mark.skip(reason="select ENCODEC 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_ENCODEC_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}));