Module contents
Lesson 29 of 33Core 120 min

Speech synthesis and generative audio

Study neural text-to-speech, duration alignment, vocoders, residual vector quantization, codec language models, flow matching and speech evaluation.

After this lesson you can

  • Describe the TTS pipeline and errors introduced by each stage.
  • Explain attention-alignment failures and duration predictors.
  • Implement residual vector quantization and measure bitrate against reconstruction quality.
  • Explain how a codec language model conditions voice generation on an acoustic prompt.
  • Evaluate TTS with ASR WER, speaker similarity and perceptual quality measures.

Before you start

From text to waveform

A written sentence does not fully specify how it should sound. “I’ll arrive tomorrow” admits different rhythms, accents, emphasis, and pauses. The speech synthesis pipeline (text to speech, TTS) transforms text, optionally into phonemes, predicts an acoustic representation, and generates the waveform. A normalization error can turn a date into a sequence of digits; an acoustic model can skip a word; a vocoder can introduce noise even when text and representation are correct. Evaluation should separate these causes.

In Tacotron 2 a sequence-to-sequence network predicts a mel spectrogram and a conditioned WaveNet generates audio. The paper reports MOS 4.53 versus 4.58 for professional recordings in its particular test, not universal equivalence between synthetic and human speech. Mel parameters such as frequency, hop, scale, power, and normalization are part of the interface: feeding the vocoder a mel built under another convention can degrade output even if dimensions match.

From attention to durations

Duration-based text–audio alignment assigns each symbol a number of frames and expands text representations according to those durations. A decoder with unconstrained attention can drift, repeat, or skip a segment when alignment does not follow expected progress, especially on sequences unlike training. Duration expansion fixes a monotonic correspondence and avoids that specific mechanism, but an incorrect duration predictor can also omit or stretch phonemes. It does not guarantee correct pronunciation.

FastSpeech 2 incorporates duration, pitch, and energy as variation information for a non-autoregressive model. Inference speed and quality depend on architecture, implementation, and hardware. Also check abbreviations, numbers, and pauses: incorrect text normalization precedes any aligner.

InteractiveWhen several words look alike
123456789101112
1. rojo
2. rojo
3. rojo
4. azul

Columns: frames; rows: words. Scroll horizontally to see the full grid. On ties the rule picks the first match. The outline marks the selected frame.

Rule
4
Expected index2
Chosen index1
Matches3

The small bird sings by the window.

Audio for this sentence: SpeechBrain Tacotron2 and HiFi-GAN.

Columns: time; rows: normalized characters. Intensity is mean attention weight. An absent maximum does not alone demonstrate an audible omission.

Text starts at top and ends at bottom; scroll horizontally to inspect all 96 columns on mobile.

Original frames182
Input symbols35
Symbols maximal in any frame32 / 35
Above, compare a toy rule with given durations. Below, explore three matrices actually produced by Tacotron2; map columns average frame blocks and do not correspond to the simulator above.

The first map uses the correct word as an artificial signal to construct weights and shows ambiguity from repeated matches. Durations are fixed at three frames per word, so that second map is correct by construction. Below, attention from SpeechBrain Tacotron2 is shown separately, run on three fixed English sentences including a repetitive one. Audio for each was generated by HiFi-GAN from the same run’s mel. The per-frame maximum visited 32 of 35 symbols in the short, 59 of 62 in the repetitive, and 89 of 94 in the long sentence. Tracking positions across consecutive frames, the maximum moved backward 2, 0, and 5 times respectively; in the long sentence it also advanced more than one position twice. Check the original matrices, audio and manifest. This shows the maximum path is not strictly monotonic, but attention is soft: a symbol that is never maximal can receive weight. Whisper small actually transcribed all three outputs without word errors after the normalization described below: 0 of 36 words total; per-sentence hypotheses are available. That ASR can miss pronunciation errors, and three examples do not establish a failure rate. F5-TTS is a different model and does not produce these matrices.

A neural vocoder converts acoustic features into signal. HiFi-GAN uses a generator and discriminators inspecting periodicity and scales. Its adversarial and feature losses combine with a mel reconstruction loss; no single metric guarantees naturalness. Unlike Griffin–Lim, which seeks an STFT consistent with a given magnitude, a vocoder learns a waveform prior and can generate details not determined by the mel. That prior can also fail out of distribution.

Shape relationships reveal an incompatibility before listening. If the mel has TT frames and hop HH samples, the generator should produce approximately THTH samples, with stated padding and boundary adjustments. A product of upsampling factors different from HH changes duration. A period discriminator rearranges a wave into rows of length pp and can compare patterns separated by pp samples; several periods capture different regularities. Another set can examine the signal at different scales. These views are not human scores: they only define what regularities discriminators try to distinguish during training.

Feature loss compares internal discriminator activations for real and generated audio; mel loss compares acoustic representations; adversarial loss teaches the generator to fool current discriminators. A generator can improve one quantity and worsen another. Evaluate on held-out examples and listen to signals aligned in time and amplitude. For comparison with Griffin–Lim, use exactly the same mel and state that magnitude recovery does not uniquely solve phase or perceptual quality.

Quantizing the residual

Residual vector quantization (RVQ) approximates vector x\vb{x} by summing entries from several codebooks. With r0=x\vb{r}_0=\vb{x}, stage mm chooses km=arg min⁡k∥rm−1−ek(m)∥2k_m=\argmin_k\norm{\vb{r}_{m-1}-\vb{e}^{(m)}_k}^2 and updates rm=rm−1−ekm(m)\vb{r}_m=\vb{r}_{m-1}-\vb{e}^{(m)}_{k_m}. Reconstruction is x^M=∑m=1Mekm(m)\hat{\vb{x}}_M=\sum_{m=1}^M\vb{e}^{(m)}_{k_m}. Each stage encodes what earlier stages did not explain; greedy choices do not ensure the globally optimal combination.

If each codebook contains the exact zero vector, nearest-neighbor distance cannot exceed choosing zero and hence ∥rm∥≤∥rm−1∥\norm{\vb{r}_m}\le\norm{\vb{r}_{m-1}}. Without that candidate the claim fails: for zero residual and sole code 1, error rises from 0 to 1. In a neural codec, latent representation error also does not guarantee an audio perceptual metric improves monotonically after decoding. It must be measured.

A neural audio codec combines encoder, quantizer, and decoder. With ff frames per second, MM codebooks and KK fixed-length-coded entries, nominal rate is fM⌈log⁡2K⌉fM\lceil\log_2 K\rceil bits per second, excluding headers and entropy coding. It does not require entries to be equiprobable; distribution matters if entropy coding is applied. SoundStream jointly trains encoder, RVQ and decoder and uses quantizer-layer dropout to operate at different rates. Lower rate can discard detail; do not confuse index rate with effective file rate including metadata.

InteractiveThe RVQ ladder

Original audio and reconstruction: 4.00 s, mono at 24 kHz.

Original reference
Reconstruction with 2 levels
Signal-to-noise ratio by level
Latent RMS residual after each stage
Nominal rate1.50 kb/s
Waveform SNR1.68 dB
Latent residual RMS0.870
A held-out LJSpeech 1.1 clip was encoded with EnCodec 24 kHz and its first 1, 2, 4 and 8 levels decoded. The first level is manual truncation, not an official bitrate mode. Rate excludes headers, and waveform SNR does not replace perceptual evaluation.

In this example latent RMS residual falls from 0.990 with one level to 0.515 with eight; waveform SNR rises from 1.39 to 5.00 dB. These are measurements on one clip, not a guarantee of monotonicity for every signal. The codec uses 75 frames/s and 1024-entry codebooks: two, four, and eight levels correspond to nominal 1.5, 3, and 6 kb/s. The sample was resampled from 22.05 to 24 kHz with an antialias filter and cropped to four seconds. Figure WAVs were obtained with published EnCodec weights and their provenance is in the lab; LJSpeech declares its recordings public domain. The consulted EnCodec weight card does not declare a license, so redistribution requires separate checking.

Language over codes and flow

A codec language model predicts audio tokens conditioned on text and an acoustic clip. VALL-E explores a three-second recording as a prompt from an unseen speaker and generates codec codes. That prompt can contain not only voice identity but noise, emotion, and reverberation; preserving one property in an example does not demonstrate independent control of all of them. Autoregressive and non-autoregressive variants distribute sequence and quantization-level generation differently.

InteractiveFrom prompt to codes
  • Acoustic prompt
  • First level
  • Remaining levels
PPPNNNNN
Level 1
Level 2
Level 3
Level 4
Level 5
Level 6
Level 7
Level 8

P: prompt; N: new. Scroll horizontally to see all codes. New text + prompt condition the levels. The waveform is generated after completing codes.

1
StageFirst level
Prompt3 seconds
Advance from the prompt to the first generated level and then the rest. Each column is schematic, not drawn to temporal scale; the pattern illustrates a factorization, not real model data.

Flow-matching TTS learns a field transporting an initial distribution toward acoustic features conditioned on text and context. In F5-TTS, text is padded to acoustic length and a diffusion transformer learns the field without an explicit per-phoneme duration predictor. Output length still must be chosen and the path numerically solved; no explicit predictor does not mean duration is known without errors. Duplex dialogue models add turn-taking, interruptions, and concurrent generation that are not measured with one isolated sentence.

In a simple construction, take noise x0\vb{x}_0 and target features x1\vb{x}_1 and interpolate xt=(1−t)x0+tx1\vb{x}_t=(1-t)\vb{x}_0+t\vb{x}_1. The target field conditioned on that pair is x1−x0\vb{x}_1-\vb{x}_0; a network minimizes squared error given xt\vb{x}_t, time, and condition. At generation integrate x˙t=vθ(xt,t,condicioˊn)\dot{\vb{x}}_t=\vb{v}_\theta(\vb{x}_t,t,\text{condición}). A finite network and a few-step integrator introduce error: straight interpolation in the training target does not show one evaluation is enough to synthesize speech.

A full-duplex voice dialogue system must process input while emitting its own output, with silence, overlaps, and interruptions represented in time. For example, Moshi models parallel user and system speech streams and generates temporally related text and codec tokens. This permits study of non-rigid turns; it does not guarantee appropriate interruption timing or compliance with a command heard while speaking. Evaluation needs recordings with overlap, reaction latency, and turn-taking errors, in addition to this lab’s isolated-sentence synthesis metrics.

Synthesized speech requires multiple evaluation views. Use WER from an independent recognizer for intelligibility, a speaker-similarity measure from a model not used to select examples, and perceptual tests when claiming naturalness. Low WER does not measure vocal similarity or absence of artifacts; high similarity proves neither consent nor identity. Automatic evaluators can have biases and fail in the generator’s domain. Keep test sentences and speakers separate, report uncertainty, and listen to an audited sample rather than inventing human annotations. Cloning requires verifiable consent, access control, and provenance tracking; a watermark or detector helps only if evaluated against transformations and false positives.

Lab: RVQ with explicit zero

We use four-band spectral vectors extracted from a 2.67 s synthetic SAPI phrase at 16 kHz. Each frame uses a 400-sample Hann window and hop 160; bands contain spectral log1p(100 × potencia media). The 265 compressed precomputed frames are included to avoid downloads; the extractor can regenerate them from the WAV. Test is an interior block of 39 speech frames; three separation frames are left at each boundary to prevent sample overlap. The rest trains. Mean and deviation are estimated only on training. This is one utterance, not a test of generalization to new sentences or speakers. We fit eight 16-entry codebooks with the first entry fixed to zero. The first strategy applies k-means to each stage’s residual; the second updates sums and counts with exponential moving average (EMA). The metric is squared error on normalized features, not voice quality or neural-codec output. At 100 frames per second each 16-entry index occupies four bits before entropy compression.

[ ]RVQ: k-means and EMABrowser
import numpy as np
import base64,zlib
rng=np.random.default_rng(29)
blob='eJzt1/k313n/BvCPJVGI0IKWQSXLrayf1+v9Wp5vyZpGe6lmStM6JnWXLYMUSoXIlggpkRAySjstFDVJ4lOpKVMIRUWW6jv/xP3D95x5/AHXL9c51zmXRPK/VRtaguZ3WqBtWXpoXBGRbv30BDucUcU6F+VxX8N0BIUOeE2kDHWZR6P5P0xE5dmdOCh+JB4TkY9q0CfpzVc1eLP8KLznWgGaHdch1VjegUoNLyKTcQ+Q/5dS6acKVdyfswcV3jmIVvTfly5tG0ItjbdR5ZEk5PH0nlTiJcE67pHo8+wIdF9hNjpZV46iFu5GL/JmoteRVdK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fwzH+56DrMAlTPtnmaCzz06wysqH4683s1lGv5LqlCfCuGPZ0Lejiw19CKOH+9XJZYej4N1izp9YpNGCs7vJw9oMMGrW4A+XqFKlUYZk6NspMOCGvP3DcdIX5EnOfcgBhxoNXvs5jiyfo0dWdmbByx5Lvky5lDw+u0lY75EAWzb3MhXDCOIxxkcYVomAgoo3rF6mQTx6/8Qr69xh/6AJcwk5I0xVq0FVnif45hsbaerfxkLtL/7o8+LJLC/6OgnbHo9DvuqhYas0YXb7NKHbrxVZF2qhtqhuLKcfjeM8R2NtU0c05UoANnNdiy0mPUZG7b+gZfa6uOcLxk6L2tGgYiZ6oaOF959Vx7ov3iI7X1e0O9EEf9ycip6aK+OJ0pXI8Y0mHpmtibPdSpFK4xJU66OBSh58l/YZLJI2xSpL/8f341//+tf/I/8HNNdFhg=='
x=np.frombuffer(zlib.decompress(base64.b64decode(blob)),dtype='<f4').reshape(-1,4).astype(float)
raw_train=np.concatenate([x[:100],x[145:]]);raw_test=x[103:142]
mean=raw_train.mean(axis=0);std=np.maximum(raw_train.std(axis=0),1e-6)
train=(raw_train-mean)/std;test=(raw_test-mean)/std
def nearest(r,book):
    return np.argmin(((r[:,None,:]-book[None,:,:])**2).sum(-1),axis=1)
def fit_rvq(data,method,stages=8,k=16):
    residual=data.copy();books=[]
    for stage in range(stages):
        book=np.vstack([np.zeros((1,data.shape[1])),residual[rng.choice(len(residual),k-1,replace=False)]])
        if method=='kmeans':
            for _ in range(12):
                ids=nearest(residual,book)
                for j in range(1,k):
                    selected=residual[ids==j]
                    if len(selected):book[j]=selected.mean(0)
        else:
            counts=np.ones(k);sums=book.copy()
            for _ in range(80):
                batch=residual[rng.integers(len(residual),size=64)];ids=nearest(batch,book)
                bc=np.bincount(ids,minlength=k);bs=np.zeros_like(book);np.add.at(bs,ids,batch)
                counts=.95*counts+.05*bc;sums=.95*sums+.05*bs
                book[1:]=sums[1:]/np.maximum(counts[1:,None],1e-8)
        residual-=book[nearest(residual,book)];books.append(book)
    return books
def evaluate(data,books):
    r=data.copy();errors=[float(np.mean(r*r))];usage=[]
    for book in books:
        ids=nearest(r,book);usage.append(len(np.unique(ids)));r-=book[ids];errors.append(float(np.mean(r*r)))
    return errors,usage
[ ]Codebooks fitted by k-meansBrowser
books=fit_rvq(train,'kmeans');errors,usage=evaluate(test,books)
assert all(a>=b-1e-12 for a,b in zip(errors,errors[1:]))
print('kmeans MSE 0/1/2/4/8:',[round(errors[i],5) for i in (0,1,2,4,8)],'códigos usados:',usage)
[ ]Codebooks updated by EMABrowser
books=fit_rvq(train,'ema');errors,usage=evaluate(test,books)
assert all(a>=b-1e-12 for a,b in zip(errors,errors[1:]))
print('EMA MSE 0/1/2/4/8:',[round(errors[i],5) for i in (0,1,2,4,8)],'códigos usados:',usage)
print('tasa 1/2/4/8 etapas (bit/s):',[100*m*4 for m in (1,2,4,8)])

Entries with no assignments receive no new k-means mean; EMA can retain barely used codes. Counting codes used on test can detect that symptom, though it is insufficient to judge codebook quality. In real training dead codes can be reinitialized with data residuals and usage and distortion tracked on validation; the example retains entries without restarting so the diagnosis remains visible.

Local lab: mel to waveform and text to speech

The LJSpeech preparer takes the original LJSpeech 1.1 archive, checks SHA-256, and extracts the first 1100 WAVs in archive order: 1000 training, 50 validation and 50 test. The compressed archive is about 2.75 GB. It records one speaker: the split separates sentences, not speakers. Keep the manifest with samples and avoid tuning thresholds on test sentences.

The compact vocoder trains from scratch with a transposed-convolution generator and three period discriminators of 2, 3 and 5. Each update combines adversarial, feature and mel losses on 4096-sample crops, about 186 ms. This short context does not by itself measure coherence of a long sentence. It uses 80 magnitude bands, Slaney scale and normalization, 8 kHz maximum frequency, FFT 1024, hop 256 and 22050 Hz sampling. These parameters must match the pretrained vocoder; a mel with different power or scale is not interchangeable. The checkpoint includes optimizers and random states, and a PAUSE file in the output folder requests saving and stopping after the next step. Remove it before resuming. Do not replace an incomplete run with a randomly initialized checkpoint.

Before running the campaign, verify upsampling-layer geometry. This local cell only checks dimensions and gradients with artificial data; real training runs with the program and speech dataset indicated below.

[ ]Checking the upsampling factorLocal GPU
import torch
from torch import nn
torch.set_num_threads(2);torch.manual_seed(29)
factors=(8,8,2,2);channels=(80,64,32,16,1)
layers=[nn.ConvTranspose1d(channels[i],channels[i+1],2*s,stride=s,padding=s//2)
        for i,s in enumerate(factors)]
model=nn.Sequential(*layers);mel=torch.randn(1,80,16);wave=model(mel)
loss=wave.square().mean();loss.backward()
print('tramas',mel.shape[-1],'muestras',wave.shape[-1],
      'producto de factores',wave.shape[-1]//mel.shape[-1],
      'gradiente finito',bool(torch.isfinite(layers[0].weight.grad).all()))
assert wave.shape[-1]==16*256 and torch.isfinite(loss)
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

The comparator supplies the same mel to the trained network, SpeechBrain HiFi-GAN, and Griffin–Lim with 32 iterations, starting from a mel pseudoinverse clipped to nonnegative magnitudes. For one held-out sentence the mel was checked against SpeechBrain’s recommended function: the 80 × 447 matrices matched exactly in this run. The pretrained system adds five padding frames on each side during inference: corresponding samples at the start are removed before comparison. Log-mel distance and waveform SNR capture different errors; the latter penalizes phase changes even if sound is plausible. Neither is a human naturalness score.

On an RTX 3060, the compact GAN trained for 100,000 steps in 7754.3 accumulated seconds, about 2.15 hours, with batches of eight crops. The campaign resumed the 40,000-step checkpoint with optimizers and random states retained; time excludes the pause between segments. Highest recorded CUDA allocated-memory peak was 82.4 MB. On the same 50 test sentences, mean per-sentence absolute log-mel error was 0.3484 for the GAN, 0.2322 for HiFi-GAN and 0.1204 for Griffin–Lim. GAN errors ranged from 0.3162 to 0.3756; per-sentence mean waveform SNRs were respectively −1.62, −2.82 and −2.92 dB. Griffin–Lim’s better mel error here does not prove greater naturalness: it optimizes a reconstruction related to input magnitude. Values concern this architecture, dataset and run, not a universal ranking. The per-sentence detail, training protocol, evaluation protocol, resumption lineage and checkpoint enable auditing.

At the 40,000-step intermediate point, the GAN achieved mean log-mel error 0.4065 on the same sentences. The difference from 100,000 steps describes this particular trajectory and metric; it does not directly measure perceptual quality. The protocol and intermediate checkpoint are also retained.

Listen to the first held-out sentence: the same original recording and three reconstructions. WAVs are converted to 16-bit PCM with amplitude clipping; the metrics above were calculated before that conversion.

Original:

Compact GAN:

Pretrained HiFi-GAN:

Griffin-Lim:

The F5-TTS experiment uses a complete validation recording from the same speaker as reference and the first ten test transcripts of 35 to 90 characters as targets. It generates with 32 integration steps and a fixed seed per sentence. Similarity evaluation compares outputs with reference using ECAPA; cosine is not a calibrated identity decision. A control manifest uses natural recordings of those same sentences. For intelligibility, a preparer resamples the natural control to 16 kHz and gathers both groups with the same text reference; Whisper small applies the same normalization to reference and hypothesis. The consulted F5-TTS v1 weights are licensed CC BY-NC 4.0; HiFi-GAN and ECAPA are distributed under Apache-2.0 according to their cards. A recording’s public-domain status does not itself establish a person’s consent to other uses of their voice. Splits separate sentences within this experiment but do not establish that those sentences or this voice were absent from published model pretraining. Measures on one voice do not prove generalization to unseen speakers.

All ten sentences were generated on the RTX 3060; peak CUDA allocated memory for that run was 2.09 GB. ECAPA gave mean cosine 0.6536 against reference audio. As a control, the ten original recordings of those sentences gave 0.5513 against the same reference. Both series are from the same speaker, and the difference reminds us cosine depends on sentence, duration, and acoustic conditions: it does not show synthetic voice is more faithful than the original. This is a descriptive measure with one evaluator, not an identity probability or naturalness score. The ten WAVs and manifest retain hashes and text references to audit per-sentence recognition; they were generated using noncommercial F5-TTS v1 weights.

On the same ten pairs, Whisper small made 12 errors in 121 words for F5, micro WER 9.92%, and 10 in 121 on natural recordings, 8.26%. Per-sentence hypotheses and errors and the twenty paired WAVs permit inspection. Normalization lowercases, separates punctuation and symbols, and does not expand digits: a numeral and the same quantity in words count as different, as do some acronym variants. For example, “tenth” versus “10th” counts as an error in both groups; three sentences with numbers or acronyms account for nine errors in each group. This one-speaker, ten-sentence comparison measures recognition with that ASR and normalization; it does not identify each error’s cause or demonstrate naturalness.

As an example, listen to the first output generated from “The wards had open fires, but the separate cells were not warmed at all.”; it is one of ten sentences chosen before generation, not selected by quality.

To reproduce, install dependencies in an isolated environment with compatible CUDA PyTorch and torchaudio, transformers, scipy and einops. The run used PyTorch and torchaudio 2.11.0+cu128, transformers 5.23.0, NumPy 2.5.4 and SciPy 1.18.1. Then install the tested complementary versions with pip install --no-deps -r requirements-tts.txt, retaining already installed base libraries. Programs accept paths as arguments and do not depend on internal project folders. The model downloader pins revisions and checks hashes; the seven sets occupy about 2.72 GB, of which F5 weights take about 1.35 GB. You can download one with --only and the name shown in its help. Sources include SWivid/F5-TTS, charactr/vocos-mel-24khz, speechbrain/tts-hifigan-ljspeech and speechbrain/spkrec-ecapa-voxceleb. Download the script package into a working directory and run, for example:

python prepare_ljspeech.py --archive LJSpeech-1.1.tar.bz2 --out ljspeech-subset
python prepare_models.py --out models
python tacotron_alignment.py --model models/tacotron2-ljspeech --vocoder models/hifigan-ljspeech --out tacotron-attention
python vocoder_lab.py --data ljspeech-subset --output vocoder-run --steps 100000
python compare_vocoder.py --data ljspeech-subset --checkpoint vocoder-run/checkpoint.pt --pretrained models/hifigan-ljspeech --out vocoder-eval
python f5_synthesize.py --data ljspeech-subset --model models/f5-tts-v1/F5TTS_v1_Base --vocoder models/vocos-mel-24khz --out f5-eval
python speaker_similarity.py --generated f5-eval --reference ljspeech-subset/subset/LJ010-0255.wav --model models/ecapa-voxceleb --out f5-similarity.json
python natural_control_manifest.py --generated f5-eval --data ljspeech-subset --out natural-control
python speaker_similarity.py --generated natural-control --reference ljspeech-subset/subset/LJ010-0255.wav --model models/ecapa-voxceleb --out natural-similarity.json
python prepare_asr_control.py --generated f5-eval --data ljspeech-subset --out tts-asr
python evaluate_whisper.py --manifest tts-asr/manifest.jsonl --model models/whisper-small --out tts-asr-wer.json

The EnCodec figure can be repeated with the reconstruction program, checkpoint facebook/encodec_24khz at revision c1dbe2ae3f1de713481a3b3e7c47f357092ee040, and a mono 22050 Hz WAV. For the attention matrix, Tacotron2 requires revision d01e530d6d8e1b388c04b882305867addbed4389 of speechbrain/tts-tacotron2-ljspeech. That figure’s archive contains 16 kHz WAVs and the manifest accepted by evaluate_whisper.py. Programs retain hashes and seeds; these fix the protocol but do not guarantee bit-identical results across devices or versions. On Windows with torchaudio 2.11, SpeechBrain 1.0.3 calls a removed backend API; scripts needing it apply a local compatibility adjustment and read WAVs with SciPy.

Exercises

Numeric
A codec produces 75 frames per second and uses 8 codebooks of 1024 entries with fixed-length indices. What is nominal rate in kbps, excluding headers?
Quiz
What changes when unconstrained attention is replaced by monotonic duration expansion?
Quiz
What protocol better evaluates a cloning system without listening to every sample?
Quiz
What combination addresses voice impersonation risk?
Code
Implement rvq_encode(x, codebooks) and rvq_decode(codes, codebooks). x is a matrix of vectors by row and each codebook a matrix of entries by row. Return indices of shape (n, stages), choosing the residual's neighbor at each stage; decode sums selected entries. Decreasing-error tests include a zero vector in every codebook.
def rvq_encode(x,codebooks):
  pass
def rvq_decode(codes,codebooks):
  pass
Shift+Enter to run
Key idea
Synthesis separates text, acoustic representation and waveform; RVQ trades rate against reconstruction, while intelligibility, identity and naturalness require different evaluations.