Algorithm Search⌘K

Algorithmadvanced

HMM-based speech synthesis

Also called statistical parametric speech synthesis, HTS.

Model spectrum, pitch and duration with context-dependent HMMs trained on speech, then pick state durations, generate smooth parameters and drive a vocoder.

Time
O(N h + T M) worst
Space
Θ(T M) extra
Where
M = the number of static parameters per frame; N = the number of HMM states of the utterance; T = the number of frames; h = the depth of the decision trees
Properties
deterministicnot exactnot in placeoffline
Origin
Takayoshi Yoshimura, Keiichi Tokuda, Takashi Masuko, Takao Kobayashi, Tadashi Kitamura, 1999

HMM-based speech synthesis is the classic method of statistical parametric text-to-speech. It does not store speech to replay, as unit selection does. It stores a statistical model of speech parameters. Each phone in its context has a small left-to-right hidden Markov model, whose states give Gaussian distributions for the spectrum, the pitch and their delta features, plus a Gaussian for the duration of each state. There are far too many contexts to train each one, so decision trees cluster them, separately for each kind of parameter. To speak a sentence, the system builds the chain of state models for its context labels, chooses how many frames each state lasts, generates the smooth parameter trajectory of highest likelihood with maximum likelihood parameter generation (MLPG), and drives a vocoder with it. The HTS toolkit, built on HTK, is the reference implementation, which is why the method is often called HTS.

In plain words

Record a speaker and measure, for every short frame, the shape of the sound and its pitch. Then learn a simple average model of how each speech sound behaves, given the sounds around it, the stress and the place in the sentence. Each sound is split into a few parts, and each part stores an average, a spread, and how long it usually lasts.

To say a new sentence, look up the parts for each sound, decide how many frames each part lasts, and draw the most likely smooth path of sound shapes and pitch through them. A vocoder, a simple model of the voice, turns that path into audio.

The voice is small, smooth and easy to change, for example to a new speaker with little data. But the averaging makes it sound muffled next to real recordings.

The problem

Input. A text, turned by a front end into a sequence of full-context labels, one per phone. A label holds the phone, its neighbors, its position in the syllable, word and phrase, stress, part of speech and similar facts. The trained model has, for each of the S=5S = 5 emitting states of a phone model, a decision tree for each stream: mel-cepstral coefficients with their deltas, log⁡F0\log F_0 with its deltas, and the state duration. Each leaf of a tree holds a Gaussian.

Output. A waveform whose parameters, frame by frame, have high likelihood under the model for the given labels.

Training, in short. Extract mel-cepstral coefficients and log⁡F0\log F_0 at a fixed frame rate, add delta and delta-delta features, and train the context-dependent HMMs with the Baum-Welch algorithm. Cluster the states by decision trees grown with questions about the context, separately for each stream, until a stopping rule such as minimum description length says stop. Fit the duration Gaussians from the state occupancies. F0F_0 is not defined in unvoiced frames, so the pitch stream uses a multi-space distribution: a weight for voiced and unvoiced, and a Gaussian for log⁡F0\log F_0 in the voiced space.

The algorithm

  1. HMM-SYNTHESIZE(text, trees, rho)
  2. 1labels <- FRONT-END(text) // one full-context label per phone
  3. 2for each label l, for each state k = 1 .. 5 of its phone model do
  4. 3(m, v) <- duration Gaussian of the leaf of the duration tree for (l, k)
  5. 4G[k] <- leaves of the spectrum and F0 trees for (l, k)
  6. 5d <- max(1, round(m + rho * v)) // rho = 0 gives the mean durations
  7. 6append d copies of G[k] to the frame sequence
  8. 7voiced <- frames whose voiced weight is above 1/2
  9. 8c <- MLPG(means and variances of the spectrum stream, static, delta and delta-delta windows)
  10. 9f <- MLPG(the same for log F0, over each voiced region)
  11. 10excitation <- pulses at F0 = exp(f) in voiced frames, white noise in unvoiced frames
  12. 11return VOCODER-FILTER(excitation, c) // for example an MLSA filter

Line L5 sets the duration of each state. If the total length TT of the utterance is given, the choice ρ=(T−∑kmk)/∑kvk\rho = (T - \sum_k m_k) / \sum_k v_k over all states of the utterance gives the durations of highest likelihood with that total; ρ\rho then works as a speaking rate control. Lines L8 and L9 are MLPG, one banded linear solve per parameter dimension. Line L11 is a source-filter vocoder: the excitation is the source and the mel-cepstrum sets the filter.

Example

Durations. Take three states with duration means m=(3,5,2)m = (3, 5, 2) frames and variances v=(1,4,1)v = (1, 4, 1). With ρ=0\rho = 0 the durations are the means, (3,5,2)(3, 5, 2), 10 frames. For a slower rendering with T=16T = 16 frames, ρ=(16−10)/(1+4+1)=1\rho = (16 - 10) / (1 + 4 + 1) = 1 and the durations are (3+1,5+4,2+1)=(4,9,3)(3 + 1, 5 + 4, 2 + 1) = (4, 9, 3), which sum to 16. The state with the largest variance takes most of the extra time, because stretching it costs the least likelihood. For T=7T = 7, ρ=−3/6=−0.5\rho = -3 / 6 = -0.5 and the durations are (2.5,3,1.5)(2.5, 3, 1.5) before rounding.

Trajectory. With the durations fixed, each frame has the Gaussians of its state. If two states of 3 frames each have static means 0 and 1, static variance 1 and a delta variance of 1/4 with zero delta means, the frame-wise means form a step (0,0,0,1,1,1)(0, 0, 0, 1, 1, 1). MLPG turns this into the smooth curve (0.2,0.3,0.3,0.7,0.7,0.8)(0.2, 0.3, 0.3, 0.7, 0.7, 0.8), as worked out on the MLPG page.

A toy. The code with this page is a toy, not HTS. It runs lines L1 to L11 on one-dimensional streams with hand-made trees: a phone list as the front end, durations by line L5, MLPG solved by dense elimination, and a pulse or noise source through a first-order all-pole filter as the vocoder. It trains nothing.

Correctness

The whole system has no single correct output; its quality is measured by listening tests. Three of its steps are exact for the model.

Duration choice (theorem). Treat the state durations as real numbers d1,…,dNd_1, \ldots, d_N with Gaussian log-likelihood ∑klog⁡N(dk;mk,vk)\sum_k \log \mathcal{N}(d_k; m_k, v_k) and the constraint ∑kdk=T\sum_k d_k = T. The objective is strictly concave, so a stationary point of the Lagrangian ∑k−(dk−mk)22vk+ρ(∑kdk−T)\sum_k -\frac{(d_k - m_k)^2}{2 v_k} + \rho (\sum_k d_k - T) is the unique maximum. Setting the derivative to 0 gives dk=mk+ρvkd_k = m_k + \rho v_k, and the constraint gives ρ=(T−∑kmk)/∑kvk\rho = (T - \sum_k m_k) / \sum_k v_k. Rounding to integers and the lower bound of 1 frame on line L5 make the result approximate.

Parameter generation (theorem). For the fixed state sequence, lines L8 and L9 return the trajectory of highest likelihood under the static and delta Gaussians, by the proof on the MLPG page.

Training (theorem). Each Baum-Welch iteration does not lower the training likelihood, as for any EM algorithm. Decision tree clustering is greedy and gives no optimality guarantee.

The step from durations to trajectory is a heuristic. The best pair of a state sequence and a trajectory, and the best trajectory over all state sequences, are harder problems; the fixed durations of line L5 replace them.

Proof: The exact steps of the toy HMM synthesizer, durations of highest likelihood and the MLPG trajectoryfull

The full system has no single correct output, so this note proves the two steps that are exact for the model, and states what the toy code does around them. The code is a toy: one-dimensional streams, hand-made trees, dense linear algebra and a first-order filter as the vocoder.

Durations (line L5)

Fix N≥1N \ge 1 states with duration means mkm_k and variances vk>0v_k > 0, and a total TT. Over real vectors dd with ∑kdk=T\sum_k d_k = T, maximize

ℓ(d)=∑k=1N(−12log⁡(2πvk)−(dk−mk)22vk).\ell(d) = \sum_{k=1}^{N} \Bigl( -\tfrac{1}{2} \log (2 \pi v_k) - \frac{(d_k - m_k)^2}{2 v_k} \Bigr).

Theorem 1. The unique maximizer is dk=mk+ρvkd_k = m_k + \rho v_k with ρ=(T−∑kmk)/∑kvk\rho = (T - \sum_k m_k) / \sum_k v_k.

Proof. The function ℓ\ell is a sum of strictly concave quadratics, so it is strictly concave, and the constraint set is an affine subspace. A point of that subspace is the unique maximum if and only if the gradient of ℓ\ell there is orthogonal to the subspace, that is, all partial derivatives −(dk−mk)/vk-(d_k - m_k) / v_k are equal to one number ρ\rho. This gives dk=mk+ρvkd_k = m_k + \rho v_k, and summing over kk gives ∑kmk+ρ∑kvk=T\sum_k m_k + \rho \sum_k v_k = T, which fixes ρ\rho. □\square

With ρ=0\rho = 0 the rule returns the means, the unconstrained maximum. Integer vectors with the same total form a subset of the real ones, so their likelihood is at most ℓ\ell at the real maximizer; the tests check this against every integer vector for small NN and TT. The code rounds each dkd_k and raises it to at least 1, so the integer result is close to, but not always equal to, the best integer vector.

Trajectory (lines L8 and L9)

For a fixed frame sequence with static means μts\mu^s_t, variances vtsv^s_t, delta means μtd\mu^d_t and variances vtdv^d_t, and the clamped delta window Δct=12(cmin⁡(t+1,T−1)−cmax⁡(t−1,0))\Delta c_t = \frac{1}{2}(c_{\min(t+1, T-1)} - c_{\max(t-1, 0)}), the objective

J(c)=−∑t((ct−μts)22vts+(Δct−μtd)22vtd)J(c) = -\sum_{t} \Bigl( \frac{(c_t - \mu^s_t)^2}{2 v^s_t} + \frac{(\Delta c_t - \mu^d_t)^2}{2 v^d_t} \Bigr)

is a concave quadratic −12c⊤Pc+r⊤c+const-\frac{1}{2} c^\top P c + r^\top c + \text{const} with P=∑rowsww⊤/vP = \sum_{\text{rows}} w w^\top / v and r=∑rowswμ/vr = \sum_{\text{rows}} w \mu / v, summed over the static and delta rows that the code builds.

Theorem 2. If all static variances are finite and positive, PP is positive definite and the unique maximizer of JJ is c∗=P−1rc^* = P^{-1} r, which the code returns.

Proof. The static rows alone give the diagonal matrix with entries 1/vts>01 / v^s_t > 0, and the delta rows add positive semidefinite terms, so PP is positive definite. The gradient of JJ is r−Pcr - P c, which vanishes only at c∗=P−1rc^* = P^{-1} r, and strict concavity makes it the maximum. Gaussian elimination with partial pivoting solves Pc=rP c = r for any nonsingular PP. □\square

The code builds PP and rr from exactly these rows, so it maximizes JJ. The tests check the page example (0.2,0.3,0.3,0.7,0.7,0.8)(0.2, 0.3, 0.3, 0.7, 0.7, 0.8) and that random perturbations of the result lower JJ. When every row has infinite variance, P=0P = 0 and the code raises an error. Line L9 applies the same solve to each run of voiced frames alone, which is the maximization of the same objective restricted to that run.

The rest

Lines L1 to L4 and L6 are lookups and copies: each phone gets 5 states, each state gets the leaves its context reaches in each tree, and each state is copied dkd_k times, so there are ∑kdk\sum_k d_k frames. Lines L10 and L11 make T⋅hopT \cdot \text{hop} samples from the excitation and the filter, with the filter coefficient clamped to [−0.99,0.99][-0.99, 0.99] so that it is stable.

Complexity

The tree lookups of lines L3 and L4 cost O(h)O(h) for each of the NN states, for each of the three streams. Line L6 writes TT frames. MLPG solves one banded system for each of the MM static dimensions in O(T)O(T) time for fixed window widths, so lines L8 and L9 cost O(TM)O(T M). The vocoder filter of line L11 costs a constant per sample for each cepstral coefficient, so it is linear in the length of the audio. The total is O(Nh+TM)O(N h + T M) plus the vocoder, and the memory is Θ(TM)\Theta(T M) for the frame means, variances and outputs.

A voice is small: one Gaussian per leaf of each tree, against hours of stored audio for a unit selection voice.

Properties

  • Deterministic. For a given text and ρ\rho the output is fixed. The model can be sampled, but the mean trajectory sounds better.
  • Smooth. The delta features and MLPG remove the jumps at state boundaries.
  • Over-smoothed. Averaging in training and the mean trajectory in synthesis lower the variance of the generated parameters below that of natural speech. This is the main reason for the muffled sound.
  • Flexible. Every part of the voice is a parameter, so speaker adaptation, speaking rate, pitch shifts and interpolation between voices are linear operations on means and variances.
  • Robust to sparse data. Context clustering shares data among similar contexts, so unseen contexts still get a model.

Variants and improvements

  • Hidden semi-Markov models. Training the state durations inside the model, as a hidden semi-Markov model, in place of fitting them afterward from the HMM occupancies.
  • Global variance. Adding a term to the generation objective that keeps the variance of each generated parameter over the utterance close to that of natural speech, which reduces over-smoothing at the cost of an iterative solve.
  • Better vocoders. Mixed excitation and spectral analysis such as STRAIGHT in place of the simple pulse or noise source.
  • Speaker adaptation. Moving the Gaussians of an average voice toward a new speaker with a few minutes of data, with linear transforms such as MLLR.
  • Neural acoustic models. Replacing the decision trees by a neural network that maps context features to the frame-wise means directly, with MLPG kept as the last step. Later, end-to-end models such as FastSpeech kept the duration idea and dropped the HMMs.

When to use it

Use it where the voice must be small, fast and controllable, and where some loss of naturalness is acceptable: embedded devices, many voices from little data, or research on prosody and adaptation where every parameter must be visible. Where naturalness matters most, neural acoustic models and vocoders such as WaveNet are better in most published tests, and unit selection is better for a large single-speaker database in a narrow domain.

Pitfalls

  • Bad alignments in training. Errors in the labels or the forced alignment put frames in the wrong states and blur the models. Check the labels against the audio.
  • Unvoiced frames. log⁡F0\log F_0 is undefined in unvoiced frames. Interpolating it, or using a single Gaussian over both spaces, gives wrong pitch at voicing boundaries; use the multi-space distribution and run MLPG over each voiced region alone.
  • Rounding of durations. Rounding each state alone can change the total length by up to half a frame per state. If the total matters, round the cumulative sums.
  • Zero or tiny variances. A leaf with very few frames gets a tiny variance and dominates the weighted least squares. Floor the variances.
  • Expecting the mean to sound natural. The trajectory of highest likelihood is smoother than any real utterance. Without global variance or a similar fix, the voice sounds muffled even when the models are accurate.

Implementations

Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.

hmm_based_speech_synthesis.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/hmm-based-speech-synthesis/. The authors are listed in prov/VMKZVY.jsonl.

"""A toy version of the synthesis stage of HMM-based speech synthesis.

This is a toy. It is not HTS and it does not train anything. It keeps the
core of the synthesis stage on one-dimensional streams:

  - a front end that turns a phone list into context labels (left, phone, right),
  - decision trees that map a (context, state) pair to a leaf with Gaussians,
  - state durations d_k = max(1, round(m_k + rho v_k)),
  - expansion of the state Gaussians to frames,
  - maximum likelihood parameter generation (MLPG) with static and delta
    windows, for a one-dimensional spectral parameter and for log F0 over each
    voiced region, solved here by dense Gaussian elimination because T is small,
  - a toy source-filter vocoder: a pulse train or white noise through a
    first-order all-pole filter whose coefficient is the spectral parameter.

The delta window is 0.5 (c[t+1] - c[t-1]) with the frame index clamped to
[0, T - 1] at the edges, as on the MLPG page.
"""

import math
import random
from typing import Dict, List, Sequence, Tuple

N_STATES = 5


def front_end(phones: Sequence[str]) -> List[Dict[str, str]]:
    """One context label per phone: the phone and its two neighbors ('#' at the edges)."""
    out = []
    for i, p in enumerate(phones):
        out.append({"left": phones[i - 1] if i > 0 else "#", "phone": p,
                    "right": phones[i + 1] if i + 1 < len(phones) else "#"})
    return out


def tree_lookup(tree, context: Dict[str, str], state: int):
    """Walk a decision tree. A node is ("leaf", payload) or ("q", key, values, yes, no);
    the key "state" asks about the state index, any other key about the context."""
    node = tree
    while node[0] == "q":
        _, key, values, yes, no = node
        x = state if key == "state" else context[key]
        node = yes if x in values else no
    return node[1]


def rho_for_total(means: Sequence[float], variances: Sequence[float], total: float) -> float:
    """The rho that makes the real-valued durations m_k + rho v_k sum to total."""
    return (total - sum(means)) / sum(variances)


def state_durations(means, variances, rho: float = 0.0) -> List[int]:
    return [max(1, int(round(m + rho * v))) for m, v in zip(means, variances)]


def mlpg_1d(mu_s, var_s, mu_d, var_d) -> List[float]:
    """The trajectory c maximizing sum_t N(c_t; mu_s, var_s) N(delta c_t; mu_d, var_d)."""
    T = len(mu_s)
    rows = []  # each row: (coefficients dict over frames, mean, variance)
    for t in range(T):
        rows.append(({t: 1.0}, mu_s[t], var_s[t]))
        lo, hi = max(t - 1, 0), min(t + 1, T - 1)
        w: Dict[int, float] = {}
        w[hi] = w.get(hi, 0.0) + 0.5
        w[lo] = w.get(lo, 0.0) - 0.5
        rows.append((w, mu_d[t], var_d[t]))
    P = [[0.0] * T for _ in range(T)]
    r = [0.0] * T
    for w, m, v in rows:
        for a, wa in w.items():
            r[a] += wa * m / v
            for b, wb in w.items():
                P[a][b] += wa * wb / v
    return _solve(P, r)


def _solve(A, b) -> List[float]:
    """Gaussian elimination with partial pivoting on copies of A and b."""
    n = len(b)
    M = [row[:] + [b[i]] for i, row in enumerate(A)]
    for k in range(n):
        p = max(range(k, n), key=lambda i: abs(M[i][k]))
        if abs(M[p][k]) < 1e-300:
            raise ValueError("singular system")
        M[k], M[p] = M[p], M[k]
        for i in range(k + 1, n):
            f = M[i][k] / M[k][k]
            if f:
                for j in range(k, n + 1):
                    M[i][j] -= f * M[k][j]
    x = [0.0] * n
    for i in range(n - 1, -1, -1):
        x[i] = (M[i][n] - sum(M[i][j] * x[j] for j in range(i + 1, n))) / M[i][i]
    return x


def synthesize(phones: Sequence[str], trees: Dict[str, tuple], rho: float = 0.0,
               hop: int = 80, fs: int = 8000, seed: int = 0):
    """Return (samples, frames) for a phone list.

    trees["dur"] leaves are (mean, variance) of a state duration in frames.
    trees["spec"] leaves are (mu_s, var_s, mu_d, var_d) of the spectral parameter.
    trees["f0"] leaves are (voiced_weight, mu_s, var_s, mu_d, var_d) of log F0.
    frames is a dict with the per-frame state means, the voicing and the trajectories.
    """
    labels = front_end(phones)  # @line L1
    spec_g, f0_g, dur_m, dur_v = [], [], [], []
    for lab in labels:  # @line L2
        for k in range(N_STATES):
            m, v = tree_lookup(trees["dur"], lab, k)  # @line L3
            dur_m.append(m)
            dur_v.append(v)
            spec_g.append(tree_lookup(trees["spec"], lab, k))  # @line L4
            f0_g.append(tree_lookup(trees["f0"], lab, k))
    d = state_durations(dur_m, dur_v, rho)  # @line L5
    spec_f, f0_f = [], []
    for k, n in enumerate(d):  # @line L6
        spec_f.extend([spec_g[k]] * n)
        f0_f.extend([f0_g[k]] * n)
    T = len(spec_f)
    voiced = [g[0] > 0.5 for g in f0_f]  # @line L7
    c = mlpg_1d(*[[g[i] for g in spec_f] for i in range(4)])  # @line L8
    logf0 = [None] * T
    t = 0
    while t < T:  # @line L9
        if not voiced[t]:
            t += 1
            continue
        u = t
        while u < T and voiced[u]:
            u += 1
        seg = f0_f[t:u]
        traj = mlpg_1d(*[[g[i] for g in seg] for i in range(1, 5)])
        logf0[t:u] = traj
        t = u
    rng = random.Random(seed)
    excitation, phase = [], 0.0
    for t in range(T):  # @line L10
        for _ in range(hop):
            if voiced[t]:
                phase += math.exp(logf0[t]) / fs
                if phase >= 1.0:
                    phase -= 1.0
                    excitation.append(1.0)
                else:
                    excitation.append(0.0)
            else:
                excitation.append(rng.gauss(0.0, 0.1))
    y, prev = [], 0.0
    for n, e in enumerate(excitation):  # @line L11
        a = max(-0.99, min(0.99, c[n // hop]))
        prev = e + a * prev
        y.append(prev)
    frames = {"durations": d, "voiced": voiced, "spec": c, "logf0": logf0,
              "spec_means": [g[0] for g in spec_f]}
    return y, frames
test_hmm_based_speech_synthesis.py 131 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/hmm-based-speech-synthesis/. The authors are listed in prov/VMKZVY.jsonl.

import itertools
import math
import random

import pytest

from hmm_based_speech_synthesis import (
    front_end,
    mlpg_1d,
    rho_for_total,
    state_durations,
    synthesize,
    tree_lookup,
)

VOWELS = {"a", "i"}

TREES = {
    # Vowels last longer; the middle state of every phone is the longest.
    "dur": ("q", "phone", VOWELS,
            ("q", "state", {2}, ("leaf", (6.0, 4.0)), ("leaf", (3.0, 1.0))),
            ("q", "state", {2}, ("leaf", (3.0, 1.0)), ("leaf", (2.0, 0.5)))),
    "spec": ("q", "phone", VOWELS,
             ("leaf", (0.8, 0.05, 0.0, 0.01)),
             ("q", "right", VOWELS, ("leaf", (0.3, 0.1, 0.0, 0.02)), ("leaf", (0.1, 0.1, 0.0, 0.02)))),
    "f0": ("q", "phone", {"s"},
           ("leaf", (0.0, 0.0, 1.0, 0.0, 1.0)),
           ("leaf", (1.0, math.log(120.0), 0.01, 0.0, 0.001))),
}


def dur_loglik(d, m, v):
    return sum(-0.5 * math.log(2 * math.pi * vk) - (dk - mk) ** 2 / (2 * vk) for dk, mk, vk in zip(d, m, v))


def test_page_duration_example():
    m, v = [3.0, 5.0, 2.0], [1.0, 4.0, 1.0]
    assert state_durations(m, v, 0.0) == [3, 5, 2]
    rho = rho_for_total(m, v, 16)
    assert rho == 1.0
    assert state_durations(m, v, rho) == [4, 9, 3]
    rho = rho_for_total(m, v, 7)
    assert rho == -0.5
    assert [mk + rho * vk for mk, vk in zip(m, v)] == [2.5, 3.0, 1.5]


def test_duration_rule_is_the_constrained_maximum():
    # The real-valued d_k = m_k + rho v_k beats every integer vector with the same total.
    rng = random.Random(4)
    for _ in range(30):
        n = rng.randint(1, 4)
        m = [float(rng.randint(1, 5)) for _ in range(n)]
        v = [float(rng.randint(1, 4)) for _ in range(n)]
        T = rng.randint(n, 14)
        rho = rho_for_total(m, v, T)
        best_real = dur_loglik([mk + rho * vk for mk, vk in zip(m, v)], m, v)
        for d in itertools.product(range(0, T + 1), repeat=n):
            if sum(d) == T:
                assert dur_loglik(d, m, v) <= best_real + 1e-12


def test_mlpg_page_example():
    c = mlpg_1d([0, 0, 0, 1, 1, 1], [1] * 6, [0] * 6, [0.25] * 6)
    for x, y in zip(c, [0.2, 0.3, 0.3, 0.7, 0.7, 0.8]):
        assert math.isclose(x, y, abs_tol=1e-12)


def test_mlpg_is_a_maximum():
    rng = random.Random(8)
    T = 9
    mu_s = [rng.uniform(-1, 1) for _ in range(T)]
    var_s = [rng.uniform(0.5, 2) for _ in range(T)]
    mu_d = [rng.uniform(-0.2, 0.2) for _ in range(T)]
    var_d = [rng.uniform(0.1, 1) for _ in range(T)]

    def obj(c):
        s = 0.0
        for t in range(T):
            d = 0.5 * (c[min(t + 1, T - 1)] - c[max(t - 1, 0)])
            s -= (c[t] - mu_s[t]) ** 2 / (2 * var_s[t]) + (d - mu_d[t]) ** 2 / (2 * var_d[t])
        return s

    c = mlpg_1d(mu_s, var_s, mu_d, var_d)
    base = obj(c)
    for _ in range(50):
        e = [rng.gauss(0, 0.05) for _ in range(T)]
        assert obj([a + b for a, b in zip(c, e)]) < base


def test_front_end_and_trees():
    labels = front_end(["s", "a"])
    assert labels == [{"left": "#", "phone": "s", "right": "a"}, {"left": "s", "phone": "a", "right": "#"}]
    assert tree_lookup(TREES["dur"], labels[1], 2) == (6.0, 4.0)
    assert tree_lookup(TREES["dur"], labels[0], 0) == (2.0, 0.5)
    assert tree_lookup(TREES["spec"], labels[0], 0) == (0.3, 0.1, 0.0, 0.02)


def test_synthesize_toy_utterance():
    y, fr = synthesize(["s", "a", "n", "i"], TREES, hop=40, fs=8000, seed=1)
    d = fr["durations"]
    assert len(d) == 4 * 5
    T = sum(d)
    assert len(y) == 40 * T
    assert len(fr["spec"]) == T
    # "s" is unvoiced, the others are voiced; pitch exists exactly on voiced frames.
    n_s = sum(d[:5])
    assert fr["voiced"][:n_s] == [False] * n_s and all(fr["voiced"][n_s:])
    assert all(x is None for x in fr["logf0"][:n_s])
    assert all(abs(math.exp(x) - 120.0) < 1.0 for x in fr["logf0"][n_s:])
    # The trajectory is smoother than the step of state means.
    jumps = lambda s: max(abs(s[t + 1] - s[t]) for t in range(len(s) - 1))
    assert jumps(fr["spec"]) < jumps(fr["spec_means"])
    assert all(math.isfinite(s) for s in y)
    # Same seed, same output.
    assert synthesize(["s", "a", "n", "i"], TREES, hop=40, fs=8000, seed=1)[0] == y


def test_rho_slows_down():
    _, a = synthesize(["n", "a"], TREES, rho=0.0, hop=10)
    _, b = synthesize(["n", "a"], TREES, rho=1.0, hop=10)
    assert sum(b["durations"]) > sum(a["durations"])
    _, c = synthesize(["n", "a"], TREES, rho=-10.0, hop=10)
    assert min(c["durations"]) == 1


def test_singular_system():
    with pytest.raises(ValueError):
        mlpg_1d([0.0, 0.0], [math.inf, math.inf], [0.0, 0.0], [math.inf, math.inf])

History

Tokuda and colleagues worked on generating speech parameters from HMMs with dynamic features in the 1990s. Yoshimura, Tokuda, Masuko, Kobayashi and Kitamura (1999) put spectrum, pitch and duration into one framework of context-dependent HMMs clustered by decision trees. Tokuda and colleagues (2000) gave the parameter generation algorithms used at synthesis time. The HTS toolkit made the method widely available. The survey of Zen, Tokuda and Black (2009) compares it with unit selection and describes the remaining problems: the vocoder, the accuracy of the acoustic models, and over-smoothing. Later, neural networks replaced the decision trees as the acoustic model, and then neural vocoders such as WaveNet (2016) and end-to-end models replaced most of the pipeline.

References

  1. Takayoshi Yoshimura, Keiichi Tokuda, Takashi Masuko, Takao Kobayashi and Tadashi Kitamura, Simultaneous modeling of spectrum, pitch and duration in HMM-based speech synthesis, Proceedings of Eurospeech 1999, pages 2347 to 2350, the context-dependent models of spectrum, F0 and duration, their clustering by decision trees, and the listening tests
  2. Heiga Zen, Keiichi Tokuda and Alan W. Black, Statistical parametric speech synthesis, Speech Communication 51(11), 2009, pages 1039 to 1064, the overview of training and synthesis, the comparison with unit selection, and the sections on vocoding, accuracy of the models and over-smoothing
  3. Keiichi Tokuda, Takayoshi Yoshimura, Takashi Masuko, Takao Kobayashi and Tadashi Kitamura, Speech parameter generation algorithms for HMM-based speech synthesis, ICASSP 2000, volume 3, pages 1315 to 1318, the generation of the parameter trajectory for a given state sequence
  4. Paul Taylor, Text-to-Speech Synthesis, Cambridge University Press, 2009, Chapter 15 (Hidden-Markov-model synthesis)

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example