Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 39 additions & 0 deletions families/vits/README.md
Original file line number Diff line number Diff line change
@@ -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.
4 changes: 4 additions & 0 deletions families/vits/__init__.py
Original file line number Diff line number Diff line change
@@ -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."""
642 changes: 642 additions & 0 deletions families/vits/model.py

Large diffs are not rendered by default.

3 changes: 3 additions & 0 deletions families/vits/requirements.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
transformers==5.3.0
safetensors>=0.5
torch>=2.6
32 changes: 32 additions & 0 deletions families/vits/runtime/CMakeLists.txt
Original file line number Diff line number Diff line change
@@ -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()
93 changes: 93 additions & 0 deletions families/vits/runtime/noise.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
/*
* SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
* SPDX-License-Identifier: Apache-2.0
*/
#pragma once

#include <cmath>
#include <cstdint>
#include <limits>
#include <optional>
#include <random>
#include <stdexcept>
#include <vector>

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<std::uint32_t>(seed)) {}

std::vector<float> normal(std::size_t count) {
std::vector<float> 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<float> transposed_normal(std::size_t channels, std::size_t frames) {
if (channels == 0 || frames == 0)
return {};
if (frames > std::numeric_limits<std::size_t>::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<float> 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<float>(engine_() & 0xffffffU) * (1.0F / 16777216.0F);
}
double uniform_double() {
const std::uint64_t high = engine_(), low = engine_();
return static_cast<double>(((high << 32) | low) & 0x1fffffffffffffULL) *
(1.0 / 9007199254740992.0);
}
float scalar() {
if (spare_) {
const auto value = *spare_;
spare_.reset();
return static_cast<float>(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<float>(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<double> spare_;
};
} // namespace trtmc::vits
185 changes: 185 additions & 0 deletions families/vits/runtime/pipeline.cpp
Original file line number Diff line number Diff line change
@@ -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 <algorithm>
#include <cmath>
#include <limits>
#include <stdexcept>

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<const internal::ConfigField> fields() {
return {kFields, 1};
}

Tensor tensor(void* data, std::vector<std::int64_t> shape, DType dtype = DType::kFloat32) {
Tensor value;
value.data = data;
value.shape = std::move(shape);
value.dtype = dtype;
return value;
}

std::vector<float> output(const TensorMap& outputs, const std::string& name,
const std::vector<std::int64_t>& 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<const float*>(found->second.data);
std::vector<float> 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<ITrtModule> conditioning, std::unique_ptr<ITrtModule> 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<std::int64_t>(config_.max_frames) * config_.upsample_factor >
std::numeric_limits<std::int32_t>::max())
throw std::invalid_argument("vits invalid engine or synthesis geometry");
}

std::vector<internal::TaskInstance> Pipeline::task_bindings() {
return {internal::bind<internal::ITextToSpeech>(*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<std::int64_t>(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<std::uint64_t>(seed));
const auto unpadded_noise = random.normal(2 * count);
std::vector<float> 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<std::int64_t>(durations[i]);
if (frames > config_.max_frames)
throw std::invalid_argument(
"vits predicted duration exceeds the bundle frame capacity");
}
frames = std::max<std::int64_t>(frames, 1);
std::vector<float> 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<std::int64_t>(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<float> 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
37 changes: 37 additions & 0 deletions families/vits/runtime/pipeline.h
Original file line number Diff line number Diff line change
@@ -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<ITrtModule> conditioning, std::unique_ptr<ITrtModule> synthesis,
Tokenizer tokenizer, Config config);
const char* task() const noexcept override { return internal::ITextToSpeech::kTask.data(); }
std::vector<internal::TaskInstance> task_bindings() override;
internal::AudioResult run(const internal::TextToSpeechRequest&, internal::ConfigView) override;

private:
using InputBuffers = std::unordered_map<std::string, DeviceTensor>;
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<ITrtModule> conditioning_, synthesis_;
Tokenizer tokenizer_;
Config config_;
bool stream_failed_{};
};
} // namespace trtmc::vits
Loading
Loading