Algorithm Search⌘K

Algorithmadvanced

Joint-sequence grapheme-to-phoneme model

Also called graphone model, Bisani-Ney G2P.

Grapheme-to-phoneme conversion with an n-gram model over graphones, pairs of a letter chunk and a phoneme chunk, trained by EM over all joint segmentations and decoded by Viterbi.

Time
Θ(n m H k) worst
Space
Θ(n m H) extra
Where
H = the number of graphone histories; k = the number of graphone shapes, L_g (L_p + 1); m = the number of phonemes of its pronunciation; n = the number of letters of a word
Properties
deterministicnot exactnot in placeoffline
Origin
Maximilian Bisani, Hermann Ney, 2008

The joint-sequence model converts the spelling of a word into its phonemes. It treats a word and its pronunciation as one sequence of graphones: each graphone pairs a short chunk of letters with a short chunk of phonemes, so "six" with the pronunciation S IH K S can be read as s:S, i:IH, x:K S. An n-gram model gives the probability of a graphone sequence. The alignment of letters to phonemes is not in the training data, so the model is trained with expectation-maximization over all the ways to cut a pair into graphones, which is the forward-backward algorithm on a lattice. A new word is converted by a Viterbi search for the best graphone sequence that spells it. Bisani and Ney (2008) gave the full method. It solves grapheme-to-phoneme conversion and was a standard baseline before neural sequence models.

In plain words

English spelling does not map letter by letter to sounds. The letter x often makes two sounds, and some letters make none. The model learns small pieces that pair a few letters with a few sounds, and it learns which pieces tend to follow which.

A dictionary gives words and their sounds, but not which letters go with which sounds. So the training starts with all pieces equally likely. For each word it looks at every way to cut the word and its sounds into pieces, and it gives each way a weight from the current model. It counts the pieces with these weights and makes new probabilities from the counts. This repeats until the numbers stop changing.

To read a new word, it finds the chain of pieces that spells the word and has the highest probability, and outputs their sounds.

The problem

The input for training is a lexicon of pairs (g,φ)(g, \varphi), where g=g1…gng = g_1 \ldots g_n is a string of letters and φ=φ1…φm\varphi = \varphi_1 \ldots \varphi_m is a string of phonemes. A graphone is a pair q=(qg,qφ)q = (q^g, q^\varphi) of a letter string and a phoneme string. In this page and its code, 1≤∣qg∣≤Lg1 \le |q^g| \le L_g and 0≤∣qφ∣≤Lp0 \le |q^\varphi| \le L_p. A joint segmentation of (g,φ)(g, \varphi) is a graphone sequence Q=q1…qKQ = q_1 \ldots q_K with q1g⋯qKg=gq_1^g \cdots q_K^g = g and q1φ⋯qKφ=φq_1^\varphi \cdots q_K^\varphi = \varphi. Let S(g,φ)S(g, \varphi) be the set of these.

The model is an MM-gram over graphones with the history padded by ⟨s⟩\langle s\rangle and an end symbol ⟨/s⟩\langle/s\rangle:

P(Q)=∏k=1K+1p(qk∣qk−M+1…qk−1),qK+1=⟨/s⟩,p(g,φ)=∑Q∈S(g,φ)P(Q).P(Q) = \prod_{k=1}^{K+1} p(q_k \mid q_{k-M+1} \ldots q_{k-1}), \qquad q_{K+1} = \langle/s\rangle, \qquad p(g, \varphi) = \sum_{Q \in S(g, \varphi)} P(Q).

Training asks for the parameters that maximize ∑log⁡p(g,φ)\sum \log p(g, \varphi) over the lexicon. Conversion asks, for a new gg, for

φ^=the phonemes of arg⁡max⁡Q: q1g⋯qKg=gP(Q).\hat\varphi = \text{the phonemes of } \arg\max_{Q:\ q_1^g \cdots q_K^g = g} P(Q).

This is the maximum approximation: the exact rule would maximize p(g,φ)p(g, \varphi), a sum over segmentations, over φ\varphi.

The algorithm

A state of the lattice of a pair is (i,j,h)(i, j, h): ii letters and jj phonemes are covered, and hh is the history, the last M−1M - 1 graphones. Write h⊕qh \oplus q for the history after qq. TRAIN works in the log semiring for sums and DECODE in the Viterbi semiring (max, +). All logs are natural, and log⁡0=−∞\log 0 = -\infty.

  1. TRAIN(lexicon, M, L_g, L_p, iterations)
  2. 1p ← uniform over the graphones that occur in some joint segmentation, and ⟨/s⟩
  3. 2repeat iterations times
  4. 3c(h, q) ← 0 for every history h and graphone or end symbol q
  5. 4for each pair (g, φ) in the lexicon do
  6. 5run FORWARD(g, φ) and the mirror BACKWARD pass; Z ← p(g, φ)
  7. 6for each lattice state (i, j, h) and each graphone q that leaves it do
  8. 7c(h, q) ← c(h, q) + α(i, j, h) · p(q | h) · β(i + |q^g|, j + |q^φ|, h ⊕ q) / Z
  9. 8p(q | h) ← c(h, q) / Σ_q' c(h, q') for each h
  10. 9return p
  11. FORWARD(g, φ) ▷ log semiring
  12. 10log α(0, 0, ⟨s⟩^(M-1)) ← 0
  13. 11for i ← 0 to |g| - 1, j ← 0 to |φ|, and each h with α(i, j, h) > 0 do
  14. 12for each q = (g[i .. i+a), φ[j .. j+b)) with 1 ≤ a ≤ L_g and 0 ≤ b ≤ L_p that fits do
  15. 13h' ← h ⊕ q
  16. 14log α(i+a, j+b, h') ← log_add(log α(i+a, j+b, h'), log α(i, j, h) + log p(q | h))
  17. 15return log Z = log_sum over h of log α(|g|, |φ|, h) + log p(⟨/s⟩ | h)
  18. DECODE(g) ▷ Viterbi semiring
  19. 16δ(0, ⟨s⟩^(M-1)) ← 0
  20. 17for i ← 0 to |g| - 1 and each h with δ(i, h) > -∞ do
  21. 18for each graphone q of the model with q^g = g[i .. i+a), 1 ≤ a ≤ L_g do
  22. 19if δ(i, h) + log p(q | h) > δ(i+a, h ⊕ q) then store it and the back pointer (i, h, q)
  23. 20h* ← the h that maximizes δ(|g|, h) + log p(⟨/s⟩ | h)
  24. 21follow the back pointers from (|g|, h*) and return the phonemes of the graphones

Line L7 is the expected number of times qq follows hh, the posterior of the arc. The end symbol gets the count α(∣g∣,∣φ∣,h) p(⟨/s⟩∣h)/Z\alpha(|g|, |\varphi|, h)\, p(\langle/s\rangle \mid h) / Z. Line L8 is the plain maximum likelihood estimate. Bisani and Ney smooth it instead, with discounting of the fractional counts and a cut of small counts; the code here does not smooth, so a graphone never seen after a history keeps probability 0. In the code, every graphone has at least one letter, so the lattice is acyclic in ii. Bisani and Ney also allow graphones with no letters, which needs a limit on how many come in a row.

Tie rule. DECODE visits the states and the graphones in a fixed sorted order, and line L19 replaces a stored value only by a strictly larger one, so the first maximizer in that order wins.

Example

Take the lexicon six S IH K S, fix F IH K S, box B AA K S, fox F AA K S, sit S IH T and bit B IH T, with M=1M = 1 (a unigram over graphones), Lg=1L_g = 1 and Lp=2L_p = 2. Each letter takes 0, 1 or 2 phonemes. There are 36 graphones that occur in some joint segmentation, so the uniform start gives each of the 37 events (with ⟨/s⟩\langle/s\rangle) the probability 1/371/37.

The pair six, S IH K S has 6 joint segmentations: the ways to write 4 as an ordered sum of 3 parts, each part at most 2. All have 3 graphones, so the uniform model gives each the same weight and the first E step gives each the posterior 1/61/6. The table shows the posteriors under the model after one EM iteration and after 30.

joint segmentation of six after 1 iteration after 30 iterations
s:(none) i:S IH x:K S 0.0798 0.0000
s:S i:IH x:K S 0.2689 1.0000
s:S i:IH K x:S 0.0965 0.0000
s:S IH i:(none) x:K S 0.4053 0.0000
s:S IH i:K x:S 0.0996 0.0000
s:S IH i:K S x:(none) 0.0498 0.0000

After one iteration the wrong cut s:S IH, i:(none) is the most likely, because s:S IH is helped by sit and the empty i is cheap. The other words pull the model to the right cut: x:K S occurs in four words and i:IH in four. The log likelihood of the lexicon rises from −75.6032-75.6032 under the uniform model to −47.5009-47.5009, and the model converges to p(⟨/s⟩)=1/4p(\langle/s\rangle) = 1/4, p(i:IH)=p(x:K S)=1/6p(\text{i:IH}) = p(\text{x:K S}) = 1/6 and 1/121/12 each for s:S, o:AA, t:T, f:F and b:B. There are 24 events in the lexicon, and these are their relative frequencies under the cuts s:S i:IH x:K S and so on.

DECODE on the unseen word sob finds s:S, o:AA, b:B with log score log⁡(1/123⋅1/4)=−8.8410\log(1/12^3 \cdot 1/4) = -8.8410, and outputs S AA B.

Correctness

The proofs file has three parts. First, the joint segmentations of (g,φ)(g, \varphi) are in bijection with the lattice paths from (0,0,⟨s⟩M−1)(0, 0, \langle s\rangle^{M-1}) to an end state, and a path has the weight of its graphone sequence. Each graphone has a letter, so increasing ii is a topological order, and an induction on ii shows that line L14 accumulates the exact sum over paths into each state; line L15 then returns log⁡p(g,φ)\log p(g, \varphi). Second, splitting each path at an arc shows that line L7 adds the exact posterior expected count of each graphone after each history. Third, line L8 maximizes the expected complete-data log likelihood row by row, so this is an EM step and the log likelihood of the lexicon never decreases (Dempster, Laird and Rubin 1977, Theorem 1). It can stop at a local maximum. DECODE is the same induction in the Viterbi semiring, and it returns a graphone sequence of the largest weight.

Proof: The graphone lattice gives the exact joint probability, the exact expected counts and the best graphone sequencefull

Fix the order MM, the chunk limits Lg≥1L_g \ge 1 and Lp≥0L_p \ge 0, and a model p(q∣h)p(q \mid h) over graphones qq and the end symbol ⟨/s⟩\langle/s\rangle. A history hh is the tuple of the last M−1M - 1 symbols, padded at the start with ⟨s⟩\langle s\rangle; write h⊕qh \oplus q for the history after qq (drop the oldest symbol, append qq). For M=1M = 1 every history is the empty tuple. The weight of a graphone sequence Q=q1…qKQ = q_1 \ldots q_K is

P(Q)=∏k=1Kp(qk∣hk−1)⋅p(⟨/s⟩∣hK),h0=⟨s⟩M−1, hk=hk−1⊕qk.P(Q) = \prod_{k=1}^{K} p(q_k \mid h_{k-1}) \cdot p(\langle/s\rangle \mid h_K), \qquad h_0 = \langle s\rangle^{M-1},\ h_k = h_{k-1} \oplus q_k.

A joint segmentation of the pair (g,φ)(g, \varphi) is a sequence QQ whose letter sides concatenate to gg and whose phoneme sides concatenate to φ\varphi, with 1≤∣qkg∣≤Lg1 \le |q_k^g| \le L_g and 0≤∣qkφ∣≤Lp0 \le |q_k^\varphi| \le L_p. Let S(g,φ)S(g, \varphi) be the set of joint segmentations and Z=∑Q∈S(g,φ)P(Q)Z = \sum_{Q \in S(g,\varphi)} P(Q).

The lattice

The states are the triples (i,j,h)(i, j, h) with 0≤i≤∣g∣0 \le i \le |g| and 0≤j≤∣φ∣0 \le j \le |\varphi|. There is an arc from (i,j,h)(i, j, h) to (i+a,j+b,h⊕q)(i + a, j + b, h \oplus q) with weight p(q∣h)p(q \mid h) for each q=(g[i..i+a),φ[j..j+b))q = (g[i..i+a), \varphi[j..j+b)) with 1≤a≤Lg1 \le a \le L_g and 0≤b≤Lp0 \le b \le L_p that fits. Every arc increases ii by at least 1, because every graphone has a letter, so the lattice is acyclic and the order of increasing ii is a topological order.

Lemma 1 (bijection). The map that sends Q∈S(g,φ)Q \in S(g, \varphi) to the path that starts at (0,0,h0)(0, 0, h_0) and follows the arcs of q1,…,qKq_1, \ldots, q_K is a bijection between S(g,φ)S(g, \varphi) and the paths from (0,0,h0)(0, 0, h_0) to a state (∣g∣,∣φ∣,h)(|g|, |\varphi|, h). The product of the arc weights of the path, times p(⟨/s⟩∣h)p(\langle/s\rangle \mid h), is P(Q)P(Q).

Proof. After kk graphones of QQ the path is at (∣q1g⋯qkg∣,∣q1φ⋯qkφ∣,hk)(|q_1^g \cdots q_k^g|, |q_1^\varphi \cdots q_k^\varphi|, h_k), and the arc for qk+1q_{k+1} exists because qk+1q_{k+1} is the next chunk of both strings. The path ends at (∣g∣,∣φ∣,hK)(|g|, |\varphi|, h_K). Conversely, a path reads off a sequence of graphones whose sides are consecutive chunks that start at 0 and end at the full lengths, so it is a joint segmentation. The two maps are inverse because the arc out of a state is fixed by its graphone. The weight claim is the definition of P(Q)P(Q). □\square

Forward and log Z (log semiring)

Let α(i,j,h)\alpha(i, j, h) be the sum, over the paths from (0,0,h0)(0, 0, h_0) to (i,j,h)(i, j, h), of the product of their arc weights. Lines L10 to L14 work in the log semiring (R∪{−∞},log_add,+,−∞,0)(\mathbb{R} \cup \{-\infty\}, \text{log\_add}, +, -\infty, 0), which is isomorphic to the probability semiring by x↦exx \mapsto e^x.

Lemma 2. When the loop of line L11 reaches letter position ii, every state (i,j,h)(i, j, h) holds log⁡α(i,j,h)\log \alpha(i, j, h).

Proof. By induction on ii. For i=0i = 0 the only state with a path is (0,0,h0)(0, 0, h_0), reached by the empty path of weight 1, and line L10 stores log⁡1=0\log 1 = 0. No arc enters a state with i=0i = 0. Let i>0i > 0. Every path into (i,j,h)(i, j, h) ends with an arc from some state (i′,j′,h′)(i', j', h') with i′<ii' < i. By the induction hypothesis that state held its final value when line L11 processed i′i', and line L14 then added (log_add) its value plus the log weight of the arc. Every such arc is processed once, because line L11 visits i′<ii' < i before ii and line L12 lists each fitting graphone once. By distributivity, the sum over paths into (i,j,h)(i, j, h) is the sum over the last arc of α(source)⋅p(q∣h′)\alpha(\text{source}) \cdot p(q \mid h'). Arcs with weight 0 are skipped, which changes no sum. □\square

Theorem 1. Line L15 returns log⁡Z\log Z.

Proof. By Lemma 2 at i=∣g∣i = |g| and Lemma 1, ∑hα(∣g∣,∣φ∣,h) p(⟨/s⟩∣h)=∑Q∈S(g,φ)P(Q)=Z\sum_h \alpha(|g|, |\varphi|, h)\, p(\langle/s\rangle \mid h) = \sum_{Q \in S(g, \varphi)} P(Q) = Z. □\square

Expected counts

Define β(i,j,h)\beta(i, j, h) as the sum over the paths from (i,j,h)(i, j, h) to an end state of the product of the arc weights times p(⟨/s⟩∣hend)p(\langle/s\rangle \mid h_{\text{end}}). The function backward computes log⁡β\log \beta by the mirror of Lemma 2, in the order of decreasing ii.

Theorem 2. For each history hh and graphone qq, line L7 accumulates

c(h,q)=∑(g,φ)∑Q∈S(g,φ)P(Q)Zg,φ nh,q(Q),c(h, q) = \sum_{(g, \varphi)} \sum_{Q \in S(g, \varphi)} \frac{P(Q)}{Z_{g,\varphi}}\, n_{h,q}(Q),

where nh,q(Q)n_{h,q}(Q) is the number of positions kk with hk−1=hh_{k-1} = h and qk=qq_k = q. The count of ⟨/s⟩\langle/s\rangle after hh is the same with nh,⟨/s⟩(Q)=[hK=h]n_{h,\langle/s\rangle}(Q) = [h_K = h].

Proof. By Lemma 1, ∑QP(Q) nh,q(Q)\sum_Q P(Q)\, n_{h,q}(Q) is the sum over the pairs (path, arc of the path with label qq out of a state with history hh) of the path weight. Split each such path at the arc: the weight is the weight of the prefix, times p(q∣h)p(q \mid h), times the weight of the suffix with the end factor. Summing over prefixes and suffixes gives α(i,j,h) p(q∣h) β(i+a,j+b,h⊕q)\alpha(i, j, h)\, p(q \mid h)\, \beta(i + a, j + b, h \oplus q), summed over the arcs with label qq out of a state with history hh. Dividing by ZZ and adding over the lexicon gives line L7. The end symbol is the same argument with the empty suffix. □\square

EM

The M step of line L8 sets p′(q∣h)=c(h,q)/∑q′c(h,q′)p'(q \mid h) = c(h, q) / \sum_{q'} c(h, q'). For a fixed hh this is the unique maximizer of ∑qc(h,q)log⁡p′(q∣h)\sum_q c(h, q) \log p'(q \mid h) over the probability vectors (Gibbs' inequality), so it maximizes the expected complete-data log likelihood ∑h,qc(h,q)log⁡p′(q∣h)\sum_{h,q} c(h, q) \log p'(q \mid h). This is the M step of the expectation-maximization algorithm with the joint segmentation as the hidden variable, so the standard EM argument (Dempster, Laird and Rubin 1977) gives ∑log⁡Zg,φ′≥∑log⁡Zg,φ\sum \log Z'_{g,\varphi} \ge \sum \log Z_{g,\varphi}: the log likelihood of the lexicon never decreases. A graphone with count 0 gets probability 0 and stays at 0 in every later iteration.

Decoding (Viterbi semiring)

decode works on the lattice of states (i,h)(i, h) for the letters alone: an arc from (i,h)(i, h) to (i+a,h⊕q)(i + a, h \oplus q) with weight p(q∣h)p(q \mid h) for each graphone qq of the model with qg=g[i..i+a)q^g = g[i..i+a). As in Lemma 1, the paths from (0,h0)(0, h_0) to a state (∣g∣,h)(|g|, h) are in bijection with the graphone sequences whose letter sides concatenate to gg.

Theorem 3. If some graphone sequence of positive weight spells gg, lines L16 to L21 return one of largest weight P(Q)P(Q), and the log of that weight.

Proof. The argument of Lemma 2 in the Viterbi semiring (R∪{−∞},max⁡,+,−∞,0)(\mathbb{R} \cup \{-\infty\}, \max, +, -\infty, 0) shows that when line L17 reaches ii, each δ(i,h)\delta(i, h) is the largest log weight of a path into (i,h)(i, h), and the stored back pointer names the last arc of one such path: line L19 replaces the stored value only by a strictly larger one, so the stored pointer always belongs to the stored value. Line L20 takes the end state that maximizes δ(∣g∣,h)+log⁡p(⟨/s⟩∣h)\delta(|g|, h) + \log p(\langle/s\rangle \mid h), which is the largest log⁡P(Q)\log P(Q). Following the pointers from it rebuilds a path whose log weight is that value, by induction on the number of arcs, and line L21 reads its graphones and phonemes. □\square

The decoder maximizes over graphone sequences, not over pronunciations: the probability of a pronunciation φ\varphi is the sum over all its joint segmentations with gg, and the φ\varphi of the best single sequence need not be the φ\varphi of the largest sum. This is the maximum approximation of Bisani and Ney.

Complexity

A lattice for a pair has at most (n+1)(m+1)H(n + 1)(m + 1) H states, where HH is the number of histories, and k=Lg(Lp+1)k = L_g (L_p + 1) arcs leave each state. FORWARD, BACKWARD and the count loop each take Θ(nmHk)\Theta(n m H k) time and Θ(nmH)\Theta(n m H) space, so one EM iteration costs this sum over the lexicon. For M=1M = 1, H=1H = 1. For larger MM, HH can grow like the number of graphones to the power M−1M - 1, but only histories seen in the lattice are stored. DECODE takes Θ(nHLgG)\Theta(n H L_g G) time, where GG is the largest number of graphones with the same letter chunk.

The brute force alternative lists the segmentations: with Lg=Lp=1L_g = L_p = 1 a pair has (nm)\binom{n}{m} of them, and with Lg=1L_g = 1, Lp=2L_p = 2 the count is the coefficient of xmx^m in (1+x+x2)n(1 + x + x^2)^n, which grows exponentially.

Properties

  • One model for alignment and conversion. The same graphone n-gram aligns the training pairs and scores new words, so no separate alignment step or hand rules are needed.
  • Generative and joint. It models p(g,φ)p(g, \varphi), not p(φ∣g)p(\varphi \mid g). The same model can convert phonemes to letters by decoding on the phoneme side.
  • Local optimum. EM increases the likelihood but can stop at a local maximum. Bisani and Ney train in stages, from small to large MM, and start each stage from the previous model.
  • Free of underflow. The lattice works with log values, so long words do not round to zero.
  • A weighted transducer. The trained model is a weighted automaton over graphones, which is a finite-state transducer from letters to phonemes; DECODE is a shortest path search through its composition with the word.

Variants and improvements

  • Graphone size. With singular graphones (at most one letter and one phoneme each) and a long history, the model does well; larger graphones are prone to overfit (measurement, reported by Bisani and Ney and by later work that cites them).
  • Smoothing. Bisani and Ney discount the fractional expected counts in a way close to Kneser-Ney smoothing, and drop counts below a threshold in the E step.
  • Sum over segmentations. Instead of the maximum approximation, decode with an n-best list of graphone sequences and add the probabilities of the ones with the same phonemes.
  • Viterbi training. Replace the expected counts by the counts on the best segmentation of each pair, as Viterbi training does for an HMM. Each iteration is cheaper, but it maximizes the weight of the best segmentation, not the likelihood.
  • Neural models. An encoder-decoder model or a transformer maps letters to phonemes with no explicit alignment, and is now the usual choice when the lexicon is large.

When to use it

Use it for a pronunciation lexicon that must cover new words: names, loan words and new terms in a text-to-speech front end or an automatic speech recognition system. It needs no aligned data, has few settings and gives a probability for each output, which helps when a recognizer wants several pronunciations per word. For a large lexicon with plenty of compute, a neural sequence model is usually more accurate.

Pitfalls

  • Graphones with no letters. If a graphone may have an empty letter side, the lattice is no longer ordered by ii and can have cycles. Limit the number of such graphones in a row, or forbid them as this code does.
  • No smoothing. With the plain maximum likelihood M step, a history not seen in training has no outgoing probability and DECODE fails on many new words. Smooth the M-gram before use on real data.
  • Testing on training words. The model fits its training lexicon very well. Report phoneme or word error rates on held-out words.
  • The uniform start. With all graphones equally likely, the first E step favors segmentations with fewer and longer graphones, since each graphone costs one factor. The example shows a wrong cut that wins after one iteration; run EM until the likelihood stops rising.
  • Ties. Two segmentations can have equal weight. Fix a tie rule if outputs are compared.

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.

joint_sequence_g2p.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/joint-sequence-g2p/. The authors are listed in prov/Z0KB29.jsonl.

"""Joint-sequence (graphone) model for grapheme-to-phoneme conversion, after
Bisani and Ney (2008).

A graphone is a pair (letters, phonemes) of a chunk of 1 to lmax letters and a
chunk of 0 to pmax phonemes. A word and its pronunciation are the letter and
phoneme sides of a sequence of graphones; the same pair (g, phi) has many such
joint segmentations. The model is an M-gram model over graphones with the
history padded by M - 1 copies of "<s>" and the end symbol "</s>" predicted:

    p(q_1 .. q_K) = prod_{k=1}^{K+1} p(q_k | q_{k-M+1} .. q_{k-1}),  q_{K+1} = "</s>",
    p(g, phi)     = sum over the joint segmentations of (g, phi) of p(q_1 .. q_K).

train_em fits the model by EM over the joint segmentations (forward-backward
on the lattice of positions (i, j, history), in the log semiring). decode
returns the phonemes of the best graphone sequence whose letter side is the
word (the maximum approximation, Viterbi semiring). Every log is natural.

Restriction of this code: every graphone has at least one letter. Bisani and
Ney also allow graphones with no letters. The M step is the plain maximum
likelihood estimate; the paper smooths the M-gram model, which this code does
not do, so an unseen history or graphone has probability 0.
"""

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

from nlslog import NEG_INF, log_add, log_sum, safe_log

BOS = "<s>"
EOS = "</s>"

Graphone = Tuple[Tuple[str, ...], Tuple[str, ...]]
Model = Dict[tuple, Dict[object, float]]  # history -> graphone or EOS -> log probability


def start_history(order: int) -> tuple:
    return tuple([BOS] * (order - 1))


def next_history(h: tuple, q, order: int) -> tuple:
    """The last order - 1 symbols of h followed by q."""
    if order == 1:
        return ()
    return (h + (q,))[-(order - 1):]


def _arcs(g: Sequence[str], phi: Sequence[str], i: int, j: int, lmax: int, pmax: int):
    """The graphones that start at letter i and phoneme j and fit inside (g, phi)."""
    for a in range(1, lmax + 1):
        if i + a > len(g):
            break
        for b in range(0, pmax + 1):
            if j + b > len(phi):
                break
            yield a, b, (tuple(g[i:i + a]), tuple(phi[j:j + b]))


def inventory(lexicon, lmax: int, pmax: int) -> List[Graphone]:
    """All graphones that occur in some joint segmentation of some pair of the lexicon."""
    seen = set()
    for g, phi in lexicon:
        n, m = len(g), len(phi)
        fwd = {(0, 0)}
        for i in range(n + 1):
            for j in range(m + 1):
                if (i, j) in fwd:
                    for a, b, q in _arcs(g, phi, i, j, lmax, pmax):
                        fwd.add((i + a, j + b))
        bwd = {(n, m)}
        for i in range(n, -1, -1):
            for j in range(m, -1, -1):
                for a, b, q in _arcs(g, phi, i, j, lmax, pmax):
                    if (i + a, j + b) in bwd:
                        bwd.add((i, j))
        for (i, j) in fwd:
            for a, b, q in _arcs(g, phi, i, j, lmax, pmax):
                if (i + a, j + b) in bwd:
                    seen.add(q)
    return sorted(seen)


def uniform_model(lexicon, order: int, lmax: int, pmax: int) -> Model:
    """p(q | h) uniform over the inventory and EOS, for every history that can occur."""
    inv = inventory(lexicon, lmax, pmax)
    events = list(inv) + [EOS]
    lp = -math.log(len(events))
    hists = {start_history(order)}
    for _ in range(order - 1):
        hists |= {next_history(h, q, order) for h in list(hists) for q in inv}
    return {h: {e: lp for e in events} for h in hists}


def _lp(model: Model, h: tuple, q) -> float:
    return model.get(h, {}).get(q, NEG_INF)


def forward(model: Model, g, phi, order: int, lmax: int, pmax: int):
    """Log semiring. alpha[(i, j, h)] is the log of the total probability of the
    graphone prefixes that cover g[:i] and phi[:j] and leave history h.
    Returns (alpha, log Z) with Z = p(g, phi)."""
    n, m = len(g), len(phi)
    cells: Dict[Tuple[int, int], Dict[tuple, float]] = {(0, 0): {start_history(order): 0.0}}  # @line L10
    for i in range(n):  # @line L11
        for j in range(m + 1):
            for h, a0 in cells.get((i, j), {}).items():
                for a, b, q in _arcs(g, phi, i, j, lmax, pmax):  # @line L12
                    w = _lp(model, h, q)
                    if w == NEG_INF:
                        continue
                    h2 = next_history(h, q, order)  # @line L13
                    cell = cells.setdefault((i + a, j + b), {})
                    cell[h2] = log_add(cell.get(h2, NEG_INF), a0 + w)  # @line L14
    alpha = {(i, j, h): v for (i, j), cell in cells.items() for h, v in cell.items()}
    z = log_sum(v + _lp(model, h, EOS) for h, v in cells.get((n, m), {}).items())  # @line L15
    return alpha, z


def backward(model: Model, g, phi, order: int, lmax: int, pmax: int, alpha):
    """Log semiring. beta[(i, j, h)] is the log of the total probability of the
    suffixes from state (i, j, h) to the end, EOS included. States are those of alpha."""
    n, m = len(g), len(phi)
    beta = {}
    for key in sorted(alpha, key=lambda k: (-k[0], -k[1])):
        i, j, h = key
        if i == n and j == m:
            beta[key] = _lp(model, h, EOS)
            continue
        acc = NEG_INF
        for a, b, q in _arcs(g, phi, i, j, lmax, pmax):
            w = _lp(model, h, q)
            nxt = (i + a, j + b, next_history(h, q, order))
            if w != NEG_INF and nxt in beta:
                acc = log_add(acc, w + beta[nxt])
        beta[key] = acc
    return beta


def joint_log_prob(model: Model, g, phi, order: int, lmax: int, pmax: int) -> float:
    """log p(g, phi), the sum over all joint segmentations."""
    return forward(model, tuple(g), tuple(phi), order, lmax, pmax)[1]


def expected_counts(model: Model, lexicon, order: int, lmax: int, pmax: int):
    """The E step. Returns (counts, log likelihood), where counts[h][q] is the
    expected number of times graphone q (or EOS) follows history h."""
    counts: Dict[tuple, Dict[object, float]] = {}  # @line L3
    total = 0.0
    for g, phi in lexicon:  # @line L4
        g, phi = tuple(g), tuple(phi)
        alpha, z = forward(model, g, phi, order, lmax, pmax)  # @line L5
        if z == NEG_INF:
            raise ValueError("the pair %r has probability 0 under the model" % ((g, phi),))
        beta = backward(model, g, phi, order, lmax, pmax, alpha)
        total += z
        n, m = len(g), len(phi)
        for (i, j, h), a0 in alpha.items():  # @line L6
            row = counts.setdefault(h, {})
            if i == n and j == m:
                w = _lp(model, h, EOS)
                if w != NEG_INF:
                    row[EOS] = row.get(EOS, 0.0) + math.exp(a0 + w - z)
                continue
            for a, b, q in _arcs(g, phi, i, j, lmax, pmax):
                w = _lp(model, h, q)
                bt = beta.get((i + a, j + b, next_history(h, q, order)), NEG_INF)
                if w == NEG_INF or bt == NEG_INF:
                    continue
                row[q] = row.get(q, 0.0) + math.exp(a0 + w + bt - z)  # @line L7
    return counts, total


def m_step(counts) -> Model:
    """Maximum likelihood estimate p(q | h) = c(h, q) / sum over q' of c(h, q')."""
    model: Model = {}
    for h, row in counts.items():  # @line L8
        s = sum(row.values())
        if s > 0:
            model[h] = {q: safe_log(c / s) for q, c in row.items() if c > 0}
    return model


def train_em(lexicon, order: int = 1, lmax: int = 2, pmax: int = 2, iterations: int = 10, model: Model = None):
    """Run EM from the uniform model (or from the given model).
    Returns (model, lls), where lls[k] is the log likelihood of the lexicon
    under the model before the (k + 1)-th M step."""
    lexicon = [(tuple(g), tuple(phi)) for g, phi in lexicon]
    if model is None:
        model = uniform_model(lexicon, order, lmax, pmax)  # @line L1
    lls = []
    for _ in range(iterations):  # @line L2
        counts, ll = expected_counts(model, lexicon, order, lmax, pmax)
        lls.append(ll)
        model = m_step(counts)
    return model, lls  # @line L9


def decode(model: Model, g, order: int, lmax: int):
    """The best graphone sequence whose letter side is g, in the Viterbi semiring.

    Returns (phonemes, graphones, log score), where the score includes EOS.
    Raises ValueError if no graphone sequence of the model spells g.
    Tie rule: candidates are tried in a fixed order and a later one replaces the
    stored one only if it is strictly better.
    """
    g = tuple(g)
    n = len(g)
    by_letters: Dict[Tuple[str, ...], set] = {}
    for row in model.values():
        for q in row:
            if q != EOS:
                by_letters.setdefault(q[0], set()).add(q)
    by_letters = {k: sorted(v) for k, v in by_letters.items()}
    cells: List[Dict[tuple, float]] = [dict() for _ in range(n + 1)]
    back: List[Dict[tuple, tuple]] = [dict() for _ in range(n + 1)]
    cells[0][start_history(order)] = 0.0  # @line L16
    for i in range(n):  # @line L17
        for h in sorted(cells[i], key=repr):
            d = cells[i][h]
            for a in range(1, min(lmax, n - i) + 1):
                for q in by_letters.get(g[i:i + a], []):  # @line L18
                    w = _lp(model, h, q)
                    if w == NEG_INF:
                        continue
                    h2 = next_history(h, q, order)
                    if d + w > cells[i + a].get(h2, NEG_INF):  # @line L19
                        cells[i + a][h2] = d + w
                        back[i + a][h2] = (i, h, q)
    best_h, best = None, NEG_INF
    for h in sorted(cells[n], key=repr):  # @line L20
        s = cells[n][h] + _lp(model, h, EOS)
        if s > best:
            best_h, best = h, s
    if best_h is None:
        raise ValueError("no graphone sequence of the model spells %r" % (g,))
    seq = []
    i, h = n, best_h
    while i > 0:
        i, h, q = back[i][h]
        seq.append(q)
    seq.reverse()
    return [p for q in seq for p in q[1]], seq, best  # @line L21
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_joint_sequence_g2p.py 212 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/joint-sequence-g2p/. The authors are listed in prov/Z0KB29.jsonl.

import math
import random
from fractions import Fraction
from math import comb

import pytest

from joint_sequence_g2p import (
    EOS,
    decode,
    expected_counts,
    forward,
    inventory,
    joint_log_prob,
    next_history,
    start_history,
    train_em,
    uniform_model,
)
from nlslog import NEG_INF, log_sum


def segmentations(g, phi, lmax, pmax):
    """Every joint segmentation of (g, phi), by plain recursion."""
    if not g:
        return [[]] if not phi else []
    out = []
    for a in range(1, min(lmax, len(g)) + 1):
        for b in range(0, min(pmax, len(phi)) + 1):
            q = (tuple(g[:a]), tuple(phi[:b]))
            for rest in segmentations(g[a:], phi[b:], lmax, pmax):
                out.append([q] + rest)
    return out


def seq_score(model, seq, order):
    h = start_history(order)
    s = 0.0
    for q in list(seq) + [EOS]:
        w = model.get(h, {}).get(q, NEG_INF)
        if w == NEG_INF:
            return NEG_INF
        s += w
        h = next_history(h, q, order)
    return s


def random_model(lexicon, order, lmax, pmax, rng):
    m = uniform_model(lexicon, order, lmax, pmax)
    out = {}
    for h, row in m.items():
        ws = {q: rng.uniform(0.05, 1.0) for q in row}
        s = sum(ws.values())
        out[h] = {q: math.log(w / s) for q, w in ws.items()}
    return out


def random_word(rng, n, alphabet):
    return tuple(rng.choice(alphabet) for _ in range(n))


def test_segmentation_count_one_letter_per_graphone():
    # lmax = 1, pmax = 1: each letter takes 0 or 1 phoneme, so C(n, m) segmentations.
    for n in range(0, 7):
        for m in range(0, n + 2):
            got = len(segmentations("x" * n, "y" * m, 1, 1))
            assert got == (comb(n, m) if m <= n else 0)


def test_six_has_six_segmentations():
    segs = segmentations("six", ("S", "IH", "K", "S"), 1, 2)
    assert len(segs) == 6


@pytest.mark.parametrize("order", [1, 2, 3])
def test_forward_equals_sum_over_segmentations(order):
    rng = random.Random(11 + order)
    for _ in range(6):
        lex = [
            (random_word(rng, rng.randint(1, 4), "ab"), random_word(rng, rng.randint(0, 4), "xy"))
            for _ in range(3)
        ]
        lmax, pmax = rng.randint(1, 2), rng.randint(1, 2)
        lex = [p for p in lex if segmentations(p[0], p[1], lmax, pmax)]
        if not lex:
            continue
        model = random_model(lex, order, lmax, pmax, rng)
        for g, phi in lex:
            brute = log_sum(seq_score(model, s, order) for s in segmentations(g, phi, lmax, pmax))
            assert joint_log_prob(model, g, phi, order, lmax, pmax) == pytest.approx(brute, abs=1e-9)


@pytest.mark.parametrize("order", [1, 2])
def test_expected_counts_equal_brute_force(order):
    rng = random.Random(23 + order)
    for _ in range(5):
        lex = [
            (random_word(rng, rng.randint(1, 4), "ab"), random_word(rng, rng.randint(1, 4), "xy"))
            for _ in range(3)
        ]
        lmax, pmax = 2, 2
        lex = [p for p in lex if segmentations(p[0], p[1], lmax, pmax)]
        model = random_model(lex, order, lmax, pmax, rng)
        brute = {}
        for g, phi in lex:
            segs = segmentations(g, phi, lmax, pmax)
            scores = [seq_score(model, s, order) for s in segs]
            z = log_sum(scores)
            for s, sc in zip(segs, scores):
                post = math.exp(sc - z)
                h = start_history(order)
                for q in s + [EOS]:
                    brute[(h, q)] = brute.get((h, q), 0.0) + post
                    h = next_history(h, q, order)
        counts, _ = expected_counts(model, lex, order, lmax, pmax)
        got = {(h, q): c for h, row in counts.items() for q, c in row.items() if c > 0}
        assert set(got) == set(brute)
        for k in brute:
            assert got[k] == pytest.approx(brute[k], abs=1e-9)


def test_uniform_unigram_exact():
    # Under the uniform unigram model every segmentation of length K has
    # probability V^-(K + 1); check log Z against an exact Fraction sum.
    lex = [("six", ("S", "IH", "K", "S"))]
    model = uniform_model(lex, 1, 1, 2)
    v = len(inventory(lex, 1, 2)) + 1
    exact = sum(Fraction(1, v ** (len(s) + 1)) for s in segmentations(*lex[0], 1, 2))
    got = joint_log_prob(model, *lex[0], 1, 1, 2)
    assert got == pytest.approx(math.log(exact.numerator) - math.log(exact.denominator), abs=1e-12)


@pytest.mark.parametrize("order", [1, 2])
def test_em_likelihood_never_decreases(order):
    rng = random.Random(5 + order)
    lex = [
        (random_word(rng, rng.randint(2, 5), "abc"), random_word(rng, rng.randint(2, 5), "xyz"))
        for _ in range(6)
    ]
    lex = [p for p in lex if segmentations(p[0], p[1], 2, 2)]
    _, lls = train_em(lex, order=order, lmax=2, pmax=2, iterations=8)
    for a, b in zip(lls, lls[1:]):
        assert b >= a - 1e-9


@pytest.mark.parametrize("order", [1, 2])
def test_decode_equals_brute_force(order):
    rng = random.Random(41 + order)
    lex = [
        (random_word(rng, rng.randint(1, 3), "ab"), random_word(rng, rng.randint(1, 3), "xy"))
        for _ in range(4)
    ]
    lmax, pmax = 2, 2
    model = random_model(lex, order, lmax, pmax, rng)
    graphones = sorted({q for row in model.values() for q in row if q != EOS})

    def spell(g):
        if not g:
            return [[]]
        out = []
        for q in graphones:
            a = len(q[0])
            if tuple(g[:a]) == q[0]:
                out += [[q] + rest for rest in spell(g[a:])]
        return out

    for _ in range(6):
        g = random_word(rng, rng.randint(1, 4), "ab")
        cands = [(seq_score(model, s, order), s) for s in spell(g)]
        best = max(c[0] for c in cands)
        phonemes, seq, score = decode(model, g, order, lmax)
        assert score == pytest.approx(best, abs=1e-9)
        assert seq_score(model, seq, order) == pytest.approx(best, abs=1e-9)
        assert "".join("".join(q[0]) for q in seq) == "".join(g)
        assert phonemes == [p for q in seq for p in q[1]]


def test_no_spelling_raises():
    lex = [("ab", ("x",))]
    model = uniform_model(lex, 1, 1, 1)
    with pytest.raises(ValueError):
        decode(model, "c", 1, 1)


def test_long_pair_does_not_underflow():
    # 200 letters, 100 phonemes, one letter per graphone and at most one phoneme.
    # Both graphones have probability 1/100 and EOS has 1/2, so
    # Z = C(200, 100) * 100^-200 / 2, below the smallest positive float.
    n, m = 200, 100
    g, phi = ("a",) * n, ("x",) * m
    model = {(): {(("a",), ()): math.log(0.01), (("a",), ("x",)): math.log(0.01), EOS: math.log(0.5)}}
    want = math.lgamma(n + 1) - math.lgamma(m + 1) - math.lgamma(n - m + 1) + n * math.log(0.01) + math.log(0.5)
    assert want < math.log(5e-324)
    _, z = forward(model, g, phi, 1, 1, 1)
    assert z == pytest.approx(want, rel=1e-12)


def test_em_learns_a_consistent_mapping():
    lex = [
        ("six", ("S", "IH", "K", "S")),
        ("fix", ("F", "IH", "K", "S")),
        ("box", ("B", "AA", "K", "S")),
        ("fox", ("F", "AA", "K", "S")),
        ("sit", ("S", "IH", "T")),
        ("bit", ("B", "IH", "T")),
    ]
    model, lls = train_em(lex, order=1, lmax=1, pmax=2, iterations=30)
    assert decode(model, "sob", 1, 1)[0] == ["S", "AA", "B"]
    assert decode(model, "fit", 1, 1)[0] == ["F", "IH", "T"]

History

Rule systems for letter to sound conversion came first, followed by data-driven methods that needed a fixed one-to-one alignment of letters and phonemes. Joint n-gram models over letter and phoneme units, with the alignment learned by EM, appeared around 2000, and Chen (2003) compared joint and conditional models of this kind. Maximilian Bisani and Hermann Ney, at RWTH Aachen, gave the full joint-sequence framework in 2008, with the name graphone, the EM training with smoothing, and a study of graphone size and model order on several pronunciation lexica. Bisani released the method as the Sequitur G2P tool, which became a common baseline. Neural sequence models have since replaced it in many systems.

References

  1. Maximilian Bisani and Hermann Ney, Joint-sequence models for grapheme-to-phoneme conversion, Speech Communication 50(5), 2008, pages 434 to 451, the graphone definition, the EM training over joint segmentations, the smoothed M-gram model, the maximum approximation in decoding, and the experiments on graphone size and model order
  2. Chen 2003, the joint n-gram model over aligned letter and phoneme units
  3. Arthur P. Dempster, Nan M. Laird and Donald B. Rubin, Maximum likelihood from incomplete data via the EM algorithm, Journal of the Royal Statistical Society Series B 39(1), 1977, pages 1 to 38, Theorem 1 (the likelihood does not decrease)

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