Algorithm Search⌘K

Algorithmcore

GMM-UBM speaker verification

Also called universal background model, GMM-UBM, adapted GMM speaker verification.

Verify a claimed speaker by the average log likelihood ratio per frame between a speaker GMM, MAP-adapted from a universal background model, and that background model.

Time
O(T M d) worst
Space
O(M d) extra
Where
C = the number of components kept per frame in fast scoring; M = the number of Gaussians in the UBM; T = the number of frames of the test utterance; d = the feature dimension
Properties
deterministicexactonlineiterative
Origin
Douglas A. Reynolds, Thomas F. Quatieri, Robert B. Dunn, 2000

GMM-UBM speaker verification decides whether a test utterance comes from a claimed speaker. A large Gaussian mixture, the universal background model (UBM), describes the speech of people in general. Enrollment turns it into a speaker model by moving its means toward the speaker's frames with MAP adaptation. A test utterance gets the score Λ=1T∑t[log⁡p(yt∣speaker)−log⁡p(yt∣UBM)]\Lambda = \frac{1}{T} \sum_t [\log p(y_t \mid \text{speaker}) - \log p(y_t \mid \text{UBM})], and the claim is accepted when Λ\Lambda reaches a threshold.

In plain words

First, build one general model of how people sound, from many hours of many speakers. When a new person enrolls, change this general model a little toward the person's own speech, so that you get a personal model. Parts of the general model that the person's speech does not touch stay as they are.

When someone claims to be that person, ask two questions about each short slice of the test speech. How well does the personal model explain it? How well does the general model explain it? If the personal model wins clearly on average, accept the claim. If not, reject it.

Comparing with the general model is the key step. A slice that every voice produces scores high in both models, so it gives no evidence either way.

The problem

This is the speaker verification problem. The input is a test utterance, given as feature frames Y=y1,…,yTY = y_1, \ldots, y_T (for example MFCCs with deltas, after voice activity detection), and an identity claim ss. Two hypotheses compete: H0H_0, the utterance comes from ss, and H1H_1, it comes from someone else. The system must output a score, and a decision at a threshold θ\theta.

The likelihood ratio p(Y∣H0)/p(Y∣H1)p(Y \mid H_0) / p(Y \mid H_1) is the best statistic if both densities are known (likelihood ratio test). GMM-UBM models H0H_0 with the speaker model and H1H_1 with the UBM, a Gaussian mixture with MM components (often 512 to 2048) and diagonal covariances, trained by EM on many speakers. The enrollment data of ss are frames x1,…,xNx_1, \ldots, x_N.

The algorithm

  1. ENROLL(X, UBM = (c, μ, Σ), r) ▷ r: relevance factor
  2. 1γ_m(t) ← c_m N(x_t; μ_m, Σ_m) / p(x_t | UBM) for every t, m ▷ in log space
  3. 2n_m ← Σ_t γ_m(t), E_m ← (1/n_m) Σ_t γ_m(t) x_t
  4. 3α_m ← n_m / (n_m + r)
  5. 4μ̂_m ← α_m E_m + (1 - α_m) μ_m
  6. 5return the speaker model (c, μ̂, Σ)
  7. SCORE(Y, speaker, UBM, θ)
  8. 6Λ ← (1/T) Σ_t [log p(y_t | speaker) - log p(y_t | UBM)]
  9. 7accept if Λ ≥ θ, else reject

Only the means are adapted. The speaker model keeps the weights and the covariances of the UBM, and component mm of the speaker model describes the same part of the feature space as component mm of the UBM. A component with nm=0n_m = 0 keeps its UBM mean. Each mixture density is a sum of MM terms; the code computes its log with the log-sum-exp trick.

Fast scoring. For each test frame, find the CC components with the largest weighted UBM density, for a small CC such as 5. Sum both mixtures over these CC components only. Because the speaker components are adapted from the UBM components, the components that matter for the UBM are usually the ones that matter for the speaker model.

Example

Take a one-dimensional UBM with two components: c=(0.5,0.5)c = (0.5, 0.5), μ=(−1,1)\mu = (-1, 1), σ2=1\sigma^2 = 1. The speaker enrolls with four frames, 1.5,2.0,2.5,0.51.5, 2.0, 2.5, 0.5, and r=4r = 4. The usual value is r=16r = 16; a smaller value is used here so that four frames move the means visibly.

frame xtx_t 1.5 2.0 2.5 0.5
γ1(t)\gamma_1(t) 0.047426 0.017986 0.006693 0.268941
γ2(t)\gamma_2(t) 0.952574 0.982014 0.993307 0.731059
component nmn_m EmE_m αm\alpha_m μ^m\hat\mu_m
1 0.341046 0.757416 0.078563 -0.861932
2 3.658954 1.705866 0.477735 1.337217

Component 2 has most of the data and moves from 1 to 1.337217. Component 1 moves only a little.

Now score two test utterances of two frames each.

test utterance per-frame log likelihood ratios Λ\Lambda
1.8,2.21.8, 2.2 (the speaker) 0.217649, 0.348872 0.283261
−1.2,0.8-1.2, 0.8 (an impostor) -0.082495, -0.053297 -0.067896

With θ=0\theta = 0, the first claim is accepted and the second is rejected. The frame 0.80.8 is close to the UBM mean 11, where the speaker model has less density than the UBM, so its ratio is negative.

Correctness

The proof is in proofs/correctness.md. Enrollment is one step of MAP-EM, started at the UBM, with the prior N(μm,Σm/r)\mathcal{N}(\mu_m, \Sigma_m / r) on each mean; the MAP page proves that this step maximizes the penalized auxiliary function. With frames that are independent given the model, Λ\Lambda is the log likelihood ratio of the whole utterance divided by TT, and the log-sum-exp form computes each mixture density exactly in real arithmetic. If the two models were the true densities, thresholding Λ\Lambda would be the most powerful test at its false alarm rate, by the Neyman-Pearson lemma. Top-CC scoring equals the exact score when C=MC = M, and its UBM term is within log⁡(M/C)\log(M/C) of the exact term for any CC; the speaker term has no such bound.

Proof: GMM-UBM enrollment is a MAP step and the score is the average log likelihood ratiofull

We use the notation of the page. The universal background model (UBM) is a mixture of MM Gaussians with weights cm>0c_m > 0, means μm∈Rd\mu_m \in \mathbb{R}^d and diagonal covariances Σm\Sigma_m. All logs are natural logs. For a mixture λ\lambda write p(x∣λ)=∑mcmN(x;μm(λ),Σm)p(x \mid \lambda) = \sum_m c_m \mathcal{N}(x; \mu_m(\lambda), \Sigma_m), and am(x,λ)=log⁡(cmN(x;μm(λ),Σm))a_m(x, \lambda) = \log\big(c_m \mathcal{N}(x; \mu_m(\lambda), \Sigma_m)\big) for the terms in log form.

Lemma 1 (log-sum-exp is exact). For real numbers a1,…,aMa_1, \ldots, a_M with maximum a∗a^*, log⁡∑meam=a∗+log⁡∑meam−a∗\log \sum_m e^{a_m} = a^* + \log \sum_m e^{a_m - a^*}, and the inner sum lies in [1,M][1, M].

Proof. Multiply and divide the sum by ea∗e^{a^*}. Each term eam−a∗e^{a_m - a^*} is in (0,1](0, 1], and the term of the largest ama_m is 1. □\square

So the code evaluates log⁡p(x∣λ)\log p(x \mid \lambda) without forming the densities, whose values can be below the smallest double. The posterior of line L1 is γm(t)=eam−z\gamma_m(t) = e^{a_m - z} with z=log⁡p(xt∣UBM)z = \log p(x_t \mid \text{UBM}), which is the exact posterior cmN(xt;μm,Σm)/p(xt∣UBM)c_m \mathcal{N}(x_t; \mu_m, \Sigma_m) / p(x_t \mid \text{UBM}).

Theorem 2 (enrollment is one MAP-EM step). Put the prior μms∼N(μm,Σm/r)\mu^{s}_m \sim \mathcal{N}(\mu_m, \Sigma_m / r), independent over mm, on the means of the speaker model, and keep its weights and covariances equal to those of the UBM. Start MAP-EM at the UBM. Then lines L1 to L4 compute the means after one MAP-EM step, and this step does not lower log⁡p(X∣λ)+log⁡p(λ)\log p(X \mid \lambda) + \log p(\lambda) for the enrollment frames XX.

Proof. At the start, the current model is the UBM, so the E-step posteriors are the γm(t)\gamma_m(t) of line L1, and nmn_m and EmE_m of line L2 are the occupancy and the data mean. With αm=nm/(nm+r)\alpha_m = n_m / (n_m + r), line L4 gives

μ^m=αmEm+(1−αm)μm=∑tγm(t)xt+rμmnm+r,\hat\mu_m = \alpha_m E_m + (1 - \alpha_m) \mu_m = \frac{\sum_t \gamma_m(t) x_t + r \mu_m}{n_m + r},

and for nm=0n_m = 0 it keeps μm\mu_m, which is the same formula. This is the maximizer of the penalized auxiliary function with τ=r\tau = r, by Lemma 1 of the proof on the MAP speaker adaptation page, and that page's Theorem 2 gives the monotonicity. □\square

Theorem 3 (the score). Under the assumption that the frames are independent given the model, line L6 computes

Λ(Y)=1Tlog⁡p(y1,…,yT∣speaker)p(y1,…,yT∣UBM),\Lambda(Y) = \frac{1}{T} \log \frac{p(y_1, \ldots, y_T \mid \text{speaker})}{p(y_1, \ldots, y_T \mid \text{UBM})},

the log likelihood ratio of the two hypotheses divided by the number of frames.

Proof. With independent frames, log⁡p(Y∣λ)=∑tlog⁡p(yt∣λ)\log p(Y \mid \lambda) = \sum_t \log p(y_t \mid \lambda), and by Lemma 1 each term is computed exactly in real arithmetic. The difference of two sums is the sum of the differences, and line L6 divides it by TT. □\square

Corollary 4 (the decision rule). If the speaker model and the UBM were the true distributions of the target speaker and of the impostors, then for a fixed TT the test "accept when Λ(Y)≥θ\Lambda(Y) \ge \theta" is a likelihood ratio test with the threshold eTθe^{T\theta} on the ratio. By the Neyman-Pearson lemma, no other test with the same false alarm rate has a lower miss rate.

Proof. Λ(Y)≥θ\Lambda(Y) \ge \theta if and only if p(Y∣speaker)/p(Y∣UBM)≥eTθp(Y \mid \text{speaker}) / p(Y \mid \text{UBM}) \ge e^{T \theta}, because x↦eTxx \mapsto e^{T x} is increasing. □\square

The models are only estimates and the frames are not independent, so in practice the optimality is not exact, and the threshold is set on development data. The division by TT makes the scores of utterances of different lengths more comparable, but it is a heuristic: the true log likelihood ratio grows with TT.

Proposition 5 (fast scoring). Let StS_t be the set of the CC components with the largest am(yt,UBM)a_m(y_t, \text{UBM}). If C=MC = M, the top-CC score equals Λ(Y)\Lambda(Y). For any CC, the UBM term of the top-CC score is within log⁡(M/C)\log(M / C) of the exact term: log⁡p(yt∣UBM)−log⁡(M/C)≤log⁡∑m∈Steam(yt,UBM)≤log⁡p(yt∣UBM)\log p(y_t \mid \text{UBM}) - \log(M/C) \le \log \sum_{m \in S_t} e^{a_m(y_t, \text{UBM})} \le \log p(y_t \mid \text{UBM}).

Proof. For C=MC = M every sum is over all components. For C<MC < M, the upper bound holds because the terms are positive. The CC largest of MM positive numbers have at least the fraction C/MC/M of their sum, which gives the lower bound. □\square

There is no such bound for the speaker term: a speaker component that moved far from its UBM component can be large at a frame where the UBM component is not among the top CC. So the top-CC score can be above or below Λ(Y)\Lambda(Y). The method relies on MAP adaptation keeping each speaker component close to its UBM component, which holds when nmn_m is small next to rr or the data mean is close to μm\mu_m.

Complexity

In the real RAM, enrollment evaluates MM Gaussians of dimension dd at each of NN frames: O(NMd)O(N M d) time and O(Md)O(M d) extra memory. Scoring evaluates both mixtures at each of TT frames, O(TMd)O(T M d). Fast scoring still evaluates the whole UBM, but only CC speaker components per frame, so it costs O(T(M+C)d)O(T (M + C) d) plus the selection of the top CC in O(TM)O(T M). When one test utterance is scored against many speaker models, the UBM part and the top-CC lists are computed once, and each extra model costs only O(TCd)O(T C d). The scores are sums over frames, so the scoring is online: each frame can be added as it arrives.

Properties

  • Exact for the model. The score is the exact average log likelihood ratio of the two mixtures, under independent frames.
  • Aligned models. Every speaker model has the same components as the UBM, so fast scoring works, and the stacked adapted means form a fixed-length vector per speaker.
  • Robust with little data. A component that saw no enrollment data keeps the UBM mean, so its ratio is near 0 for frames that it explains. Unseen sounds therefore give little evidence either way, which is what one wants.
  • Heuristics. The relevance factor 16, mean-only adaptation and a small CC are choices found by experiment in Reynolds et al. 2000.
  • Not calibrated. The average per frame is not the log likelihood ratio of the utterance, and the frames are not independent. Scores need normalization or calibration before a Bayes threshold can be applied.

Variants and improvements

  • Score normalization. Z-norm shifts and scales a speaker's scores by the mean and standard deviation of the scores of impostor utterances against this speaker model. T-norm uses the scores of the test utterance against a set of impostor models. Both make one threshold work for all speakers.
  • GMM supervectors with an SVM. Stack the adapted means, scaled by the weights and covariances, into one long vector, and train a support vector machine per speaker.
  • Factor analysis and i-vectors. Joint factor analysis splits the supervector into a speaker part and a channel part. The i-vector model maps each utterance to a short vector, which is scored with PLDA.
  • Channel compensation. Feature warping, cepstral mean normalization and nuisance attribute projection reduce the effect of the microphone and the channel.
  • Neural embeddings. x-vectors replaced the GMM with a network trained to classify speakers; the PLDA back end stayed.

When to use it

Use GMM-UBM when the training data are small, when a simple and well understood system is needed, or as a baseline. It needs no labels of speakers to train the UBM, and it enrolls a speaker with seconds of speech. With large labeled corpora, i-vector and x-vector systems with PLDA are more accurate.

Pitfalls

  • A UBM from the wrong data. The UBM must match the test conditions: language, channel, gender balance. A UBM from clean read speech gives poor ratios on telephone speech.
  • Silence in the score. Silence frames give ratios near 0 and dilute Λ\Lambda. Remove them with a voice activity detector.
  • Products of densities. A test utterance has hundreds of frames, and the product of the densities underflows. Add logs, and compute each mixture with the log-sum-exp trick.
  • Threshold by speaker. Raw scores of different speakers lie on different scales. Normalize the scores, or the error rate at a single threshold goes up.
  • Adapting variances with little data. The variance update can shrink a variance near 0 and give a few frames huge ratios. Adapt only the means, or floor the variances.

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.

gmm_ubm_speaker_verification.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/gmm-ubm-speaker-verification/. The authors are listed in prov/AXV6G0.jsonl.

"""GMM-UBM speaker verification (Reynolds, Quatieri and Dunn 2000).

A universal background model (UBM) is a Gaussian mixture with diagonal
covariances, given as a tuple (weights, means, variances), trained elsewhere
on many speakers. Enrollment MAP-adapts the UBM means to the speaker's frames
with the relevance factor r; the weights and variances are kept. A test
utterance y_1 ... y_T is scored by the average log likelihood ratio per frame

    Lambda = (1/T) sum_t [log p(y_t | speaker) - log p(y_t | UBM)],

and the claim is accepted when Lambda >= theta. Every log is the natural log,
and every mixture density is summed in log space.

score_top_c is the fast scoring of Reynolds et al.: for each frame it keeps the
C UBM components with the largest weighted log density, and sums only those
components in both models. With C = M it equals score.
"""

import math
from typing import List, Sequence, Tuple

from nlslog import log_sum

Vector = List[float]
Matrix = List[List[float]]
GMM = Tuple[Sequence[float], Sequence[Sequence[float]], Sequence[Sequence[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 component_logs(x: Sequence[float], gmm: GMM) -> Vector:
    """Return log(c_m N(x; mu_m, Sigma_m)) for every component m."""
    weights, means, variances = gmm
    return [math.log(w) + log_gauss_diag(x, mu, v) if w > 0 else float("-inf")
            for w, mu, v in zip(weights, means, variances)]


def frame_loglik(x: Sequence[float], gmm: GMM) -> float:
    """Return log p(x | gmm)."""
    return log_sum(component_logs(x, gmm))


def enroll(frames: Sequence[Sequence[float]], ubm: GMM, r: float = 16.0) -> GMM:
    """Return the speaker model: the UBM with MAP-adapted means (relevance factor r > 0)."""
    if not r > 0:
        raise ValueError("the relevance factor must be positive")
    weights, means, variances = ubm
    M, d = len(means), len(means[0])
    n = [0.0] * M
    s = [[0.0] * d for _ in range(M)]
    for x in frames:
        lp = component_logs(x, ubm)
        z = log_sum(lp)
        for m in range(M):
            g = math.exp(lp[m] - z)  # @line L1
            if g > 0.0:
                n[m] += g  # @line L2
                for i in range(d):
                    s[m][i] += g * x[i]
    new_means = []
    for m in range(M):
        alpha = n[m] / (n[m] + r)  # @line L3
        if n[m] > 0.0:
            E = [v / n[m] for v in s[m]]
            new_means.append([alpha * E[i] + (1.0 - alpha) * means[m][i] for i in range(d)])  # @line L4
        else:
            new_means.append(list(means[m]))
    return (list(weights), new_means, [list(v) for v in variances])  # @line L5


def frame_llrs(frames: Sequence[Sequence[float]], spk: GMM, ubm: GMM) -> Vector:
    """Return log p(y_t | speaker) - log p(y_t | UBM) for every frame."""
    return [frame_loglik(y, spk) - frame_loglik(y, ubm) for y in frames]


def score(frames: Sequence[Sequence[float]], spk: GMM, ubm: GMM) -> float:
    """Return the average log likelihood ratio per frame."""
    if not frames:
        raise ValueError("no test frames")
    return math.fsum(frame_llrs(frames, spk, ubm)) / len(frames)  # @line L6


def decide(llr: float, theta: float) -> bool:
    """Accept the identity claim when the score reaches the threshold."""
    return llr >= theta  # @line L7


def score_top_c(frames: Sequence[Sequence[float]], spk: GMM, ubm: GMM, C: int = 5) -> float:
    """Return the fast top-C score: both mixtures summed over the C best UBM components of each frame.

    The speaker model must be MAP-adapted from this UBM, so that component m
    of both models describes the same region. Ties keep the lower index.
    """
    if not frames:
        raise ValueError("no test frames")
    total = []
    for y in frames:
        lu = component_logs(y, ubm)
        top = sorted(range(len(lu)), key=lambda m: (-lu[m], m))[:C]
        ls = component_logs(y, spk)
        total.append(log_sum(ls[m] for m in top) - log_sum(lu[m] for m in top))
    return math.fsum(total) / len(frames)


def bayes_threshold(p_target: float, c_miss: float = 1.0, c_fa: float = 1.0) -> float:
    """Return the Bayes threshold log(c_fa (1 - p_target) / (c_miss p_target)) for a calibrated LLR."""
    return math.log(c_fa * (1.0 - p_target) / (c_miss * p_target))
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_gmm_ubm_speaker_verification.py 158 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/gmm-ubm-speaker-verification/. The authors are listed in prov/AXV6G0.jsonl.

import math
import random

import pytest

from gmm_ubm_speaker_verification import (
    bayes_threshold,
    decide,
    enroll,
    frame_loglik,
    score,
    score_top_c,
)

UBM1 = ([0.5, 0.5], [[-1.0], [1.0]], [[1.0], [1.0]])


def plain_density(x, gmm):
    w, mu, var = gmm
    tot = 0.0
    for c, m, v in zip(w, mu, var):
        p = c
        for xi, mi, vi in zip(x, m, v):
            p *= math.exp(-0.5 * (xi - mi) ** 2 / vi) / math.sqrt(2 * math.pi * vi)
        tot += p
    return tot


def random_ubm(rng, M, d):
    w = [rng.uniform(0.5, 1.5) for _ in range(M)]
    z = sum(w)
    return ([x / z for x in w], [[rng.uniform(-3, 3) for _ in range(d)] for _ in range(M)],
            [[rng.uniform(0.5, 1.5) for _ in range(d)] for _ in range(M)])


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


def test_page_example():
    spk = enroll([[1.5], [2.0], [2.5], [0.5]], UBM1, r=4.0)
    assert spk[1][0][0] == pytest.approx(-0.861932, abs=1e-6)
    assert spk[1][1][0] == pytest.approx(1.337217, abs=1e-6)
    assert spk[0] == UBM1[0] and spk[2] == UBM1[2]
    assert score([[1.8], [2.2]], spk, UBM1) == pytest.approx(0.283261, abs=1e-6)
    assert score([[-1.2], [0.8]], spk, UBM1) == pytest.approx(-0.067896, abs=1e-6)


def test_score_against_direct_ratio_of_products():
    rng = random.Random(1)
    ubm = random_ubm(rng, 4, 3)
    spk = enroll(draw(rng, ubm, 50), ubm, r=8.0)
    test = draw(rng, ubm, 6)
    num = 1.0
    den = 1.0
    for y in test:
        num *= plain_density(y, spk)
        den *= plain_density(y, ubm)
    assert score(test, spk, ubm) == pytest.approx(math.log(num / den) / len(test), abs=1e-10)
    for y in test:
        assert frame_loglik(y, ubm) == pytest.approx(math.log(plain_density(y, ubm)), abs=1e-10)


def test_log_space_where_the_product_underflows():
    rng = random.Random(2)
    ubm = random_ubm(rng, 4, 3)
    spk = enroll(draw(rng, ubm, 40), ubm)
    test = draw(rng, ubm, 200)
    prod = 1.0
    for y in test:
        prod *= plain_density(y, ubm)
    assert prod == 0.0
    s = score(test, spk, ubm)
    assert math.isfinite(s)
    assert s == pytest.approx(sum(frame_loglik(y, spk) - frame_loglik(y, ubm) for y in test) / 200, abs=1e-9)


def test_ubm_against_itself_scores_zero_and_large_r_gives_the_ubm():
    rng = random.Random(3)
    ubm = random_ubm(rng, 3, 2)
    test = draw(rng, ubm, 20)
    assert score(test, ubm, ubm) == 0.0
    spk = enroll(draw(rng, ubm, 30), ubm, r=1e15)
    assert abs(score(test, spk, ubm)) < 1e-9


def test_enrollment_with_small_r_gives_the_ml_means():
    ubm = UBM1
    frames = [[1.5], [2.0], [2.5], [0.5]]
    spk = enroll(frames, ubm, r=1e-12)
    g = []
    for x in frames:
        a = 0.5 * math.exp(-0.5 * (x[0] + 1) ** 2)
        b = 0.5 * math.exp(-0.5 * (x[0] - 1) ** 2)
        g.append(b / (a + b))
    want = sum(gi * x[0] for gi, x in zip(g, frames)) / sum(g)
    assert spk[1][1][0] == pytest.approx(want, abs=1e-9)


def test_component_without_data_keeps_its_mean():
    ubm = ([0.5, 0.5], [[0.0], [1e4]], [[1.0], [1.0]])
    spk = enroll([[0.1], [-0.2]], ubm)
    assert spk[1][1] == [1e4]


def test_top_c():
    rng = random.Random(4)
    ubm = random_ubm(rng, 6, 2)
    spk = enroll(draw(rng, ubm, 40), ubm, r=2.0)
    test = draw(rng, ubm, 30)
    assert score_top_c(test, spk, ubm, C=6) == pytest.approx(score(test, spk, ubm), abs=1e-12)
    assert score_top_c(test, spk, ubm, C=3) == pytest.approx(score(test, spk, ubm), abs=0.05)
    assert score_top_c(test, spk, ubm, C=1) != score(test, spk, ubm)


def test_target_trials_score_higher_than_nontarget_trials():
    rng = random.Random(5)
    ubm = random_ubm(rng, 8, 2)

    def speaker(seed):
        r = random.Random(seed)
        return (ubm[0], [[a + r.uniform(-1.5, 1.5) for a in mu] for mu in ubm[1]], ubm[2])

    speakers = [speaker(s) for s in range(6)]
    models = [enroll(draw(rng, sp, 120), ubm, r=4.0) for sp in speakers]
    tgt, non = [], []
    for i, sp in enumerate(speakers):
        test = draw(rng, sp, 60)
        for j, mdl in enumerate(models):
            (tgt if i == j else non).append(score(test, mdl, ubm))
    assert min(tgt) > 0.0
    assert sum(tgt) / len(tgt) > sum(non) / len(non) + 0.05
    wins = sum(t > n for t in tgt for n in non)
    assert wins / (len(tgt) * len(non)) > 0.9


def test_decision_and_bayes_threshold():
    assert decide(0.5, 0.5) and not decide(0.49, 0.5)
    assert bayes_threshold(0.5) == 0.0
    assert bayes_threshold(0.01, c_miss=10.0, c_fa=1.0) == pytest.approx(math.log(9.9), abs=1e-12)


def test_empty_input():
    with pytest.raises(ValueError):
        score([], UBM1, UBM1)
    with pytest.raises(ValueError):
        enroll([[0.0]], UBM1, r=0.0)

History

Reynolds and Rose used Gaussian mixtures for text-independent speaker identification in 1995. The likelihood ratio against a background model replaced cohort models of selected impostors. Reynolds, Quatieri and Dunn 2000 described the complete system of the MIT Lincoln Laboratory: a single UBM trained on many speakers, mean-only MAP adaptation with a relevance factor, top-C fast scoring and score normalization. It was the reference approach of the NIST speaker recognition evaluations for the next decade, until joint factor analysis and then the i-vector of Dehak et al. 2011 took its place. Kinnunen and Li 2010 survey this period.

References

  1. 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 sections on the likelihood ratio detector, the universal background model, the adapted speaker models and fast scoring
  2. 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 EM re-estimation formula for the means under a conjugate prior
  3. Tomi Kinnunen and Haizhou Li, An overview of text-independent speaker recognition, from features to supervectors, Speech Communication 52(1), 2010, pages 12 to 40, the section on Gaussian mixture models and the universal background model

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