Practice in Lab: Search a finite-state grammar with explicit EOS and sequence scores →
Search a finite-state grammar with explicit EOS and sequence scores
A grammar constrains valid sequences, while a language model supplies their scores. Filtering illegal transitions after normalizing the original vocabulary preserves the declared model likelihood; renormalizing only legal tokens instead creates a different conditional distribution. Finished EOS paths need their own lifetime, otherwise they can be accidentally extended or charged extra probability. This finite-position exercise makes search and grammar correctness inspectable without a remote model. A narrow beam can still prune the best complete sequence.
Prepare offline
Choose Download entire course or Download entire category first. After completion, code and checks run locally on CPU. The independent example needs no account, remote service or API key.
import torch
scores = torch.tensor([[2., 0., -1.]])
print(scores.log_softmax(-1))Review the evidence
Compare a wide beam with a brute-force oracle on short sequences. Define termination, tie breaking and length scoring before adding history-dependent model calls or claiming that beam search finds the global optimum.
Your task
Search finite floating [time,vocab] position-conditioned logits under transitions[state][token]=next_state. EOS is permitted only in accepting states and terminates the hypothesis without a transition. Use original full-vocabulary log-softmax scores before grammar filtering: do not renormalize each allowed subset. Keep finished hypotheses without scoring further tokens, sort by descending accumulated score then lexicographic token sequence, and retain width hypotheses after each step. Return {tokens,score} for the best finished hypothesis; reject if none finishes. Wide beams can match exhaustive search; a finite narrow beam is not guaranteed optimal.
The explanation opens here once every check passes.