Write a JSON-schema logit processor and measure its overhead on CPU
CPU · your Macnotebook150 minrequiredGoal · A transformers LogitsProcessor that forces Qwen2.5-0.5B-Instruct to emit JSON matching a fixed schema, with a measured per-step cost for a naive and a precomputed-mask implementation.
- 1pip install torch transformers jsonschema interegular; load Qwen/Qwen2.5-0.5B-Instruct (or gpt2 if memory is tight) in float32 and pick a schema with three fields, for example name (string), age (integer 0-120) and tags (list of strings).
- 2Hand-write a regex that matches exactly the JSON documents your schema allows (fixed key order, no whitespace) and compile it to a finite state machine with interegular.
- 3Build the vocabulary map once; for every token id, decode it to text and record, for each FSM state, which next state it leads to (or that it is invalid). Store the result as a dict from state to a boolean mask tensor over the vocabulary and cache it to disk.
- 4Implement a naive processor that at each step decodes the top-512 candidate tokens, appends each to the partial output and tests the string against the FSM; mask the rest to minus infinity.
- 5Implement the precomputed processor that tracks the current FSM state and indexes the mask dict; apply it with logits.masked_fill_.
- 6Generate 50 outputs with model.generate for each processor (temperature 0.7, max_new_tokens 64) and validate every output with jsonschema; count failures for an unconstrained baseline too, treating markdown fences or trailing prose as failures.
- 7Time the processor call itself with time.perf_counter inside __call__ and accumulate per step; report mean added ms per decode step for each processor.
- 8Write three sentences on where the remaining per-step cost comes from and how a GPU engine would hide it.
- Deliverable
- A notebook with both processors, the validation counts for baseline, naive and precomputed, and a table of added ms per decode step.
- Check
- Both constrained processors produce 50 of 50 schema-valid outputs while the unconstrained baseline fails at least once; the precomputed mask adds under 2 ms per step on CPU and the naive processor costs at least 10x more per step.