How does Constrained Decoding work?
- Authors
- Name
- Amit Shekhar
- Published on
Constrained Decoding is a way of forcing an LLM to only pick words that follow a fixed set of rules, like a valid JSON format. At every step, it blocks the words that would break the rules, so the output always comes out in the shape we want.
In this blog, we will learn about how Constrained Decoding works. We will also see why we need it, how an LLM normally picks one token at a time, how a mask blocks the wrong tokens, how rules like JSON and regex are turned into a small state machine, a step-by-step walkthrough with simple numbers, and where it works well and where it fails.
We will cover the following:
- What is decoding in an LLM?
- The problem: LLMs do not always follow the format
- What is Constrained Decoding?
- The core idea: masking the wrong tokens
- A step-by-step example
- How do the rules become a state machine?
- Constrained Decoding for JSON
- The tricky part: tokens are not characters
- Constrained Decoding in code
- Constrained Decoding vs asking in the prompt
- Where it works well and where it fails
I am Amit Shekhar, Founder @ Outcome School, I have taught and mentored many developers, and their efforts landed them high-paying tech jobs, helped many tech companies in solving their unique problems, and created many open-source libraries being used by top companies. I am passionate about sharing knowledge through open-source, blogs, and videos.
I teach AI and Machine Learning at Outcome School.
Let's get started.
What is decoding in an LLM?
Before jumping into Constrained Decoding, we must know what decoding means.
An LLM (Large Language Model) does not write a full sentence in one go. It writes one small piece at a time. This small piece is called a token. A token can be a full word like cat, a part of a word like ing, or a symbol like { or ".
The LLM knows a fixed list of all the tokens it can ever use. This list is called the vocabulary. A vocabulary usually has tens of thousands of tokens.
At every step, the LLM looks at all the text so far and gives a score to every single token in its vocabulary. A higher score means "this token is a better next choice". These raw scores are called logits.
Then, these scores are turned into probabilities, which means chances that add up to 100%. Finally, one token is picked based on these chances, and it is added to the text. Then the whole process repeats for the next token.
Decoding is the process of picking the next token again and again until the answer is complete.
We have a detailed blog on Greedy Decoding and Beam Search that explains the common ways to make this pick.
Let's visualize one step of decoding as below:
Text so far: "The sky is"
LLM gives a chance to every token:
" blue" -> 70%
" clear" -> 15%
" dark" -> 10%
" banana" -> 0.1%
... (thousands more)
↓
Pick one: " blue"
↓
New text: "The sky is blue"
Here, we can see that the LLM does not know the full answer in advance. It only picks the next token, adds it, and moves on.
To master LLM Fundamentals, Tokenization, and Logits, and to build a Large Language Model (LLM) from scratch, check out our AI and Machine Learning Program at Outcome School.
Now, let's understand the problem.
The problem: LLMs do not always follow the format
Let's say we are building an app. Our app asks the LLM to read a customer message and return the result in JSON like below:
{ "name": "Amit", "age": 30 }
Here, we have a name field with a text value and an age field with a number value. Our app code will read this JSON and use the values.
Now, suppose we write in the prompt: "Reply only in JSON with name and age."
Most of the time, the LLM follows it. But sometimes it replies like below:
Sure! Here is the JSON you asked for:
{ "name": "Amit", "age": "thirty" }
Here, we can notice two problems. There is extra text before the JSON, and the age is a word, not a number.
Our app code tries to read this, and it crashes. And this happens randomly, once in many requests.
The LLM is picking tokens by chance. The prompt only makes the right tokens more likely. It does not make the wrong tokens impossible.
So, how can we make the wrong tokens impossible? The answer is Constrained Decoding.
What is Constrained Decoding?
Constrained Decoding is a technique where, at every step, we allow the LLM to pick only those tokens that keep the output valid as per our rules.
The LLM still chooses, but only from the valid options.
Here, constrained means limited by rules. So, Constrained Decoding means picking tokens one by one, but only within the rules.
Suppose a child is filling a form at a bank. One box says "Age" and only has space for digits. The child cannot write "thirty" there, because the box only allows numbers. The child still decides the number, but the form decides the shape.
The LLM is the child who decides what to write. Our rules are the form. Constrained Decoding is what makes each box accept only the right kind of input.
The rules can be of many kinds:
- A JSON format with fixed fields, often given as a JSON Schema, which is a description of what fields and types are allowed.
- A regular expression (regex), which is a short pattern that describes text, like "exactly 10 digits" for a phone number.
- A fixed list of choices, like only
positive,negative, orneutral. - A grammar, which is a full set of rules for a language, like the rules of SQL or a programming language.
Now, let's understand how it works inside.
The core idea: masking the wrong tokens
Remember, at every step, the LLM gives a score (logit) to every token. Constrained Decoding steps in right after the scores are made and right before a token is picked.
It checks every token and asks, "If we add this token now, can the output still become valid as per the rules?"
- If the answer is yes, the token is allowed. Its score stays as it is.
- If the answer is no, the token is blocked. Its score is set to minus infinity.
Why minus infinity? Because when scores are turned into chances, a score of minus infinity becomes a chance of exactly 0%. So, the blocked token can never be picked.
This list of "allowed" and "blocked" tokens is called a mask. It covers the tokens we do not want.
Let's visualize it as below:
Step 1: LLM gives scores to all tokens
+--------+-------+
| Token | Score |
+--------+-------+
| "Sure" | 5.1 |
| "{" | 4.8 |
| "Here" | 3.0 |
+--------+-------+
↓
Step 2: Apply the mask (rule: output must start with "{")
+--------+-------+---------+
| Token | Score | Status |
+--------+-------+---------+
| "Sure" | -inf | blocked |
| "{" | 4.8 | allowed |
| "Here" | -inf | blocked |
+--------+-------+---------+
↓
Step 3: Pick from what is left: "{"
Here, we can see that the LLM actually liked "Sure" the most. But "Sure" cannot be the start of a JSON object, so it got blocked. The best allowed token, "{", is picked.
Very important: Constrained Decoding does not change the LLM itself. It does not retrain anything. It only filters the choices at the time of picking.
Planning your move into AI?
No matter which tech domain you work in today, with your effort, you can transition to these roles:
- AI Engineer
- Forward Deployed Engineer
- AI Agent Engineer
- Harness Engineer
- Voice AI Engineer
- AI Architect
- LLM Engineer
- LLM Inference Engineer
- Gen AI Engineer
- MLOps Engineer
- ML Engineer
- Deep Learning Engineer
Our AI and Machine Learning Program at Outcome School takes you there.
A step-by-step example
The best way to learn this is by taking an example.
Let's say we want the LLM to classify a review as positive or negative, and nothing else. For the sake of understanding, assume each of these is one token.
Our rule: the output must be exactly positive or exactly negative.
The review is: "The food was cold and the waiter was rude."
Step 1: The LLM gives scores to all tokens. For the sake of example, suppose the chances look like below:
"The" -> 40%
"negative" -> 35%
"positive" -> 5%
"Negative" -> 10%
others -> 10%
Here, the LLM wants to start with "The" to write something like "The review is negative". That would break our rule.
Step 2: We apply the mask. Only positive and negative are allowed. Everything else gets minus infinity.
"The" -> blocked
"negative" -> 35%
"positive" -> 5%
"Negative" -> blocked
others -> blocked
Step 3: We make the chances add up to 100% again among the allowed tokens. This is called renormalizing. 35 + 5 = 40, so:
"negative" -> 35 / 40 = 87.5%
"positive" -> 5 / 40 = 12.5%
Step 4: We pick negative, which is the most likely one.
Step 5: Now the rule says the output is complete. So, the only allowed token is the special end token, which tells the LLM to stop. The LLM stops.
The final output is exactly negative. No extra words, no capital letter, no full stop. It works perfectly.
Notice one thing here. The LLM still did the real thinking. It decided negative is much more likely than positive. The mask only removed the tokens that break the rule.
A quick note for you
No matter which tech domain you work in, get familiar with these topics:
- LLM
- RAG
- MCP
- Agent
- Fine-tuning
- Quantization
We put it all together in one video:
AI Engineering Explained: LLM, RAG, MCP, Agent, Fine-Tuning, and Quantization
No need to stop reading - bookmark it and watch later when you get time. Future you will thank you.
Now, let's get back to the topic.
How do the rules become a state machine?
The example above was easy because there were only two choices. But JSON and regex rules are much bigger. How do we check, at every step, which tokens are allowed?
Here comes the state machine into the picture.
A state machine is a simple map of "where we are now" and "where we can go next".
Think of a metro map. From our current station, only some lines go out, and we can only follow those lines. Each station is a state, and each line is a move labeled with the character that takes us there.
Let's say our rule is a simple regex: a phone number of exactly 3 digits, a dash, and 4 digits, like 555-1234. The state machine looks like below:
[S0] start
↓
[S1] 1 digit written
↓
[S2] 2 digits written
↓
[S3] 3 digits written
↓
[S4] dash "-" written
↓
[S5] 1 more digit written
↓
[S6] 2 more digits written
↓
[S7] 3 more digits written
↓
[END] 4 more digits written
Here, each arrow is one allowed character. We start at S0, only digits are allowed until S3, then only a dash - is allowed, and then four more digits take us to END.
Now, at every step of decoding, we look at the current state and ask, "Which characters are allowed from here?" Any token that would take us off the map gets blocked. After a token is picked, we move along the map to the new state, and the next step starts from there.
So, the full loop of Constrained Decoding looks like below:
LLM gives scores to all tokens
↓
State machine says which tokens are allowed now
↓
Block the rest (set to -inf)
↓
Pick a token from the allowed ones
↓
Move the state machine forward
↓
Repeat from the top until END
This is how a rule becomes something a computer can check very fast at every step.
Constrained Decoding for JSON
Now, let's take the real use case, which is JSON.
Suppose our app needs this shape, described by a JSON Schema:
{
"type": "object",
"properties": {
"name": { "type": "string" },
"age": { "type": "integer" }
},
"required": ["name", "age"]
}
Here, we have described that the output must be an object with a name that is text and an age that is a whole number.
A library takes this schema and turns it into rules, and then into a state machine, just like the phone number example. For the sake of understanding, assume that the keys must come in this order and the spacing is fixed. Then, the rules are simple:
- The output must start with
{ "name": ". - Then any text characters, until a closing
". - Then
, "age":. - Then only digits.
- Then
}, and then stop.
Let's walk through it as below:
Forced: { "name": "
LLM free: Amit (only text characters allowed)
Forced: ", "age":
LLM free: 30 (only digits allowed)
Forced: }
Here, we can notice something interesting. Some parts are forced. At those steps, only one token is allowed, so the LLM has no choice at all. Some libraries do not even run the LLM for those steps. They just add the forced text directly, which saves time. We have a detailed blog on How does SGLang work? that covers how an inference engine uses this to make structured output faster.
Other parts are free, where the LLM fills in the real content. But even there, it is limited. Inside age, only digits are allowed, so the word "thirty" is impossible.
Now, our app can read the output every time.
Note: JSON can also have nested objects and lists inside lists. A simple state machine cannot track "how many brackets are still open" when the nesting can go deeper and deeper. For that, libraries use a more powerful tool called a context-free grammar, which is like a state machine with a stack of open brackets. The idea of masking stays exactly the same.
The tricky part: tokens are not characters
The state machine works on characters. But the LLM works on tokens, and one token can be many characters.
For example, a token can be {", or name, or ": ", or 12. So, the state machine cannot just check one character. It must check the full token.
So, for every token, we ask, "If we walk this whole token character by character on our map, do we stay on the map?"
- Token
{"from the start:{is allowed, then"is allowed. So, the token is allowed. - Token
Surefrom the start:Sis not allowed. So, the token is blocked.
But the vocabulary has thousands of tokens. Checking all of them at every step is slow.
So, here comes precomputation to the rescue. Before decoding starts, the library goes over every state in the map, and for each state, it makes a list of which tokens are allowed from that state. This list is saved. Later, at decoding time, finding the mask is just a quick lookup.
Libraries like Outlines made this precomputation idea popular for regex and JSON. Other tools like XGrammar use their own techniques to keep the per-step cost very small, even for full grammars.
There is one more subtle issue. Suppose the LLM naturally writes 30 as one token, but the rules only allow the space and the digits as separate small tokens. The text is valid, but it is split in a way the LLM rarely saw while learning. This can slightly lower the quality. Good libraries try to handle such token boundaries carefully.
Stay updated: Subscribe to our newsletter to get our latest AI and Machine Learning blogs straight to your inbox.
Constrained Decoding in code
Now, let's see how it looks in practice. Here, we will use the outlines library in Python. The exact function names change between versions, so for the sake of understanding, we will focus on the idea.
First, we describe the shape we want using a Python class, as below:
from pydantic import BaseModel
class Person(BaseModel):
name: str
age: int
Here, we have created a class Person with two fields. name must be text and age must be a whole number. This class acts as our JSON Schema.
Then, we ask the model to generate output that must match this shape, like below:
import outlines
model = outlines.from_transformers(llm, tokenizer) # load our model
result = model(
"Extract the person: Amit is thirty years old.",
Person, # the rule: output must match Person
)
print(result)
Here, llm and tokenizer are a Hugging Face model and its tokenizer that we have already loaded. We are passing Person as the output type. The library turns it into a state machine and applies the mask at every step. We are not just asking in the prompt. We are forcing the shape.
It will print the following:
{ "name": "Amit", "age": 30 }
Here, we can see that even though the prompt said "thirty" in words, the output has 30 as a number. The mask allowed only digits inside age, so the LLM had to write the number.
Note: The output is a JSON string, which we can then load into a Person object.
Now, let's see the core masking idea in plain code, without any library, as below:
import math
def apply_mask(scores, allowed_tokens):
masked = {}
for token, score in scores.items():
if token in allowed_tokens:
masked[token] = score # keep it
else:
masked[token] = -math.inf # block it
return masked
Here, we have:
scores, which are the logits the LLM gave to each token.allowed_tokens, which the state machine gives us for the current state.- For each token, we keep its score if allowed, otherwise we set it to minus infinity.
After this, the normal picking happens on the masked scores. This function is the core of Constrained Decoding.
Note: Many hosted LLM services now offer a built-in feature, often called structured outputs. We just pass a schema, and the service makes sure the output follows it, so we do not need to touch the logits ourselves.
If we want to go deep into LLM Inference Engineering and Hugging Face, we cover them in our AI and Machine Learning Program at Outcome School in depth.
Constrained Decoding vs asking in the prompt
Let me tabulate the differences between asking in the prompt and Constrained Decoding for your better understanding.
| Point | Asking in the prompt | Constrained Decoding |
|---|---|---|
| How it works | Makes the right format more likely | Makes the wrong format impossible |
| Valid format guaranteed | No | Yes, the shape always follows the rules |
| Needs retries on failure | Yes, sometimes | No, for format errors |
| Changes the LLM | No | No, it only filters choices |
| Extra setup | None | A schema, regex, or grammar |
| Speed | Normal | Small extra cost per step, sometimes faster due to forced tokens |
| Content correct | Not guaranteed | Not guaranteed |
Here, the last row is very important. Neither approach guarantees that the content is true.
Where it works well and where it fails
Where it works well:
- Apps that read LLM output with code. JSON for APIs, forms, and data extraction always has the shape the parser expects.
- Classification. The output is always one of our fixed labels.
- Tool calling. When an LLM recommends a function call, the arguments must match the function's expected shape. Constrained Decoding guarantees this.
- Code and query generation. A grammar can force the output to follow the syntax of SQL or a programming language.
- Small models. Small models follow format instructions less reliably, so Constrained Decoding helps them a lot.
Where it fails or needs care:
- Valid shape, wrong content. The mask guarantees the format, not the truth. The LLM can still write
"age": 25when the right answer is 30. The shape is correct, but the fact is wrong. - Too strict rules can hurt quality. If we force the LLM into an unnatural path, it has to pick from tokens it did not like much. Some studies have found that forcing a strict format can lower the reasoning quality on some tasks. A common fix is to let the LLM think freely first, and then constrain only the final answer.
- Getting stuck. If the rules allow a string to go on forever, the LLM can keep writing and never close it. We must set a maximum length.
- Needs access to the scores. We can only apply a mask if we can touch the logits. With our own model, this is easy. With a hosted service, we depend on whether they support it.
So, the best practice is this. We use Constrained Decoding to guarantee the shape, and we still check the content in our app code.
Now we must have understood how Constrained Decoding works, and where it works well and where it fails.
Frequently Asked Questions
Does Constrained Decoding retrain or change the LLM?
No. Constrained Decoding does not change the LLM and does not retrain anything. The LLM still gives a score to every token as usual. Constrained Decoding only steps in right before a token is picked and sets the score of every token that breaks the rules to minus infinity, so those tokens can never be picked.
Does Constrained Decoding guarantee a correct answer?
No. Constrained Decoding guarantees the format, not the truth. The output always has the right shape, but the LLM can still write a wrong value, like an age of 25 when the right answer is 30. So, we use Constrained Decoding to guarantee the shape, and we still check the content in our app code.
Does Constrained Decoding make generation slower?
Only a little. Before decoding starts, the library makes a list of allowed tokens for every state of the state machine, so finding the mask at each step is just a quick lookup. It can even be faster, because forced parts of the output can be added directly without running the LLM for those steps.
Can we use Constrained Decoding with a hosted LLM service?
Yes, if the service supports it. We can only apply a mask when we can touch the logits, which is easy with our own model. Many hosted LLM services offer a built-in feature, often called structured outputs, where we just pass a schema and the service makes sure the output follows it.
That's it for now.
Thanks
Amit Shekhar
Founder @ Outcome School
You can connect with me on:
Follow Outcome School on:
