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
- Model
- Word RAM
- Properties
- deterministicnot exactnot in placeoffline
- Evidence
- Proof sketchCode in 1 languages
- 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 , where is a string of letters and is a string of phonemes. A graphone is a pair of a letter string and a phoneme string. In this page and its code, and . A joint segmentation of is a graphone sequence with and . Let be the set of these.
The model is an -gram over graphones with the history padded by and an end symbol :
Training asks for the parameters that maximize over the lexicon. Conversion asks, for a new , for
This is the maximum approximation: the exact rule would maximize , a sum over segmentations, over .
The algorithm
A state of the lattice of a pair is : letters and phonemes are covered, and is the history, the last graphones. Write for the history after . TRAIN works in the log semiring for sums and DECODE in the Viterbi semiring (max, +). All logs are natural, and .
TRAIN(lexicon, M, L_g, L_p, iterations)- 1
p ← uniform over the graphones that occur in some joint segmentation, and ⟨/s⟩ - 2
repeat iterations times - 3
c(h, q) ← 0 for every history h and graphone or end symbol q - 4
for each pair (g, φ) in the lexicon do - 5
run FORWARD(g, φ) and the mirror BACKWARD pass; Z ← p(g, φ) - 6
for each lattice state (i, j, h) and each graphone q that leaves it do - 7
c(h, q) ← c(h, q) + α(i, j, h) · p(q | h) · β(i + |q^g|, j + |q^φ|, h ⊕ q) / Z - 8
p(q | h) ← c(h, q) / Σ_q' c(h, q') for each h - 9
return p FORWARD(g, φ) ▷ log semiring- 10
log α(0, 0, ⟨s⟩^(M-1)) ← 0 - 11
for i ← 0 to |g| - 1, j ← 0 to |φ|, and each h with α(i, j, h) > 0 do - 12
for each q = (g[i .. i+a), φ[j .. j+b)) with 1 ≤ a ≤ L_g and 0 ≤ b ≤ L_p that fits do - 13
h' ← h ⊕ q - 14
log α(i+a, j+b, h') ← log_add(log α(i+a, j+b, h'), log α(i, j, h) + log p(q | h)) - 15
return log Z = log_sum over h of log α(|g|, |φ|, h) + log p(⟨/s⟩ | h) DECODE(g) ▷ Viterbi semiring- 16
δ(0, ⟨s⟩^(M-1)) ← 0 - 17
for i ← 0 to |g| - 1 and each h with δ(i, h) > -∞ do - 18
for each graphone q of the model with q^g = g[i .. i+a), 1 ≤ a ≤ L_g do - 19
if δ(i, h) + log p(q | h) > δ(i+a, h ⊕ q) then store it and the back pointer (i, h, q) - 20
h* ← the h that maximizes δ(|g|, h) + log p(⟨/s⟩ | h) - 21
follow the back pointers from (|g|, h*) and return the phonemes of the graphones
Line L7 is the expected number of times follows , the posterior of the arc. The end symbol gets the count . 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 . 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 (a unigram over graphones), and . 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 ) the probability .
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 . 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 under the uniform model to , and the model converges to , and 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 , and outputs S AA B.
Correctness
The proofs file has three parts. First, the joint segmentations of are in bijection with the lattice paths from to an end state, and a path has the weight of its graphone sequence. Each graphone has a letter, so increasing is a topological order, and an induction on shows that line L14 accumulates the exact sum over paths into each state; line L15 then returns . 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 , the chunk limits and , and a model over graphones and the end symbol . A history is the tuple of the last symbols, padded at the start with ; write for the history after (drop the oldest symbol, append ). For every history is the empty tuple. The weight of a graphone sequence is
A joint segmentation of the pair is a sequence whose letter sides concatenate to and whose phoneme sides concatenate to , with and . Let be the set of joint segmentations and .
The lattice
The states are the triples with and . There is an arc from to with weight for each with and that fits. Every arc increases by at least 1, because every graphone has a letter, so the lattice is acyclic and the order of increasing is a topological order.
Lemma 1 (bijection). The map that sends to the path that starts at and follows the arcs of is a bijection between and the paths from to a state . The product of the arc weights of the path, times , is .
Proof. After graphones of the path is at , and the arc for exists because is the next chunk of both strings. The path ends at . 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 .
Forward and log Z (log semiring)
Let be the sum, over the paths from to , of the product of their arc weights. Lines L10 to L14 work in the log semiring , which is isomorphic to the probability semiring by .
Lemma 2. When the loop of line L11 reaches letter position , every state holds .
Proof. By induction on . For the only state with a path is , reached by the empty path of weight 1, and line L10 stores . No arc enters a state with . Let . Every path into ends with an arc from some state with . By the induction hypothesis that state held its final value when line L11 processed , 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 before and line L12 lists each fitting graphone once. By distributivity, the sum over paths into is the sum over the last arc of . Arcs with weight 0 are skipped, which changes no sum.
Theorem 1. Line L15 returns .
Proof. By Lemma 2 at and Lemma 1, .
Expected counts
Define as the sum over the paths from to an end state of the product of the arc weights times . The function backward computes by the mirror of Lemma 2, in the order of decreasing .
Theorem 2. For each history and graphone , line L7 accumulates
where is the number of positions with and . The count of after is the same with .
Proof. By Lemma 1, is the sum over the pairs (path, arc of the path with label out of a state with history ) of the path weight. Split each such path at the arc: the weight is the weight of the prefix, times , times the weight of the suffix with the end factor. Summing over prefixes and suffixes gives , summed over the arcs with label out of a state with history . Dividing by and adding over the lexicon gives line L7. The end symbol is the same argument with the empty suffix.
EM
The M step of line L8 sets . For a fixed this is the unique maximizer of over the probability vectors (Gibbs' inequality), so it maximizes the expected complete-data log likelihood . 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 : 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 for the letters alone: an arc from to with weight for each graphone of the model with . As in Lemma 1, the paths from to a state are in bijection with the graphone sequences whose letter sides concatenate to .
Theorem 3. If some graphone sequence of positive weight spells , lines L16 to L21 return one of largest weight , and the log of that weight.
Proof. The argument of Lemma 2 in the Viterbi semiring shows that when line L17 reaches , each is the largest log weight of a path into , 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 , which is the largest . 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.
The decoder maximizes over graphone sequences, not over pronunciations: the probability of a pronunciation is the sum over all its joint segmentations with , and the of the best single sequence need not be the of the largest sum. This is the maximum approximation of Bisani and Ney.
Complexity
A lattice for a pair has at most states, where is the number of histories, and arcs leave each state. FORWARD, BACKWARD and the count loop each take time and space, so one EM iteration costs this sum over the lexicon. For , . For larger , can grow like the number of graphones to the power , but only histories seen in the lattice are stored. DECODE takes time, where is the largest number of graphones with the same letter chunk.
The brute force alternative lists the segmentations: with a pair has of them, and with , the count is the coefficient of in , 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 , not . 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 , 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 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.
# 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
- 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
- Chen 2003, the joint n-gram model over aligned letter and phoneme units
- 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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag Z0KB29 Edit this page History Report an error Markdown