LESSON 22.02 · 6 STAGES · 2 CONTROLS · 3 CHECKS
Compiling a regex or schema into a token FSM
See a JSON schema become a regex, a state machine and a token mask.
EXPLAINER · 22.02 · FSM BAY
01
Stage 1 of 6 · Schema to regex
The JSON Schema compiles to a regex. The object, the field and the integer type each write pieces.
Explain it simply
The block of text is a JSON Schema. It asks for an object with one field, n, that holds a whole number. Each part turns into a piece of a regex, a pattern that says which text is allowed. The braces come from the object, and the digits come from the integer type.
The regex \{"n":-?[0-9]+\} is shown as pieces, each named for the schema part it comes from.
The toy model's scores are seeded, not trained.
regex and statestokensmasked, or a walk that breaksdies late or top score blockedpicked tokens
Toy: 3 constraints, 12 or 19 tokens
HOVER OR TAP A SHAPE TO SEE ITS NUMBERS
Object schema
Pick the regex or the schema to compile.
With merged
Single characters only, or merged tokens too.
MATH · STAGE 1HOVER A SYMBOL OR A SHAPE
The constraint becomes one regex R.
Show the code ▾Hide the code ▴ · Try it yourself · Python 3
REGEX = "\\{\"n\":-?[0-9]+\\}"
CHARS = ["-","1","2","3","5",".","{","\"","n",":","}"]
MERGED = ["12","-3",".5","1.5","{\"","n\":","5}"]
VOCAB = CHARS + MERGED + ["eos"]
ALPHABET = "{\"n:-0123456789.}"
# Compile a regex into a character state machine, walk every token through it
# (the token index), then decode with one mask per step.
def parse(re): # regex -> tree: literals, \x, [a-b], ?, +, *, (a|b)
pos = 0
def atom():
nonlocal pos
c = re[pos]; pos += 1
if c == "(":
node = alt(); pos += 1; return node
if c == "[":
chars = set()
while re[pos] != "]":
if re[pos + 1] == "-" and re[pos + 2] != "]":
chars |= {chr(k) for k in range(ord(re[pos]), ord(re[pos + 2]) + 1)}; pos += 3
else:
chars.add(re[pos]); pos += 1
pos += 1
return ("set", chars)
if c == "\\":
pos += 1; return ("set", {re[pos - 1]})
return ("set", {c})
def repeat():
nonlocal pos
node = atom()
while pos < len(re) and re[pos] in "?+*":
node = (re[pos], node); pos += 1
return node
def cat():
node = ("eps",)
while pos < len(re) and re[pos] not in "|)":
node = ("cat", node, repeat())
return node
def alt():
nonlocal pos
node = cat()
while pos < len(re) and re[pos] == "|":
pos += 1; node = ("alt", node, cat())
return node
return alt()
def compile_fsm(re, alphabet):
eps, edges = [], [] # Thompson NFA
def new():
eps.append([]); return len(eps) - 1
def build(n):
s, e = new(), new()
if n[0] == "eps": eps[s].append(e)
elif n[0] == "set": edges.append((s, n[1], e))
elif n[0] in ("cat", "alt"):
a1, a2 = build(n[1]); b1, b2 = build(n[2])
if n[0] == "cat": eps[s].append(a1); eps[a2].append(b1); eps[b2].append(e)
else: eps[s] += [a1, b1]; eps[a2].append(e); eps[b2].append(e)
else:
a1, a2 = build(n[1]); eps[s].append(a1); eps[a2].append(e)
if n[0] != "+": eps[s].append(e)
if n[0] != "?": eps[a2].append(a1)
return s, e
start, end = build(parse(re))
def closure(states):
out, stack = set(states), list(states)
while stack:
for t in eps[stack.pop()]:
if t not in out: out.add(t); stack.append(t)
return frozenset(out)
# subset construction, states numbered breadth-first
sets = [closure([start])]; delta = []
for cur in sets:
row = {}
for c in alphabet:
moved = [e for (s, chars, e) in edges if s in cur and c in chars]
if moved:
nxt = closure(moved)
if nxt not in sets: sets.append(nxt)
row[c] = sets.index(nxt)
delta.append(row)
accept = [end in s for s in sets]
return delta, accept # (these regexes give a minimal machine directly)
def walk(delta, accept, s, tok):
if tok == "eos": return s if accept[s] else None
for c in tok:
s = delta[s].get(c)
if s is None: return None
return s
def mulberry32(seed): # the toy model's seeded scores (not trained)
a = seed & 0xFFFFFFFF
def nxt():
nonlocal a
a = (a + 0x6D2B79F5) & 0xFFFFFFFF
t = ((a ^ (a >> 15)) * (1 | a)) & 0xFFFFFFFF
t = ((t + (((t ^ (t >> 7)) * (61 | t)) & 0xFFFFFFFF)) & 0xFFFFFFFF) ^ t
return ((t ^ (t >> 14)) & 0xFFFFFFFF) / 4294967296
return nxt
def js_round(x): # JavaScript's Math.round(x * 100) / 100
import math
return math.floor(x * 100 + 0.5) / 100
ALL = CHARS + MERGED + ["eos"]
def scores(k):
r = mulberry32(3700 + k)
out = {}
for t in ALL:
length = 1 if t == "eos" else len(t)
stop = 0.3 * k if t in ("eos", "}", "5}") else 0
out[t] = js_round(r() * 1.5 + 0.8 * (length - 1) + stop)
return out
delta, accept = compile_fsm(REGEX, ALPHABET)
index = [{t: walk(delta, accept, s, t) for t in VOCAB if walk(delta, accept, s, t) is not None} for s in range(len(delta))]
print(len(delta), "states, accept:", [s for s in range(len(delta)) if accept[s]])
print("index:", sum(len(row) for row in index), "of", len(delta) * len(VOCAB), "pairs")
state, out = 0, []
for k in range(14):
z = scores(k)
mask = index[state] # one row: the allowed tokens and where each leads
tok = max(mask, key=lambda t: (z[t], -VOCAB.index(t)))
print("step", k + 1, "state", state, "allowed", len(mask), "pick", tok)
if tok == "eos": break
out.append(tok); state = mask[tok]
print("".join(out))
# It prints:
# 9 states, accept: [8]
# index: 29 of 171 pairs
# step 1 state 0 allowed 2 pick {"
# step 2 state 2 allowed 2 pick n":
# step 3 state 5 allowed 8 pick -3
# step 4 state 7 allowed 7 pick 12
# step 5 state 7 allowed 7 pick 5}
# step 6 state 8 allowed 1 pick eos
# {"n":-3125}
Copy it into a file and run it. It needs no packages.
Common mix-ups
MYTHA token fits if its first character fits.
FIXUnder the integer regex, 1.5 starts with a digit, but no edge reads the dot. The index walks every character.
MYTHThe regex is checked against every token at each step.
FIXThe index is built once, with 175 character reads. Each decode step then reads one row of it.
Predict, then reveal
0 / 3 REVEALEDQ01With characters only, does the object take more or fewer decode steps?
1 · GUESS2 · TRY IT IN THE DIAGRAM
Q02With merged tokens, can the token 1.5 start the decimal regex?
1 · GUESS2 · TRY IT IN THE DIAGRAM
Q03Under the integer regex, can the text end right after the minus sign?
1 · GUESS2 · TRY IT IN THE DIAGRAM
Takeaways
- A regex or schema compiles once into a finite-state machine over characters.
- Walking every token through it gives an index from each state to its tokens.
- Each decode step reads one row of the index as the mask.