Algorithmadvanced
Stack decoding
Also called A* stack decoder.
Best-first search over partial word sequences ordered by score plus an estimate of the rest, extending the top of a priority queue.
- Time
- O(V^2 n^2 log(V n) + V n^2 L) worst
- Space
- O(V^2 n^2) extra
- Where
- L = the largest number of phones in a word; V = the vocabulary size; n = the number of frames
- Model
- Word RAM
- Properties
- deterministicexactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Frederick Jelinek, Lalit Bahl, Robert Mercer, Douglas B. Paul, 1969
A stack decoder recognizes speech by a best-first search over partial sentences. Each entry of its "stack", which is a priority queue, is a word sequence that explains the first frames, with its score. The decoder pops the entry whose score plus an estimate of the score of the remaining frames is largest, extends it by every possible next word, and pushes the results. It stops when it pops a complete sentence. If the estimate is an upper bound on the true rest, as in A* search, the first complete sentence popped is the best one. Unlike time-synchronous beam search, the search is not ordered by time: an entry that covers few frames can be extended before one that covers many.
In plain words
Keep a list of half-finished guesses at the sentence. Each guess says which words explain the speech up to some point, and how well. To compare a short guess with a long one, add to each a hopeful estimate of how well the rest of the speech could go.
Always take the guess that looks best with its estimate, and try every next word on it. When the best-looking guess is a whole sentence, stop. If the estimate is never too low, nothing you skipped could have beaten it.
The problem
The input is frames of acoustic scores , a lexicon, and a bigram language model. As on the page for time-synchronous beam search, each phone is one HMM state with a self loop of log probability and a forward move of log probability , also used for the word exit. The task is the word sequence and segmentation that maximize
with the start and the end in . and are tuned heuristics.
A partial hypothesis covers the frames , and its score is the best score of these words in these frames. The estimate of the rest must satisfy, for A*, the score of every complete sentence that extends the hypothesis. The code uses
which is such a bound when the transitions and language model terms are log probabilities, so at most 0.
The algorithm
STACK-DECODE(lexicon, lm, e, n, h)- 1
push (words = (), t = 0, g = 0) with priority h(0) - 2
while the stack is not empty do - 3
pop the entry with the largest priority - 4
if it is complete then return it - 5
if (last word, t) is closed then skip it; otherwise close it - 6
for each word w and each end t' > t: g' ← g + seg(w, t, t') + λ log p(w | last) + log ip - 7
if t' = n then push it as complete with priority g' + λ log p(⟨/s⟩ | w) - 8
else push (words + w, t', g') with priority g' + h(t') - 9
if the stack holds more than max_stack entries then drop the worst - 10
return failure
is the best score of in the frames , from a Viterbi pass through the phones of . One pass from gives it for every , and the code keeps it in a table per . The closed set of line L5 is a recombination: with a bigram, two hypotheses with the same last word and the same have the same future, so only the first one popped needs to be extended.
Example
The lexicon has , and , all language model scores are 0, , , and . There are two frames: and , and every other emission is . Then , and .
| pop | entry | pushed (priority) |
|---|---|---|
| 1 | at , priority | at (), complete (), complete (), at (), complete () |
| 2 | at , priority | complete (), complete () |
| 3 | complete, | stop |
The prefix looks best after the first expansion, because its first frame is perfect and the estimate of its second frame is optimistic. Its extensions are poor, so the complete , with , rises to the top and is returned. It is the best sentence.
With a stack of size 1, line L9 keeps only after the first pop and drops . The search then returns with . A limited stack, like a narrow beam, can lose the best path.
Correctness
The proof is in proofs/correctness.md. The estimate is admissible: each frame can add at most its best emission, transitions and language model terms add at most 0, and at most more words fit. It is also consistent: extending by one word never raises . So the priorities of the entries that are pushed never exceed the priority of the entry that was popped, and a complete entry has its true score as priority. When a complete entry is popped, every prefix of the best sentence on the stack has a priority at least as large as the best score, so the popped score is the best one.
The tests check this against exhaustive search over all sequences of at most 5 words and all their segmentations. They also check two failures: a stack of size 1 on the example, and an estimate far below the true rest, , which makes every complete sentence look better than any partial one and returns a one-word sentence that is about 3.9 worse than the best.
Proof: With an admissible, consistent heuristic, the stack decoder returns the best word sequencefull
We use the notation of the page. There are frames. A full path is a word sequence with and a segmentation of the frames into the phones of the words, at least one frame per phone. Its score is
with , where is the emission and transition score of word in its frames, its exit move included. A partial hypothesis covers the frames , and its score is the sum of the first terms. Let be the best score of a full path. We assume , , and log probabilities , and that there is no stack limit.
Lemma 1 (the best segment). For a word and frames , the value computed by the word Viterbi pass is the best score of occupying exactly the frames .
Proof. It is the Viterbi algorithm on the left-to-right chain of the phones of , started in the first phone at frame , read in the last phone at frame , plus the exit .
So the best full path is found by choosing, for each word, its best segmentation inside its frames: the search over words and end frames, with Lemma 1 for the inside, covers every full path at its best segmentation.
Lemma 2 (admissible and consistent). Let , and . Then
- for every extension of a partial hypothesis at by a word that covers frames , its added score satisfies ;
- the final term is ;
- so every partial hypothesis at has the score of every full path that extends it.
Proof. The added score is . The segment adds one emission per frame, each at most the maximum emission of its frame, and transitions that are . The language model term is , and since . Adding up gives claim 1. Claim 2 holds because log probabilities are . Claim 3 follows by adding claim 1 along the extensions up to and then claim 2.
Lemma 3 (priorities do not grow). If an entry with priority is popped, every entry that its expansion pushes has priority at most . A complete entry has priority equal to its score.
Proof. A partial child has priority by Lemma 2.1. A complete child has priority by Lemma 2.1 and 2.2.
Lemma 4 (closing is safe). The future of a partial hypothesis, the set of score sums its extensions can add, depends only on its last word and . When the first entry with key (last word , ) is popped, its is the best score of any partial hypothesis with that key.
Proof. The extensions depend on (which frames remain) and on (the next language model term), and on nothing else, so the first claim holds. For the second, suppose a hypothesis with the same key has a larger score . Some prefix of is on the stack (or is itself): the root was on the stack, and the expansion of each popped prefix pushes the next one, unless its key was already closed, a case that the same argument handles by induction on the pop order. By Lemma 2.1 along the extensions from to , the priority of is at least , which is larger than the priority of the popped entry. That contradicts the choice of the popped entry as the largest.
Theorem (optimality). With as in Lemma 2 and no stack limit, the first complete entry that is popped has the score .
Proof. Let be a best full path. Before the pop of a complete entry , some prefix of , or itself as a complete entry, is on the stack, or a prefix with the same key and a score at least as good (Lemma 4), which extends to a full path of score at least . By Lemma 2.3 its priority is at least . The popped entry has the largest priority, so the score of , which is its priority, is at least . It is the score of a full path, so it is at most .
Termination. Each key (word, ) is expanded at most once, there are at most keys, and each expansion pushes at most entries, so the loop ends.
Remark (when it fails). The proof uses two assumptions, and the tests show what happens without them.
- Stack limit. Dropping entries can drop every prefix of . In the example of the page, a stack of size 1 keeps the prefix , whose priority is the largest after the first expansion, and drops the complete ; every extension of scores , worse than .
- A heuristic below the true rest. Lemma 2.3 fails, and a complete entry can be popped while a prefix of a better path waits with a lower priority. With , the test returns a one-word sentence about 3.9 worse than the best two-word sentence.
Complexity
Let be the number of frames, the vocabulary size and the largest number of phones in a word. With the closed set there are at most expansions, each pushes at most entries, and each push or pop costs on a heap of at most entries. The segment scores take per , for pairs. This gives the worst case time and space, with back pointers in the entries. The code copies the word sequence into each entry for clarity, which adds a factor of to the space.
In practice the search pops far fewer entries, and how many depends on how tight is. A loose makes the search close to breadth-first; a tight one goes almost straight to the answer. Without recombination, the stack decoder searches a tree of word sequences, which is exponential in the number of words, as Paul 1990 points out.
Properties
- Exact with an admissible estimate and no stack limit. It then returns the best sentence. With a limit, or an estimate that can be too low, it is not exact.
- Not time-synchronous. Entries cover different numbers of frames. This makes long-span language models easy, since each entry holds its full word history, but makes it hard to compare entries without a good estimate.
- Not online. The estimate uses the frames after , so the decoder needs the whole utterance, or a bound on its future frames.
- Whole words at a time. Each step adds a whole word with its best segmentation, so the acoustic match of a word runs once per start frame.
Variants and improvements
- Fast match. Real stack decoders do not try every word. A cheap acoustic and language model match gives a short list of candidates for each entry, as in Paul 1990.
- Normalizing by time. Instead of an estimate of the rest, compare entries by score minus the best score up to their end frame, or by score per frame. These are not admissible, but they work in practice.
- A stack per end frame. Keep one stack for each and extend the best entries of each in order of . This becomes a time-ordered search, close to beam stack search.
- N-best output. Do not stop at the first complete entry, and do not close keys. The next complete entries popped are then the next best sentences, in order, when the estimate is admissible and consistent. The closed set of line L5 would drop the second-best history of each key.
- Machine translation. The same idea, with one stack per number of source words covered, is phrase-based stack decoding.
When to use it
Use it when the language model has a long history that a time-synchronous search would have to copy into many tree copies, or when you want the exact best sentence for a small task with an admissible estimate. Use it also to produce N-best lists. For large vocabularies with real-time limits, time-synchronous beam search or a WFST decoder is the usual choice, because its cost per frame is easy to control.
Pitfalls
- A loose estimate. If is a poor bound, the decoder extends many short entries before any long one, and the stack grows fast.
- An estimate that is too low. Short entries then look worse than long ones, and the decoder returns the first complete sentence it reaches, as in the test.
- Stack limits. A size limit is needed in practice, and it makes the search inexact, as in the example.
- Scores of different lengths. Without an estimate of the rest, a short entry has a better log score than a long one only because it covers fewer frames. Comparing raw scores is wrong.
- Positive scores. The bound assumes that transitions and language model terms are at most 0. A positive insertion bonus or scaled scores must enter , as does in the code.
Implementations
The Python code runs A* over (words, end frame) with a heap, a closed set on (last word, end frame), a table of word segment scores per (word, start frame), an optional stack limit, and an optional custom estimate. The tests compare it with exhaustive search over all sequences of at most 5 words and their segmentations on random tasks, check the word segment scores and the bound, check that a stack of size 1 returns on the example, and check that an estimate below the true rest returns a worse one-word sentence.
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
# 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
stack_decoding.py 134 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/stack-decoding/. The authors are listed in prov/A0NEW4.jsonl.
"""Stack decoding: best-first (A*) search over partial word sequences.
The model is the one of the time-synchronous beam search page: a lexicon
word -> tuple of phones, one emitting state per phone with a self loop (log
probability loop) and a forward move (log probability fwd, also used for the
word exit), emission scores emit[t][phone], and a bigram lm[(v, w)] in log
probability. Scores are log probabilities, higher is better. The score of a
word sequence with a segmentation is
sum of emissions + transitions + sum over words of (lm_weight * lm + ip)
+ lm_weight * lm(last word, </s>).
A partial hypothesis is (words, t): the words cover frames 0..t-1 exactly. Its
score g is the best score of that prefix. The search pops the hypothesis with
the largest g + h(t), where h(t) is an upper bound on the score of frames
t..T-1:
h(t) = sum over u >= t of max_phone emit[u][phone] + (T - t) * max(0, ip).
This bound is valid (admissible) when loop <= 0, fwd <= 0, lm <= 0 and
lm_weight >= 0, since then every transition and language model term is at
most 0 and at most T - t more words fit. It is also consistent: extending by
one word never raises g + h. So the first complete hypothesis that is popped
is the best one, and a hypothesis (last word, t) can be closed after its first
pop, because its future depends only on the last word and t.
The search is not limited to a fixed number of words. A stack limit max_stack
drops the worst entries and makes the search inexact; so does a heuristic that
is not an upper bound.
"""
import heapq
import itertools
import math
from typing import Callable, Dict, List, Optional, Sequence, Tuple
from nlslog import NEG_INF
BOS = "<s>"
EOS = "</s>"
def word_scores(phones: Sequence[str], emit: Sequence[Dict[str, float]], t: int, loop: float, fwd: float) -> Dict[int, float]:
"""Return {t1: best log score of the word occupying frames t..t1-1, exit included}."""
T = len(emit)
k = len(phones)
alpha = [NEG_INF] * k
alpha[0] = emit[t][phones[0]]
out: Dict[int, float] = {}
for u in range(t, T):
if u > t:
new = [NEG_INF] * k
for j in range(k):
best = alpha[j] + loop
if j > 0:
best = max(best, alpha[j - 1] + fwd)
new[j] = best + emit[u][phones[j]]
alpha = new
if alpha[k - 1] > NEG_INF:
out[u + 1] = alpha[k - 1] + fwd
return out
def default_heuristic(emit: Sequence[Dict[str, float]], ip: float) -> List[float]:
"""Return h[t] for t = 0..T: the admissible bound of the module docstring."""
T = len(emit)
h = [0.0] * (T + 1)
for t in range(T - 1, -1, -1):
h[t] = h[t + 1] + max(emit[t].values()) + max(0.0, ip)
return h
def decode(
lexicon: Dict[str, Sequence[str]],
lm: Dict[Tuple[str, str], float],
emit: Sequence[Dict[str, float]],
lm_weight: float = 1.0,
ip: float = 0.0,
loop: float = math.log(0.5),
fwd: float = math.log(0.5),
heuristic: Optional[Callable[[int], float]] = None,
max_stack: Optional[int] = None,
):
"""Return (words, ends, score, pops): the best hypothesis found and the number of pops.
ends[i] is the last frame of words[i]. Return ([], [], -inf, pops) if no
complete hypothesis is found.
"""
T = len(emit)
if heuristic is None:
table = default_heuristic(emit, ip)
heuristic = table.__getitem__
memo: Dict[Tuple[str, int], Dict[int, float]] = {}
def seg(w: str, t: int) -> Dict[int, float]:
if (w, t) not in memo:
memo[(w, t)] = word_scores(lexicon[w], emit, t, loop, fwd)
return memo[(w, t)]
counter = itertools.count()
# Entries: (-priority, order, complete, g, words, ends)
stack: List = [(-heuristic(0), next(counter), False, 0.0, (), ())] # @line L1
closed = set()
pops = 0
while stack: # @line L2
_, _, complete, g, words, ends = heapq.heappop(stack) # @line L3
pops += 1
if complete: # @line L4
return list(words), list(ends), g, pops
t = ends[-1] + 1 if ends else 0
last = words[-1] if words else BOS
if (last, t) in closed: # @line L5
continue
closed.add((last, t))
for w in sorted(lexicon): # @line L6
lm_w = lm.get((last, w), NEG_INF)
if lm_w == NEG_INF:
continue
for t1, s in seg(w, t).items():
g1 = g + s + lm_weight * lm_w + ip
if t1 == T: # @line L7
end = lm.get((w, EOS), NEG_INF)
if end > NEG_INF:
total = g1 + lm_weight * end
heapq.heappush(stack, (-total, next(counter), True, total, words + (w,), ends + (t1 - 1,)))
elif (w, t1) not in closed: # @line L8
heapq.heappush(stack, (-(g1 + heuristic(t1)), next(counter), False, g1, words + (w,), ends + (t1 - 1,)))
if max_stack is not None and len(stack) > max_stack: # @line L9
stack = heapq.nsmallest(max_stack, stack)
heapq.heapify(stack)
return [], [], NEG_INF, pops # @line L10
test_stack_decoding.py 138 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/stack-decoding/. The authors are listed in prov/A0NEW4.jsonl.
import itertools
import math
import random
from nlslog import NEG_INF
from stack_decoding import BOS, EOS, decode, default_heuristic, word_scores
PHONES = ["p", "q", "r"]
LOG_HALF = math.log(0.5)
def brute_force(lexicon, lm, emit, lm_weight=1.0, ip=0.0, max_words=5):
"""Best score over all word sequences of at most max_words words and all segmentations."""
T = len(emit)
best = NEG_INF
for k in range(1, max_words + 1):
for words in itertools.product(sorted(lexicon), repeat=k):
phones = [ph for w in words for ph in lexicon[w]]
if len(phones) > T:
continue
lm_part, prev = 0.0, BOS
for w in list(words) + [EOS]:
lm_part += lm_weight * lm.get((prev, w), NEG_INF)
prev = w
if lm_part == NEG_INF:
continue
for cuts in itertools.combinations(range(1, T), len(phones) - 1):
bounds = (0,) + cuts + (T,)
s = lm_part + k * ip
for j, ph in enumerate(phones):
d = bounds[j + 1] - bounds[j]
s += sum(emit[u][ph] for u in range(bounds[j], bounds[j + 1])) + (d - 1) * LOG_HALF + LOG_HALF
best = max(best, s)
return best
def random_task(rng: random.Random, T: int):
lexicon = {w: tuple(rng.choice(PHONES) for _ in range(rng.randint(1, 2))) for w in ["A", "B", "C"]}
vocab = sorted(lexicon)
lm = {}
for v in [BOS] + vocab:
probs = [rng.random() + 0.1 for _ in range(len(vocab) + 1)]
z = sum(probs)
for w, p in zip(vocab + [EOS], probs):
lm[(v, w)] = math.log(p / z)
emit = [{ph: -rng.uniform(0.0, 4.0) for ph in PHONES} for _ in range(T)]
return lexicon, lm, emit
def test_word_scores():
emit = [{"a": -1.0, "b": -2.0}, {"a": -3.0, "b": -0.5}, {"a": -1.0, "b": -1.0}]
out = word_scores(("a", "b"), emit, 0, LOG_HALF, LOG_HALF)
assert set(out) == {2, 3}
assert abs(out[2] - (-1.0 - 0.5 + 2 * LOG_HALF)) < 1e-12
assert abs(out[3] - (-1.0 - 0.5 - 1.0 + 3 * LOG_HALF)) < 1e-12
def test_heuristic_is_an_upper_bound():
rng = random.Random(30)
for _ in range(30):
lexicon, lm, emit = random_task(rng, 4)
h = default_heuristic(emit, 0.0)
for t in range(5):
rest = emit[t:]
if rest:
# The best score of any single word that covers the rest is at most h[t].
for w in lexicon:
s = word_scores(lexicon[w], emit, t, LOG_HALF, LOG_HALF).get(4, NEG_INF)
assert s <= h[t] + 1e-12
def test_matches_brute_force():
rng = random.Random(31)
for _ in range(60):
T = rng.randint(1, 5)
lexicon, lm, emit = random_task(rng, T)
kw = {"lm_weight": rng.choice([0.5, 1.0, 2.0]), "ip": rng.choice([-1.0, 0.0, 0.5])}
words, ends, score, _ = decode(lexicon, lm, emit, **kw)
expected = brute_force(lexicon, lm, emit, **kw)
if expected == NEG_INF:
assert (words, ends, score) == ([], [], NEG_INF)
continue
assert abs(score - expected) < 1e-9
assert ends[-1] == T - 1
assert all(a < b for a, b in zip(ends, ends[1:]))
def test_wide_stack_changes_nothing():
rng = random.Random(32)
for _ in range(30):
lexicon, lm, emit = random_task(rng, 5)
a = decode(lexicon, lm, emit)
b = decode(lexicon, lm, emit, max_stack=10 ** 6)
assert a[:3] == b[:3]
def narrow_task():
lexicon = {"x": ("a",), "y": ("b",), "z": ("c", "d")}
lm = {(v, w): 0.0 for v in [BOS, "x", "y", "z"] for w in ["x", "y", "z", EOS]}
emit = [{"a": 0.0, "b": -9.0, "c": -1.0, "d": -9.0}, {"a": -9.0, "b": -9.0, "c": -9.0, "d": -1.0}]
return lexicon, lm, emit
def test_narrow_stack_misses_the_best_path():
lexicon, lm, emit = narrow_task()
words, ends, score, _ = decode(lexicon, lm, emit)
assert (words, ends) == (["z"], [1]) and abs(score - (-2.0 + 2 * LOG_HALF)) < 1e-12
words, ends, score, _ = decode(lexicon, lm, emit, max_stack=1)
assert words[0] == "x"
assert abs(score - (-9.0 + 2 * LOG_HALF)) < 1e-12
def test_inadmissible_heuristic_can_fail():
lexicon = {"x": ("a",), "y": ("b",)}
lm = {(BOS, "x"): LOG_HALF, (BOS, "y"): LOG_HALF}
for v in ["x", "y"]:
for w in ["x", "y", EOS]:
lm[(v, w)] = math.log(1 / 3)
emit = [{"a": 0.0, "b": -5.0}, {"a": -5.0, "b": 0.0}]
best = decode(lexicon, lm, emit)
assert best[0] == ["x", "y"]
assert abs(best[2] - (2 * LOG_HALF + LOG_HALF + 2 * math.log(1 / 3))) < 1e-12
# A heuristic far below the true rest makes any complete hypothesis look better than a partial one.
worse = decode(lexicon, lm, emit, heuristic=lambda t: -100.0 * (2 - t))
assert len(worse[0]) == 1
assert worse[2] < best[2] - 3.0
def test_closed_set_limits_pops():
rng = random.Random(33)
lexicon, lm, emit = random_task(rng, 5)
_, _, _, pops = decode(lexicon, lm, emit)
# At most one expansion per (last word, start frame), plus duplicate and complete pops.
pushes_bound = 1 + (len(lexicon) + 1) * 6 * len(lexicon) * 6
assert pops <= pushes_bound
History
Jelinek 1969 gave the stack algorithm for the sequential decoding of convolutional codes. The IBM speech group applied it to continuous speech recognition, and Bahl, Jelinek and Mercer 1983 describe stack decoding as part of their statistical approach. Paul 1990 described a version that is an optimal A* search, which is guaranteed to find the most likely sentence, and a second algorithm that linearizes the search at the cost of approximating some path likelihoods. Time-synchronous beam search later became the more common decoder for large vocabularies, but the stack decoder idea lives on in phrase-based machine translation and in N-best search.
References
- Frederick Jelinek, Fast sequential decoding algorithm using a stack, IBM Journal of Research and Development 13(6), 1969, pages 675 to 685, the stack algorithm for sequential decoding
- Lalit R. Bahl, Frederick Jelinek and Robert L. Mercer, A maximum likelihood approach to continuous speech recognition, IEEE Transactions on Pattern Analysis and Machine Intelligence 5(2), 1983, pages 179 to 190, the discussion of decoding by stack search
- Douglas B. Paul, Algorithms for an optimal A* search and linearizing the search in the stack decoder, Speech and Natural Language Workshop, Hidden Valley, 1990, the abstract and the stack decoder loop (pop the best theory, stop at the end of the sentence, extend by a short list of candidate words)
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 A0NEW4 Edit this page History Report an error Markdown