Code Lab / Challenge 18

Constrained JSON Decoding with a Schema Walker

HardMasking invalid tokens against a schema during decode

The problem, as an interviewer would set it

Force a model to emit schema-conforming JSON by masking the logits at every
decoding step, so only grammatically valid tokens survive. The vocabulary is
character level, 42 tokens: digits 0-9, lowercase a-z (which also spell the
pieces of `true` and `false`), the characters " { } : , and one EOS token.

Implement:
    SchemaWalker(schema, max_str_len=8, max_int_digits=4)
        `schema` is flat, e.g. {"name": "string", "age": "integer",
        "active": "boolean"}, and the walker accepts exactly
            {"<key1>":<value1>,...,"<keyN>":<valueN>}<EOS>
        keys in schema order, no whitespace, string values of 1..max_str_len
        alphanumeric characters, integers with no leading zeros past a bare 0,
        booleans spelled one character at a time.
        allowed_next() -> set[int]  ids that keep a complete document
                                    reachable, empty only after EOS
        advance(token_id) -> None   consume a token, ValueError if illegal
    mask_logits(logits, allowed) -> np.ndarray
        copy of `logits` with disallowed entries at -inf, input untouched
    constrained_decode(model_fn, walker, max_len=64, rng=None) -> list[int]
        `model_fn(prefix_ids) -> np.ndarray` of shape (VOCAB_SIZE,). Sample from
        softmax(mask_logits(logits, walker.allowed_next())), advance, stop on
        EOS or max_len.

numpy and the standard library only. Mask the logits before the softmax, never
the probabilities after it.
What interviewers look for

Masking before softmax, why constrained decoding shifts the distribution, DFA vs pushdown for nested JSON

A strong solution demonstrates:
- The grammar is the decoder. A flat schema is a regular language, so a DFA is
  enough, and so is any non-recursive schema with bounded nesting (it unrolls
  into a bigger regex). Recursive schemas and arbitrary JSON are not: matching
  arbitrarily deep braces needs a stack, so engines such as XGrammar and
  llguidance run a pushdown automaton or an Earley-style parser, while
  regex-first designs compile the regular parts to a DFA.
- Constrained decoding shifts the distribution. Renormalising onto the allowed
  set gives the model's conditional given validity, which is not its belief
  about good content: forcing a key order it did not want, or truncating a
  field, pushes it into low-probability regions and can hurt quality (reported
  mostly on reasoning tasks, and the evidence is mixed). Describing the schema
  in the prompt as well as masking keeps the two closer, and putting a free
  text reasoning field before the answer fields gives the model room to think.
- Cost awareness. The mask is a vocabulary-sized boolean per step, and at 100k+
  vocabularies rebuilding it per token is a visible slice of the step budget.
  Production systems cache masks per parser state, precompute the
  token-to-state transitions offline, and compute the next mask on the CPU
  while the GPU runs the forward pass, so the hot path is a lookup.
Common mistakes: masking after the softmax without renormalising, so the
probabilities no longer sum to 1; using 0.0 instead of -inf, which leaves
disallowed tokens weight exp(0) = 1; dead states, where a legal prefix has no
legal continuation, every logit is -inf and the softmax is NaN; allowing EOS
anywhere, so the model can stop mid-object; letting an integer field open with
a quote because the value grammar is not keyed off the declared type.
Follow-ups: nested objects and arrays with a state stack; regex-constrained
fields; multi-character (BPE) tokens, where one token straddles a grammar
boundary so the mask must be built over token strings; measuring the KL between
the constrained and unconstrained distributions to price the quality cost; why
"JSON mode" (any valid JSON) is weaker than schema-constrained structured
output, and what a hosted API still cannot guarantee (semantic correctness,
values that pass business rules).

Write your own version first. The reference solution and its tests are one click away when you are ready.

Next challenge