PythiloLesson 6 of 8 · progress kept in this browser

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.

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.

This lesson uses torch, which Python in this browser does not include. Read it here, and run and check it in the Pythilo app on iPhone or iPad.