Algorithm Search⌘K

Algorithmadvanced

Phonetic decision tree state tying

Also called tree-based state tying.

Cluster triphone HMM states by a tree of yes or no questions about phone context, splitting greedily by likelihood gain.

Time
O(q n d k + k^3 d) worst
Space
O(n d + q) extra
Where
d = the dimension of the features; k = the number of leaves; n = the number of triphone states in the pool; q = the number of questions
Properties
deterministicnot exactofflineiterative
Origin
Steve J. Young, Julian J. Odell, Philip C. Woodland, 1994

Phonetic decision tree state tying clusters the HMM states of triphone models, so that states with similar acoustics share one output distribution. For each phone and each state position, it puts all the triphone states into one root node and splits the nodes by yes or no questions about the left and the right phone, for example "is the left phone a nasal?". Each split takes the question that most increases the log likelihood of the training frames under one Gaussian per node, and the splits stop when the gain falls below a threshold. Each leaf becomes one tied state, and a triphone that never occurs in the training data still reaches a leaf by its answers to the questions.

In plain words

A recognizer that models each sound in the context of its two neighbors has tens of thousands of such sounds, and most of them occur only a few times in the training data, or never. So you group the contexts that sound alike and train one model per group.

To find the groups, start with all the contexts of one sound in one group. Ask a list of questions about the neighbors, such as "is the sound on the left a vowel?". Each question splits the group in two. Keep the question that makes the two halves fit the data best, and repeat on each half. Stop when no question helps enough. A new context that was never in the training data answers the same questions and lands in one of the groups, so it still gets a model.

The problem

The input is the pool of triphone states of one base phone and one state position, for example the middle state of every triphone of "ae". State ss has a context (a left phone lsl_s and a right phone rsr_s) and the statistics of its training frames from a Viterbi or Baum-Welch alignment: the occupancy NsN_s, the mean μs\mu_s and the diagonal variance σs2\sigma^2_s, each of dimension dd. There is also a list of questions. A question asks whether the left phone, or the right phone, is in a given set of phones, such as the nasals or the vowels.

For a set SS of states, let L(S)L(S) be the log likelihood of all their frames under one diagonal Gaussian fitted to them by maximum likelihood. With natural logs,

L(S)=−12N(S)(dlog⁡(2π)+∑k=1dlog⁡σk2(S)+d),L(S) = -\tfrac{1}{2} N(S) \Big( d \log(2 \pi) + \sum_{k=1}^{d} \log \sigma^2_k(S) + d \Big),

where N(S)=∑s∈SNsN(S) = \sum_{s \in S} N_s and the pooled variance is σk2(S)=∑sNs(σs,k2+μs,k2)/N(S)−μk(S)2\sigma^2_k(S) = \sum_s N_s (\sigma^2_{s,k} + \mu_{s,k}^2) / N(S) - \mu_k(S)^2. So L(S)L(S) needs only the statistics of the states and not the frames. The gain of a question QQ at a node SS is

Δ(Q,S)=L(Syes)+L(Sno)−L(S).\Delta(Q, S) = L(S_{\text{yes}}) + L(S_{\text{no}}) - L(S).

The task is a partition of the pool into tied states, one per leaf of a tree of questions, with a large total likelihood and with enough data in each leaf. The best such tree is not computed: the method is greedy.

The algorithm

  1. BUILD-TREE(states, questions, θ, n_min)
  2. 1leaves ← [a root node with all the states]
  3. 2repeat
  4. 3for each new leaf: cand[leaf] ← the question with the largest gain Δ such that both sides have occupancy ≥ n_min
  5. 4ℓ ← the leaf with the largest candidate gain
  6. 5if no leaf has a candidate, or the gain of ℓ is below θ, then stop
  7. 6split ℓ by its question into a yes child and a no child, and record the question at ℓ
  8. 7return the tree and its leaves
  9. MERGE(leaves, θ)
  10. 8while there are at least two clusters do
  11. 9find the pair a, b with the smallest loss L(a) + L(b) - L(a ∪ b)
  12. 10if that loss is at least θ then stop
  13. 11replace a and b by a ∪ b

Line L3 computes the candidate of the root first and then of each pair of new children. A question that puts all the states on one side is not a candidate. Ties go to the first question in the list. After the tree, the merge stage can join two leaves from different branches, which the tree alone cannot do. The function tie of the code runs both and returns the tied state of each triphone.

To find the tied state of a triphone, seen or unseen, start at the root of the tree of its base phone and state position, and follow its answers down to a leaf. The function classify of the code does this.

Example

Take the middle state of four triphones of "ae", with d=1d = 1, and three questions: "is the left phone a vowel?" (L_vowel), "is the right phone a nasal?" (R_nasal) and "is the right phone t?" (R_t). The threshold is θ=5\theta = 5 and nmin⁡=50n_{\min} = 50.

state NsN_s μs\mu_s σs2\sigma^2_s
k-ae+t 100 1.0 0.5
t-ae+k 80 1.2 0.5
iy-ae+t 60 3.0 0.4
aa-ae+n 60 2.8 0.6

The root has N=300N = 300, mean 1.8133331.813333 and variance 1.2971561.297156, so L=−464.71L = -464.71. The three questions give:

question yes side L(yes)L(\text{yes}) L(no)L(\text{no}) gain
L_vowel iy-ae+t, aa-ae+n -129.87 -194.79 140.05
R_nasal aa-ae+n -69.81 -359.10 35.80
R_t k-ae+t, iy-ae+t -253.95 -209.63 1.13

The yes side of L_vowel has N=120N = 120, mean 2.92.9 and variance 0.510.51, and the no side has N=180N = 180, mean 1.0888891.088889 and variance 0.5098770.509877. The root splits by L_vowel. In the vowel child the best question is R_nasal with a gain of 2.41, and in the other child it is R_t with a gain of 1.76. Both are below θ=5\theta = 5, so the tree stops with two leaves: {iy-ae+t, aa-ae+n} and {k-ae+t, t-ae+k}. The merge stage would lose 140.05 by joining them, so it does nothing. The unseen triphone uw-ae+m answers yes to L_vowel, if uw is in the vowel set, and shares the model of the first leaf.

Correctness

The proof is in proofs/correctness.md. It shows four facts, all theorems.

  • The pooled statistics of a set of states equal the mean and the variance of the union of their frames, so the split rule can work from statistics alone.
  • L(S)L(S) has the closed form above: at the maximum likelihood estimate, the quadratic term of the Gaussian log density sums to N(S) dN(S)\, d over the frames.
  • The gain is never negative, because the two children can always use the parameters of the parent, and their own maximum likelihood estimates are at least as good.
  • The tree that line L4 grows does not depend on the order in which the leaves split, if there is no limit on the number of leaves, because the decision at a leaf depends only on its states. The total log likelihood of the leaves is L(root)L(\text{root}) plus the sum of the gains of the splits, and every context reaches exactly one leaf.

The tree is not optimal. The proof gives an example in which the mean depends on the exclusive or of two questions: no single question has any gain, so the greedy tree stops at the root, while the tree with two levels gains a lot. The test test_greedy_misses_an_xor_context checks this.

Proof: The split gains of a phonetic decision tree are exact and never negativefull

We use the notation of the page. A pool is the set of triphone states of one base phone and one state position. Each state ss has an occupancy Ns>0N_s > 0, a mean μs∈Rd\mu_s \in \mathbb{R}^d and a diagonal variance σs2∈Rd\sigma^2_s \in \mathbb{R}^d, computed from the frames FsF_s that are assigned to it: Ns=∣Fs∣N_s = |F_s|, μsk=1Ns∑o∈Fsok\mu_{sk} = \frac{1}{N_s} \sum_{o \in F_s} o_k and σsk2=1Ns∑o∈Fs(ok−μsk)2\sigma^2_{sk} = \frac{1}{N_s} \sum_{o \in F_s} (o_k - \mu_{sk})^2. All logs are natural logs. We prove the statements for these hard assignments. With soft occupancies the same algebra holds for the weighted sums, and L(S)L(S) is then the auxiliary function of EM with the state posteriors held fixed, which is the approximation that Young, Odell and Woodland make.

Lemma 1 (pooled statistics). For a set SS of states with the frames F(S)=⋃s∈SFsF(S) = \bigcup_{s \in S} F_s, the statistics of F(S)F(S) are

N(S)=∑s∈SNs,μk(S)=1N(S)∑s∈SNsμsk,σk2(S)=1N(S)∑s∈SNs(σsk2+μsk2)−μk(S)2.N(S) = \sum_{s \in S} N_s, \qquad \mu_k(S) = \frac{1}{N(S)} \sum_{s \in S} N_s \mu_{sk}, \qquad \sigma^2_k(S) = \frac{1}{N(S)} \sum_{s \in S} N_s (\sigma^2_{sk} + \mu_{sk}^2) - \mu_k(S)^2.

Proof. The frame sets are disjoint. The sum of oko_k over FsF_s is NsμskN_s \mu_{sk}, and the sum of ok2o_k^2 over FsF_s is Ns(σsk2+μsk2)N_s(\sigma^2_{sk} + \mu^2_{sk}), because the variance is the mean square minus the square of the mean. Add over ss, divide by N(S)N(S), and use the same identity for F(S)F(S). □\square

Lemma 2 (closed form of LL). Let L(S)L(S) be the largest log likelihood of the frames F(S)F(S) under one Gaussian with a diagonal covariance. If every σk2(S)>0\sigma^2_k(S) > 0, then

L(S)=−12N(S)(dlog⁡(2π)+∑k=1dlog⁡σk2(S)+d).L(S) = -\tfrac{1}{2} N(S) \Big( d \log(2\pi) + \sum_{k=1}^{d} \log \sigma^2_k(S) + d \Big).

Proof. With a diagonal covariance, the log density is a sum over the dimensions, so the log likelihood is ∑kℓk(mk,vk)\sum_k \ell_k(m_k, v_k) with ℓk=−12∑o∈F(S)(log⁡(2πvk)+(ok−mk)2/vk)\ell_k = -\frac{1}{2} \sum_{o \in F(S)} \big( \log(2\pi v_k) + (o_k - m_k)^2 / v_k \big). Each ℓk\ell_k is maximized at the sample mean mk=μk(S)m_k = \mu_k(S) and the sample variance vk=σk2(S)v_k = \sigma^2_k(S) (the usual maximum likelihood estimate; see maximum-likelihood-estimation). At this point ∑o(ok−mk)2/vk=N(S)\sum_{o} (o_k - m_k)^2 / v_k = N(S), which gives the formula. □\square

By Lemmas 1 and 2, L(S)L(S) needs only NsN_s, μs\mu_s and σs2\sigma^2_s of the states in SS, not the frames. The code computes it in O(∣S∣d)O(|S| d) time.

Theorem 1 (gains are never negative). For every set SS and every split of SS into non-empty parts SyS_y and SnS_n, the gain Δ=L(Sy)+L(Sn)−L(S)\Delta = L(S_y) + L(S_n) - L(S) is at least 0.

Proof. Let gg be the Gaussian that attains L(S)L(S). The log likelihood of F(S)F(S) under gg is the sum of the log likelihoods of F(Sy)F(S_y) and of F(Sn)F(S_n) under gg. Each part is at most the largest log likelihood of that part, which is L(Sy)L(S_y) or L(Sn)L(S_n). □\square

Theorem 2 (what the greedy tree computes). Let BUILD-TREE run with a threshold θ\theta and a minimum occupancy mm, and without a limit on the number of leaves. Then:

  1. For each leaf that it splits, the question is one with the largest gain among the allowed questions of that leaf (both sides with occupancy at least mm).
  2. A leaf is split if and only if its largest allowed gain is at least θ\theta. So the final tree does not depend on the order in which the leaves are taken.
  3. The leaves partition the pool, and ∑leaves SL(S)=L(pool)+∑splitsΔ\sum_{\text{leaves } S} L(S) = L(\text{pool}) + \sum_{\text{splits}} \Delta.
  4. Every context (l,r)(l, r), seen in training or not, reaches exactly one leaf.

Proof. (1) Line L3 computes the gain of every allowed question of a leaf by Lemmas 1 and 2, and keeps the largest. (2) The best allowed split of a leaf depends only on the states of the leaf. Lines L4 and L5 split some leaf whose best gain is at least θ\theta as long as one exists, and splitting a leaf does not change the candidates of the other leaves. When the loop stops, no leaf has an allowed gain of at least θ\theta, and every split that was made had a gain of at least θ\theta when it was made. So the set of splits is determined by the leaves alone, whatever the order. (3) Each split replaces one block SS of a partition by SyS_y and SnS_n, so the sum of LL over the blocks grows by exactly Δ\Delta. (4) A question is a test on ll or rr with the answer yes or no for every phone, so the walk from the root is defined for every context and ends at one leaf. □\square

Remark (no global optimum). Theorem 2 is about the greedy procedure. It does not say that the tree has the largest likelihood among all trees with the same number of leaves. The test test_greedy_misses_an_xor_context builds a pool in which the mean depends on "the left phone is a vowel" exclusive-or "the right phone is a nasal". No single question changes the mean, so every first split has a small gain, and with a threshold above it the tree stays one leaf, although a tree of depth two has a gain more than four times as large.

Proposition (merge stage). Each merge of lines L8 to L11 joins the two clusters a,ba, b with the smallest loss L(a)+L(b)−L(a∪b)≥0L(a) + L(b) - L(a \cup b) \ge 0 (by Theorem 1), and only while this loss is below θ\theta. So the total log likelihood drops by less than θ\theta per merge, and the number of clusters drops by one per merge, so the stage stops after fewer merges than there are leaves.

Complexity

A node with nvn_v states evaluates qq questions, and each one pools the statistics of nvn_v states in O(nvd)O(n_v d) time. Each state is in one node per level of the tree, and the depth is less than kk, so the tree takes O(qndk)O(q n d k) time. In practice the tree is balanced enough that the depth is about log⁡k\log k, and the time is close to O(qndlog⁡k)O(q n d \log k). The merge stage with cached cluster statistics takes O(k2d)O(k^2 d) time per merge and O(k3d)O(k^3 d) in all. The code recomputes the pooled statistics in each step, which is simpler and slower.

The space is the statistics of the states, O(nd)O(n d), the questions and the tree. A recognizer builds one tree for each phone and each state position, and each tree uses only the states of its pool, so the trees are independent and can be built in parallel.

Properties

  • Statistics only. The split rule needs NsN_s, μs\mu_s and σs2\sigma^2_s of each state, and no frames. One alignment of the training data with single Gaussian untied triphones gives these statistics.
  • Unseen contexts. Every left and right phone answers every question, so every triphone has a leaf, including the ones that never occur in the training data. Bottom-up clustering of the seen triphones has no rule for the unseen ones.
  • Phonetic knowledge. The questions encode phonetic classes, such as nasals, fricatives or front vowels. The algorithm chooses which ones matter from the data.
  • Greedy. Each split is the best one locally, and the result can miss structure that needs two questions together.
  • Heuristic thresholds. The threshold θ\theta and the minimum occupancy nmin⁡n_{\min} set the number of tied states. They are tuned on development data, and the right values depend on the amount of data and on the features.

Variants and improvements

  • Questions on a wider context. The same method ties the states of quinphones, with questions about the phones two places away, and it can ask about word boundaries or stress.
  • One tree per phone. Some systems build one tree for all the states of a phone, or for all phones, with questions about the state position and the base phone. This shares data between the positions.
  • Stopping rules from model selection. A penalty from the Bayesian information criterion or minimum description length in place of a fixed θ\theta gives a threshold that grows with the number of parameters.
  • Gaussian mixtures after tying. The trees use one Gaussian per state. After tying, the recognizer splits each tied state into a mixture of Gaussians and retrains it, as in a GMM-HMM acoustic model.
  • Neural acoustic models. A hybrid DNN-HMM uses the tied states of a GMM-HMM tree as its output classes, so the trees are still part of such systems.
  • Bottom-up clustering. Agglomerative clustering of the seen triphones, as in the generalized triphones of Lee 1990, is the older method.

When to use it

Use tree-based state tying for context-dependent HMM acoustic models when the number of contexts is much larger than the data can support, and when the recognizer must handle contexts that the training data does not contain, as in large vocabulary recognition across word boundaries. With a small vocabulary and enough data per word, whole word models need no tying.

Pitfalls

  • Poor statistics. The statistics come from an alignment. If the alignment is poor, the trees cluster noise. Align with a good model first.
  • The variance floor. A state with very few frames, or with identical frames, has a variance near 0, and its log likelihood goes to +∞+\infty. Floor the variances, and use the minimum occupancy.
  • A threshold in the wrong units. The gain is a sum over frames, so it scales with the amount of data. A threshold tuned on one corpus does not transfer to a corpus of a different size.
  • A poor question set. The tree can only use the classes in the questions. Include single phones as well as broad classes.
  • Expecting the global optimum. The tree is greedy, and the merge stage only partly repairs this.

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.

phonetic_decision_tree_state_tying.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/phonetic-decision-tree-state-tying/. The authors are listed in prov/7CSFNE.jsonl.

"""Phonetic decision tree state tying (Young, Odell and Woodland 1994).

The input is the set of triphone states that share one base phone and one state
position, for example state 2 of every triphone of the phone "ae". Each state s
has a context (left phone, right phone) and the statistics of its frames: the
occupancy N_s (a frame count, or a sum of state posteriors), the mean mu_s and
the diagonal variance var_s, each a list of d numbers.

The log likelihood of the frames of a set S under one diagonal Gaussian fitted
to them by maximum likelihood is, with log the natural log,

    L(S) = -(1/2) N(S) (d log(2 pi) + sum_k log var_k(S) + d),

and it needs only the pooled statistics, not the frames. A question asks whether
the left (or the right) context phone is in a set of phones. The tree splits
leaves greedily by the question with the largest gain
L(S_yes) + L(S_no) - L(S), and stops when no split gains at least the threshold
with at least min_occ frames on each side. A merge stage then joins pairs of
leaves while the loss of likelihood stays below the threshold.
"""

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

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


class State:
    """One context-dependent state: its context and its frame statistics."""

    def __init__(self, name, left, right, occ, mean, var):
        self.name, self.left, self.right = name, left, right
        self.occ, self.mean, self.var = float(occ), list(mean), list(var)

    def __repr__(self):
        return "State(%r)" % (self.name,)


def stats_from_frames(frames: Sequence[Sequence[float]]):
    """Return (N, mean, var) of a list of frames, with the variance divided by N."""
    n = len(frames)
    d = len(frames[0])
    mean = [math.fsum(f[k] for f in frames) / n for k in range(d)]
    var = [math.fsum((f[k] - mean[k]) ** 2 for f in frames) / n for k in range(d)]
    return n, mean, var


def pool(states: Sequence[State], var_floor: float = 0.0):
    """Return the pooled (N, mean, var) of a set of states, from their statistics only.

    N = sum N_s, mean = sum N_s mu_s / N, var_k = sum N_s (var_sk + mu_sk^2) / N - mean_k^2.
    The variance is floored at var_floor.
    """
    N = math.fsum(s.occ for s in states)
    d = len(states[0].mean)
    mean = [math.fsum(s.occ * s.mean[k] for s in states) / N for k in range(d)]
    var = []
    for k in range(d):
        second = math.fsum(s.occ * (s.var[k] + s.mean[k] ** 2) for s in states) / N
        var.append(max(second - mean[k] ** 2, var_floor))
    return N, mean, var


def log_likelihood(states: Sequence[State], var_floor: float = 1e-6) -> float:
    """L(S): the log likelihood of the frames of S under one ML diagonal Gaussian."""
    if not states:
        return 0.0
    N, _, var = pool(states, var_floor)
    d = len(var)
    return -0.5 * N * (d * LOG_2PI + math.fsum(math.log(v) for v in var) + d)


def answer(question, state: State) -> bool:
    """A question is (name, side, phones) with side "L" or "R"."""
    _, side, phones = question
    return (state.left if side == "L" else state.right) in phones


def split(states, question):
    yes = [s for s in states if answer(question, s)]
    no = [s for s in states if not answer(question, s)]
    return yes, no


def best_question(states, questions, min_occ: float, var_floor: float = 1e-6):
    """Return (gain, question, yes, no) of the best allowed split, or None.

    A split is allowed if both sides have an occupancy of at least min_occ.
    Ties go to the first question in the list.
    """
    base = log_likelihood(states, var_floor)
    best = None
    for q in questions:
        yes, no = split(states, q)
        if not yes or not no:
            continue
        if sum(s.occ for s in yes) < min_occ or sum(s.occ for s in no) < min_occ:
            continue
        gain = log_likelihood(yes, var_floor) + log_likelihood(no, var_floor) - base
        if best is None or gain > best[0]:
            best = (gain, q, yes, no)
    return best


class Node:
    """A tree node. A leaf has question None and holds its states."""

    def __init__(self, states):
        self.states = states
        self.question = None
        self.yes: Optional["Node"] = None
        self.no: Optional["Node"] = None
        self.gain = 0.0


def build_tree(states, questions, threshold: float, min_occ: float, max_leaves: Optional[int] = None, var_floor: float = 1e-6):
    """Grow the tree greedily. Return (root, leaves).

    Each round splits the leaf whose best question has the largest gain.
    Without max_leaves the result does not depend on this order, because the
    decision for a leaf depends only on its own states.
    """
    root = Node(list(states))
    leaves = [root]  # @line L1
    cand = {id(root): best_question(root.states, questions, min_occ, var_floor)}  # @line L3
    while max_leaves is None or len(leaves) < max_leaves:  # @line L2
        best_leaf = None
        for leaf in leaves:  # @line L4
            c = cand[id(leaf)]
            if c is not None and (best_leaf is None or c[0] > cand[id(best_leaf)][0]):
                best_leaf = leaf
        if best_leaf is None or cand[id(best_leaf)][0] < threshold:  # @line L5
            break
        gain, q, yes, no = cand.pop(id(best_leaf))
        best_leaf.question, best_leaf.gain = q, gain  # @line L6
        best_leaf.yes, best_leaf.no = Node(yes), Node(no)
        leaves.remove(best_leaf)
        for child in (best_leaf.yes, best_leaf.no):
            leaves.append(child)
            cand[id(child)] = best_question(child.states, questions, min_occ, var_floor)
    return root, leaves  # @line L7


def merge_leaves(leaves, threshold: float, var_floor: float = 1e-6):
    """Join pairs of leaves while the smallest loss L(a) + L(b) - L(a u b) is below the threshold.

    Return a list of clusters, each a list of states. The leaves may come from
    different branches of the tree.
    """
    clusters = [list(leaf.states) if isinstance(leaf, Node) else list(leaf) for leaf in leaves]
    L = [log_likelihood(c, var_floor) for c in clusters]
    while len(clusters) > 1:  # @line L8
        best = None
        for a in range(len(clusters)):  # @line L9
            for b in range(a + 1, len(clusters)):
                loss = L[a] + L[b] - log_likelihood(clusters[a] + clusters[b], var_floor)
                if best is None or loss < best[0]:
                    best = (loss, a, b)
        if best[0] >= threshold:  # @line L10
            break
        _, a, b = best
        clusters[a] = clusters[a] + clusters[b]  # @line L11
        L[a] = log_likelihood(clusters[a], var_floor)
        del clusters[b], L[b]
    return clusters


def classify(root: Node, left: str, right: str) -> Node:
    """Return the leaf of a triphone context, seen in training or not."""
    probe = State(None, left, right, 0.0, [], [])
    node = root
    while node.question is not None:
        node = node.yes if answer(node.question, probe) else node.no
    return node


def tie(states, questions, threshold: float, min_occ: float, var_floor: float = 1e-6):
    """Build the tree, merge the leaves, and return (root, a map from state name to cluster index)."""
    root, leaves = build_tree(states, questions, threshold, min_occ, var_floor=var_floor)
    clusters = merge_leaves(leaves, threshold, var_floor)
    index = {s.name: c for c, cl in enumerate(clusters) for s in cl}
    return root, index
test_phonetic_decision_tree_state_tying.py 182 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/phonetic-decision-tree-state-tying/. The authors are listed in prov/7CSFNE.jsonl.

import math
import random

import pytest

from phonetic_decision_tree_state_tying import (
    State,
    best_question,
    build_tree,
    classify,
    log_likelihood,
    merge_leaves,
    pool,
    stats_from_frames,
    tie,
)

VOWELS = {"aa", "ae", "iy", "uw"}
NASALS = {"m", "n"}
STOPS = {"p", "t", "k"}
PHONES = sorted(VOWELS | NASALS | STOPS)
QUESTIONS = [
    ("L_vowel", "L", VOWELS),
    ("L_nasal", "L", NASALS),
    ("L_stop", "L", STOPS),
    ("R_vowel", "R", VOWELS),
    ("R_nasal", "R", NASALS),
    ("R_stop", "R", STOPS),
] + [("L_" + p, "L", {p}) for p in PHONES] + [("R_" + p, "R", {p}) for p in PHONES]


def make_states(rng, mean_of, n_states=24, d=2, sd=0.5, contexts=None):
    if contexts is None:
        contexts = rng.sample([(l, r) for l in PHONES for r in PHONES], n_states)
    states, frames = [], {}
    for l, r in contexts:
        mu = mean_of(l, r)
        fr = [[rng.gauss(mu[k], sd) for k in range(d)] for _ in range(rng.randint(30, 60))]
        name = l + "-ae+" + r
        N, mean, var = stats_from_frames(fr)
        states.append(State(name, l, r, N, mean, var))
        frames[name] = fr
    return states, frames


def gauss_loglik(frames):
    """The log likelihood of the frames under their own ML diagonal Gaussian, summed frame by frame."""
    _, mean, var = stats_from_frames(frames)
    return math.fsum(
        -0.5 * (math.log(2 * math.pi * var[k]) + (f[k] - mean[k]) ** 2 / var[k]) for f in frames for k in range(len(f))
    )


def planted(l, r):
    return [3.0 if l in VOWELS else 0.0, 1.5 if r in NASALS else 0.0]


def test_pooled_statistics_match_the_frames():
    rng = random.Random(1)
    states, frames = make_states(rng, planted)
    for _ in range(20):
        sub = rng.sample(states, rng.randint(1, 8))
        N, mean, var = pool(sub)
        N2, mean2, var2 = stats_from_frames([f for s in sub for f in frames[s.name]])
        assert N == N2
        assert mean == pytest.approx(mean2, abs=1e-9)
        assert var == pytest.approx(var2, abs=1e-9)
        # the closed form of L(S) equals the sum of the Gaussian log densities of the frames
        assert log_likelihood(sub) == pytest.approx(gauss_loglik([f for s in sub for f in frames[s.name]]), abs=1e-6)


def test_best_question_against_brute_force_from_frames():
    rng = random.Random(2)
    for trial in range(15):
        states, frames = make_states(random.Random(100 + trial), planted, n_states=rng.randint(4, 16))
        all_frames = [f for s in states for f in frames[s.name]]
        base = gauss_loglik(all_frames)
        brute = []
        for q in QUESTIONS:
            yes = [f for s in states if (s.left if q[1] == "L" else s.right) in q[2] for f in frames[s.name]]
            no = [f for s in states if (s.left if q[1] == "L" else s.right) not in q[2] for f in frames[s.name]]
            if len(yes) >= 40 and len(no) >= 40:
                brute.append((gauss_loglik(yes) + gauss_loglik(no) - base, q[0]))
        got = best_question(states, QUESTIONS, min_occ=40)
        if not brute:
            assert got is None
            continue
        g, name = max(brute, key=lambda t: t[0])
        assert got[0] == pytest.approx(g, abs=1e-6)
        assert got[1][0] == name


def test_gain_is_never_negative():
    rng = random.Random(3)
    states, _ = make_states(rng, lambda l, r: [rng.uniform(-1, 1), rng.uniform(-1, 1)])
    for _ in range(200):
        sub = rng.sample(states, rng.randint(2, 12))
        q = rng.choice(QUESTIONS)
        yes = [s for s in sub if (s.left if q[1] == "L" else s.right) in q[2]]
        no = [s for s in sub if s not in yes]
        if yes and no:
            assert log_likelihood(yes) + log_likelihood(no) - log_likelihood(sub) >= -1e-9


def test_planted_tree():
    states, _ = make_states(random.Random(4), planted, n_states=40)
    root, leaves = build_tree(states, QUESTIONS, threshold=50.0, min_occ=100)
    assert root.question[0] == "L_vowel"
    assert {root.yes.question[0], root.no.question[0]} == {"R_nasal"}
    assert len(leaves) == 4
    # the likelihood of the leaves is the root likelihood plus the gains of the splits
    total = sum(log_likelihood(leaf.states) for leaf in leaves)
    gains = root.gain + root.yes.gain + root.no.gain
    assert total == pytest.approx(log_likelihood(states) + gains, abs=1e-6)
    # each leaf is pure in the two planted features
    for leaf in leaves:
        assert len({(s.left in VOWELS, s.right in NASALS) for s in leaf.states}) == 1


def test_unseen_triphone_goes_to_the_right_leaf():
    states, _ = make_states(random.Random(4), planted, n_states=40)
    root, _ = build_tree(states, QUESTIONS, threshold=50.0, min_occ=100)
    seen = {(s.left, s.right) for s in states}
    unseen = [(l, r) for l in PHONES for r in PHONES if (l, r) not in seen]
    assert unseen
    for l, r in unseen:
        leaf = classify(root, l, r)
        assert all((s.left in VOWELS, s.right in NASALS) == (l in VOWELS, r in NASALS) for s in leaf.states)


def test_min_occupancy_blocks_small_leaves():
    states, _ = make_states(random.Random(5), planted, n_states=10)
    big = best_question(states, QUESTIONS, min_occ=10 ** 6)
    assert big is None
    root, leaves = build_tree(states, QUESTIONS, threshold=0.0, min_occ=100)
    assert all(sum(s.occ for s in leaf.states) >= 100 for leaf in leaves)


def test_greedy_misses_an_xor_context():
    # The mean depends on (left is a vowel) xor (right is a nasal), and every
    # left context occurs with two nasals and two other phones on the right. No
    # single question changes the mean, so a greedy tree with a high threshold
    # stops at the root, while the two-level tree that it cannot see gains a lot.
    def xor(l, r):
        return [2.0 if (l in VOWELS) != (r in NASALS) else 0.0, 0.0]

    contexts = [(l, r) for l in ("aa", "iy", "p", "t") for r in ("m", "n", "k", "uw")]
    states, _ = make_states(random.Random(6), xor, contexts=contexts)
    first = best_question(states, QUESTIONS, min_occ=100)
    yes, no = [s for s in states if s.left in VOWELS], [s for s in states if s.left not in VOWELS]
    two_level = sum(
        log_likelihood([s for s in side if (s.right in NASALS) == flag]) for side in (yes, no) for flag in (True, False)
    ) - log_likelihood(states)
    assert two_level > 4 * first[0]
    root, leaves = build_tree(states, QUESTIONS, threshold=first[0] + 1.0, min_occ=100)
    assert len(leaves) == 1


def test_merge_joins_leaves_from_different_branches():
    rng = random.Random(7)
    means = [[0.0, 0.0], [3.0, 0.0], [0.0, 0.0], [3.0, 0.0]]
    clusters = []
    for c, mu in enumerate(means):
        cl = []
        for k in range(3):
            fr = [[rng.gauss(mu[0], 0.5), rng.gauss(mu[1], 0.5)] for _ in range(50)]
            N, mean, var = stats_from_frames(fr)
            cl.append(State("c%d_%d" % (c, k), "x", "y", N, mean, var))
        clusters.append(cl)
    merged = merge_leaves(clusters, threshold=30.0)
    groups = sorted(sorted({s.name[:2] for s in cl}) for cl in merged)
    assert groups == [["c0", "c2"], ["c1", "c3"]]


def test_tie_maps_every_state():
    states, _ = make_states(random.Random(8), planted, n_states=30)
    root, index = tie(states, QUESTIONS, threshold=50.0, min_occ=100)
    assert set(index) == {s.name for s in states}
    assert len(set(index.values())) == 4

History

Before decision trees, systems clustered triphone models bottom up: Lee 1990 merged similar triphone models into generalized triphones. Young, Odell and Woodland 1994 tied states and not whole models, and built the clusters top down with phonetic decision trees, with one tree for each state of each phone and a set of 202 questions. They stopped the splits by a threshold on the gain and a minimum occupancy, and then merged leaves, which reduced the number of states by 10 to 20 percent. These counts are from the paper. On the Resource Management Feb'89 test set, about 1600 tied states gave a word error rate of 3.87 percent, against 4.10 percent for bottom-up clustering (a measurement). On the Wall Street Journal Nov'93 tests the system had 4.90 percent errors on the 5k task and 12.67 percent on the 20k task (measurements). The method, as implemented in HTK and later in Kaldi, became the standard way to build context-dependent acoustic models (Gales and Young 2008).

References

  1. Steve J. Young, Julian J. Odell and Philip C. Woodland, Tree-based state tying for high accuracy acoustic modelling, Human Language Technology: Proceedings of a Workshop held at Plainsboro, New Jersey, 1994, pages 307 to 312 (ACL Anthology H94-1062), equations (1) to (3) for the likelihood and the split rule, Table 2 for the Resource Management results, and the Wall Street Journal results
  2. 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 section on context-dependent phone models and decision tree clustering
  3. Kai-Fu Lee, Context-dependent phonetic hidden Markov models for speaker-independent continuous speech recognition, IEEE Transactions on Acoustics, Speech, and Signal Processing 38(4), 1990, pages 599 to 609, the generalized triphones, an earlier bottom-up clustering of triphone models

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