Algorithm Search⌘K

Algorithmadvanced

Maximum likelihood parameter generation

Also called MLPG.

Turn per-frame Gaussian means and variances of static and delta features into the smooth static trajectory of highest likelihood, by one banded linear solve in O(T) time.

Time
O(T D b^2) worst
Space
Θ(T b) extra
Where
D = the number of windows; T = the number of frames; b = the half-bandwidth, twice the largest window offset
Properties
deterministicexactnot in placeoffline
Origin
Keiichi Tokuda, Takayoshi Yoshimura, Takashi Masuko, Takao Kobayashi, Tadashi Kitamura, 2000

Maximum likelihood parameter generation (MLPG) is the step of HMM-based speech synthesis that turns a sequence of Gaussian distributions into a smooth trajectory of speech parameters. The model gives, for each frame, a mean and a variance for each static feature and for its delta features, the slope and the curvature over time. The most likely value of each frame alone would be the static mean, a step function that jumps at each state boundary. MLPG instead asks for the static trajectory whose static and delta values together have the highest likelihood. This is a weighted least squares problem, and its normal equations have a banded matrix, so a banded Cholesky solve gives the exact answer in time linear in the number of frames. Tokuda and colleagues gave the method in 2000.

In plain words

A statistical voice predicts each short frame of speech from the sound being spoken. For each frame it gives a best value and how sure it is. It also gives a best value for how fast the parameter should change at that frame, and how fast that change should change.

If you just take the best value of each frame, the result jumps at every sound boundary and sounds buzzy. MLPG looks at all the frames together. It finds the one smooth curve that best fits both the values and the predicted rates of change, with each target weighted by how sure the model is. Where the model is sure about the value, the curve stays close to it. Where it is sure that the value changes slowly, the curve smooths over the boundary. The best curve comes from one system of linear equations, solved quickly.

The problem

Work with one feature dimension; with a diagonal covariance, the dimensions are solved one at a time. The unknown is the static trajectory c=(c0,…,cT−1)c = (c_0, \ldots, c_{T-1}). A window w(d)w^{(d)} is a map from offsets τ\tau to coefficients, and the dd-th feature at frame tt is

ot,d=∑τwτ(d) ct+τ.o_{t,d} = \sum_\tau w^{(d)}_\tau\, c_{t+\tau}.

The usual windows are static {0:1}\{0: 1\}, delta {−1:−12, 1:12}\{-1: -\tfrac12,\ 1: \tfrac12\} and delta-delta {−1:1, 0:−2, 1:1}\{-1: 1,\ 0: -2,\ 1: 1\}. Stack the ot,do_{t,d} into o=Wco = Wc, where WW is a DT×TDT \times T matrix. A frame t+τt + \tau outside 0…T−10 \ldots T-1 must be given a rule. The code uses the nearest end frame by default (the trajectory is held constant beyond its ends) and offers the rule that drops the term (the trajectory is 0 beyond its ends).

The model gives a mean μt,d\mu_{t,d} and a variance σt,d2>0\sigma^2_{t,d} > 0 for each frame and window, usually by repeating the parameters of each HMM state for its duration. With U=diag(σt,d2)U = \mathrm{diag}(\sigma^2_{t,d}), find

c∗=arg⁡max⁡clog⁡N(Wc; μ, U)=arg⁡min⁡c (Wc−μ)⊤U−1(Wc−μ).c^* = \arg\max_c \log \mathcal{N}(Wc;\ \mu,\ U) = \arg\min_c\ (Wc - \mu)^\top U^{-1} (Wc - \mu).

Setting the gradient to zero gives the normal equations

Pc=r,P=W⊤U−1W,r=W⊤U−1μ.P c = r, \qquad P = W^\top U^{-1} W, \qquad r = W^\top U^{-1} \mu.

The algorithm

Let LL be the largest ∣τ∣|\tau| of any window. Then PP is symmetric with half-bandwidth b=2Lb = 2L: entry (u,v)(u, v) is 0 when ∣u−v∣>b|u - v| > b. MLPG builds PP and rr row by row of WW and solves with a banded LDL⊤LDL^\top factorization, the form of Cholesky without square roots.

  1. MLPG(μ, σ², w^(0) .. w^(D-1)) ▷ μ and σ² are T × D, w^(0) is the static window
  2. 1P ← 0 (symmetric, half-bandwidth b = 2L); r ← 0
  3. 2for t ← 0 to T - 1 and d ← 0 to D - 1 do ▷ row (t, d) of W
  4. 3for each entry (u, a) of row (t, d) do
  5. 4for each entry (v, a') of row (t, d) with v ≤ u do P[u][v] ← P[u][v] + a a' / σ²[t][d]
  6. 5r[u] ← r[u] + a μ[t][d] / σ²[t][d]
  7. 6for j ← 0 to T - 1 do ▷ banded LDL^T
  8. 7D[j] ← P[j][j] - Σ over k from max(0, j - b) to j - 1 of L[j][k]² D[k]; stop with an error if D[j] ≤ 0
  9. 8for i ← j + 1 to min(T - 1, j + b) do L[i][j] ← (P[i][j] - Σ over k from max(0, i - b) to j - 1 of L[i][k] L[j][k] D[k]) / D[j]
  10. 9solve L y = r by forward substitution inside the band
  11. 10z[t] ← y[t] / D[t] for each t
  12. 11solve L^T c = z by back substitution inside the band
  13. 12return c

Lines L1 to L5 never form WW: each row of WW has at most 2L+12L + 1 entries, and line L4 adds their pairwise products to PP. Lines L6 to L8 are the dense LDL⊤LDL^\top formulas with every sum cut to the band. The factorization makes no fill outside the band, so the cut loses nothing. The method uses only addition, subtraction, multiplication and division, so the code runs on Fraction for exact checks and on float for speed.

Example

Take two HMM states of 3 frames each, so T=6T = 6, with static means 0 and 1, static variance 1, delta mean 0 and delta variance 1/41/4 in both states, and the static and delta windows with the end frames held. So μ\mu static is (0,0,0,1,1,1)(0, 0, 0, 1, 1, 1). Then PP and rr are

P=(3−1−1000−130−100−1030−100−1030−100−103−1000−1−13),r=(0,0,0,1,1,1),P = \begin{pmatrix} 3 & -1 & -1 & 0 & 0 & 0 \\ -1 & 3 & 0 & -1 & 0 & 0 \\ -1 & 0 & 3 & 0 & -1 & 0 \\ 0 & -1 & 0 & 3 & 0 & -1 \\ 0 & 0 & -1 & 0 & 3 & -1 \\ 0 & 0 & 0 & -1 & -1 & 3 \end{pmatrix}, \qquad r = (0, 0, 0, 1, 1, 1),

with half-bandwidth 2. The diagonal 3 is 11 from the static row plus 2⋅(1/2)2/(1/4)2 \cdot (1/2)^2 / (1/4) from the two delta rows that touch the frame. The solution is

c∗=(0.2, 0.3, 0.3, 0.7, 0.7, 0.8),c^* = (0.2,\ 0.3,\ 0.3,\ 0.7,\ 0.7,\ 0.8),

with deltas (0.05,0.05,0.2,0.2,0.05,0.05)(0.05, 0.05, 0.2, 0.2, 0.05, 0.05). The trajectory rises across the boundary instead of jumping. The objective −12(Wc−μ)⊤U−1(Wc−μ)-\tfrac12 (Wc - \mu)^\top U^{-1} (Wc - \mu) is −0.4-0.4 at c∗c^* and −1-1 at the step c=(0,0,0,1,1,1)c = (0, 0, 0, 1, 1, 1), whose deltas 0.50.5 at frames 2 and 3 are far from their mean 0.

Adding the delta-delta window with mean 0 and variance 1/41/4 gives c∗=(0.2352,0.2951,0.4163,0.5837,0.7049,0.7648)c^* = (0.2352, 0.2951, 0.4163, 0.5837, 0.7049, 0.7648), rounded to 4 places, a smoother S-shaped curve. The pairs of equal values in the first result come from the central delta window, which links frame tt only to frames t±1t \pm 1 through a difference over two frames; see the pitfalls.

Correctness

The proofs file shows four facts. With a static window, x⊤Px≥∑txt2/σt,02>0x^\top P x \ge \sum_t x_t^2 / \sigma^2_{t,0} > 0 for x≠0x \ne 0, so PP is positive definite. Writing c=c∗+xc = c^* + x gives ℓ(c)=ℓ(c∗)−12x⊤Px\ell(c) = \ell(c^*) - \tfrac12 x^\top P x, so c∗=P−1rc^* = P^{-1} r is the unique maximizer. Each row of WW touches columns within LL of its frame under both end rules, so PP has half-bandwidth 2L2L. An induction over the columns shows that LL stays inside the same band, so the banded formulas equal the dense ones, and Sylvester's criterion gives positive pivots. The tests compare the result in Fraction with dense Gaussian elimination on W⊤U−1WW^\top U^{-1} W for many random cases, and check that the gradient is exactly 0 and that random moves lower the objective.

Proof: MLPG returns the unique maximizer of the Gaussian log likelihood, and the banded factorization has no fillfull

Fix T≥1T \ge 1 frames and DD windows w(0),…,w(D−1)w^{(0)}, \ldots, w^{(D-1)}, each a finite map from offsets τ\tau to coefficients, with ∣τ∣≤L|\tau| \le L for every offset. The matrix WW has DTDT rows indexed by (t,d)(t, d) and TT columns. Row (t,d)(t, d) has the entry ∑wτ(d)\sum w^{(d)}_\tau in column uu, where the sum runs over the offsets with κ(t+τ)=u\kappa(t + \tau) = u; for the clamp rule κ(x)=min⁡(max⁡(x,0),T−1)\kappa(x) = \min(\max(x, 0), T - 1), and for the zero rule κ(x)=x\kappa(x) = x and the offsets with t+τt + \tau outside 0…T−10 \ldots T-1 are dropped. Let U=diag(σt,d2)U = \mathrm{diag}(\sigma^2_{t,d}) with every σt,d2>0\sigma^2_{t,d} > 0, and let μ\mu be the vector of the means μt,d\mu_{t,d}. Define

ℓ(c)=−12(Wc−μ)⊤U−1(Wc−μ),P=W⊤U−1W,r=W⊤U−1μ.\ell(c) = -\tfrac12 (Wc - \mu)^\top U^{-1} (Wc - \mu), \qquad P = W^\top U^{-1} W, \qquad r = W^\top U^{-1} \mu.

The log density log⁡N(Wc;μ,U)\log \mathcal{N}(Wc; \mu, U) is ℓ(c)\ell(c) plus a constant that does not depend on cc.

The maximizer

Lemma 1. If one window is the static window {0↦1}\{0 \mapsto 1\}, then PP is symmetric positive definite.

Proof. P⊤=W⊤U−⊤W=PP^\top = W^\top U^{-\top} W = P because UU is diagonal. For any xx, x⊤Px=∑t,d(Wx)t,d2/σt,d2≥∑txt2/σt,02x^\top P x = \sum_{t,d} (W x)_{t,d}^2 / \sigma^2_{t,d} \ge \sum_t x_t^2 / \sigma^2_{t,0}, keeping only the static rows, whose entries are (Wx)t,0=xt(Wx)_{t,0} = x_t under both edge rules. This is positive for x≠0x \ne 0. □\square

Theorem 1. If PP is positive definite, ℓ\ell has the unique maximizer c∗=P−1rc^* = P^{-1} r.

Proof. Expanding, ℓ(c)=−12c⊤Pc+c⊤r−12μ⊤U−1μ\ell(c) = -\tfrac12 c^\top P c + c^\top r - \tfrac12 \mu^\top U^{-1} \mu. For any cc, write c=c∗+xc = c^* + x. Then ℓ(c)=ℓ(c∗)−12x⊤Px+x⊤(r−Pc∗)=ℓ(c∗)−12x⊤Px\ell(c) = \ell(c^*) - \tfrac12 x^\top P x + x^\top (r - P c^*) = \ell(c^*) - \tfrac12 x^\top P x, which is less than ℓ(c∗)\ell(c^*) for x≠0x \ne 0. □\square

If PP is only positive semidefinite, for example with no static window, then ℓ\ell is constant along the null space of WW and the maximizer is not unique. The code finds a pivot that is not positive and raises an error in that case (Lemma 3).

Lines L1 to L5 build P and r

Line L4 adds a c/σt,d2a\,c / \sigma^2_{t,d} to entry (u,v)(u, v) for every pair of entries (u,a)(u, a) and (v,c)(v, c) of row (t,d)(t, d), and line L5 adds a μt,d/σt,d2a\, \mu_{t,d} / \sigma^2_{t,d} to rur_u. Summed over the rows, these are ∑t,dW(t,d),uW(t,d),v/σt,d2=Puv\sum_{t,d} W_{(t,d),u} W_{(t,d),v} / \sigma^2_{t,d} = P_{uv} and ∑t,dW(t,d),u μt,d/σt,d2=ru\sum_{t,d} W_{(t,d),u}\, \mu_{t,d} / \sigma^2_{t,d} = r_u. The code stores only u≥vu \ge v, which is enough because PP is symmetric.

Lemma 2 (band). Puv=0P_{uv} = 0 when ∣u−v∣>2L|u - v| > 2L.

Proof. Every nonzero entry of row (t,d)(t, d) is in a column κ(t+τ)\kappa(t + \tau) with ∣τ∣≤L|\tau| \le L. Under both rules this column lies in [t−L,t+L][t - L, t + L], because clamping moves a column toward tt. A term of PuvP_{uv} needs uu and vv in the same row, so ∣u−v∣≤2L|u - v| \le 2L. □\square

So PP has half-bandwidth b=2Lb = 2L.

Lines L6 to L8: the banded LDL factorization

Lemma 3. Let PP be symmetric with half-bandwidth bb. If PP is positive definite, lines L6 to L8 compute a unit lower triangular LL with Lij=0L_{ij} = 0 for i−j>bi - j > b and positive D1,…,DTD_1, \ldots, D_T with P=L diag(D) L⊤P = L\, \mathrm{diag}(D)\, L^\top. If PP is singular, some pivot DjD_j is not positive and the code raises an error.

Proof. Equating the entries of P=L diag(D) L⊤P = L\,\mathrm{diag}(D)\,L^\top on and below the diagonal gives, column by column,

Dj=Pjj−∑k<jLjk2Dk,Lij=(Pij−∑k<jLikLjkDk)/Dj(i>j).D_j = P_{jj} - \sum_{k<j} L_{jk}^2 D_k, \qquad L_{ij} = \Bigl(P_{ij} - \sum_{k<j} L_{ik} L_{jk} D_k\Bigr) / D_j \quad (i > j).

These are the formulas of the dense factorization. By induction on jj, the entries LikL_{ik} with i−k>bi - k > b are 0: for i−j>bi - j > b, Pij=0P_{ij} = 0 by the band, and every term LikLjkL_{ik} L_{jk} with k<jk < j has i−k>bi - k > b, so it is 0 by the induction hypothesis. So the dense formulas reduce to the sums over k≥max⁡(0,i−b)k \ge \max(0, i - b) of the code, and the code computes the same LL and DD as the dense formulas, with no fill outside the band.

The leading j×jj \times j block satisfies P[j]=L[j] diag(D1,…,Dj) L[j]⊤P_{[j]} = L_{[j]}\,\mathrm{diag}(D_1, \ldots, D_j)\,L_{[j]}^\top with det⁡L[j]=1\det L_{[j]} = 1, so D1⋯Dj=det⁡P[j]D_1 \cdots D_j = \det P_{[j]}. If PP is positive definite, every leading minor is positive (Sylvester's criterion), so by induction every Dj=det⁡P[j]/det⁡P[j−1]>0D_j = \det P_{[j]} / \det P_{[j-1]} > 0 and the division is safe. If PP is not positive definite, some leading minor is not positive, again by Sylvester's criterion. Take the first such jj. The pivots before it are positive, so Dj=det⁡P[j]/det⁡P[j−1]≤0D_j = \det P_{[j]} / \det P_{[j-1]} \le 0, and line L7 raises an error. In exact arithmetic this test is exact; in floating point a nearly singular PP can give a tiny positive pivot instead. □\square

Lines L9 to L12: the solves

Line L9 solves Ly=rL y = r by forward substitution, line L10 sets z=diag(D)−1yz = \mathrm{diag}(D)^{-1} y, and line L11 solves L⊤c=zL^\top c = z by back substitution, each using only the entries inside the band. Then L diag(D) L⊤c=rL\,\mathrm{diag}(D)\,L^\top c = r, so Pc=rPc = r and c=c∗c = c^* by Theorem 1.

Theorem 2. If one window is static, MLPG returns the unique cc that maximizes log⁡N(Wc;μ,U)\log \mathcal{N}(Wc; \mu, U). Every step uses only ++, −-, ×\times and //, so with Fraction inputs the result is exact.

Proof. Lemma 1, Theorem 1, Lemma 3 and the solves above. □\square

Cost

Building PP and rr costs ∑t,dsd2=O(T∑dsd2)\sum_{t,d} s_d^2 = O(T \sum_d s_d^2) operations, where sd≤2L+1s_d \le 2L + 1 is the number of offsets of window dd. The factorization does at most bb inner steps for each of the at most bb entries of each of the TT columns, so O(Tb2)O(T b^2), and the solves cost O(Tb)O(T b). The storage is O(Tb)O(T b). For fixed windows, the whole computation is Θ(T)\Theta(T).

Complexity

Lines L2 to L5 cost O(T∑dsd2)O(T \sum_d s_d^2), where sd≤2L+1s_d \le 2L + 1 is the number of taps of window dd. The factorization costs O(Tb2)O(T b^2) and the two solves cost O(Tb)O(T b). The band of PP and LL takes Θ(Tb)\Theta(T b) space. With the usual windows L=1L = 1 and b=2b = 2, so the whole computation is Θ(T)\Theta(T), against Θ(T3)\Theta(T^3) for a dense solve. A sentence of a few hundred frames and a few dozen feature dimensions is a few hundred thousand operations.

Properties

  • Exact. It returns the true maximizer of the Gaussian likelihood for the given state sequence and durations, not an approximation.
  • Linear in the means. c∗c^* is a fixed linear function P−1W⊤U−1P^{-1} W^\top U^{-1} of μ\mu, so it is a smoother, close in spirit to a smoothing spline, with the variances as local weights.
  • Variances matter. Unlike the frame-wise maximum, which ignores the variances, MLPG trades the static and delta targets by their precisions. A small delta variance gives a flatter curve.
  • Not online. The answer at a frame depends on all frames. The Rauch-Tung-Striebel smoother solves the same kind of banded system in a forward and a backward pass. A system with low latency must solve over a sliding block of frames instead.
  • Over-smoothing. The generated trajectories have less variance over time than natural speech, a measured effect that makes the voice sound muffled (Zen, Tokuda and Black 2009).

Variants and improvements

  • Hidden state sequence. Tokuda and colleagues also treat the case where the state and mixture sequence is not fixed, maximizing over it with an EM-type iteration. Most systems instead fix the states and durations from a duration model and use the closed form.
  • Global variance. Toda and Tokuda (2007) add a term for the likelihood of the variance of the whole trajectory, which counters over-smoothing; the objective is no longer quadratic and is maximized iteratively.
  • Trajectory HMM. Training with the same constraint o=Wco = Wc gives the trajectory HMM of Zen, Tokuda and Kitamura (2007), so training and generation agree.
  • Neural acoustic models. Deep network and recurrent acoustic models often predict static and delta means and variances and still run MLPG at the end, or predict a smooth trajectory directly.
  • Full covariance. With a covariance between dimensions, the system couples all dimensions and the band holds blocks instead of numbers.

When to use it

Use MLPG whenever a model gives per-frame Gaussians over static and dynamic features and a single smooth trajectory is needed: the spectral, F0 and aperiodicity streams of an HMM-based or DNN-based parametric synthesizer, voice conversion with Gaussian mixture models, and articulatory or motion synthesis. If the model already outputs a trajectory, as end-to-end neural synthesizers such as Tacotron do, there is nothing for MLPG to do.

Pitfalls

  • The edges. The windows reach past the first and last frames. Holding the end frames and dropping the terms are different models; dropping them makes the delta-delta window pull the end frames toward 0. Use the same rule as the one used to compute the deltas in training.
  • Central delta and odd-even split. With the delta window 12(ct+1−ct−1)\tfrac12 (c_{t+1} - c_{t-1}) alone, PP links each frame only to frames two apart, except at the ends, so the even and odd frames are nearly separate problems and the curve can show pairs or a zigzag. Add the delta-delta window, which links neighbors.
  • No static window. Without a static window, a constant shift does not change any delta, so PP is singular. The code stops with an error.
  • A dense solve. Forming the dense T×TT \times T matrix and inverting it costs Θ(T3)\Theta(T^3) time and Θ(T2)\Theta(T^2) space; keep the band.
  • Unvoiced frames. F0 is undefined in unvoiced regions. Generate F0 only over the voiced segments, which is what the multi-space distribution of HMM-based synthesis supports.

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.

maximum_likelihood_parameter_generation.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/maximum-likelihood-parameter-generation/. The authors are listed in prov/5JS7A5.jsonl.

"""Maximum likelihood parameter generation (MLPG), after Tokuda et al. (2000).

One feature dimension. For frames t = 0 .. T-1 the model gives a Gaussian with
mean mu[t][d] and variance var[t][d] for each window d = 0 .. D-1 (the static
feature, its delta, its delta-delta and so on). A window is a dict
{offset: coefficient}; the d-th observed feature at frame t is

    o[t][d] = sum over (tau, w) in windows[d] of w * c[t + tau],

and a frame t + tau outside 0 .. T-1 is replaced by the nearest end frame
(edge = "clamp", the default) or the term is dropped (edge = "zero").
So o = W c for a (D T) x T matrix W. MLPG returns the static trajectory c that
maximizes log N(W c; mu, U) with U = diag(var), which is the solution of

    (W^T U^-1 W) c = W^T U^-1 mu.

The matrix P = W^T U^-1 W is symmetric and banded with half-bandwidth
b = 2 L, where L is the largest |offset| of any window. It is solved by a
banded LDL^T factorization (Cholesky without square roots), in O(T b^2) time,
so the code runs on Fraction for exact checks and on float.

For several feature dimensions with a diagonal covariance, call it once per
dimension.
"""

from typing import Dict, List, Sequence

Window = Dict[int, object]

STATIC: Window = {0: 1}
DELTA: Window = {-1: -0.5, 1: 0.5}
DELTA2: Window = {-1: 1, 0: -2, 1: 1}


def half_bandwidth(windows: Sequence[Window]) -> int:
    reach = max((abs(k) for w in windows for k in w), default=0)
    return 2 * reach


def window_rows(T: int, windows: Sequence[Window], edge: str = "clamp"):
    """The rows of W as lists of (column, coefficient), in the order (t, d).

    edge = "clamp": a frame t + tau outside 0 .. T-1 is replaced by the nearest
    end frame (the trajectory is held constant beyond its ends).
    edge = "zero": such a term is dropped (the trajectory is 0 beyond its ends).
    """
    if edge not in ("clamp", "zero"):
        raise ValueError("edge must be 'clamp' or 'zero'")
    rows = []
    for t in range(T):
        for d, w in enumerate(windows):
            acc = {}
            for tau, coef in sorted(w.items()):
                u = t + tau
                if not 0 <= u < T:
                    if edge == "zero":
                        continue
                    u = min(max(u, 0), T - 1)
                acc[u] = acc.get(u, 0) + coef
            rows.append((t, d, sorted(acc.items())))
    return rows


def normal_equations(mu, var, windows: Sequence[Window], edge: str = "clamp"):
    """Return (P, r, b): P as a dict {(i, j): value} for i >= j within the band,
    r as a list, b the half-bandwidth."""
    T = len(mu)
    b = half_bandwidth(windows)
    P = {}
    r = [0 * mu[0][0] for _ in range(T)] if T else []  # @line L1
    for t, d, row in window_rows(T, windows, edge):  # @line L2
        inv = 1 / var[t][d]
        for u, a in row:  # @line L3
            for v, c in row:
                if u >= v:
                    P[(u, v)] = P.get((u, v), 0) + a * c * inv  # @line L4
            r[u] += a * mu[t][d] * inv  # @line L5
    return P, r, b


def banded_ldl_solve(P, r, b: int):
    """Solve P c = r for symmetric positive definite P with half-bandwidth b.

    P is a dict {(i, j): value} for i >= j. Raises ValueError if a pivot is not
    positive (P is singular or not positive definite)."""
    T = len(r)
    L = {}
    D = [None] * T
    for j in range(T):  # @line L6
        s = P.get((j, j), 0)
        for k in range(max(0, j - b), j):
            s -= L[(j, k)] * L[(j, k)] * D[k]
        if not s > 0:
            raise ValueError("the matrix W^T U^-1 W is not positive definite")
        D[j] = s  # @line L7
        for i in range(j + 1, min(T, j + b + 1)):  # @line L8
            s = P.get((i, j), 0)
            for k in range(max(0, i - b), j):
                s -= L[(i, k)] * L[(j, k)] * D[k]
            L[(i, j)] = s / D[j]
    y = list(r)
    for i in range(T):  # @line L9
        for k in range(max(0, i - b), i):
            y[i] -= L[(i, k)] * y[k]
    z = [y[i] / D[i] for i in range(T)]  # @line L10
    c = list(z)
    for i in range(T - 1, -1, -1):  # @line L11
        for k in range(i + 1, min(T, i + b + 1)):
            c[i] -= L[(k, i)] * c[k]
    return c


def mlpg(mu, var, windows: Sequence[Window] = (STATIC, DELTA, DELTA2), edge: str = "clamp") -> List:
    """The static trajectory c that maximizes log N(W c; mu, diag(var)).

    mu and var are T x D lists (D = len(windows)); every variance must be positive.
    edge is the rule for window terms beyond the ends, as in window_rows.
    """
    T = len(mu)
    if T == 0:
        return []
    if any(len(row) != len(windows) for row in list(mu) + list(var)):
        raise ValueError("each frame needs one mean and one variance per window")
    if any(not v > 0 for row in var for v in row):
        raise ValueError("variances must be positive")
    P, r, b = normal_equations(mu, var, windows, edge)
    return banded_ldl_solve(P, r, b)  # @line L12


def log_likelihood_quadratic(c, mu, var, windows: Sequence[Window], edge: str = "clamp"):
    """-1/2 (W c - mu)^T U^-1 (W c - mu), the part of log N(W c; mu, U) that depends on c."""
    q = 0
    for t, d, row in window_rows(len(mu), windows, edge):
        o = sum(a * c[u] for u, a in row)
        q += (o - mu[t][d]) * (o - mu[t][d]) / var[t][d]
    return -q / 2


def expand_states(means, variances, durations):
    """Repeat the per-state means and variances (each a list of D values) by the
    state durations, giving the T x D frame lists that mlpg takes."""
    mu, var = [], []
    for m, v, n in zip(means, variances, durations):
        if n < 0:
            raise ValueError("durations must be non-negative")
        for _ in range(n):
            mu.append(list(m))
            var.append(list(v))
    return mu, var
test_maximum_likelihood_parameter_generation.py 200 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/maximum-likelihood-parameter-generation/. The authors are listed in prov/5JS7A5.jsonl.

import random
import time
from fractions import Fraction as F

import pytest

from maximum_likelihood_parameter_generation import (
    DELTA,
    DELTA2,
    STATIC,
    banded_ldl_solve,
    expand_states,
    half_bandwidth,
    log_likelihood_quadratic,
    mlpg,
    normal_equations,
    window_rows,
)

FSTATIC = {0: F(1)}
FDELTA = {-1: F(-1, 2), 1: F(1, 2)}
FDELTA2 = {-1: F(1), 0: F(-2), 1: F(1)}
FWIDE = {-2: F(-1, 5), -1: F(-1, 10), 1: F(1, 10), 2: F(1, 5)}


def dense_solve(A, y):
    """Gaussian elimination with exact pivot search, for Fraction matrices."""
    n = len(A)
    M = [list(A[i]) + [y[i]] for i in range(n)]
    for col in range(n):
        piv = next(i for i in range(col, n) if M[i][col] != 0)
        M[col], M[piv] = M[piv], M[col]
        for i in range(n):
            if i != col and M[i][col] != 0:
                f = M[i][col] / M[col][col]
                M[i] = [a - f * b for a, b in zip(M[i], M[col])]
    return [M[i][n] / M[i][i] for i in range(n)]


def dense_normal_equations(mu, var, windows, edge="clamp"):
    """W, then W^T U^-1 W and W^T U^-1 mu, with W built as a full matrix."""
    T = len(mu)
    W, m, u = [], [], []
    for t in range(T):
        for d, w in enumerate(windows):
            row = [F(0)] * T
            for tau, coef in w.items():
                if 0 <= t + tau < T:
                    row[t + tau] += coef
                elif edge == "clamp":
                    row[0 if t + tau < 0 else T - 1] += coef
            W.append(row)
            m.append(mu[t][d])
            u.append(var[t][d])
    A = [[sum(W[k][i] * W[k][j] / u[k] for k in range(len(W))) for j in range(T)] for i in range(T)]
    y = [sum(W[k][i] * m[k] / u[k] for k in range(len(W))) for i in range(T)]
    return A, y


def random_frames(rng, T, D):
    mu = [[F(rng.randint(-20, 20), rng.randint(1, 5)) for _ in range(D)] for _ in range(T)]
    var = [[F(rng.randint(1, 9), rng.randint(1, 4)) for _ in range(D)] for _ in range(T)]
    return mu, var


WINDOW_SETS = [
    [FSTATIC],
    [FSTATIC, FDELTA],
    [FSTATIC, FDELTA, FDELTA2],
    [FSTATIC, FWIDE],
    [FSTATIC, FWIDE, FDELTA2],
]


@pytest.mark.parametrize("edge", ["clamp", "zero"])
@pytest.mark.parametrize("k", range(len(WINDOW_SETS)))
def test_exact_against_dense_gaussian_elimination(k, edge):
    windows = WINDOW_SETS[k]
    rng = random.Random(100 + k)
    for T in range(1, 9):
        mu, var = random_frames(rng, T, len(windows))
        A, y = dense_normal_equations(mu, var, windows, edge)
        assert mlpg(mu, var, windows, edge) == dense_solve(A, y)


@pytest.mark.parametrize("edge", ["clamp", "zero"])
def test_banded_matrix_matches_dense_and_band(edge):
    rng = random.Random(7)
    windows = [FSTATIC, FWIDE, FDELTA2]
    T = 9
    mu, var = random_frames(rng, T, 3)
    P, r, b = normal_equations(mu, var, windows, edge)
    A, y = dense_normal_equations(mu, var, windows, edge)
    assert b == 4 == half_bandwidth(windows)
    for i in range(T):
        for j in range(T):
            if abs(i - j) > b:
                assert A[i][j] == 0
            elif i >= j:
                assert P.get((i, j), 0) == A[i][j]
    assert r == y


def test_static_window_alone_returns_the_means():
    rng = random.Random(3)
    mu, var = random_frames(rng, 7, 1)
    assert mlpg(mu, var, [FSTATIC]) == [row[0] for row in mu]


def test_gradient_is_zero_and_perturbations_lower_the_likelihood():
    rng = random.Random(9)
    windows = [FSTATIC, FDELTA, FDELTA2]
    for T in (2, 5, 8):
        mu, var = random_frames(rng, T, 3)
        c = mlpg(mu, var, windows)
        P, r, b = normal_equations(mu, var, windows)
        for i in range(T):
            pc = sum(P.get((max(i, j), min(i, j)), 0) * c[j] for j in range(T))
            assert pc == r[i]
        best = log_likelihood_quadratic(c, mu, var, windows)
        for _ in range(10):
            e = [F(rng.randint(-3, 3), 7) for _ in range(T)]
            if all(x == 0 for x in e):
                continue
            moved = [a + x for a, x in zip(c, e)]
            assert log_likelihood_quadratic(moved, mu, var, windows) < best


def test_float_matches_fraction():
    rng = random.Random(21)
    for T in (1, 4, 12):
        mu, var = random_frames(rng, T, 3)
        exact = mlpg(mu, var, [FSTATIC, FDELTA, FDELTA2])
        fl = mlpg([[float(x) for x in row] for row in mu], [[float(x) for x in row] for row in var], [STATIC, DELTA, DELTA2])
        for a, b in zip(exact, fl):
            assert b == pytest.approx(float(a), rel=1e-9, abs=1e-9)


def test_singular_system_raises():
    # Delta alone: with clamped ends a constant trajectory has every delta 0,
    # and with zero ends on 3 frames the rows are c1 / 2, (c2 - c0) / 2 and
    # -c1 / 2, so c0 + c2 is not determined. W^T U^-1 W is singular in both.
    mu = [[F(0)], [F(1)], [F(0)]]
    var = [[F(1)]] * 3
    for edge in ("clamp", "zero"):
        with pytest.raises(ValueError):
            mlpg(mu, var, [FDELTA], edge)
    with pytest.raises(ValueError):
        mlpg(mu, var, [FDELTA], "mirror")


def test_bad_input_raises():
    with pytest.raises(ValueError):
        mlpg([[0.0, 0.0]], [[1.0, 0.0]], [STATIC, DELTA])
    with pytest.raises(ValueError):
        mlpg([[0.0]], [[1.0]], [STATIC, DELTA])
    assert mlpg([], [], [STATIC, DELTA]) == []


def test_window_rows_at_the_ends():
    rows = window_rows(3, [FSTATIC, FDELTA], "zero")
    assert rows[1] == (0, 1, [(1, F(1, 2))])
    assert rows[5] == (2, 1, [(1, F(-1, 2))])
    rows = window_rows(3, [FSTATIC, FDELTA], "clamp")
    assert rows[1] == (0, 1, [(0, F(-1, 2)), (1, F(1, 2))])
    assert rows[5] == (2, 1, [(1, F(-1, 2)), (2, F(1, 2))])


def test_two_state_example():
    # The example of the page: states with static means 0 and 1, 3 frames each,
    # delta mean 0, static variance 1 and delta variance 1/4, clamped ends.
    mu, var = expand_states([[F(0), F(0)], [F(1), F(0)]], [[F(1), F(1, 4)], [F(1), F(1, 4)]], [3, 3])
    windows = [FSTATIC, FDELTA]
    c = mlpg(mu, var, windows)
    assert c == [F(1, 5), F(3, 10), F(3, 10), F(7, 10), F(7, 10), F(4, 5)]
    assert log_likelihood_quadratic(c, mu, var, windows) == F(-2, 5)
    assert log_likelihood_quadratic([row[0] for row in mu], mu, var, windows) == -1
    c3 = mlpg(*expand_states([[F(0)] * 3, [F(1), F(0), F(0)]], [[F(1), F(1, 4), F(1, 4)]] * 2, [3, 3]), [FSTATIC, FDELTA, FDELTA2])
    assert c3 == [F(163, 693), F(409, 1386), F(577, 1386), F(809, 1386), F(977, 1386), F(530, 693)]
    # With zero ends the delta-delta window pulls the last frame toward 0.
    cz = mlpg(*expand_states([[F(0)] * 3, [F(1), F(0), F(0)]], [[F(1), F(1, 4), F(1, 4)]] * 2, [3, 3]), [FSTATIC, FDELTA, FDELTA2], "zero")
    assert cz[5] < cz[4]


def test_long_float_run_is_linear_and_solves_the_system():
    rng = random.Random(5)
    T = 3000
    mu = [[rng.uniform(-1, 1), rng.uniform(-0.1, 0.1), rng.uniform(-0.1, 0.1)] for _ in range(T)]
    var = [[rng.uniform(0.5, 2), rng.uniform(0.05, 0.2), rng.uniform(0.05, 0.2)] for _ in range(T)]
    start = time.perf_counter()
    c = mlpg(mu, var, [STATIC, DELTA, DELTA2])
    assert time.perf_counter() - start < 5
    P, r, b = normal_equations(mu, var, [STATIC, DELTA, DELTA2])
    for i in range(0, T, 97):
        pc = sum(P.get((max(i, j), min(i, j)), 0.0) * c[j] for j in range(max(0, i - b), min(T, i + b + 1)))
        assert pc == pytest.approx(r[i], abs=1e-9)
    assert banded_ldl_solve(P, r, b) == c

History

Tokuda, Kobayashi and Imai described parameter generation from HMMs with dynamic features in 1995. The 2000 ICASSP paper by Tokuda, Yoshimura, Masuko, Kobayashi and Kitamura gave the algorithms in the form used afterwards: the closed form for a given state sequence and iterative algorithms for a hidden state and mixture sequence. With the HMM-based synthesizer of Yoshimura and colleagues (1999), it became the generation step of the HTS system and of most statistical parametric synthesizers of the 2000s. Toda and Tokuda added the global variance in 2007 to reduce over-smoothing, and neural acoustic models kept the step in the early 2010s before end-to-end models made it unneeded.

References

  1. 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 solution for a given state sequence and the algorithms for a hidden state and mixture sequence
  2. Heiga Zen, Keiichi Tokuda and Alan W. Black, Statistical parametric speech synthesis, Speech Communication 51(11), 2009, pages 1039 to 1064, the description of parameter generation with dynamic features and the discussion of over-smoothing
  3. Paul Taylor, Text-to-Speech Synthesis, Cambridge University Press, 2009, the chapter Hidden Markov model synthesis

Where this leads

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