diff --git a/families/vits/README.md b/families/vits/README.md new file mode 100644 index 0000000000..41b281946d --- /dev/null +++ b/families/vits/README.md @@ -0,0 +1,39 @@ +# English MMS-TTS + +This family builds `facebook/mms-tts-eng` revision +`c71de0fe7204c83f1c10820a7d696d0b450048ba` for the public `TextToSpeech` +Task. The selected profile uses FP32, batch size one, tensor parallel size one, +128 character/blank tokens, and at most 1024 acoustic frames. Output is mono +16 kHz float PCM. The published speaking rate and noise scales remain fixed. + +The conditioning engine owns the relative-position text encoder and stochastic +duration predictor, including its inverse rational-quadratic splines. A second +engine owns prior sampling, residual coupling flows, and HiFi-GAN synthesis. +Its frame dimension is dynamic, so padding cannot leak into waveform edges. +All model math runs through TensorRT. The native runtime owns character +normalization, seeded CPU noise, duration alignment, and request validation. + +The `seed` configuration field defaults to zero. Repeated requests reset both +noise draws to the same request-local stream. The selected checkpoint supports +English; language may be absent, `en`, or `eng`. Empty normalized text and text +or predicted durations beyond the bundle capacities are rejected. + +Install `requirements.txt` and `tests/requirements.txt`. Native builds require +ICU development headers and libraries. Build `trtmc_model_vits`, `vits_e2e`, +`vits_tokenizer`, and `vits_noise`. Set `TRTMC_RUNTIME_ROOT` to the build directory +and `TRTMC_VITS_MODEL_DIR` to the pinned local checkpoint. + +```bash +PYTHONPATH=core/builder:apps/benchmark:. python3 -m tools.model_ci validate +PYTHONPATH=core/builder:apps/benchmark:. python3 -m pytest \ + families/vits/tests --e2e-model vits -q +``` + +The selected test uses unmodified Transformers 5.3.0 and Torch 2.12 CPU FP32 as +the oracle. Small-model conditioning, durations, flows, and waveforms must match +at absolute/relative tolerance `5e-5`, with exact integer durations. The real +checkpoint must match all sample counts and its waveform at absolute tolerance +`5e-4` and relative tolerance `1e-4`. Tests cover multiple texts, seeds, dynamic +lengths, repeated requests, and recovery after invalid input. Native token IDs +must match the upstream tokenizer exactly; CPU normal samples are checked at +absolute/relative tolerance `2e-6` across scalar, vector, and tail lengths. diff --git a/families/vits/__init__.py b/families/vits/__init__.py new file mode 100644 index 0000000000..e487dc550f --- /dev/null +++ b/families/vits/__init__.py @@ -0,0 +1,4 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""VITS text-to-speech family ownership boundary.""" diff --git a/families/vits/model.py b/families/vits/model.py new file mode 100644 index 0000000000..571ea7a6bd --- /dev/null +++ b/families/vits/model.py @@ -0,0 +1,642 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +"""VITS text conditioning, stochastic durations, residual flows, and HiFi-GAN.""" + +import json +import math +from pathlib import Path + +import numpy as np +import tensorrt as trt + + +class Graph: + def __init__(self, network, config, weights, capacity): + self.n, self.c, self.w, self.capacity = network, config, weights, capacity + self.constants = [] + + def constant(self, value, dtype=np.float32): + value = np.array(value, dtype=dtype, order="C") + self.constants.append(value) + return self.n.add_constant(value.shape, trt.Weights(value)).get_output(0) + + def binary(self, x, y, op=trt.ElementWiseOperation.SUM): + if isinstance(y, (float, int)): + y = self.constant(np.full((1,) * len(x.shape), y)) + return self.n.add_elementwise(x, y, op).get_output(0) + + def add(self, x, y): + return self.binary(x, y) + + def sub(self, x, y): + return self.binary(x, y, trt.ElementWiseOperation.SUB) + + def mul(self, x, y): + return self.binary(x, y, trt.ElementWiseOperation.PROD) + + def div(self, x, y): + return self.binary(x, y, trt.ElementWiseOperation.DIV) + + def unary(self, x, op): + return self.n.add_unary(x, op).get_output(0) + + def reshape(self, x, shape, transpose=None): + layer = self.n.add_shuffle(x) + layer.reshape_dims = shape + if transpose is not None: + layer.second_transpose = transpose + return layer.get_output(0) + + def concat(self, values, axis): + layer = self.n.add_concatenation(values) + layer.axis = axis + return layer.get_output(0) + + def slice(self, x, start, size): + return self.n.add_slice(x, start, size, (1,) * len(size)).get_output(0) + + def channels(self, x, first, count): + length = x.shape[2] + layer = self.n.add_slice(x, (0, first, 0), (1, count, max(length, 1)), (1, 1, 1)) + if length < 0: + shape = self.n.add_shape(x).get_output(0) + length_tensor = self.n.add_gather(shape, self.constant([2], np.int32), 0).get_output(0) + layer.set_input(2, self.concat([self.constant([1, count], np.int64), length_tensor], 0)) + return layer.get_output(0) + + def output(self, x, name): + x.name = name + self.n.mark_output(x) + + def activation(self, x, kind, alpha=None): + if kind == trt.ActivationType.LEAKY_RELU: + # Preserve the reference's comparison and negative-branch multiply. + positive = self.binary(x, 0, trt.ElementWiseOperation.GREATER) + return self.n.add_select(positive, x, self.mul(x, alpha)).get_output(0) + layer = self.n.add_activation(x, kind) + if alpha is not None: + layer.alpha = alpha + return layer.get_output(0) + + def gelu(self, x): + erf = self.unary(self.div(x, math.sqrt(2)), trt.UnaryOperation.ERF) + return self.mul(self.mul(x, 0.5), self.add(erf, 1)) + + def norm(self, x, name, epsilon=1e-5): + mean = self.n.add_reduce(x, trt.ReduceOperation.AVG, 2, True).get_output(0) + centered = self.sub(x, mean) + variance = self.n.add_reduce( + self.mul(centered, centered), trt.ReduceOperation.AVG, 2, True + ).get_output(0) + normalized = self.div( + centered, self.unary(self.add(variance, epsilon), trt.UnaryOperation.SQRT) + ) + normalized = self.mul(normalized, self.constant(self.w[name + ".weight"].reshape(1, -1, 1))) + return self.add(normalized, self.constant(self.w[name + ".bias"].reshape(1, -1, 1))) + + def linear(self, x, name): + width, length = x.shape[1], x.shape[2] + values = self.reshape(x, (width, length), (1, 0)) + values = self.n.add_matrix_multiply( + values, + trt.MatrixOperation.NONE, + self.constant(self.w[name + ".weight"]), + trt.MatrixOperation.TRANSPOSE, + ).get_output(0) + if name + ".bias" in self.w: + values = self.add(values, self.constant(self.w[name + ".bias"].reshape(1, -1))) + out = self.w[name + ".weight"].shape[0] + return self.reshape(values, (1, length, out), (0, 2, 1)) + + def conv(self, x, name, dilation=1, groups=1, stride=1, transpose=False, padding=None): + weights = self.w[name + ".weight"] + length, kernel = x.shape[2], weights.shape[-1] + inputs = self.reshape(x, (1, x.shape[1], length, 1)) + output_channels = weights.shape[1] * groups if transpose else weights.shape[0] + bias = self.w.get(name + ".bias", np.zeros(output_channels, np.float32)) + self.constants.append(bias) + operation = self.n.add_deconvolution_nd if transpose else self.n.add_convolution_nd + layer = operation( + inputs, + output_channels, + (kernel, 1), + trt.Weights(weights.reshape(*weights.shape, 1)), + trt.Weights(bias), + ) + layer.num_groups = groups + layer.stride_nd = (stride, 1) + layer.padding_nd = ( + ((kernel - stride) // 2 if transpose else (kernel - 1) * dilation // 2) + if padding is None + else padding, + 0, + ) + if not transpose: + layer.dilation_nd = (dilation, 1) + result = layer.get_output(0) + return self.reshape(result, (1, output_channels, -1)) + + def attention(self, x, mask, name): + c, length = self.c, self.capacity + heads, width = c["num_attention_heads"], c["hidden_size"] + dim = width // heads + q = self.mul(self.linear(x, name + ".q_proj"), dim**-0.5) + k, v = (self.linear(x, name + "." + part + "_proj") for part in ("k", "v")) + + def split(value): + value = self.reshape(value, (width, length), (1, 0)) + return self.reshape(value, (length, heads, dim), (1, 0, 2)) + + q, k, v = split(q), split(k), split(v) + scores = self.n.add_matrix_multiply( + q, trt.MatrixOperation.NONE, k, trt.MatrixOperation.TRANSPOSE + ).get_output(0) + window = c["window_size"] + + def relative(kind): + value = self.w[name + ".emb_rel_" + kind] + pad = max(length - window - 1, 0) + value = np.pad(value, ((0, 0), (pad, pad), (0, 0))) + first = max(window + 1 - length, 0) + return self.constant(value[:, first : first + 2 * length - 1]) + + relative_scores = self.n.add_matrix_multiply( + q, trt.MatrixOperation.NONE, relative("k"), trt.MatrixOperation.TRANSPOSE + ).get_output(0) + relative_scores = self.concat( + [relative_scores, self.constant(np.zeros((heads, length, 1)))], 2 + ) + relative_scores = self.reshape(relative_scores, (heads, length * 2 * length)) + relative_scores = self.concat( + [relative_scores, self.constant(np.zeros((heads, length - 1)))], 1 + ) + relative_scores = self.reshape(relative_scores, (heads, length + 1, 2 * length - 1)) + scores = self.add( + scores, self.slice(relative_scores, (0, 0, length - 1), (heads, length, length)) + ) + inactive = self.binary(mask, 0, trt.ElementWiseOperation.EQUAL) + attention_mask = self.n.add_select( + inactive, + self.constant(np.full((1, 1, length), np.finfo(np.float32).min)), + self.constant(np.zeros((1, 1, length))), + ).get_output(0) + softmax = self.n.add_softmax(self.add(scores, attention_mask)) + softmax.axes = 4 + probabilities = softmax.get_output(0) + output = self.n.add_matrix_multiply( + probabilities, trt.MatrixOperation.NONE, v, trt.MatrixOperation.NONE + ).get_output(0) + relative_probabilities = self.concat( + [probabilities, self.constant(np.zeros((heads, length, length - 1)))], 2 + ) + relative_probabilities = self.reshape( + relative_probabilities, (heads, length * (2 * length - 1)) + ) + relative_probabilities = self.concat( + [self.constant(np.zeros((heads, length))), relative_probabilities], 1 + ) + relative_probabilities = self.reshape(relative_probabilities, (heads, length, 2 * length)) + relative_probabilities = self.slice( + relative_probabilities, (0, 0, 1), (heads, length, 2 * length - 1) + ) + relative_output = self.n.add_matrix_multiply( + relative_probabilities, + trt.MatrixOperation.NONE, + relative("v"), + trt.MatrixOperation.NONE, + ).get_output(0) + output = self.add(output, relative_output) + output = self.reshape(output, (heads, length, dim), (1, 0, 2)) + output = self.reshape(output, (1, length, width), (0, 2, 1)) + return self.linear(output, name + ".out_proj") + + def text_encoder(self, ids, mask): + c, length = self.c, self.capacity + embeddings = self.n.add_gather( + self.constant(self.w["text_encoder.embed_tokens.weight"]), ids, 0 + ).get_output(0) + hidden = self.reshape(embeddings, (1, length, c["hidden_size"]), (0, 2, 1)) + hidden = self.mul(self.mul(hidden, math.sqrt(c["hidden_size"])), mask) + for index in range(c["num_hidden_layers"]): + prefix = f"text_encoder.encoder.layers.{index}" + hidden = self.norm( + self.add(hidden, self.attention(hidden, mask, prefix + ".attention")), + prefix + ".layer_norm", + c["layer_norm_eps"], + ) + feed = self.conv(self.mul(hidden, mask), prefix + ".feed_forward.conv_1") + feed = self.activation(feed, trt.ActivationType.RELU) + feed = self.mul(self.conv(self.mul(feed, mask), prefix + ".feed_forward.conv_2"), mask) + hidden = self.norm( + self.add(hidden, feed), prefix + ".final_layer_norm", c["layer_norm_eps"] + ) + hidden = self.mul(hidden, mask) + stats = self.mul(self.conv(hidden, "text_encoder.project"), mask) + means, logs = (self.channels(stats, first, c["flow_size"]) for first in (0, c["flow_size"])) + return hidden, means, logs + + def dds(self, x, mask, name, condition=None): + if condition is not None: + x = self.add(x, condition) + for index in range(self.c["depth_separable_num_layers"]): + hidden = self.conv( + self.mul(x, mask), + name + f".convs_dilated.{index}", + dilation=self.c["duration_predictor_kernel_size"] ** index, + groups=self.c["hidden_size"], + ) + hidden = self.gelu(self.norm(hidden, name + f".norms_1.{index}")) + hidden = self.conv(hidden, name + f".convs_pointwise.{index}") + hidden = self.gelu(self.norm(hidden, name + f".norms_2.{index}")) + x = self.add(x, hidden) + return self.mul(x, mask) + + def columns(self, x, first, count): + return self.slice(x, (0, first), (self.capacity, count)) + + def spline_inverse(self, inputs, parameters): + bins, tail, length = ( + self.c["duration_predictor_flow_bins"], + self.c["duration_predictor_tail_bound"], + self.capacity, + ) + parameters = self.reshape(parameters, (3 * bins - 1, length), (1, 0)) + widths = self.div(self.columns(parameters, 0, bins), math.sqrt(self.c["hidden_size"])) + heights = self.div(self.columns(parameters, bins, bins), math.sqrt(self.c["hidden_size"])) + derivatives = self.columns(parameters, 2 * bins, bins - 1) + boundary = self.constant(np.full((length, 1), np.log(np.expm1(1 - 1e-3)))) + derivatives = self.concat([boundary, derivatives, boundary], 1) + softplus = self.n.add_activation(derivatives, trt.ActivationType.SOFTPLUS) + softplus.alpha = softplus.beta = 1.0 + derivatives = self.add(softplus.get_output(0), 1e-3) + lower = self.constant(np.full((length, 1), -tail)) + upper = self.constant(np.full((length, 1), tail)) + + def cumulative(values): + probabilities = self.n.add_softmax(values) + probabilities.axes = 2 + values = self.add(self.mul(probabilities.get_output(0), 1 - 1e-3 * bins), 1e-3) + total = self.n.add_cumulative( + values, self.constant(1, np.int32), trt.CumulativeOperation.SUM, False, False + ).get_output(0) + total = self.add(self.mul(total, 2 * tail), -tail) + return self.concat([lower, self.columns(total, 0, bins - 1), upper], 1) + + cumwidths, cumheights = cumulative(widths), cumulative(heights) + widths = self.sub(self.columns(cumwidths, 1, bins), self.columns(cumwidths, 0, bins)) + heights = self.sub(self.columns(cumheights, 1, bins), self.columns(cumheights, 0, bins)) + original = self.reshape(inputs, (length, 1)) + inside = self.binary( + self.binary(original, -tail, trt.ElementWiseOperation.GREATER), + self.binary(original, tail, trt.ElementWiseOperation.LESS), + trt.ElementWiseOperation.AND, + ) + # Evaluate the inverse at the first valid knot for identity-tail inputs. + safe = self.n.add_select(inside, original, lower).get_output(0) + lows = self.columns(cumheights, 0, bins) + highs = self.columns(cumheights, 1, bins) + above = self.unary( + self.binary(safe, lows, trt.ElementWiseOperation.LESS), trt.UnaryOperation.NOT + ) + below = self.binary(safe, highs, trt.ElementWiseOperation.LESS) + chosen = self.binary(above, below, trt.ElementWiseOperation.AND) + chosen = self.n.add_cast(chosen, trt.float32).get_output(0) + + def select(values): + return self.n.add_reduce( + self.mul(values, chosen), trt.ReduceOperation.SUM, 2, True + ).get_output(0) + + start_x = select(self.columns(cumwidths, 0, bins)) + start_y = select(lows) + width = select(widths) + height = select(heights) + delta = select(self.div(heights, widths)) + first_d = select(self.columns(derivatives, 0, bins)) + last_d = select(self.columns(derivatives, 1, bins)) + intermediate1 = self.sub(self.add(first_d, last_d), self.mul(delta, 2)) + intermediate2 = self.sub(safe, start_y) + intermediate3 = self.mul(intermediate2, intermediate1) + a = self.add(self.mul(height, self.sub(delta, first_d)), intermediate3) + b = self.sub(self.mul(height, first_d), intermediate3) + c = self.mul(self.unary(delta, trt.UnaryOperation.NEG), intermediate2) + discriminant = self.sub(self.mul(b, b), self.mul(self.mul(a, 4), c)) + root = self.div( + self.mul(c, 2), + self.sub( + self.unary(b, trt.UnaryOperation.NEG), + self.unary(discriminant, trt.UnaryOperation.SQRT), + ), + ) + output = self.add(self.mul(root, width), start_x) + output = self.n.add_select(inside, output, original).get_output(0) + return self.reshape(output, (1, 1, length)) + + def duration_predictor(self, hidden, mask, noise): + prefix = "duration_predictor" + condition = self.conv(hidden, prefix + ".conv_pre") + condition = self.dds(condition, mask, prefix + ".conv_dds") + condition = self.mul(self.conv(condition, prefix + ".conv_proj"), mask) + latents = self.mul(noise, self.c["noise_scale_duration"]) + flows = list(range(self.c["duration_predictor_num_flows"], 0, -1)) + # The published reverse path omits the first convolutional flow. + for index in flows[:-1]: + latents = self.concat([self.channels(latents, 1, 1), self.channels(latents, 0, 1)], 1) + first, second = self.channels(latents, 0, 1), self.channels(latents, 1, 1) + name = prefix + f".flows.{index}" + params = self.conv(first, name + ".conv_pre") + params = self.dds(params, mask, name + ".conv_dds", condition) + params = self.mul(self.conv(params, name + ".conv_proj"), mask) + second = self.spline_inverse(second, params) + latents = self.mul(self.concat([first, second], 1), mask) + latents = self.concat([self.channels(latents, 1, 1), self.channels(latents, 0, 1)], 1) + translate = self.constant(self.w[prefix + ".flows.0.translate"].reshape(1, 2, 1)) + scale = self.unary( + self.constant(-self.w[prefix + ".flows.0.log_scale"].reshape(1, 2, 1)), + trt.UnaryOperation.EXP, + ) + latents = self.mul(self.mul(self.sub(latents, translate), scale), mask) + return self.channels(latents, 0, 1) + + def wavenet(self, inputs, mask, name): + width = self.c["hidden_size"] + output = None + layers = self.c["prior_encoder_num_wavenet_layers"] + for index in range(layers): + hidden = self.conv( + inputs, + name + f".in_layers.{index}", + dilation=self.c["wavenet_dilation_rate"] ** index, + ) + acts = self.mul( + self.activation(self.channels(hidden, 0, width), trt.ActivationType.TANH), + self.activation(self.channels(hidden, width, width), trt.ActivationType.SIGMOID), + ) + acts = self.conv(acts, name + f".res_skip_layers.{index}") + if index + 1 < layers: + inputs = self.mul(self.add(inputs, self.channels(acts, 0, width)), mask) + acts = self.channels(acts, width, width) + output = acts if output is None else self.add(output, acts) + return self.mul(output, mask) + + def prior_flow(self, latents, mask): + half = self.c["flow_size"] // 2 + for index in reversed(range(self.c["prior_encoder_num_flows"])): + # The source flips the complete channel axis, including each half. + reverse_indices = self.constant(np.arange(self.c["flow_size"] - 1, -1, -1), np.int32) + latents = self.n.add_gather(latents, reverse_indices, 1).get_output(0) + first, second = self.channels(latents, 0, half), self.channels(latents, half, half) + prefix = f"flow.flows.{index}" + hidden = self.mul(self.conv(first, prefix + ".conv_pre"), mask) + hidden = self.wavenet(hidden, mask, prefix + ".wavenet") + mean = self.mul(self.conv(hidden, prefix + ".conv_post"), mask) + second = self.mul(self.sub(second, mean), mask) + latents = self.concat([first, second], 1) + return latents + + def vocoder(self, x): + c = self.c + x = self.conv(x, "decoder.conv_pre") + kernels = len(c["resblock_kernel_sizes"]) + for index, stride in enumerate(c["upsample_rates"]): + x = self.activation(x, trt.ActivationType.LEAKY_RELU, c["leaky_relu_slope"]) + x = self.conv(x, f"decoder.upsampler.{index}", stride=stride, transpose=True) + total = None + for block in range(kernels): + hidden = x + prefix = f"decoder.resblocks.{index * kernels + block}" + for layer, dilation in enumerate(c["resblock_dilation_sizes"][block]): + residual = hidden + hidden = self.activation( + hidden, trt.ActivationType.LEAKY_RELU, c["leaky_relu_slope"] + ) + hidden = self.conv(hidden, prefix + f".convs1.{layer}", dilation=dilation) + hidden = self.activation( + hidden, trt.ActivationType.LEAKY_RELU, c["leaky_relu_slope"] + ) + hidden = self.conv(hidden, prefix + f".convs2.{layer}") + hidden = self.add(hidden, residual) + total = hidden if total is None else self.add(total, hidden) + x = self.div(total, kernels) + x = self.activation(x, trt.ActivationType.LEAKY_RELU, 0.01) + return self.activation(self.conv(x, "decoder.conv_post"), trt.ActivationType.TANH) + + +def load_weights(root): + import torch + from transformers import VitsModel + + model, info = VitsModel.from_pretrained( + root, + dtype=torch.float32, + trust_remote_code=False, + use_safetensors=True, + output_loading_info=True, + ) + if info.get("missing_keys") or info.get("mismatched_keys") or info.get("error_msgs"): + raise ValueError("vits checkpoint has missing or mismatched model tensors") + weights = { + name: value.detach().float().cpu().numpy() + for name, value in model.named_parameters() + if ".parametrizations." not in name + } + # Materialize the published CPU weight-normalization parametrizations once. + for name, module in model.named_modules(): + if isinstance(module, (torch.nn.Conv1d, torch.nn.ConvTranspose1d)): + weights[name + ".weight"] = module.weight.detach().float().cpu().numpy() + return weights + + +def compile_engine(config, weights, capacity, mode, verbose=False): + logger = trt.Logger(trt.Logger.VERBOSE if verbose else trt.Logger.WARNING) + builder = trt.Builder(logger) + network = builder.create_network(0) + graph = Graph(network, config, weights, capacity) + if mode == "conditioning": + ids = network.add_input("input_ids", trt.int32, (1, capacity)) + mask = network.add_input("input_mask", trt.float32, (1, 1, capacity)) + noise = network.add_input("duration_noise", trt.float32, (1, 2, capacity)) + hidden, means, logs = graph.text_encoder(ids, mask) + log_duration = graph.duration_predictor(hidden, mask, noise) + durations = graph.unary( + graph.mul( + graph.mul(graph.unary(log_duration, trt.UnaryOperation.EXP), mask), + 1 / config["speaking_rate"], + ), + trt.UnaryOperation.CEIL, + ) + for tensor, name in ( + (hidden, "hidden"), + (means, "prior_means"), + (logs, "prior_logs"), + (log_duration, "log_duration"), + (durations, "durations"), + ): + graph.output(tensor, name) + elif mode == "synthesis": + channels = config["flow_size"] + means = network.add_input("means", trt.float32, (1, channels, -1)) + logs = network.add_input("logs", trt.float32, (1, channels, -1)) + noise = network.add_input("noise", trt.float32, (1, channels, -1)) + mask = network.add_input("output_mask", trt.float32, (1, 1, -1)) + for tensor in (means, logs, noise, mask): + tensor.set_dimension_name(2, "frames") + latents = graph.add( + means, + graph.mul( + graph.mul(noise, graph.unary(logs, trt.UnaryOperation.EXP)), config["noise_scale"] + ), + ) + spectrogram = graph.mul(graph.prior_flow(latents, mask), mask) + graph.output(spectrogram, "spectrogram") + graph.output(graph.vocoder(spectrogram), "waveform") + else: + raise ValueError("vits unknown engine stage") + options = builder.create_builder_config() + options.builder_optimization_level = 3 + options.clear_flag(trt.BuilderFlag.TF32) + if mode == "synthesis": + profile = builder.create_optimization_profile() + for name, width in ( + ("means", channels), + ("logs", channels), + ("noise", channels), + ("output_mask", 1), + ): + profile.set_shape(name, (1, width, 1), (1, width, 128), (1, width, 1024)) + options.add_optimization_profile(profile) + plan = builder.build_serialized_network(network, options) + if plan is None: + raise RuntimeError("vits TensorRT engine build failed") + return bytes(plan) + + +def validate_config(config): + if config.get("model_type") != "vits" or config.get("hidden_act") != "relu": + raise ValueError("vits requires the VITS ReLU text encoder") + if config.get("num_speakers") != 1 or config.get("speaker_embedding_size") != 0: + raise ValueError("vits selected profile supports one unconditioned speaker") + if ( + not config.get("use_stochastic_duration_prediction") + or config.get("depth_separable_channels") != 2 + ): + raise ValueError("vits requires the two-channel stochastic duration predictor") + for name in ( + "hidden_size", + "flow_size", + "num_hidden_layers", + "num_attention_heads", + "ffn_dim", + "vocab_size", + "window_size", + "prior_encoder_num_flows", + "prior_encoder_num_wavenet_layers", + "duration_predictor_num_flows", + "depth_separable_num_layers", + "sampling_rate", + ): + if not isinstance(config.get(name), int) or config[name] <= 0: + raise ValueError(f"vits invalid {name}") + if config["hidden_size"] % config["num_attention_heads"] or config["flow_size"] % 2: + raise ValueError("vits invalid attention or coupling channel geometry") + for name in ("ffn_kernel_size", "wavenet_kernel_size", "duration_predictor_kernel_size"): + if config[name] <= 0 or config[name] % 2 != 1: + raise ValueError("vits requires odd same-padding convolution kernels") + if not 2 <= config["duration_predictor_flow_bins"] < 1000: + raise ValueError("vits invalid spline bin count") + for name in ( + "noise_scale", + "noise_scale_duration", + "speaking_rate", + "duration_predictor_tail_bound", + "layer_norm_eps", + ): + if not math.isfinite(config[name]) or config[name] <= 0: + raise ValueError(f"vits invalid {name}") + if len(config["upsample_rates"]) != len(config["upsample_kernel_sizes"]): + raise ValueError("vits mismatched vocoder stages") + for rate, kernel in zip(config["upsample_rates"], config["upsample_kernel_sizes"]): + if rate <= 0 or kernel < rate or (kernel - rate) % 2: + raise ValueError("vits invalid transpose-convolution geometry") + if not config["resblock_kernel_sizes"]: + raise ValueError("vits requires at least one vocoder residual block") + if len(config["resblock_kernel_sizes"]) != len(config["resblock_dilation_sizes"]): + raise ValueError("vits mismatched vocoder residual blocks") + if any(kernel <= 0 or kernel % 2 != 1 for kernel in config["resblock_kernel_sizes"]): + raise ValueError("vits requires odd residual convolution kernels") + return config + + +def tokenizer_vocabulary(root): + tokenizer = json.loads((root / "tokenizer_config.json").read_text()) + expected = { + "language": "eng", + "is_uroman": False, + "phonemize": False, + "add_blank": True, + "normalize": True, + "pad_token": "k", + } + if any(tokenizer.get(name) != value for name, value in expected.items()): + raise ValueError("vits requires the published English MMS character normalization") + vocab = json.loads((root / "vocab.json").read_text()) + if ( + not isinstance(vocab, dict) + or len(vocab) != 38 + or "" in vocab + or any(type(token_id) is not int for token_id in vocab.values()) + or set(vocab.values()) != set(range(38)) + or vocab.get("k") != 0 + or " " not in vocab + ): + raise ValueError("vits invalid English MMS vocabulary") + return vocab + + +def build(request, writer): + if request.dynamic_kv_cache: + raise NotImplementedError("vits does not support dynamic_kv_cache") + if request.task != "text_to_speech" or request.precision != "fp32" or request.backend != "trt": + raise ValueError("vits requires text_to_speech, precision=fp32, backend=trt") + for field, value, default in ( + ("max_batch_size", request.max_batch_size, 1), + ("tensor_parallel_size", request.tensor_parallel_size, 1), + ("context_parallel_size", request.context_parallel_size, 1), + ("image_height", request.image_height, None), + ("image_width", request.image_width, None), + ("video_num_frames", request.video_num_frames, None), + ("mtp_seq_len", request.mtp_seq_len, None), + ("fp32_layers", request.fp32_layers, ()), + ): + if value != default: + raise NotImplementedError(f"vits does not support {field}") + if request.quantization not in (None, "none"): + raise NotImplementedError("vits does not support quantization") + root = Path(request.model_dir) + from transformers import VitsConfig + + config = validate_config(VitsConfig.from_pretrained(root, trust_remote_code=False).to_dict()) + capacity = request.max_sequence_length or 128 + if not 3 <= capacity <= 512: + raise ValueError("vits token capacity must be between 3 and 512") + vocab = tokenizer_vocabulary(root) + weights = load_weights(root) + if max(vocab.values()) >= weights["text_encoder.embed_tokens.weight"].shape[0]: + raise ValueError("vits tokenizer ID exceeds the checkpoint embedding table") + writer.set_header(family="vits", task=request.task, backend=request.backend) + for mode in ("conditioning", "synthesis"): + writer.add_bytes( + mode + ".plan", compile_engine(config, weights, capacity, mode, request.verbose) + ) + writer.add_json("tokenizer.json", vocab) + writer.add_json( + "runtime.json", + { + "schema_version": 1, + "token_capacity": capacity, + "flow_size": config["flow_size"], + "max_frames": 1024, + "sample_rate": config["sampling_rate"], + "upsample_factor": math.prod(config["upsample_rates"]), + }, + ) diff --git a/families/vits/requirements.txt b/families/vits/requirements.txt new file mode 100644 index 0000000000..74d712252a --- /dev/null +++ b/families/vits/requirements.txt @@ -0,0 +1,3 @@ +transformers==5.3.0 +safetensors>=0.5 +torch>=2.6 diff --git a/families/vits/runtime/CMakeLists.txt b/families/vits/runtime/CMakeLists.txt new file mode 100644 index 0000000000..72e76b0b9d --- /dev/null +++ b/families/vits/runtime/CMakeLists.txt @@ -0,0 +1,32 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +find_package(ICU REQUIRED COMPONENTS uc i18n) +add_library(trtmc_model_vits SHARED pipeline.cpp plugin.cpp tokenizer.cpp) +target_include_directories(trtmc_model_vits PRIVATE + ${PROJECT_SOURCE_DIR} ${PROJECT_SOURCE_DIR}/core/runtime/include) +target_include_directories(trtmc_model_vits SYSTEM PRIVATE ${TRTMC_CUDA_INCLUDE_DIR}) +target_link_libraries(trtmc_model_vits PRIVATE + trtmc_core nlohmann_json::nlohmann_json ICU::uc ICU::i18n ${TRTMC_CUDART_LIBRARY}) +target_compile_options(trtmc_model_vits PRIVATE -Wall -Wextra -Wpedantic) +set_target_properties(trtmc_model_vits PROPERTIES + LIBRARY_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}" + BUILD_RPATH "\$ORIGIN" INSTALL_RPATH "\$ORIGIN") +install(TARGETS trtmc_model_vits LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR}) + +if(TRTMC_BUILD_TESTS) + add_executable(vits_e2e ${PROJECT_SOURCE_DIR}/families/vits/tests/cpp/e2e_consumer.cpp) + target_include_directories(vits_e2e PRIVATE ${PROJECT_SOURCE_DIR}) + target_link_libraries(vits_e2e PRIVATE trtmc_c nlohmann_json::nlohmann_json) + set_target_properties(vits_e2e PROPERTIES RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}") + + add_executable(vits_tokenizer ${PROJECT_SOURCE_DIR}/families/vits/tests/cpp/tokenizer_consumer.cpp tokenizer.cpp) + target_include_directories(vits_tokenizer PRIVATE ${PROJECT_SOURCE_DIR}) + target_link_libraries(vits_tokenizer PRIVATE nlohmann_json::nlohmann_json ICU::uc ICU::i18n) + set_target_properties(vits_tokenizer PROPERTIES RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}") + + add_executable(vits_noise ${PROJECT_SOURCE_DIR}/families/vits/tests/cpp/noise_consumer.cpp) + target_include_directories(vits_noise PRIVATE ${PROJECT_SOURCE_DIR}) + target_link_libraries(vits_noise PRIVATE nlohmann_json::nlohmann_json) + set_target_properties(vits_noise PROPERTIES RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}") +endif() diff --git a/families/vits/runtime/noise.h b/families/vits/runtime/noise.h new file mode 100644 index 0000000000..e9e8c53923 --- /dev/null +++ b/families/vits/runtime/noise.h @@ -0,0 +1,93 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + */ +#pragma once + +#include +#include +#include +#include +#include +#include +#include + +namespace trtmc::vits { + +// Seeded CPU float-normal stream used by the declared upstream reference. +// Short requests retain a double Box-Muller spare. Contiguous requests of at +// least sixteen values transform blocks of eight pairs and redraw the tail. +class Noise { + public: + explicit Noise(std::uint64_t seed) : engine_(static_cast(seed)) {} + + std::vector normal(std::size_t count) { + std::vector result(count); + if (count < 16) { + for (auto& value : result) + value = scalar(); + return result; + } + for (auto& value : result) + value = uniform_float(); + for (std::size_t offset = 0; offset + 16 <= count; offset += 16) + transform(result.data() + offset); + if (count % 16) { + auto* tail = result.data() + count - 16; + for (std::size_t i = 0; i < 16; ++i) + tail[i] = uniform_float(); + transform(tail); + } + return result; + } + + std::vector transposed_normal(std::size_t channels, std::size_t frames) { + if (channels == 0 || frames == 0) + return {}; + if (frames > std::numeric_limits::max() / channels) + throw std::length_error("vits transposed noise sample count overflows"); + const auto count = channels * frames; + if (channels == 1 || frames == 1) + return normal(count); + // randn_like preserves the expanded prior's transposed (frame, channel) + // storage. The CPU noncontiguous path uses scalar double normal pairs. + std::vector result(count); + for (std::size_t frame = 0; frame < frames; ++frame) + for (std::size_t channel = 0; channel < channels; ++channel) + result[channel * frames + frame] = scalar(); + return result; + } + + private: + float uniform_float() { + return static_cast(engine_() & 0xffffffU) * (1.0F / 16777216.0F); + } + double uniform_double() { + const std::uint64_t high = engine_(), low = engine_(); + return static_cast(((high << 32) | low) & 0x1fffffffffffffULL) * + (1.0 / 9007199254740992.0); + } + float scalar() { + if (spare_) { + const auto value = *spare_; + spare_.reset(); + return static_cast(value); + } + const auto angle_uniform = uniform_double(), radius_uniform = uniform_double(); + const double radius = std::sqrt(-2.0 * std::log1p(-radius_uniform)); + const double theta = 6.2831853071795864769 * angle_uniform; + spare_ = radius * std::sin(theta); + return static_cast(radius * std::cos(theta)); + } + static void transform(float* values) { + for (std::size_t i = 0; i < 8; ++i) { + const float radius = std::sqrt(-2.0F * std::log(1.0F - values[i])); + const float theta = 6.2831853071795864769F * values[i + 8]; + values[i] = radius * std::cos(theta); + values[i + 8] = radius * std::sin(theta); + } + } + std::mt19937 engine_; + std::optional spare_; +}; +} // namespace trtmc::vits diff --git a/families/vits/runtime/pipeline.cpp b/families/vits/runtime/pipeline.cpp new file mode 100644 index 0000000000..803dd4c61f --- /dev/null +++ b/families/vits/runtime/pipeline.cpp @@ -0,0 +1,185 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + */ +#include "families/vits/runtime/pipeline.h" + +#include "families/vits/runtime/noise.h" + +#include +#include +#include +#include + +namespace trtmc::vits { +namespace { +const internal::ConfigField kFields[] = { + {"seed", internal::ConfigKind::I64, internal::ConfigValue{std::int64_t{0}}, + "Nonnegative seed for the request-local CPU normal stream."}, +}; +Span fields() { + return {kFields, 1}; +} + +Tensor tensor(void* data, std::vector shape, DType dtype = DType::kFloat32) { + Tensor value; + value.data = data; + value.shape = std::move(shape); + value.dtype = dtype; + return value; +} + +std::vector output(const TensorMap& outputs, const std::string& name, + const std::vector& shape) { + const auto found = outputs.find(name); + if (found == outputs.end() || !found->second.data || found->second.dtype != DType::kFloat32 || + found->second.shape != shape) + throw std::runtime_error("vits invalid engine output: " + name); + const auto* first = static_cast(found->second.data); + std::vector result(first, first + found->second.numel()); + if (!std::all_of(result.begin(), result.end(), [](float x) { return std::isfinite(x); })) + throw std::runtime_error("vits nonfinite engine output: " + name); + return result; +} +} // namespace + +Pipeline::Pipeline(std::unique_ptr conditioning, std::unique_ptr synthesis, + Tokenizer tokenizer, Config config) + : conditioning_(std::move(conditioning)), synthesis_(std::move(synthesis)), + tokenizer_(std::move(tokenizer)), config_(config) { + if (!conditioning_ || !conditioning_->ok() || !synthesis_ || !synthesis_->ok() || + config_.token_capacity < 3 || config_.flow_size <= 0 || config_.max_frames <= 0 || + config_.upsample_factor <= 0 || config_.sample_rate <= 0 || + static_cast(config_.max_frames) * config_.upsample_factor > + std::numeric_limits::max()) + throw std::invalid_argument("vits invalid engine or synthesis geometry"); +} + +std::vector Pipeline::task_bindings() { + return {internal::bind(*this, fields())}; +} + +TensorMap Pipeline::forward(ITrtModule& module, InputBuffers& buffers, const TensorMap& inputs) { + for (const auto& [name, tensor] : inputs) { + if (!module.has_input(name) || module.tensor_dtype(name) != tensor.dtype) + throw std::runtime_error("vits invalid engine input: " + name); + auto buffer = buffers.find(name); + const bool dynamic = module.input_is_dynamic(name); + if (!dynamic && module.tensor_shape(name) != tensor.shape) + throw std::runtime_error("vits invalid engine input shape: " + name); + if (buffer == buffers.end()) { + auto shape = dynamic ? module.input_profile_shape(name, module.profile_idx(), + ProfileShapeSelector::kMax) + : tensor.shape; + if (shape.size() != tensor.shape.size() || + std::any_of(shape.begin(), shape.end(), [](auto extent) { return extent <= 0; })) + throw std::runtime_error("vits invalid engine input profile: " + name); + DeviceTensor allocated(std::move(shape), tensor.dtype, module.stream()); + if (!allocated.ok()) + throw std::runtime_error("vits could not allocate device input: " + name); + buffer = buffers.try_emplace(name, std::move(allocated)).first; + } + auto& device = buffer->second; + if (tensor.nbytes() > device.nbytes()) + throw std::runtime_error("vits missing device input capacity: " + name); + module.bind_external(name, device.data(), tensor.shape); + // The synchronous transfer consumes the host source before returning. + // TensorRT only uses the device allocation, including on the error path. + const auto status = + cudaMemcpy(device.data(), tensor.data, tensor.nbytes(), cudaMemcpyHostToDevice); + if (status != cudaSuccess) + throw std::runtime_error("vits input upload failed for " + name + ": " + + cudaGetErrorString(status)); + } + // Synchronous H2D copies use the default stream and may still be staged there. + const auto status = cudaStreamSynchronize(nullptr); + if (status != cudaSuccess) { + stream_failed_ = true; + throw std::runtime_error(std::string("vits input stream failed: ") + + cudaGetErrorString(status)); + } + try { + return module.forward({}); + } catch (...) { + stream_failed_ = true; + module.sync(); + stream_failed_ = false; + throw; + } +} + +internal::AudioResult Pipeline::run(const internal::TextToSpeechRequest& request, + internal::ConfigView supplied) { + if (stream_failed_) + throw std::runtime_error("vits TensorRT stream failed to synchronize"); + internal::validate_config(fields(), supplied); + const auto seed = internal::config_get(supplied, fields(), "seed").value(); + if (seed < 0) + throw std::invalid_argument("vits seed must be nonnegative"); + if (request.language && *request.language != "eng" && *request.language != "en") + throw std::invalid_argument("vits selected checkpoint supports English speech"); + auto ids = tokenizer_.encode(request.text); + if (ids.empty()) + throw std::invalid_argument("vits requires nonempty normalized text"); + const auto count = ids.size(); + const auto capacity = config_.token_capacity; + Noise random(static_cast(seed)); + const auto unpadded_noise = random.normal(2 * count); + std::vector noise(2 * capacity), mask(capacity); + for (std::size_t i = 0; i < count; ++i) { + mask[i] = 1; + noise[i] = unpadded_noise[i]; + noise[capacity + i] = unpadded_noise[count + i]; + } + ids.resize(capacity, 0); + const auto encoded = + forward(*conditioning_, conditioning_inputs_, + { + {"input_ids", tensor(ids.data(), {1, capacity}, DType::kInt32)}, + {"input_mask", tensor(mask.data(), {1, 1, capacity})}, + {"duration_noise", tensor(noise.data(), {1, 2, capacity})}, + }); + const auto durations = output(encoded, "durations", {1, 1, capacity}); + const auto width = config_.flow_size; + const auto means = output(encoded, "prior_means", {1, width, capacity}); + const auto logs = output(encoded, "prior_logs", {1, width, capacity}); + std::int64_t frames = 0; + for (std::size_t i = 0; i < count; ++i) { + if (durations[i] < 0 || durations[i] > config_.max_frames || + std::floor(durations[i]) != durations[i]) + throw std::invalid_argument( + "vits predicted duration exceeds the bundle frame capacity"); + frames += static_cast(durations[i]); + if (frames > config_.max_frames) + throw std::invalid_argument( + "vits predicted duration exceeds the bundle frame capacity"); + } + frames = std::max(frames, 1); + std::vector expanded_means(width * frames), expanded_logs(width * frames); + for (std::int32_t channel = 0; channel < width; ++channel) { + std::int64_t position = 0; + for (std::size_t i = 0; i < count; ++i) { + const auto duration = static_cast(durations[i]); + std::fill_n(expanded_means.begin() + channel * frames + position, duration, + means[channel * capacity + i]); + std::fill_n(expanded_logs.begin() + channel * frames + position, duration, + logs[channel * capacity + i]); + position += duration; + } + } + auto acoustic_noise = random.transposed_normal(width, frames); + std::vector output_mask(frames, 1); + const auto decoded = forward(*synthesis_, synthesis_inputs_, + { + {"means", tensor(expanded_means.data(), {1, width, frames})}, + {"logs", tensor(expanded_logs.data(), {1, width, frames})}, + {"noise", tensor(acoustic_noise.data(), {1, width, frames})}, + {"output_mask", tensor(output_mask.data(), {1, 1, frames})}, + }); + internal::AudioResult result; + result.samples = output(decoded, "waveform", {1, 1, frames * config_.upsample_factor}); + result.sample_rate = config_.sample_rate; + result.channels = 1; + return result; +} +} // namespace trtmc::vits diff --git a/families/vits/runtime/pipeline.h b/families/vits/runtime/pipeline.h new file mode 100644 index 0000000000..1ae301dd7a --- /dev/null +++ b/families/vits/runtime/pipeline.h @@ -0,0 +1,37 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + */ +#pragma once +#include "families/vits/runtime/tokenizer.h" +#include "trtmc/internal/audio.h" +#include "trtmc/internal/model.h" +#include "trtmc/runtime/trt_module.h" + +namespace trtmc::vits { +struct Config { + std::int32_t token_capacity{128}, flow_size{192}, max_frames{1024}; + std::int32_t upsample_factor{256}, sample_rate{16000}; +}; + +class Pipeline final : public internal::IModel, public internal::ITextToSpeech { + public: + Pipeline(std::unique_ptr conditioning, std::unique_ptr synthesis, + Tokenizer tokenizer, Config config); + const char* task() const noexcept override { return internal::ITextToSpeech::kTask.data(); } + std::vector task_bindings() override; + internal::AudioResult run(const internal::TextToSpeechRequest&, internal::ConfigView) override; + + private: + using InputBuffers = std::unordered_map; + TensorMap forward(ITrtModule& module, InputBuffers& buffers, const TensorMap& inputs); + + // The modules bind these device buffers and are destroyed before the buffers. + InputBuffers conditioning_inputs_, synthesis_inputs_; + + std::unique_ptr conditioning_, synthesis_; + Tokenizer tokenizer_; + Config config_; + bool stream_failed_{}; +}; +} // namespace trtmc::vits diff --git a/families/vits/runtime/plugin.cpp b/families/vits/runtime/plugin.cpp new file mode 100644 index 0000000000..ce51af44fc --- /dev/null +++ b/families/vits/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/vits/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("vits does not support --kv-cache-size"); + if (context.reader.info().task != std::string(trtmc::internal::ITextToSpeech::kTask)) + throw std::invalid_argument("vits supports the text_to_speech Task"); + const auto value = nlohmann::json::parse(context.reader.read_section("runtime.json")); + if (value.at("schema_version").get() != 1) + throw std::invalid_argument("vits unsupported runtime schema"); + trtmc::vits::Config config; + config.token_capacity = value.at("token_capacity"); + config.flow_size = value.at("flow_size"); + config.max_frames = value.at("max_frames"); + config.upsample_factor = value.at("upsample_factor"); + config.sample_rate = value.at("sample_rate"); + auto load = [&](const char* name) { + const auto plan = context.reader.read_section(name); + return context.backend.create_module(plan.data(), plan.size(), {}); + }; + auto conditioning = load("conditioning.plan"); + auto synthesis = load("synthesis.plan"); + const auto vocab = nlohmann::json::parse(context.reader.read_section("tokenizer.json")); + return new trtmc::vits::Pipeline( + std::move(conditioning), std::move(synthesis), + trtmc::vits::Tokenizer(vocab.get>(), + config.token_capacity), + config); +} diff --git a/families/vits/runtime/tokenizer.cpp b/families/vits/runtime/tokenizer.cpp new file mode 100644 index 0000000000..0efba74952 --- /dev/null +++ b/families/vits/runtime/tokenizer.cpp @@ -0,0 +1,79 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + */ +#include "families/vits/runtime/tokenizer.h" + +#include +#include +#include +#include + +namespace trtmc::vits { +Tokenizer::Tokenizer(std::unordered_map vocab, std::int32_t capacity) + : vocab_(std::move(vocab)), capacity_(capacity) { + const auto pad = vocab_.find("k"); + if (capacity_ < 3 || vocab_.size() != 38 || pad == vocab_.end() || pad->second != 0 || + vocab_.count(" ") == 0) + throw std::invalid_argument("vits requires the English MMS character vocabulary"); + for (const auto& [piece, id] : vocab_) + if (piece.empty() || id < 0 || id >= 38) + throw std::invalid_argument("vits invalid character vocabulary"); +} + +std::vector Tokenizer::encode(std::string_view text) const { + if (text.size() > static_cast(std::numeric_limits::max())) + throw std::invalid_argument("vits input text is too long"); + const auto unicode = icu::UnicodeString::fromUTF8(icu::StringPiece(text.data(), text.size())); + const auto space = vocab_.at(" "); + std::vector ids; + bool in_segment = false; + std::size_t pending_spaces = 0; + auto emit = [&](std::int32_t id) { + // The checkpoint's pad spelling "k" is also an added special token. + // Its bare ID separates independently blank-interspersed text chunks. + if (id == 0) { + ids.push_back(0); + in_segment = false; + } else { + if (!in_segment) + ids.push_back(0); + ids.push_back(id); + ids.push_back(0); + in_segment = true; + } + if (ids.size() > static_cast(capacity_)) + throw std::invalid_argument("vits text exceeds the bundle token capacity"); + }; + for (int32_t i = 0; i < unicode.length();) { + const auto codepoint = unicode.char32At(i); + i += U16_LENGTH(codepoint); + icu::UnicodeString lower(codepoint); + std::string original; + lower.toUTF8String(original); + if (!vocab_.count(original)) + lower.toLower(icu::Locale::getRoot()); + for (int32_t j = 0; j < lower.length();) { + const auto normalized = lower.char32At(j); + j += U16_LENGTH(normalized); + std::string piece; + icu::UnicodeString(normalized).toUTF8String(piece); + const auto found = vocab_.find(piece); + if (found == vocab_.end()) + continue; + if (found->second == space) { + if (!ids.empty()) + ++pending_spaces; + continue; + } + if (pending_spaces > static_cast(capacity_)) + throw std::invalid_argument("vits text exceeds the bundle token capacity"); + for (std::size_t pending = 0; pending < pending_spaces; ++pending) + emit(space); + pending_spaces = 0; + emit(found->second); + } + } + return ids; +} +} // namespace trtmc::vits diff --git a/families/vits/runtime/tokenizer.h b/families/vits/runtime/tokenizer.h new file mode 100644 index 0000000000..b7bdea9a35 --- /dev/null +++ b/families/vits/runtime/tokenizer.h @@ -0,0 +1,22 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + */ +#pragma once +#include +#include +#include +#include +#include + +namespace trtmc::vits { +class Tokenizer { + public: + Tokenizer(std::unordered_map vocab, std::int32_t capacity); + std::vector encode(std::string_view text) const; + + private: + std::unordered_map vocab_; + std::int32_t capacity_; +}; +} // namespace trtmc::vits diff --git a/families/vits/support.py b/families/vits/support.py new file mode 100644 index 0000000000..0b2311d3fd --- /dev/null +++ b/families/vits/support.py @@ -0,0 +1,10 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +from tensorrt_model_connect.model_support import family_support + +describe = family_support( + model_types=("vits",), + tasks=("text_to_speech",), + default_task="text_to_speech", + default_precision="fp32", +) diff --git a/families/vits/tests/__init__.py b/families/vits/tests/__init__.py new file mode 100644 index 0000000000..52a7a9daf0 --- /dev/null +++ b/families/vits/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/vits/tests/cpp/e2e_consumer.cpp b/families/vits/tests/cpp/e2e_consumer.cpp new file mode 100644 index 0000000000..e5399fe34c --- /dev/null +++ b/families/vits/tests/cpp/e2e_consumer.cpp @@ -0,0 +1,85 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + */ +#include "trtmc/audio.hpp" + +#include +#include +#include +#include +#include + +int main(int argc, char** argv) { + try { + if (argc != 5) + throw std::invalid_argument( + "usage: vits_e2e BUNDLE RUNTIME_ROOT REQUESTS_JSON OUTPUT_DIRECTORY"); + std::ifstream file(argv[3]); + const auto requests = nlohmann::json::parse(file); + trtmc::LoadOptions options; + options.runtime_root = argv[2]; + auto model = trtmc::Model::load(argv[1], options); + auto task = model.task(); + nlohmann::json results = nlohmann::json::array(); + std::vector first_samples; + for (const auto& request : requests) { + trtmc::Config config{{"seed", request.at("seed").get()}}; + auto result = task.run({request.at("text").get()}, config); + const auto samples = result.samples(); + if (result.channels() != 1 || result.sample_rate() != 16000 || samples.empty()) + throw std::runtime_error("vits invalid public speech result"); + if (results.empty()) + first_samples.assign(samples.begin(), samples.end()); + const auto name = "samples-" + std::to_string(results.size()) + ".f32"; + const auto path = std::filesystem::path(argv[4]) / name; + std::ofstream output(path, std::ios::binary); + output.write(reinterpret_cast(samples.data()), + samples.size() * sizeof(float)); + if (!output) + throw std::runtime_error("cannot save native speech samples"); + results.push_back({{"file", name}, + {"sample_rate", result.sample_rate()}, + {"channels", result.channels()}, + {"samples", samples.size()}}); + } + const auto& first = requests.at(0); + for (int mode = 0; mode < 7; ++mode) { + trtmc::TextToSpeechRequest input{first.at("text").get()}; + trtmc::Config config; + if (mode == 6) + config.add("seed", true); + else + config.add("seed", + mode == 0 ? std::int64_t{-1} : first.at("seed").get()); + if (mode == 1) + config.add("unknown", std::int64_t{1}); + if (mode == 2) + input.text.clear(); + if (mode == 3) + input.text = "!!!"; + if (mode == 4) + input.language = "fra"; + if (mode == 5) + input.text = std::string(1000, 'a'); + bool rejected = false; + try { + task.run(input, config); + } catch (const trtmc::Error&) { + rejected = true; + } + if (!rejected) + throw std::runtime_error("vits accepted an invalid speech request"); + } + trtmc::Config config{{"seed", first.at("seed").get()}}; + auto recovered = task.run({first.at("text").get()}, config); + const auto samples = recovered.samples(); + if (std::vector(samples.begin(), samples.end()) != first_samples) + throw std::runtime_error("vits state leaked after a rejected speech request"); + std::cout << results.dump() << '\n'; + return 0; + } catch (const std::exception& error) { + std::cerr << error.what() << '\n'; + return 1; + } +} diff --git a/families/vits/tests/cpp/noise_consumer.cpp b/families/vits/tests/cpp/noise_consumer.cpp new file mode 100644 index 0000000000..d0a2d9066c --- /dev/null +++ b/families/vits/tests/cpp/noise_consumer.cpp @@ -0,0 +1,35 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + */ +#include "families/vits/runtime/noise.h" + +#include +#include +#include + +int main(int argc, char** argv) { + try { + if (argc < 3) + throw std::invalid_argument("expected seed and normal sample counts"); + trtmc::vits::Noise noise(std::stoull(argv[1])); + if (std::string(argv[2]) == "--audio") { + if (argc != 6) + throw std::invalid_argument("expected text tokens, channels, and frames"); + const auto duration = noise.normal(2 * std::stoull(argv[3])); + const auto acoustic = + noise.transposed_normal(std::stoull(argv[4]), std::stoull(argv[5])); + std::cout << nlohmann::json({{"duration", duration}, {"acoustic", acoustic}}).dump() + << '\n'; + } else { + nlohmann::json values = nlohmann::json::array(); + for (int i = 2; i < argc; ++i) + values.push_back(noise.normal(std::stoull(argv[i]))); + std::cout << values.dump() << '\n'; + } + return 0; + } catch (const std::exception& error) { + std::cerr << error.what() << '\n'; + return 1; + } +} diff --git a/families/vits/tests/cpp/tokenizer_consumer.cpp b/families/vits/tests/cpp/tokenizer_consumer.cpp new file mode 100644 index 0000000000..9a560c7abe --- /dev/null +++ b/families/vits/tests/cpp/tokenizer_consumer.cpp @@ -0,0 +1,30 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + */ +#include "families/vits/runtime/tokenizer.h" + +#include +#include +#include +#include + +int main(int argc, char** argv) { + try { + if (argc != 3) + throw std::invalid_argument("expected vocabulary and text fixtures"); + std::ifstream vocabulary(argv[1]), texts(argv[2]); + const auto vocab = nlohmann::json::parse(vocabulary); + trtmc::vits::Tokenizer tokenizer(vocab.get>(), + 512); + const auto inputs = nlohmann::json::parse(texts); + nlohmann::json output = nlohmann::json::array(); + for (const auto& text : inputs) + output.push_back(tokenizer.encode(text.get())); + std::cout << output.dump() << '\n'; + return 0; + } catch (const std::exception& error) { + std::cerr << error.what() << '\n'; + return 1; + } +} diff --git a/families/vits/tests/manifests/mms-tts-eng.json b/families/vits/tests/manifests/mms-tts-eng.json new file mode 100644 index 0000000000..c613d4b6a0 --- /dev/null +++ b/families/vits/tests/manifests/mms-tts-eng.json @@ -0,0 +1,26 @@ +{ + "name": "mms-tts-eng", + "hf_id": "facebook/mms-tts-eng", + "hf_revision": "c71de0fe7204c83f1c10820a7d696d0b450048ba", + "family": "vits", + "task": "text_to_speech", + "precision": "fp32", + "max_sequence_length": 128, + "tensor_parallel_size": 1, + "bundle": "mms-tts-eng.bundle", + "testcases": [ + { + "name": "mms-tts-eng-fp32", + "premerge": true, + "reference_precision": "fp32", + "waveform_atol": 0.0005, + "waveform_rtol": 0.0001, + "requests": [ + {"text": "Hello, my dog is cute.", "seed": 555}, + {"text": "The quick brown fox jumps over the lazy dog.", "seed": 555}, + {"text": "Hello, my dog is cute.", "seed": 777}, + {"text": "Hello, my dog is cute.", "seed": 555} + ] + } + ] +} diff --git a/families/vits/tests/math_check.py b/families/vits/tests/math_check.py new file mode 100644 index 0000000000..06ee89dd32 --- /dev/null +++ b/families/vits/tests/math_check.py @@ -0,0 +1,162 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Compare complete VITS stages with the unmodified upstream implementation.""" + + +def check_vits_stages(tmp_path): + import torch + import tensorrt as trt + from transformers import VitsConfig, VitsModel + from families.vits import model as owned + + torch.set_num_threads(8) + torch.backends.cuda.matmul.allow_tf32 = False + torch.backends.cudnn.allow_tf32 = False + torch.manual_seed(2199) + config = VitsConfig( + hidden_size=8, + ffn_dim=16, + flow_size=8, + num_hidden_layers=2, + num_attention_heads=2, + window_size=2, + duration_predictor_num_flows=2, + duration_predictor_flow_bins=4, + depth_separable_num_layers=2, + prior_encoder_num_flows=2, + prior_encoder_num_wavenet_layers=2, + posterior_encoder_num_wavenet_layers=2, + upsample_initial_channel=16, + upsample_rates=[2, 2], + upsample_kernel_sizes=[4, 4], + resblock_kernel_sizes=[3], + resblock_dilation_sizes=[[1, 3]], + wavenet_kernel_size=3, + attn_implementation="eager", + ) + model = VitsModel(config).eval() + checkpoint = tmp_path / "tiny-checkpoint" + model.save_pretrained(checkpoint) + weights = owned.load_weights(checkpoint) + logger = trt.Logger(trt.Logger.WARNING) + runtime = trt.Runtime(logger) + + def make(mode): + plan = owned.compile_engine(config.to_dict(), weights, 16, mode) + engine = runtime.deserialize_cuda_engine(plan) + assert engine is not None + return engine, engine.create_execution_context() + + def run(pair, source): + engine, context = pair + tensors = {name: value.contiguous().cuda() for name, value in source.items()} + for name, value in tensors.items(): + if -1 in tuple(engine.get_tensor_shape(name)): + assert context.set_input_shape(name, tuple(value.shape)) + outputs = {} + for index in range(engine.num_io_tensors): + name = engine.get_tensor_name(index) + if engine.get_tensor_mode(name) == trt.TensorIOMode.OUTPUT: + outputs[name] = torch.empty(tuple(context.get_tensor_shape(name)), device="cuda") + 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 {name: value.cpu() for name, value in outputs.items()} + + with torch.inference_mode(): + conditioning = make("conditioning") + for count in (3, 7, 15): + ids = torch.arange(1, count + 1).reshape(1, count) + mask = torch.ones(1, 1, count) + encoded = model.text_encoder( + ids, mask.transpose(1, 2), attention_mask=torch.ones_like(ids) + ) + hidden = encoded.last_hidden_state.transpose(1, 2) + torch.manual_seed(412) + noise = torch.randn(1, 2, count) + torch.manual_seed(412) + durations = model.duration_predictor( + hidden, mask, reverse=True, noise_scale=model.noise_scale_duration + ) + padded_ids = torch.zeros(1, 16, dtype=torch.int32) + padded_ids[:, :count] = ids + padded_mask = torch.zeros(1, 1, 16) + padded_mask[..., :count] = 1 + padded_noise = torch.zeros(1, 2, 16) + padded_noise[..., :count] = noise + actual = run( + conditioning, + { + "input_ids": padded_ids, + "input_mask": padded_mask, + "duration_noise": padded_noise, + }, + ) + for name, reference in ( + ("hidden", hidden), + ("prior_means", encoded.prior_means.transpose(1, 2)), + ("prior_logs", encoded.prior_log_variances.transpose(1, 2)), + ("log_duration", durations), + ): + delta = float((actual[name][..., :count] - reference).abs().max()) + print("conditioning", count, name, delta, flush=True) + torch.testing.assert_close( + actual[name][..., :count], reference, rtol=5e-5, atol=5e-5 + ) + torch.testing.assert_close( + actual["durations"][..., :count], torch.ceil(torch.exp(durations)), rtol=0, atol=0 + ) + # At 32 the old upper-knot epsilon rounds away in float32. + spline_config = dict(config.to_dict(), duration_predictor_tail_bound=32.0) + builder = trt.Builder(logger) + network = builder.create_network(0) + options = builder.create_builder_config() + options.clear_flag(trt.BuilderFlag.TF32) + spline = owned.Graph(network, spline_config, {}, 5) + inputs = network.add_input("inputs", trt.float32, (1, 1, 5)) + parameters = network.add_input("parameters", trt.float32, (1, 11, 5)) + spline.output(spline.spline_inverse(inputs, parameters), "result") + plan = builder.build_serialized_network(network, options) + assert plan is not None + engine = runtime.deserialize_cuda_engine(plan) + assert engine is not None + endpoints = torch.tensor([[[-33.0, -32.0, 0.0, 32.0, 33.0]]]) + result = run( + (engine, engine.create_execution_context()), + {"inputs": endpoints, "parameters": torch.zeros(1, 11, 5)}, + ) + torch.testing.assert_close(result["result"], endpoints, rtol=0, atol=0) + + synthesis = make("synthesis") + for count in (1, 3, 13, 26, 1024): + torch.manual_seed(417) + means = torch.randn(1, 8, count) + logs = torch.randn(1, 8, count) * 0.15 + noise = torch.randn(1, 8, count) + mask = torch.ones(1, 1, count) + prior = means + noise * torch.exp(logs) * model.noise_scale + spectrogram = model.flow(prior, mask, reverse=True) * mask + waveform = model.decoder(spectrogram) + actual = run( + synthesis, {"means": means, "logs": logs, "noise": noise, "output_mask": mask} + ) + for name, reference in (("spectrogram", spectrogram), ("waveform", waveform)): + print( + "synthesis", + count, + name, + float((actual[name] - reference).abs().max()), + flush=True, + ) + torch.testing.assert_close(actual[name], reference, rtol=5e-5, atol=5e-5) + print("VITS conditioning and dynamic synthesis boundaries passed at 5e-5", flush=True) + + +if __name__ == "__main__": + import sys + from pathlib import Path + + check_vits_stages(Path(sys.argv[1])) diff --git a/families/vits/tests/requirements.txt b/families/vits/tests/requirements.txt new file mode 100644 index 0000000000..bd04f4b42a --- /dev/null +++ b/families/vits/tests/requirements.txt @@ -0,0 +1,2 @@ +transformers==5.3.0 +torch>=2.6 diff --git a/families/vits/tests/test_e2e.py b/families/vits/tests/test_e2e.py new file mode 100644 index 0000000000..d55eaa6539 --- /dev/null +++ b/families/vits/tests/test_e2e.py @@ -0,0 +1,239 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +"""Pinned MMS-TTS checkpoint -> TensorRT bundle -> public speech Task -> PCM.""" + +import json +import os +from pathlib import Path +import subprocess +import sys + +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/mms-tts-eng.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(",")) + models_file = metafunc.config.getoption("--e2e-models-file") + if models_file: + models.update(Path(models_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({"vits", MANIFEST["name"], case["name"]}): + continue + if cases and case["name"] not in cases: + continue + marks = [] if selected else [pytest.mark.skip(reason="select VITS E2E explicitly")] + parameters.append(pytest.param(case["name"], id=case["name"], marks=marks)) + metafunc.parametrize("case_name", parameters) + + +def _checkpoint(): + if value := os.environ.get("TRTMC_VITS_MODEL_DIR"): + return Path(value) + from huggingface_hub import snapshot_download + + return Path( + snapshot_download( + repo_id=MANIFEST["hf_id"], revision=MANIFEST["hf_revision"], local_files_only=True + ) + ) + + +def _native_helpers(root, runtime, tmp_path): + import torch + from transformers import VitsTokenizer + + texts = [ + "Hello, my dog is cute.", + " A B ", + "Café and Café", + "K İ – 0123456789", + "hello\nworld\t!", + "A_B's - test", + "中文 한국어", + " k", + "kk k ak ka", + "", + " " * 300 + "hello" + " " * 300, + ] + path = tmp_path / "tokenizer-inputs.json" + path.write_text(json.dumps(texts, ensure_ascii=False)) + result = subprocess.run( + [str(runtime / "vits_tokenizer"), str(root / "vocab.json"), str(path)], + check=True, + capture_output=True, + text=True, + timeout=60, + ) + tokenizer = VitsTokenizer.from_pretrained(root, trust_remote_code=False) + assert json.loads(result.stdout) == [tokenizer.encode(text) for text in texts] + overflow = subprocess.run( + [str(runtime / "vits_noise"), "0", "--audio", "1", str(2**63), "2"], + capture_output=True, + text=True, + timeout=60, + ) + assert overflow.returncode == 1 + assert "transposed noise sample count overflows" in overflow.stderr + counts = [1, 2, 9, 16, 17, 31, 32, 33, 148, 383, 10000, 2, 192 * 157] + for seed in (0, 555, 2027, 2**32 + 555): + result = subprocess.run( + [str(runtime / "vits_noise"), str(seed), *map(str, counts)], + check=True, + capture_output=True, + text=True, + timeout=60, + ) + actual = json.loads(result.stdout) + generator = torch.Generator().manual_seed(seed) + assert len(actual) == len(counts) + for values, count in zip(actual, counts): + expected = torch.randn(count, generator=generator) + torch.testing.assert_close(torch.tensor(values), expected, atol=2e-6, rtol=2e-6) + for tokens, frames in ((3, 1), (7, 13), (41, 157)): + result = subprocess.run( + [ + str(runtime / "vits_noise"), + str(seed), + "--audio", + str(tokens), + "192", + str(frames), + ], + check=True, + capture_output=True, + text=True, + timeout=60, + ) + actual = json.loads(result.stdout) + torch.manual_seed(seed) + expected_duration = torch.randn(1, 2, tokens) + template = torch.empty(1, frames, 192).transpose(1, 2) + expected_acoustic = torch.randn_like(template) + torch.testing.assert_close( + torch.tensor(actual["duration"]), + expected_duration.reshape(-1), + atol=2e-6, + rtol=2e-6, + ) + torch.testing.assert_close( + torch.tensor(actual["acoustic"]), + expected_acoustic.reshape(-1), + atol=2e-6, + rtol=2e-6, + ) + + +def _reference(root, requests): + import torch + from transformers import VitsModel, VitsTokenizer + + torch.set_num_threads(8) + torch.backends.cuda.matmul.allow_tf32 = False + torch.backends.cudnn.allow_tf32 = False + tokenizer = VitsTokenizer.from_pretrained(root, trust_remote_code=False) + model = ( + VitsModel.from_pretrained( + root, dtype=torch.float32, use_safetensors=True, trust_remote_code=False + ) + .cpu() + .eval() + ) + waveforms = [] + for request in requests: + torch.manual_seed(request["seed"]) + inputs = tokenizer(request["text"], return_tensors="pt") + with torch.inference_mode(): + result = model(**inputs) + waveform = result.waveform[0].numpy() + assert waveform.size == int(result.sequence_lengths[0]) + assert np.isfinite(waveform).all() and np.max(np.abs(waveform)) > 0.01 + waveforms.append(waveform.copy()) + return waveforms + + +def test_official_checkpoint_e2e(case_name, tmp_path): + case = next(case for case in MANIFEST["testcases"] if case["name"] == case_name) + assert case["reference_precision"] == "fp32" + subprocess.run( + [sys.executable, "-m", "families.vits.tests.math_check", str(tmp_path)], + check=True, + timeout=300, + ) + root = _checkpoint() + assert resolve_family(load_model_metadata(root))[0] == "vits" + runtime = Path(os.environ["TRTMC_RUNTIME_ROOT"]) + assert (runtime / "libtrtmc_model_vits.so").is_file() + assert (runtime / "libtrtmc_backend_trt.so").is_file() + _native_helpers(root, runtime, tmp_path) + record_evidence("inputs", {"manifest": MANIFEST, "case": case}) + record_evidence( + "checkpoint", + { + "model_dir": str(root), + "hf_id": MANIFEST["hf_id"], + "hf_revision": MANIFEST["hf_revision"], + }, + ) + with evidence_stage("reference"): + expected = _reference(root, case["requests"]) + np.testing.assert_array_equal(expected[0], expected[-1]) + assert expected[0].shape != expected[1].shape or not np.array_equal(expected[0], expected[1]) + assert expected[0].shape != expected[2].shape or not np.array_equal(expected[0], expected[2]) + for index, waveform in enumerate(expected): + waveform.tofile(tmp_path / f"reference-{index}.f32") + record_evidence( + "reference", + [ + {"file": str(tmp_path / f"reference-{i}.f32"), "samples": len(wave)} + for i, wave in enumerate(expected) + ], + ) + bundle = tmp_path / MANIFEST["bundle"] + with evidence_stage("build"): + build( + BuildRequest( + root, + bundle, + MANIFEST["family"], + MANIFEST["task"], + MANIFEST["precision"], + max_sequence_length=MANIFEST["max_sequence_length"], + tensor_parallel_size=MANIFEST["tensor_parallel_size"], + ) + ) + inputs = tmp_path / "requests.json" + inputs.write_text(json.dumps(case["requests"])) + with evidence_stage("native"): + command = [str(runtime / "vits_e2e"), str(bundle), str(runtime), str(inputs), str(tmp_path)] + result = subprocess.run(command, check=True, capture_output=True, text=True, timeout=300) + actual = json.loads(result.stdout.strip().splitlines()[-1]) + record_evidence("commands", {"argv": command}) + assert len(actual) == len(expected) + observed = [] + with evidence_stage("compare"): + for item, reference in zip(actual, expected): + assert item["sample_rate"] == 16000 and item["channels"] == 1 + waveform = np.fromfile(tmp_path / item["file"], dtype=np.float32) + assert item["samples"] == len(reference) == len(waveform) + assert np.isfinite(waveform).all() + np.testing.assert_allclose( + waveform, reference, atol=case["waveform_atol"], rtol=case["waveform_rtol"] + ) + observed.append(waveform) + np.testing.assert_array_equal(observed[0], observed[-1]) + record_evidence("native", actual) diff --git a/families/vits/tests/test_model.py b/families/vits/tests/test_model.py new file mode 100644 index 0000000000..2368ef895a --- /dev/null +++ b/families/vits/tests/test_model.py @@ -0,0 +1,81 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +import json + +import pytest + +from families.vits.model import load_weights, tokenizer_vocabulary, validate_config + + +def test_rejects_mismatched_flow_and_speaker_geometry(): + from transformers import VitsConfig + + config = VitsConfig(flow_size=191).to_dict() + with pytest.raises(ValueError, match="coupling"): + validate_config(config) + config.update(flow_size=192, num_speakers=2) + with pytest.raises(ValueError, match="speaker"): + validate_config(config) + + +def test_rejects_empty_vocoder_residual_blocks(): + from transformers import VitsConfig + + config = VitsConfig().to_dict() + validate_config(config) + config.update(resblock_kernel_sizes=[], resblock_dilation_sizes=[]) + with pytest.raises(ValueError, match="at least one vocoder residual block"): + validate_config(config) + + +def test_rejects_unavailable_text_normalization(tmp_path): + config = { + "language": "eng", + "is_uroman": False, + "phonemize": False, + "add_blank": True, + "normalize": True, + "pad_token": "k", + } + vocab = {"k": 0, " ": 1, **{f"piece{i}": i for i in range(2, 38)}} + (tmp_path / "vocab.json").write_text(json.dumps(vocab)) + path = tmp_path / "tokenizer_config.json" + path.write_text(json.dumps(config)) + assert tokenizer_vocabulary(tmp_path) == vocab + + path.write_text(json.dumps({**config, "is_uroman": True})) + with pytest.raises(ValueError, match="character normalization"): + tokenizer_vocabulary(tmp_path) + + path.write_text(json.dumps(config)) + for missing, replacement in ((" ", "@"), ("piece2", "")): + invalid = dict(vocab) + invalid[replacement] = invalid.pop(missing) + (tmp_path / "vocab.json").write_text(json.dumps(invalid)) + with pytest.raises(ValueError, match="invalid English MMS vocabulary"): + tokenizer_vocabulary(tmp_path) + + +def test_missing_checkpoint_tensor_cannot_become_initialized_weights(tmp_path): + from safetensors.torch import load_file, save_file + from transformers import VitsConfig, VitsModel + + config = VitsConfig( + hidden_size=8, + ffn_dim=16, + flow_size=8, + num_hidden_layers=1, + num_attention_heads=2, + upsample_initial_channel=16, + upsample_rates=[2], + upsample_kernel_sizes=[4], + resblock_kernel_sizes=[3], + resblock_dilation_sizes=[[1]], + ) + VitsModel(config).save_pretrained(tmp_path) + path = tmp_path / "model.safetensors" + tensors = load_file(path) + del tensors["text_encoder.embed_tokens.weight"] + save_file(tensors, path, metadata={"format": "pt"}) + with pytest.raises(ValueError, match="missing or mismatched"): + load_weights(tmp_path) diff --git a/families/vits/tests/test_support.py b/families/vits/tests/test_support.py new file mode 100644 index 0000000000..ea199fee67 --- /dev/null +++ b/families/vits/tests/test_support.py @@ -0,0 +1,13 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +from tensorrt_model_connect.model_support import ModelMetadata, resolve_family +from families.vits.support import describe + + +def test_vits_speech_owner(): + family, support = resolve_family( + ModelMetadata(config={"model_type": "vits", "architectures": ["VitsModel"]}, model_index={}) + ) + assert family == "vits" + assert support.default_task == "text_to_speech" + assert describe(ModelMetadata(config={"model_type": "bark"}, model_index={})) is None