REAL PYTORCH · CPU TRAINING AND AUTOGRAD

Search a finite-state grammar with explicit EOS and sequence scores

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.

Run this Lab in Pythilo

Open Labs, choose its topic and tap Download entire topic, or Download entire category for all its Labs, including the required Python packages, then load the starter or worked answer and tap Trace. Progress, pause, resume and removal are in Downloads. Independent checks execute real CPU training and gradients.

No GPU, external model weights or API key is required. After downloading the topic and packages, this Lab runs offline.

PyTorch is unavailable in this browser runtime. The code and lessons are readable here; execution and checks run in the app.

Pythilo on the App Store →

Read lesson: Search a finite-state grammar with explicit EOS and sequence scores →

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.

Starter

import torch

def constrained_beam(logits, transitions, start, accepting, eos, width=4):
    # TODO: implement constrained_beam under the declared contract.
    return None
Inspect the worked answer
import torch

def constrained_beam(logits, transitions, start, accepting, eos, width=4):
    if logits.ndim!=2 or min(logits.shape)==0 or not logits.is_floating_point() or not torch.isfinite(logits).all() or type(width)!=int or width<1:raise ValueError('Expected finite nonempty position logits and positive beam width.')
    if type(eos)!=int or not 0<=eos<logits.shape[1] or start not in transitions:raise ValueError('Invalid EOS or start state.')
    for row in transitions.values():
        if not isinstance(row,dict) or any(type(t)!=int or t==eos or not 0<=t<logits.shape[1] or s not in transitions for t,s in row.items()):raise ValueError('Invalid grammar transition.')
    log_probs=logits.detach().double().log_softmax(-1)
    beam=[([],start,0.,False)]
    for position in range(len(logits)):
        candidates=[]
        for tokens,state,score,finished in beam:
            if finished:
                candidates.append((tokens,state,score,True))
                continue
            if state in accepting:candidates.append((tokens+[eos],state,score+log_probs[position,eos].item(),True))
            for token,next_state in transitions[state].items():
                candidates.append((tokens+[token],next_state,score+log_probs[position,token].item(),False))
        beam=sorted(candidates,key=lambda item:(-item[2],item[0]))[:width]
        if not beam:break
        if all(row[3] for row in beam):break
    finished=[row for row in beam if row[3]]
    if not finished:raise ValueError('No accepted EOS-terminated sequence within this beam and time budget.')
    best=sorted(finished,key=lambda item:(-item[2],item[0]))[0]
    return {'tokens':best[0],'score':best[2]}

About this algorithm

How Search a finite-state grammar with explicit EOS and sequence scores works

The idea

Constrained decoding forces a model's output to follow a grammar. Here it is a finite-state machine: each state lists the tokens it allows and the state each one leads to, and EOS is legal only in an accepting state. Beam search runs on top, each hypothesis carrying its tokens, grammar state, score and a finished flag.

Two choices make the scores meaningful. Log probabilities come from a softmax over the full vocabulary, taken before the grammar filters anything. The grammar removes options but does not renormalize the survivors, so a score stays the model's own log probability of that sequence and hypotheses remain comparable. Finished hypotheses stay in the beam with their score frozen and compete against unfinished ones. A narrow beam can still miss the best valid sequence.

How it works

  1. Validate the logits, width, eos and every transition, then compute log_probs once with log_softmax over the whole vocabulary.
  2. Start the beam with one hypothesis: no tokens, the start state, score 0 and not finished.
  3. At each position, carry finished hypotheses forward unchanged.
  4. For an unfinished one, add an EOS candidate if its state is in accepting, and one candidate per allowed token with its next state.
  5. Sort the candidates by score from high to low, then by token sequence, keep width, and stop early once all are finished.
  6. Return the best finished hypothesis as tokens and score, or raise ValueError when none finished.

What it costs

Per position
sort up to w·(a+1) rows
Scores
one log-softmax, O(T·V)
Optimal
only with a wide beam

With width w and at most a allowed tokens per state, each position creates and sorts about w·(a + 1) candidates, and copying token lists adds a factor of the sequence length.

Where it is used

  • llama.cpp accepts GBNF grammars and rejects tokens that would break the grammar during sampling.
  • The Outlines library compiles regular expressions and JSON schemas into finite-state machines over tokens to guide generation.
  • Hugging Face Transformers generate() takes prefix_allowed_tokens_fn, which restricts the tokens beam search may choose at each step.

Watch out for

  • Taking the softmax over the allowed tokens only: that renormalizes every step and inflates paths through states with few choices.
  • Allowing EOS in any state: a sequence may end only in an accepting state, however large the EOS logit is.
  • Dropping finished hypotheses from the beam, or adding more scores to them: they must stay in the beam with their score frozen.