Algorithm Search⌘K

Algorithmadvanced

MAP speaker adaptation

Also called maximum a posteriori adaptation, Gauvain-Lee adaptation.

Adapt acoustic model parameters by MAP estimation with the speaker-independent model as prior, so well-observed Gaussians move most.

Time
O(k T M n) worst
Space
O(M n) extra
Where
M = the number of Gaussians; T = the number of adaptation frames; k = the number of EM iterations; n = the feature dimension
Properties
deterministicnot exactofflineiterative
Origin
Jean Luc Gauvain, Chin Hui Lee, 1994

MAP speaker adaptation moves the Gaussians of a speaker independent model toward the data of one speaker, and it uses the old model as a prior. Each new mean is a weighted average of the old mean and the mean of the data assigned to that Gaussian, μ^m=(τμm0+∑tγm(t)ot)/(τ+∑tγm(t))\hat\mu_m = (\tau \mu^0_m + \sum_t \gamma_m(t) o_t) / (\tau + \sum_t \gamma_m(t)). A Gaussian that saw much data moves almost to the data mean, and a Gaussian that saw none stays where it was. With more and more data, the result tends to the speaker dependent maximum likelihood model.

In plain words

A speech model stores many small averages, each one describing a sound piece. You get some speech from a new speaker, and you want to move each average toward how this speaker sounds.

For each average, look at the speech that matches it, and count how much there is. If there is a lot, trust the new speech and move the average almost all the way to it. If there is a little, move it only a little. If there is none, leave it. A single number controls how much speech counts as "a lot".

This is a cautious kind of learning: the old model is the starting belief, and the new speech changes it in proportion to the evidence.

The problem

The prior model is a mixture of MM Gaussians, or the Gaussians of the states of a GMM-HMM acoustic model. Gaussian mm has the weight cmc_m, the mean μm0∈Rn\mu^0_m \in \mathbb{R}^n and the diagonal covariance Σm\Sigma_m. The input is TT frames o1,…,oTo_1, \ldots, o_T of the target speaker, with a transcript in the HMM case. The prior on the means is

μm∼N(μm0,Σm/τ),independent over m,\mu_m \sim \mathcal{N}(\mu^0_m, \Sigma_m / \tau), \quad \text{independent over } m,

with one constant τ>0\tau > 0. A large τ\tau means a tight prior. The task is to find the means that maximize the posterior p(μ∣O)∝p(O∣μ) p(μ)p(\mu \mid O) \propto p(O \mid \mu)\, p(\mu) with the weights and covariances fixed. Gauvain and Lee 1994 solve the more general problem in which the weights and the covariances have priors too.

The algorithm

MAP-EM is EM with a penalty from the prior. The E-step is the same as in maximum likelihood EM. The M-step mixes the prior mean with the statistics.

  1. MAP-ADAPT(O, c, μ⁰, Σ, τ, iters)
  2. 1μ_m ← μ⁰_m for every m
  3. 2repeat iters times
  4. 3γ_m(t) ← c_m N(o_t; μ_m, Σ_m) / Σ_j c_j N(o_t; μ_j, Σ_j) for every t, m ▷ in log space
  5. 4n_m ← Σ_t γ_m(t), s_m ← Σ_t γ_m(t) o_t
  6. 5μ_m ← (τ μ⁰_m + s_m) / (τ + n_m)
  7. 6return μ

Line L5 always shrinks toward the prior mean μm0\mu^0_m, not toward the mean of the last iteration. Write αm=nm/(nm+τ)\alpha_m = n_m / (n_m + \tau) and Em=sm/nmE_m = s_m / n_m. Then line L5 is

μ^m=αmEm+(1−αm) μm0,\hat\mu_m = \alpha_m E_m + (1 - \alpha_m)\, \mu^0_m,

the form of Reynolds, Quatieri and Dunn 2000, who call τ\tau the relevance factor rr. In practice one iteration is common, mainly in speaker verification. In an HMM system the posteriors of line L3 come from the forward-backward algorithm over the transcript.

Example

One Gaussian. Take n=1n = 1, μ0=0\mu^0 = 0, τ=16\tau = 16, and data whose mean is E=2E = 2. Every frame belongs to the one Gaussian, so n1=Tn_1 = T:

frames TT α=T/(T+16)\alpha = T/(T + 16) μ^=2α\hat\mu = 2\alpha
4 0.2 0.4
16 0.5 1.0
64 0.8 1.6

At T=τT = \tau the new mean is halfway between the prior and the data. So τ\tau acts as a number of "virtual frames" of prior data.

Two Gaussians. Take c=(0.5,0.5)c = (0.5, 0.5), μ0=(−1,1)\mu^0 = (-1, 1), σ2=1\sigma^2 = 1, and the four frames 0.5,1.5,2.5,3.00.5, 1.5, 2.5, 3.0. The posterior of Gaussian 2 at frame xx is 1/(1+e−2x)1/(1 + e^{-2x}):

frame 0.5 1.5 2.5 3.0
γ2\gamma_2 0.731059 0.952574 0.993307 0.997527

So n=(0.325533,3.674467)n = (0.325533, 3.674467) and E=(0.705795,1.978584)E = (0.705795, 1.978584). The new means are:

τ\tau α1\alpha_1 μ^1\hat\mu_1 α2\alpha_2 μ^2\hat\mu_2
16 0.019940 -0.965986 0.186763 1.182763
2 0.139982 -0.761219 0.647544 1.633676

Gaussian 2 has most of the data and moves much more than Gaussian 1. With τ=0\tau = 0, the means would be the data means EE, which is one step of maximum likelihood EM.

Correctness

The proof is in proofs/correctness.md. For fixed posteriors, the expected complete-data log likelihood plus the log prior separates over the Gaussians and the coordinates. Each part is a strictly concave quadratic in one coordinate of one mean, and its maximizer is line L5. The Jensen argument of EM then shows that each iteration does not decrease the log posterior log⁡p(O∣μ)+log⁡p(μ)\log p(O \mid \mu) + \log p(\mu). For one Gaussian the result is the exact posterior mean of a Gaussian mean with a Gaussian conjugate prior. For a mixture, MAP-EM finds a stationary point, which can be a local maximum.

Proof: The MAP mean update maximizes the penalized auxiliary function and never lowers the log posteriorfull

We use the notation of the page. The prior model is a mixture of MM Gaussians with weights cm>0c_m > 0, means μm0∈Rn\mu^0_m \in \mathbb{R}^n and diagonal covariances Σm=diag(σm,12,…,σm,n2)\Sigma_m = \mathrm{diag}(\sigma^2_{m,1}, \ldots, \sigma^2_{m,n}). The weights and the covariances are fixed. The unknown means μ=(μ1,…,μM)\mu = (\mu_1, \ldots, \mu_M) have the prior

p(μ)=∏m=1MN(μm; μm0, Σm/τ),τ>0.p(\mu) = \prod_{m=1}^{M} \mathcal{N}\big(\mu_m;\ \mu^0_m,\ \Sigma_m / \tau\big), \qquad \tau > 0.

The data are the frames O=o1,…,oTO = o_1, \ldots, o_T, and p(O∣μ)=∏t∑mcmN(ot;μm,Σm)p(O \mid \mu) = \prod_t \sum_m c_m \mathcal{N}(o_t; \mu_m, \Sigma_m). MAP estimation maximizes the log posterior up to a constant, J(μ)=log⁡p(O∣μ)+log⁡p(μ)J(\mu) = \log p(O \mid \mu) + \log p(\mu). All logs are natural logs.

Fix the current means μold\mu^{\mathrm{old}}. Let γm(t)\gamma_m(t) be the posterior of Gaussian mm at frame tt under them (line L3), and let nm=∑tγm(t)n_m = \sum_t \gamma_m(t) and sm=∑tγm(t)ots_m = \sum_t \gamma_m(t) o_t (line L4). The penalized auxiliary function is

F(μ)=∑t=1T∑m=1Mγm(t)log⁡(cmN(ot;μm,Σm))+log⁡p(μ).\mathcal{F}(\mu) = \sum_{t=1}^{T} \sum_{m=1}^{M} \gamma_m(t) \log\big( c_m \mathcal{N}(o_t; \mu_m, \Sigma_m) \big) + \log p(\mu).

Lemma 1 (the M-step). F\mathcal{F} has the unique maximizer μm=(τμm0+sm)/(τ+nm)\mu_m = (\tau \mu^0_m + s_m) / (\tau + n_m) for every mm, the update of line L5.

Proof. Collect the terms of F\mathcal{F} that depend on coordinate ii of μm\mu_m. With diagonal covariances they are

f(x)=−12σm,i2(∑tγm(t)(ot,i−x)2+τ(x−μm,i0)2),f(x) = -\frac{1}{2 \sigma^2_{m,i}} \Big( \sum_t \gamma_m(t) (o_{t,i} - x)^2 + \tau (x - \mu^0_{m,i})^2 \Big),

and no other term depends on x=μm,ix = \mu_{m,i}. The second derivative is −(nm+τ)/σm,i2<0-(n_m + \tau)/\sigma^2_{m,i} < 0, so ff is strictly concave, and its maximum is where the derivative is zero:

∑tγm(t)(ot,i−x)+τ(μm,i0−x)=0  ⟺  x=τμm,i0+sm,iτ+nm.□\sum_t \gamma_m(t) (o_{t,i} - x) + \tau (\mu^0_{m,i} - x) = 0 \iff x = \frac{\tau \mu^0_{m,i} + s_{m,i}}{\tau + n_m}. \qquad \square

Theorem 2 (MAP-EM is monotone). Let μnew\mu^{\mathrm{new}} be the means of line L5 computed from the posteriors of μold\mu^{\mathrm{old}}. Then J(μnew)≥J(μold)J(\mu^{\mathrm{new}}) \ge J(\mu^{\mathrm{old}}).

Proof. Write p(ot,m∣μ)=cmN(ot;μm,Σm)p(o_t, m \mid \mu) = c_m \mathcal{N}(o_t; \mu_m, \Sigma_m), so that γm(t)=p(ot,m∣μold)/p(ot∣μold)\gamma_m(t) = p(o_t, m \mid \mu^{\mathrm{old}}) / p(o_t \mid \mu^{\mathrm{old}}) is a distribution over mm. By Jensen's inequality for the concave log, for any μ\mu,

log⁡p(ot∣μ)p(ot∣μold)=log⁡∑mγm(t)p(ot,m∣μ)p(ot,m∣μold)≥∑mγm(t)log⁡p(ot,m∣μ)p(ot,m∣μold).\log \frac{p(o_t \mid \mu)}{p(o_t \mid \mu^{\mathrm{old}})} = \log \sum_m \gamma_m(t) \frac{p(o_t, m \mid \mu)}{p(o_t, m \mid \mu^{\mathrm{old}})} \ge \sum_m \gamma_m(t) \log \frac{p(o_t, m \mid \mu)}{p(o_t, m \mid \mu^{\mathrm{old}})}.

Sum over tt and add log⁡p(μ)−log⁡p(μold)\log p(\mu) - \log p(\mu^{\mathrm{old}}) to both sides: J(μ)−J(μold)≥F(μ)−F(μold)J(\mu) - J(\mu^{\mathrm{old}}) \ge \mathcal{F}(\mu) - \mathcal{F}(\mu^{\mathrm{old}}). By Lemma 1, F(μnew)≥F(μold)\mathcal{F}(\mu^{\mathrm{new}}) \ge \mathcal{F}(\mu^{\mathrm{old}}). □\square

So the iteration of lines L2 to L5 climbs the posterior, and at a fixed point the gradient of JJ is zero. Like any EM, it can stop at a local maximum.

Proposition 3 (one Gaussian: the exact posterior). If M=1M = 1, then γ1(t)=1\gamma_1(t) = 1 for every frame, and the update is the mean of the exact posterior distribution of μ1\mu_1, which is

μ1∣O ∼ N(τμ0+∑totτ+T, Στ+T).\mu_1 \mid O \ \sim\ \mathcal{N}\Big( \frac{\tau \mu^0 + \sum_t o_t}{\tau + T},\ \frac{\Sigma}{\tau + T} \Big).

Proof. The prior is Gaussian and the likelihood of a Gaussian mean with a known covariance is Gaussian in the mean, so the posterior is Gaussian (conjugate prior). Its precision is the sum of the prior precision τΣ−1\tau \Sigma^{-1} and the data precision TΣ−1T \Sigma^{-1}, and its mean is the precision weighted average of μ0\mu^0 and the sample mean oˉ\bar o: (τμ0+Toˉ)/(τ+T)(\tau \mu^0 + T \bar o)/(\tau + T). One update with n1=Tn_1 = T and s1=Toˉs_1 = T \bar o gives the same value, and further iterations do not change it, because the posteriors stay 1. □\square

For M>1M > 1 the posterior of the means is a mixture over all assignments of frames to Gaussians, and the MAP-EM result is only a mode of it.

Proposition 4 (the relevance factor form). With αm=nm/(nm+r)\alpha_m = n_m / (n_m + r) and Em=sm/nmE_m = s_m / n_m for nm>0n_m > 0, the form of Reynolds, Quatieri and Dunn, μ^m=αmEm+(1−αm)μm0\hat\mu_m = \alpha_m E_m + (1 - \alpha_m) \mu^0_m, equals one step of line L5 with τ=r\tau = r.

Proof. αmEm+(1−αm)μm0=nmnm+r⋅smnm+rnm+rμm0=sm+rμm0nm+r\alpha_m E_m + (1 - \alpha_m) \mu^0_m = \frac{n_m}{n_m + r} \cdot \frac{s_m}{n_m} + \frac{r}{n_m + r} \mu^0_m = \frac{s_m + r \mu^0_m}{n_m + r}. For nm=0n_m = 0 both forms give μm0\mu^0_m. □\square

Remark (what is not claimed). Gauvain and Lee 1994 also place a Dirichlet prior on the weights and a normal-Wishart prior on the means and precisions jointly, and give EM updates for all of them. The weight and variance updates of Reynolds et al. 2000 are a one-step heuristic with the same form; they are not shown here to be the maximizer of a posterior. The value r=16r = 16 is a choice made on development data, not a result.

Complexity

In the real RAM, line L3 evaluates MM Gaussians of dimension nn at each of TT frames, O(TMn)O(T M n), and line L4 costs the same. Line L5 costs O(Mn)O(M n). With kk iterations the time is O(kTMn)O(k T M n). The extra memory is O(Mn)O(M n) for the statistics; the posteriors are added frame by frame and need not be stored. In a large system, most of the time goes into the E-step, as in ML training.

Properties

  • Asymptotic behavior. As nm→∞n_m \to \infty with τ\tau fixed, αm→1\alpha_m \to 1 and the MAP mean tends to the ML mean. For an infinite amount of data, MAP adaptation and ML training agree.
  • Local update. Only Gaussians with data move. This is the main difference from MLLR, where a shared transform moves every Gaussian of a class. With little data MLLR is better, and with much data MAP is better; Gales and Young 2008 describe this trade-off.
  • A heuristic constant. The relevance factor r=16r = 16 of Reynolds et al. 2000 was chosen by experiment, and other systems tune the value on development data. It is a heuristic, not a result of the theory.
  • Monotone MAP-EM. Each iteration does not decrease the log posterior (Theorem 2 of the proof).
  • Aligned components. The adapted model keeps the order and the meaning of the components of the prior model. This makes MAP-adapted models easy to compare: the stacked adapted means form a fixed-length "GMM supervector" for each speaker. The i-vector extractor uses the same statistics nmn_m and sms_m.

Variants and improvements

  • Weights and variances. Reynolds et al. 2000 also adapt the weights, c^m=β [αmnm/T+(1−αm)cm]\hat c_m = \beta\,[\alpha_m n_m / T + (1 - \alpha_m) c_m] with β\beta chosen so that the weights sum to 1, and the variances, σ^m2=αmEm[x2]+(1−αm)(σm2+(μm0)2)−μ^m2\hat\sigma^2_m = \alpha_m E_m[x^2] + (1 - \alpha_m)(\sigma^2_m + (\mu^0_m)^2) - \hat\mu_m^2 per dimension. In their speaker verification experiments, adapting only the means gave the best results; this is a measurement on their data. The code implements both forms.
  • Separate factors. Use a separate τ\tau for the weights, the means and the variances, as in the general Gauvain and Lee formulas.
  • MAP on top of MLLR. Use the MLLR-adapted model as the prior mean, so that unseen Gaussians also move, and refine the Gaussians with much data by MAP.
  • Joint factor analysis and eigenvoices. Constrain the supervector of adapted means to a low-dimensional subspace. With little data, this moves all Gaussians in a coordinated way. The i-vector model is the later form of this idea.

When to use it

Use MAP adaptation when the target speaker or condition has enough data to see most Gaussians several times, for example minutes of speech for a GMM-HMM recognizer, or when the model must keep the components of the prior model aligned, as in GMM-UBM speaker verification. With only a few seconds of data, use MLLR or another transform with few parameters, or combine the two.

Pitfalls

  • Shrinking toward the wrong mean. Line L5 shrinks toward the prior mean μm0\mu^0_m at every iteration. Shrinking toward the last iterate makes the prior weaker at each step.
  • Too small a relevance factor. With τ\tau near 0, a Gaussian that saw one or two frames jumps to them. The model then fits noise, and its variance is no longer correct for the new mean.
  • Posteriors from the wrong model. In speaker verification, the posteriors come from the universal background model. In iterative MAP-EM, they come from the current adapted model. Mixing the two changes the result.
  • Variance adaptation without a floor. The adapted variance formula subtracts μ^m2\hat\mu_m^2 and can give values near 0 with very little data. Floor the variances.
  • Products of densities. Compute the posteriors of line L3 in log space with the log-sum-exp trick; densities of frames far from every mean are 0 in double precision.

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.

map_speaker_adaptation.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/map-speaker-adaptation/. The authors are listed in prov/TAZK46.jsonl.

"""MAP adaptation of the means of a Gaussian mixture (Gauvain and Lee 1994).

The prior model is a mixture of M Gaussians with diagonal covariances: weights
c[m], means mu0[m] and variances var[m]. The prior on the mean of Gaussian m is
N(mu0[m], var[m] / tau), independent over m, and the weights and variances are
fixed. One EM step of MAP estimation is

    mu_m = (tau mu0_m + sum_t gamma_m(t) o_t) / (tau + sum_t gamma_m(t)),

where gamma_m(t) is the posterior of Gaussian m at frame t under the current
means. map_adapt iterates this step; one step is the usual practice.

reynolds_adapt is the one-step form of Reynolds, Quatieri and Dunn 2000, which
also adapts the weights and the variances with the coefficient
alpha_m = n_m / (n_m + r) for a relevance factor r. For the means it gives the
same value as one step of map_adapt with tau = r.

Every log is the natural log. Posteriors are computed in log space.
"""

import math
from typing import List, Sequence, Tuple

from nlslog import log_sum

Vector = List[float]
Matrix = List[List[float]]

LOG_2PI = math.log(2.0 * math.pi)


def log_gauss_diag(x: Sequence[float], mu: Sequence[float], var: Sequence[float]) -> float:
    """Return log N(x; mu, diag(var))."""
    s = 0.0
    for xi, mi, vi in zip(x, mu, var):
        s += LOG_2PI + math.log(vi) + (xi - mi) * (xi - mi) / vi
    return -0.5 * s


def posteriors(frame: Sequence[float], weights: Sequence[float], means: Sequence[Sequence[float]],
               variances: Sequence[Sequence[float]]) -> Tuple[Vector, float]:
    """Return (gamma, log p(frame)) for a diagonal Gaussian mixture."""
    lp = [math.log(w) + log_gauss_diag(frame, m, v) if w > 0 else float("-inf")
          for w, m, v in zip(weights, means, variances)]
    z = log_sum(lp)
    return [math.exp(x - z) for x in lp], z


def statistics(frames: Sequence[Sequence[float]], weights: Sequence[float], means: Sequence[Sequence[float]],
               variances: Sequence[Sequence[float]]) -> Tuple[Vector, Matrix, Matrix, float]:
    """Return (n, s, q, log likelihood): n_m = sum gamma, s_m = sum gamma o, q_m = sum gamma o^2 per dimension."""
    M, d = len(means), len(means[0])
    n = [0.0] * M
    s = [[0.0] * d for _ in range(M)]
    q = [[0.0] * d for _ in range(M)]
    ll = 0.0
    for o in frames:
        g, z = posteriors(o, weights, means, variances)  # @line L3
        ll += z
        for m in range(M):
            gm = g[m]
            if gm > 0.0:
                n[m] += gm  # @line L4
                for i in range(d):
                    s[m][i] += gm * o[i]
                    q[m][i] += gm * o[i] * o[i]
    return n, s, q, ll


def map_means(mu0: Sequence[Sequence[float]], n: Sequence[float], s: Sequence[Sequence[float]], tau: float) -> Matrix:
    """Return mu_m = (tau mu0_m + s_m) / (tau + n_m). Needs tau > 0 or n_m > 0."""
    out = []
    for m in range(len(mu0)):
        den = tau + n[m]
        if den <= 0.0:
            raise ValueError("tau + n_m must be positive")
        out.append([(tau * a + b) / den for a, b in zip(mu0[m], s[m])])  # @line L5
    return out


def log_prior(means: Sequence[Sequence[float]], mu0: Sequence[Sequence[float]],
              variances: Sequence[Sequence[float]], tau: float) -> float:
    """Return sum_m log N(mu_m; mu0_m, diag(var_m) / tau)."""
    return math.fsum(log_gauss_diag(mu, m0, [v / tau for v in var]) for mu, m0, var in zip(means, mu0, variances))


def map_adapt(frames: Sequence[Sequence[float]], weights: Sequence[float], mu0: Sequence[Sequence[float]],
              variances: Sequence[Sequence[float]], tau: float, iterations: int = 1) -> Tuple[Matrix, List[float]]:
    """Run MAP-EM on the means. Return (means, objective values).

    The objective is log p(frames | means) + log prior(means), given before
    each iteration and after the last one (tau > 0 for the prior term).
    """
    means = [list(map(float, m)) for m in mu0]  # @line L1
    history = []
    for _ in range(iterations):  # @line L2
        n, s, _, ll = statistics(frames, weights, means, variances)
        history.append(ll + log_prior(means, mu0, variances, tau))
        means = map_means(mu0, n, s, tau)
    ll = statistics(frames, weights, means, variances)[3]
    history.append(ll + log_prior(means, mu0, variances, tau))
    return means, history  # @line L6


def reynolds_adapt(frames: Sequence[Sequence[float]], weights: Sequence[float], means: Sequence[Sequence[float]],
                   variances: Sequence[Sequence[float]], r: float = 16.0, adapt: str = "wmv",
                   var_floor: float = 1e-6) -> Tuple[Vector, Matrix, Matrix]:
    """One-step adaptation of weights (w), means (m) and variances (v) with alpha_m = n_m / (n_m + r).

    Return (weights, means, variances); the parts not named in adapt stay.
    """
    T = len(frames)
    M, d = len(means), len(means[0])
    n, s, q, _ = statistics(frames, weights, means, variances)
    alpha = [n[m] / (n[m] + r) if n[m] + r > 0 else 0.0 for m in range(M)]
    new_w = list(weights)
    if "w" in adapt:
        raw = [alpha[m] * n[m] / T + (1.0 - alpha[m]) * weights[m] for m in range(M)]
        z = math.fsum(raw)
        new_w = [x / z for x in raw]
    new_mu = [list(mu) for mu in means]
    new_var = [list(v) for v in variances]
    for m in range(M):
        if n[m] <= 0.0:
            continue
        E = [x / n[m] for x in s[m]]
        E2 = [x / n[m] for x in q[m]]
        mu_hat = [alpha[m] * E[i] + (1.0 - alpha[m]) * means[m][i] for i in range(d)]
        if "m" in adapt:
            new_mu[m] = mu_hat
        if "v" in adapt:
            # Reynolds et al. 2000: the second moment is interpolated, then the square of the adapted mean is removed.
            new_var[m] = [max(var_floor, alpha[m] * E2[i] + (1.0 - alpha[m]) * (variances[m][i] + means[m][i] ** 2)
                              - mu_hat[i] ** 2) for i in range(d)]
    return new_w, new_mu, new_var
nlslog.py 152 lines
# SPDX-License-Identifier: MIT
# Shared helper of the natural-language-and-speech pages of https://algorithm.tamnd.com/. The authors are listed in prov/.

"""Log-space arithmetic and semirings for the natural-language-and-speech pages.

Every log is the natural log. A probability of 0 is NEG_INF (float("-inf")),
never a large negative number. A cost is -log p, so a probability of 0 is a
cost of POS_INF.

The semirings are (K, plus, times, zero, one) as on the weighted-automaton page:

    PROB      probabilities         plus = +        times = *   zero = 0       one = 1
    LOG       log probabilities     plus = log_add  times = +   zero = -inf    one = 0
    VITERBI   log probabilities     plus = max      times = +   zero = -inf    one = 0
    TROPICAL  costs -log p          plus = min      times = +   zero = +inf    one = 0
    LOG_COST  costs -log p          plus = -log_add(-a, -b), times = +, zero = +inf, one = 0
    BOOLEAN   truth values          plus = or       times = and zero = False   one = True
    COUNTING  path counts           plus = +        times = *   zero = 0       one = 1

This module holds no algorithm of any page: no forward, Viterbi, CKY, Eisner,
CTC or DTW recursion. The pages build their dynamic programs on top of it.
"""

import math
from dataclasses import dataclass
from typing import Any, Callable, Iterable, List, Sequence

NEG_INF = float("-inf")
POS_INF = float("inf")


def safe_log(p) -> float:
    """Return log p, and NEG_INF for p = 0. Raise ValueError for p < 0."""
    if p < 0:
        raise ValueError("log of a negative number")
    if p == 0:
        return NEG_INF
    return math.log(p)


def log_add(a: float, b: float) -> float:
    """Return log(exp(a) + exp(b)) = max(a, b) + log(1 + exp(-|a - b|)).

    log_add(NEG_INF, NEG_INF) is NEG_INF. No exp of a large number is taken.
    """
    if a < b:
        a, b = b, a
    if b == NEG_INF or a == POS_INF:
        return a
    return a + math.log1p(math.exp(b - a))


def log_sum(xs: Iterable[float]) -> float:
    """Return log(sum of exp(x)) over xs. An empty input gives NEG_INF."""
    xs = list(xs)
    if not xs:
        return NEG_INF
    m = max(xs)
    if m == NEG_INF or m == POS_INF:
        return m
    return m + math.log(math.fsum(math.exp(x - m) for x in xs))


def log_normalize(xs: Sequence[float]) -> List[float]:
    """Return the list x - log_sum(xs): log values whose exps sum to 1.

    Raise ValueError if every value is NEG_INF (nothing to normalize).
    """
    z = log_sum(xs)
    if z == NEG_INF:
        raise ValueError("every weight is zero")
    return [x - z for x in xs]


def log_softmax(xs: Sequence[float]) -> List[float]:
    """Return log softmax(xs): the logits xs turned into log probabilities."""
    return log_normalize(xs)


def softmax(xs: Sequence[float], temperature: float = 1.0) -> List[float]:
    """Return the probabilities exp(x / temperature) / sum, computed stably.

    The temperature must be positive. Logits of NEG_INF get probability 0.
    """
    if not temperature > 0:
        raise ValueError("the temperature must be positive")
    m = max(xs)
    if m == NEG_INF:
        raise ValueError("every logit is -inf")
    es = [math.exp((x - m) / temperature) for x in xs]
    s = math.fsum(es)
    return [e / s for e in es]


def argmax(xs: Sequence[Any]) -> int:
    """Return the first index of a largest value. Raise ValueError if xs is empty."""
    if len(xs) == 0:
        raise ValueError("argmax of an empty sequence")
    best = 0
    for i in range(1, len(xs)):
        if xs[i] > xs[best]:
            best = i
    return best


@dataclass(frozen=True)
class Semiring:
    """A semiring (K, plus, times, zero, one). idempotent is True when a plus a = a."""

    name: str
    plus: Callable[[Any, Any], Any]
    times: Callable[[Any, Any], Any]
    zero: Any
    one: Any
    idempotent: bool


def _add(a, b):
    return a + b


def _mul(a, b):
    return a * b


def _log_add_cost(a: float, b: float) -> float:
    return -log_add(-a, -b)


PROB = Semiring("probability", _add, _mul, 0, 1, False)
LOG = Semiring("log", log_add, _add, NEG_INF, 0.0, False)
VITERBI = Semiring("viterbi", max, _add, NEG_INF, 0.0, True)
TROPICAL = Semiring("tropical", min, _add, POS_INF, 0.0, True)
LOG_COST = Semiring("log-cost", _log_add_cost, _add, POS_INF, 0.0, False)
BOOLEAN = Semiring("boolean", lambda a, b: a or b, lambda a, b: a and b, False, True, True)
COUNTING = Semiring("counting", _add, _mul, 0, 1, False)


def sr_sum(sr: Semiring, xs: Iterable[Any]) -> Any:
    """Return the semiring sum of xs, and sr.zero for an empty input."""
    acc = sr.zero
    for x in xs:
        acc = sr.plus(acc, x)
    return acc


def sr_prod(sr: Semiring, xs: Iterable[Any]) -> Any:
    """Return the semiring product of xs, and sr.one for an empty input."""
    acc = sr.one
    for x in xs:
        acc = sr.times(acc, x)
    return acc
test_map_speaker_adaptation.py 166 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/map-speaker-adaptation/. The authors are listed in prov/TAZK46.jsonl.

import math
import random
from fractions import Fraction as F

import pytest

from map_speaker_adaptation import (
    log_gauss_diag,
    log_prior,
    map_adapt,
    map_means,
    posteriors,
    reynolds_adapt,
    statistics,
)


def mixture(rng, weights, means, variances, T):
    out = []
    for _ in range(T):
        u, m, acc = rng.random(), 0, weights[0]
        while u > acc and m < len(weights) - 1:
            m += 1
            acc += weights[m]
        out.append([rng.gauss(mu, math.sqrt(v)) for mu, v in zip(means[m], variances[m])])
    return out


def test_one_gaussian_exact_values():
    # Prior mean 0, data mean 2, tau = 16: n = 4, 16, 64 give alpha = 1/5, 1/2, 4/5.
    for n, want in ((4, F(2, 5)), (16, F(1)), (64, F(8, 5))):
        (mu,) = map_means([[F(0)]], [F(n)], [[F(2 * n)]], F(16))
        assert mu[0] == want


def test_one_gaussian_is_the_conjugate_posterior_mean():
    rng = random.Random(1)
    var, mu0, tau = 2.5, 1.0, 7.0
    xs = [rng.gauss(3.0, math.sqrt(var)) for _ in range(20)]
    means, _ = map_adapt([[x] for x in xs], [1.0], [[mu0]], [[var]], tau, iterations=1)
    # Posterior of a normal mean with known variance: precisions add.
    prior_prec, data_prec = tau / var, len(xs) / var
    want = (prior_prec * mu0 + data_prec * (sum(xs) / len(xs))) / (prior_prec + data_prec)
    assert means[0][0] == pytest.approx(want, abs=1e-12)


def test_page_example_two_components():
    frames = [[0.5], [1.5], [2.5], [3.0]]
    w, mu0, var = [0.5, 0.5], [[-1.0], [1.0]], [[1.0], [1.0]]
    n, s, _, _ = statistics(frames, w, mu0, var)
    assert n[0] == pytest.approx(0.325533, abs=1e-6)
    assert n[1] == pytest.approx(3.674467, abs=1e-6)
    m16 = map_means(mu0, n, s, 16.0)
    m2 = map_means(mu0, n, s, 2.0)
    assert [m16[0][0], m16[1][0]] == pytest.approx([-0.965986, 1.182763], abs=1e-6)
    assert [m2[0][0], m2[1][0]] == pytest.approx([-0.761219, 1.633676], abs=1e-6)


def test_limits_of_tau():
    rng = random.Random(2)
    w = [0.3, 0.7]
    mu0 = [[0.0, 0.0], [3.0, 1.0]]
    var = [[1.0, 0.5], [0.7, 1.2]]
    frames = mixture(rng, w, [[0.5, 0.2], [2.5, 1.5]], var, 60)
    n, s, _, _ = statistics(frames, w, mu0, var)
    ml = [[x / n[m] for x in s[m]] for m in range(2)]
    assert map_means(mu0, n, s, 0.0) == [pytest.approx(row, abs=1e-12) for row in ml]
    big = map_means(mu0, n, s, 1e12)
    for a, b in zip(big, mu0):
        assert a == pytest.approx(b, abs=1e-9)


def test_map_em_never_decreases_the_log_posterior():
    rng = random.Random(3)
    w = [0.25, 0.25, 0.25, 0.25]
    mu0 = [[-2.0, 0.0], [2.0, 0.0], [0.0, 2.0], [0.0, -2.0]]
    var = [[1.0, 1.0], [0.8, 1.0], [1.0, 0.6], [1.2, 1.0]]
    frames = mixture(rng, w, [[-1.0, 1.0], [3.0, 0.5], [0.5, 3.0], [0.0, -1.0]], var, 150)
    _, hist = map_adapt(frames, w, mu0, var, tau=4.0, iterations=12)
    for a, b in zip(hist, hist[1:]):
        assert b >= a - 1e-9
    assert hist[-1] > hist[0]


def test_m_step_is_a_stationary_point_of_the_auxiliary_function():
    rng = random.Random(4)
    w = [0.5, 0.5]
    mu0 = [[0.0, 1.0], [2.0, -1.0]]
    var = [[1.0, 2.0], [0.5, 1.0]]
    tau = 3.0
    frames = mixture(rng, w, mu0, var, 40)
    gam = [posteriors(o, w, mu0, var)[0] for o in frames]
    n, s, _, _ = statistics(frames, w, mu0, var)
    new = map_means(mu0, n, s, tau)

    def objective(means):
        q = math.fsum(g[m] * log_gauss_diag(o, means[m], var[m]) for o, g in zip(frames, gam) for m in range(2))
        return q + log_prior(means, mu0, var, tau)

    h = 1e-6
    best = objective(new)
    for m in range(2):
        for i in range(2):
            up = [row[:] for row in new]
            dn = [row[:] for row in new]
            up[m][i] += h
            dn[m][i] -= h
            assert abs((objective(up) - objective(dn)) / (2 * h)) < 1e-5
            up[m][i] += 0.1
            assert objective(up) < best


def test_reynolds_adapt():
    rng = random.Random(5)
    w = [0.2, 0.5, 0.3]
    mu = [[-2.0], [0.0], [3.0]]
    var = [[1.0], [0.5], [2.0]]
    frames = mixture(rng, w, [[-1.5], [0.5], [3.0]], [[1.2], [0.4], [1.5]], 80)
    n, s, q, _ = statistics(frames, w, mu, var)
    # Weights sum to 1 and the means agree with one MAP step with tau = r.
    nw, nm, nv = reynolds_adapt(frames, w, mu, var, r=16.0)
    assert math.fsum(nw) == pytest.approx(1.0, abs=1e-12)
    assert nm == [pytest.approx(row, abs=1e-12) for row in map_means(mu, n, s, 16.0)]
    assert all(v[0] > 0 for v in nv)
    # r = 0 gives the maximum likelihood re-estimate of one EM step.
    w0, m0, v0 = reynolds_adapt(frames, w, mu, var, r=0.0)
    T = len(frames)
    for m in range(3):
        assert w0[m] == pytest.approx(n[m] / T, abs=1e-12)
        E = s[m][0] / n[m]
        assert m0[m][0] == pytest.approx(E, abs=1e-12)
        assert v0[m][0] == pytest.approx(q[m][0] / n[m] - E * E, abs=1e-9)
    # A huge r leaves the model unchanged.
    wb, mb, vb = reynolds_adapt(frames, w, mu, var, r=1e12)
    assert wb == pytest.approx(w, abs=1e-9)
    assert [x[0] for x in mb] == pytest.approx([x[0] for x in mu], abs=1e-9)
    assert [x[0] for x in vb] == pytest.approx([x[0] for x in var], abs=1e-6)
    # Only the named parts change.
    ww, wm, wv = reynolds_adapt(frames, w, mu, var, r=16.0, adapt="m")
    assert ww == w and wv == var


def test_component_without_data_keeps_its_prior_mean():
    frames = [[0.0], [0.1], [-0.1]]
    w = [0.5, 0.5]
    mu0 = [[0.0], [1000.0]]
    var = [[1.0], [1.0]]
    means, _ = map_adapt(frames, w, mu0, var, tau=16.0)
    assert means[1][0] == pytest.approx(1000.0, abs=1e-9)


def test_log_space_where_plain_densities_underflow():
    w = [0.5, 0.5]
    mu0 = [[0.0], [10.0]]
    var = [[1.0], [1.0]]
    x = [-900.0]
    assert [wi * math.exp(-0.5 * (x[0] - m[0]) ** 2) for wi, m in zip(w, mu0)] == [0.0, 0.0]
    g, z = posteriors(x, w, mu0, var)
    assert g[0] == pytest.approx(1.0) and g[1] < 1e-300
    assert math.isfinite(z)
    means, _ = map_adapt([x], w, mu0, var, tau=1.0)
    assert means[0][0] == pytest.approx(-450.0, abs=1e-9)
    assert means[1][0] == pytest.approx(10.0, abs=1e-9)

History

Gauvain and Lee 1994 gave the MAP estimate of the parameters of Gaussian mixture HMMs, with Dirichlet priors on the weights and normal-Wishart priors on the means and precisions, and EM updates for all of them. They used it for speaker adaptation and for training with little data. Reynolds, Quatieri and Dunn 2000 made the one-step mean update with a relevance factor the standard way to build speaker models from a universal background model. Joint factor analysis and the i-vector model later replaced the free per-Gaussian update with a low-dimensional one for speaker recognition.

References

  1. Jean-Luc Gauvain and Chin-Hui Lee, Maximum a posteriori estimation for multivariate Gaussian mixture observations of Markov chains, IEEE Transactions on Speech and Audio Processing 2(2), 1994, pages 291 to 298, the choice of the Dirichlet and normal-Wishart priors and the EM re-estimation formulas for the weights, means and covariances
  2. Douglas A. Reynolds, Thomas F. Quatieri and Robert B. Dunn, Speaker verification using adapted Gaussian mixture models, Digital Signal Processing 10(1-3), 2000, pages 19 to 41, the section on the adapted speaker model (the data-dependent adaptation coefficients and the relevance factor)
  3. Mark Gales and Steve Young, The application of hidden Markov models in speech recognition, Foundations and Trends in Signal Processing 1(3), 2008, pages 195 to 304, the chapter on adaptation and normalization

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