LESSON 22.01 · 5 STAGES · 3 CONTROLS · 3 CHECKS
Constrained decoding with token masking
A token mask makes a model write JSON that always fits its schema.
EXPLAINER · 22.01 · DECODER BAY
01
Stage 1 of 5 · Score tokens
At step 8, the model gives each of 14 tokens a logit. Softmax makes them probabilities; "ten" leads.
Explain it simply
Each row is one token the model knows, and its bar shows how likely that token comes next. Here the model wants the word ten in quotes for the age. That's text, but the schema may want a number.
Fourteen token rows with probability bars at step 8. The top token is "ten" with 0.38.
probabilities, outputschema, grammar, maskblocked token (mask on)breaks the grammar
Toy: 14 tokens · a hand-set model (not trained) · greedy picks · schema with name and age
HOVER OR TAP A SHAPE TO SEE ITS NUMBERS
On
Turn the grammar's mask on or off.
Integer
Set the type of age in the schema.
Age value
Pick the decoding step that the bars show.
MATH · STAGE 1HOVER A SYMBOL OR A SHAPE
Each probability is the exponent of its logit over the sum.
Show the code ▾Hide the code ▴ · Try it yourself · Python 3
import json
import math
TOKENS = ['Sure', '!', '{', '}', '"name"', '"age"', ':', ',', '"Ada"', '"Bo"', '"ten"', '7', '42', '<end>']
STR = ['"Ada"', '"Bo"', '"ten"']
INT = ['7', '42']
MASK_ON = True
AGE_TYPE = "integer" # the schema's type for age
def scores(prev, key):
"""Hand-set logits (not trained): read the previous token and the last key."""
if prev == "start":
row = {"Sure": 2.2, "{": 1.6, '"name"': 0.4}
elif prev == "Sure":
row = {"!": 2.0, "{": 1.2, ",": 0.2}
elif prev == "!":
row = {"{": 2.0, "Sure": 0.0, '"name"': 0.5}
elif prev == "{":
row = {'"name"': 2.2, '"age"': 1.0, "}": 0.2}
elif prev == '"name"':
row = {":": 2.4, ",": 0.4}
elif prev == '"age"':
row = {":": 2.4, ",": 0.2}
elif prev == ":" and key == '"age"':
row = {'"ten"': 1.9, "42": 1.5, "7": 0.6, '"Ada"': -0.2}
elif prev == ":":
row = {'"Ada"': 2.0, '"Bo"': 1.2, '"ten"': 0.3, "7": 0.0}
elif prev in STR + INT and key == '"age"':
row = {"}": 2.1, ",": 0.8, "!": 0.0}
elif prev in STR + INT:
row = {",": 2.0, "}": 0.9, "!": 0.0}
elif prev == ",":
row = {'"age"': 2.0, '"name"': 0.6}
elif prev == "}":
row = {"<end>": 2.5, "!": 0.3, ",": 0.2}
else:
row = {}
return [row.get(t, -1.0) for t in TOKENS]
def softmax(z):
m = max(v for v in z if v != -math.inf)
e = [0.0 if v == -math.inf else math.exp(v - m) for v in z]
s = sum(e)
return [v / s for v in e]
# the grammar the schema compiles to: one set of allowed tokens per slot
grammar = [["{"], ['"name"'], [":"], STR, [","], ['"age"'], [":"], INT if AGE_TYPE == "integer" else STR, ["}"], ["<end>"]]
out, slot, prev, key = [], 0, "start", None
while prev != "<end>" and len(out) < 16:
z = scores(prev, key)
allowed = grammar[slot] if slot < len(grammar) else []
if MASK_ON: # the token mask: -inf for every token the grammar blocks
z = [v if t in allowed else -math.inf for v, t in zip(z, TOKENS)]
p = softmax(z)
i = max(range(len(TOKENS)), key=lambda k: p[k]) # greedy: the top token
tok = TOKENS[i]
# a value of the wrong type still fills its value slot (slots 4 and 8)
if tok in allowed or (tok in STR + INT and slot in (3, 7)):
slot += 1
print(len(out) + 1, tok, f"{p[i]:.3f}", "fits" if tok in allowed else "breaks")
out.append(tok)
prev = tok
if tok in ('"name"', '"age"'):
key = tok
text = "".join(t for t in out if t != "<end>")
print(text)
try:
data = json.loads(text)
age_ok = isinstance(data.get("age"), int) if AGE_TYPE == "integer" else isinstance(data.get("age"), str)
ok = isinstance(data, dict) and set(data) == {"name", "age"} and isinstance(data["name"], str) and age_ok
print("valid" if ok else "fails the schema")
except json.JSONDecodeError:
print("not JSON")
# Output:
# 1 { 1.000 fits
# 2 "name" 1.000 fits
# 3 : 1.000 fits
# 4 "Ada" 0.613 fits
# 5 , 1.000 fits
# 6 "age" 1.000 fits
# 7 : 1.000 fits
# 8 42 0.711 fits
# 9 } 1.000 fits
# 10 <end> 1.000 fits
# {"name":"Ada","age":42}
# valid
Copy it into a file and run it. Change MASK_ON and AGE_TYPE to see the other cases.
Common mix-ups
MYTHAsking for JSON in the prompt is enough.
FIXA prompt only moves the scores. Here the model still starts with Sure at 0.46, so the text is not JSON.
MYTHValid JSON means the values are right.
FIXThe mask fixes the shape, not the facts. Integer gives 42 and string gives ten. The schema cannot tell which is true.
Predict, then reveal
0 / 3 REVEALEDQ01With the mask off, does the output start with a curly brace?
1 · GUESS2 · TRY IT IN THE DIAGRAM
Q02With the mask on and age a string in the schema, which token does the decoder write for age?
1 · GUESS2 · TRY IT IN THE DIAGRAM
Q03At the first step with the mask on, how many tokens can the decoder pick from?
1 · GUESS2 · TRY IT IN THE DIAGRAM
Takeaways
- The schema compiles to a grammar that allows a few tokens at each step.
- The mask adds −∞ to blocked logits, so their probability is exactly 0.
- The mask guarantees valid JSON, not correct values.