In this episode, our agent stops misspelling the okapi, with no training at all. Last time, its graph role copied the name wrong into its Cypher queries, and smollerGraph found nothing. Today, before each token inside a query's name, the tokens that would take the name off a list get a logit of minus infinity, which is how structured outputs keep a model to a JSON schema. We build it from scratch, with a trie of the vocabulary's tokens walked together with a trie of the names, a byte at a time. The obvious list, the names the graph has, turns the okapi into the oak titmouse, a real name and the wrong animal. The second list, the words of the task, gets it right, and we measure both on the graph role's held-out questions, and the task's words on the agent's tasks.
The code
Each step on screen is a tag in the code's repository. The code at the end of the episode is ep026/end.
Transcript
Intro
0:00 Hello and welcome back to episode twenty-six, where we change how our agent picks its tokens, so that a name in one of its queries has to come from a list, and it can't misspell the okapi. Let's begin with a quick look at where we're going to be by the end of the episode.
0:16 By the end of today, we ask our agent whether the okapi and the giraffe share a family. Its graph subagents copy each name into their queries letter for letter, and both are in Giraffidae, as the okapi is the giraffe's closest living relative. And asked how much heavier the okapi is than the lion, the agent gets both weights from smollerGraph, and the calculator gives about ninety-three thousand grams.
0:41 On the website of the series, you can find more information about the project. The code is open source on GitHub, tagged at each step of each episode, so that you can follow along, and the docs get a page on constrained decoding today. And each episode has a page here as well, with its chapters and its code.
1:00 Now, before we get to today's work, let's quickly go over what we did last time. Our agent got a fourth role, graph, which writes a Cypher query for smollerGraph, the graph database we build from scratch in a series of its own, and hands its sentence back to the agent. So the agent can put facts from the graph and sums from the calculator together, and it did about eighty-eight percent of its new tasks right, in the wordings it trained on. But asked about the okapi, the graph role copied the name wrong into its query, as Oakapi or Ookapi, and sg found nothing. Today, we don't train anything, and change how the model picks its tokens, so that a name in a query has to come from a list.
1:42 Today, before each token of a name in a query, we set aside the tokens that would take the name off a list, and the model picks the likeliest of the rest. The first list is the names the graph has, which is the obvious one, and we're going to see where it goes wrong. The second is the words of the task, so that the name has to be copied from it. And we measure both on episode twenty-four's questions, and the task's words on last episode's tasks as well, against the model writing freely. All right, let's get started with what the model picks its tokens from.
Masking the logits
2:12 At each step, the model gives a score to each token of its vocabulary, thirty-two thousand seven hundred and sixty-eight of them, and those scores are the logits. Softmax turns them into probabilities: e to the power of a token's logit, over the sum of them all, and we pick the likeliest token, greedily. Constrained decoding adds a mask to the logits before that: zero for a token that's allowed, and minus infinity for one that isn't. E to the minus infinity is zero, so a token that isn't allowed gets no probability, and the allowed ones share the model's probability out between them, in the proportions it gave them. The model's weights don't change, and nothing is trained. This is how production models keep a response to a JSON schema, in Claude's structured outputs, say, and in libraries such as Outlines.
3:00 The list is of names, and the model writes tokens, which are pieces of text of any length: an O, an A K, or an I with a quote, a brace and a bracket after it. So we put each token's bytes in a trie, a tree where each node is some bytes, with a child for each byte that can come next. A token ends at a node, and the node keeps its id. The names go in a trie of their own. From the node the name has got to, we walk both tries at once, a byte at a time, and a token is allowed as long as its bytes stay on a name. At the end of a name, the closing quote is allowed, and a token can carry on past it, with anything after the quote.
3:41 It all goes in a new file, constrain dot py. It imports torch, for the mask, and read facts from episode twenty-four's graph data dot py, which reads smollerGraph's facts file. Openers are the two ways a name starts in the graph role's queries: a brace, name, a colon and a single quote, or a double quote for a name with an apostrophe, like Finsch's francolin. They're bytes, as the text is going to be. The comment over them says what the file does. Before each token is picked, the tokens that would take the text out of what's allowed get a logit of minus infinity, so softmax gives them no chance, and the model picks the likeliest of the rest. Here, what's allowed is a name: inside a query's quotes, the model writes one of a list of names, and closes the quote after it. Then the trie, and its docstring says what it holds: byte strings that share their beginnings, with a node for each prefix, and a child for each byte that can follow. A node has its children, in a dictionary from a byte to the next node, and end, which says that a string ends there. Ids is for the vocabulary's trie, the tokens whose bytes end at the node, and under is the tokens at a node and below it, which we work out once, the first time it's needed. Add walks a string's bytes from the root, making each child that isn't there yet, then marks the end, and keeps the token's id when there is one. Find walks some bytes down, and returns the node it gets to, or none when the bytes leave the trie. All ids collects the tokens under a node, which are the tokens whose bytes start with the node's, and keeps them in under. We need those at the end of a name, where each token that starts with the closing quote is allowed, whatever comes after the quote in the token. Vocabulary puts each token's bytes in a trie, from the tokenizer's token bytes, which our BPE tokenizer from episode eleven keeps for decoding. Its docstring says why: the tokens that start with some bytes are one walk away. A list would have us go through all thirty-two thousand tokens at each step. Allowed is the heart of the file, and it takes the vocabulary's trie, the node of the names' trie that the name has got to, and the quote that opened the name. Its docstring says what it returns: the tokens whose bytes carry on from that node, along a name, or to its end and through the closing quote, after which a token can hold anything. It keeps a stack of pairs of nodes, one in each trie, starting from the vocabulary's root, and works through it until it's empty. Each pair is a node of the vocabulary, and the node of the names that those bytes reach. As the comment says, the two tries are walked together, a byte at a time, and a token is allowed as long as its bytes stay on a name. For each byte the names allow next, it looks for the vocabulary's node on that byte. A byte that's the opening quote is skipped, and its comment says why: it would close the quote, and a name with an apostrophe goes in double quotes. Without it, Turner's eremomela, in single quotes, would end as Turner. If a token's bytes can go that way, the tokens that end there are allowed, and the pair goes on the stack, to look a byte further. And when a name ends at a node, the closing quote is allowed, along with each token that starts with it, so the tokens after the name are free. Names is the constraint, and its docstring says how it's used: given the bytes written so far, it returns the tokens allowed next, or none, for any token. It keeps the vocabulary, and puts the names in a trie of their own, as bytes. Its allowed finds the last opener in the text with r find, which searches from the end, and when there's none, any token goes. The quote is the opener's last byte, and the name is what's been written since. If the quote is in it, the name is closed, and any token goes again. Otherwise, it finds the name's node, and the allowed tokens. As the comment says, when the name is off the list already, say a name that started before the constraint was on, or when no token can carry it on, the model writes it on its own. A mask with nothing allowed would leave it nothing to pick. Graph names is our first list, and its docstring says it: each name in the graph role's queries is a node's name, from the facts file that sg serve loaded. It builds the names once, from read facts, and returns a function of a role and a task, so that the graph role gets the constraint, and the other roles get none. Written is the text so far, as bytes, as the tries hold them, joined from each token's bytes. As the comment says, a token can end in the middle of a character, as an e with an accent is two bytes. Decoding half of one would give a replacement character instead. And pick is the mask, and its docstring says it: the likeliest token, or the likeliest of the allowed ones. When there's a list, it makes a mask of minus infinity the size of the logits, sets the allowed tokens to zero, and adds it to the logits, and either way, the token is the argmax. Main lets us watch the graph role write a query. It imports argparse, for the command line, prompt from agent dot py, which writes a role's first lines, the checkpoint loader, and the KV cache and pick device from the model. Its parser's description says what it's for: the graph role writing a query, a token at a time, with its names kept to the graph's. It takes the checkpoint, a task and the facts file, which is all it needs, as it doesn't send the query to sg serve. It loads the model on the GPU, in eval mode, and gets the graph role's constraint for the task. The prompt goes through the model once, with episode four's KV cache, so that each step after it is a single token. It prints a header: the name so far, the most likely token, how many tokens are allowed, their share of the probability, and the token picked. The loop runs up to the end of the query, as the comment says, as sg serve's answer would come after it. At each step, it asks the constraint for the allowed tokens, and picks. While a name is being written, softmax gives the probabilities, and as the comment says, the row shows the likeliest token, and how much of the model's probability the allowed tokens have between them. The name so far is what's been written since the last name and colon, decoded for printing, and the row pads each column to the header's width, so the table lines up. Then the token goes through the model, and main prints the prompt and the query. The tests use a tokenizer of the two hundred and fifty-six bytes and a few merges, so we know each token it has. The first walks the okapi's name with the oak titmouse on the list, and after the O, it allows the K of okapi, and the A and the A K of oak titmouse. At the end of a name, the quote closes it, and a token can run on past it. The others check that a name's constraint is off outside a name, or once the name is off the list, and that the double quotes, a name with an accent, and the mask work.
10:35 We run the new tests with pytest, and all five pass, with no model, as they check the allowed tokens and the mask, on a tokenizer of a few merges.
The graph's names
10:45 We ask the graph role for the okapi's weight, with the graph's names on the list, and watch each step of the name. At the opening quote, about six hundred tokens are allowed, and the most likely, an O, is one of them. After the O, the most likely is A K, at about twenty-five percent, and A K is allowed, because the graph has an oak titmouse. After oak, the most likely is A P, for oakapi, but the allowed tokens have almost none of the model's probability between them, and the likeliest of them is a space and a T. From there, the list makes it carry on: after the T, the most likely is still A P, and from tit on, the model would close the quote. It carries on to the oak titmouse, which is a real name, and the wrong animal.
11:29 Next, the agent, in episode twenty-one's agent dot py, which runs each context, the agent's and each subagent's, a token at a time. It imports pick and written from constrain dot py. The agent takes constrain, a function from a context's role and task to a constraint. As the comment says, that gives what a context may write: a constraint, or none, to write freely. With no function, each context writes freely, as before. When a run starts, it asks for its constraint, so that a graph subagent gets one for its own task. And at each step, the token is pick's, with the tokens the constraint allows, where it used to be the argmax. The command line gets dash dash facts, the facts file, which keeps the graph role's names to the graph's. The test scripts a graph subagent that writes the okapi with a U at the end, and checks the query the agent would send to sg serve. The constraint picks the I, the one token that keeps the name on the list.
12:31 Then the agent, asked how much heavier the okapi is than the lion, with the graph's names. Its graph subagent asks for the oak titmouse, whose weight the graph doesn't hold. So the agent says that the graph doesn't say how much the okapi weighs, and can't answer. That reads like a fair answer, and it's wrong, as the graph has the okapi's weight.
Names from the task
12:54 So the graph's names keep a name real, and that's all they do. The likeliest token can lead to a real name that isn't the one asked about, as it did with the oak titmouse. And an animal the graph hasn't got, like the Komodo dragon, has to become a name the graph has, so the graph role can hardly ever find nothing and say so. What we do know is that the name in the query is the one in the task. So the second list is the words of the task, and the name has to be copied from it, as a word or a run of words.
13:25 In constrain dot py, we import re, Python's regular expressions. Task words is the second list, and its docstring says it: each name in the graph role's queries is copied from its task, a word or a run of words. It builds the vocabulary's trie once, and for each graph context, it makes names from the runs of words in that context's task. Runs finds each word, as a run of characters that aren't spaces, and the comment gives an example: the okapi weigh, with its question mark, gives the, the okapi, the okapi weigh, okapi, okapi weigh and weigh. Then it returns each run of whole words, from any word to any word after it, without a question mark or a full stop at its end. A task is a few words long, so that's a few dozen runs, and the name is one of them. Main's description now says that the names are kept to a list. It takes dash dash names, task or graph, with the task's words by default, and dash dash facts, for the graph's names. It picks the constraint from them, the graph's names with graph, and the task's words otherwise, and then asks it for the graph role's constraint for the task. In agent dot py, main imports task words as well. Its command line gets dash dash names too, task or graph, which says where the graph role's names come from, and dash dash facts is now for the graph's names. Then it picks the constraint: none without dash dash names, the task's words with task, and the graph's names, from the facts file, with graph. And the test checks the runs of two tasks, and that the agent's own context writes freely. After the O, the okapi is all its task allows, while a Komodo dragon can still be copied, for sg to find nothing.
15:12 We ask for the okapi's weight again, with names copied from the task. At the opening quote, about fourteen tokens are allowed, the ones that start a run of the task's words. After the O, the most likely is still A K, and the two tokens allowed have about zero point one percent of the model's probability between them. The likeliest of them is K, and after O K, the model is sure of the rest: A P, then I, then the quote, each at about one hundred percent, so the query asks for the okapi.
Measuring it
15:45 Constrain eval dot py measures the two lists against the model writing freely. It imports argparse, json, os, re for the names in the queries, and time, to time each question. Then episode twenty-four's graph data and episode twenty-five's graph agent data, as modules, for their held-out sets, and the agent, with attempt and summary from episode twenty-one's agent eval. From constrain dot py, it takes the two lists, and from graph agent eval, facts, which reads the facts a task needs from its example. Graph sets are episode twenty-four's held-out questions, which we ask the graph role on its own: seen, phrasing, and missing, about animals the graph hasn't got. New sets are episode twenty-five's held-out tasks, for the agent. Name finds a name in a query, in single quotes, or in double ones, and the comment gives the okapi as an example. Measure's docstring says what it returns: each example's attempt, summed up, with the seconds an example took, and how often a query named something the graph hasn't got, a name copied wrong, or an animal that isn't in it. It starts a timer with time's perf counter, attempts each example, and sums them up with summary. The seconds are the time over the number of examples. Then it reads the names out of each run's trace, the agent's and its subagents', and looks each one up in the graph's nodes. Main's parser says what the script is for: what keeping the graph role's names to a list does to its answers. It takes the checkpoint and the facts file, with dash dash limit for a quick look at the first examples, and dash dash server, for where sg serve is listening. It loads the model on the GPU, names the results after the checkpoint's folder, graph agent here, and reads the graph's nodes from the facts file, to tell a name the graph has from one it hasn't. The modes are the three ways of writing the queries, as the comment says: freely, with the graph's names, and with names copied from the task. The results start with the model's name and an empty dictionary for each table. Agent for makes an agent with a mode's constraint, for attempt to run each example in a sandbox of its own. The first table is the graph role on episode twenty-four's questions, with a column for each mode, and how often a query named something off the graph. For each set, it puts each question under the graph role's line with as role, from last episode, and measures it in each mode. It keeps three wrong answers for us to read, and prints the row, with each mode's share right, and the share named off the graph. The second table is the agent, on episode twenty-five's tasks, as the comment says, with its graph subagents writing freely, then copying their names from their tasks. The first table is enough to show what the graph's names do, so they're left out here, and the agent's modes are free and task. For each set and each of the two modes, it measures the tasks, and the comment asks whether the graph subagents brought back what the task needs. Facts right compares what each ask graph call got back with the facts the example says it needs, as last episode did. Then it keeps three wrong answers, and prints the row. So for each set, the free run and the copied names sit next to each other, with the share of the facts that came back right for each. Then the seconds a question takes for the graph role: it averages each mode's seconds over the three sets. As the comment says, that's the model's steps, the queries to sg serve, and the masks, all in one number, and it prints them, a mode at a time. And last, as the comment says, with the graph's names, an animal the graph hasn't got becomes one it has, so it prints the first wrong answer of the missing set under the graph's names. It saves it all to results, as constrain, then the model's name, dot JSON, for the charts to read. And at the bottom, the file runs main when it's run as a script.
19:34 We run it with the facts file, and sg serve on port eighty-four eighty-four. It asks the graph role six hundred questions three ways, and the agent six hundred tasks two ways, which takes about half an hour. The last column of the first table is how often a query named something the graph hasn't got. Writing freely, that's about nine percent of the seen questions, which are names copied wrong, and with the graph's names, about one. The seconds a question takes come out about equal in each mode, so the masks cost too little to see next to the model's passes. And at the end, a missing animal under the graph's names: the marine iguana, which the graph hasn't got, became the marine otter. So the graph role says that the marine iguana is in Mustelidae, the family of otters and weasels.
20:25 Side by side, on episode twenty-four's held-out questions. Writing freely, the graph role gets about eighty-eight percent of the seen questions right. With the graph's names, about ninety-three, as some of the names it copied wrong come out right. With names copied from the task, about ninety-six. In the new wordings, the task's words take it from about seventy-seven to about eighty-two percent, and most of the misses left name an animal the graph has, so they go wrong somewhere other than the name. On the animals the graph hasn't got, writing freely gets about ninety-three percent right, and the graph's names take it down to about thirteen, as most of them become an animal the graph has. And the task's words keep the missing animals' names, at about ninety-seven percent.
21:13 And the agent, on last episode's held-out tasks, with its graph subagents copying their names from their tasks. In the wordings it trained on, it goes from about eighty-eight to about ninety-six percent, and with a fact missing from the graph, from about eighty-nine to about ninety-five. In the new wordings, from about thirty-four to about thirty-six. As last episode found, most of those misses are the agent reading a new wording as a task it knows, and the names don't change that.
Asking it
21:41 Now a few tasks of our own, starting with whether the Komodo dragon is a mammal or a bird, asked with the graph's names. The graph role asks for the Komodo rat, and the agent answers that the Komodo dragon is a mammal. With names copied from the task, the query asks for the Komodo dragon, and the agent says the graph has no species of that name, which is right, as the graph holds mammals and birds. Turner's eremomela has an apostrophe, so its query puts the name in double quotes, and the constraint keeps the name whole. And the okapi against the Baikal seal, last episode's demo from training, gets both weights right now. But the agent copies ninety thousand as nine thousand into its sum, and the math role writes the answer as twenty-four, then tern, the name of a bird, where the calculator gave two hundred and forty-one thousand. Names aren't all the model copies, and the numbers it copies could go through a constraint as well, a list of the numbers in its context, say.
22:39 And the docs get a page on constrained decoding: the mask, the two tries, the two lists, and the two tables. It goes at the end of the navigation, after last episode's page on the agent asking the graph, the docs' home page lists it, and the README gets the commands.
Wrap-up
22:55 Now, let's go over what's real here, and what's scaled down. A mask on the logits at each step is how production models keep their output to a JSON schema or a grammar. And a token rarely lines up with what's allowed, so they check the tokens' bytes against it too, as we did. What's scaled down is what we keep to a list: the names in one kind of query. A grammar would cover the whole query, its brackets, labels and properties, and the Outlines library, say, turns a regular expression or a grammar into a state machine for that. And we walk the tries in Python at each step, where Outlines builds an index over the vocabulary once, from the state machine's states, so that each step is a lookup.
23:38 So, today, our agent's graph role picks its tokens through a mask, and nothing was trained. The allowed tokens come from two tries, the vocabulary's and the names', walked together a byte at a time. The graph's names keep a name real, not right: the okapi became the oak titmouse, and a missing animal became one the graph has. Copied from the task, the okapi's name comes out right. On episode twenty-four's questions, the graph role went from about eighty-eight to about ninety-six percent in the seen wordings, and on last episode's tasks, the agent from about eighty-eight to about ninety-six.
24:15 If there's a name you think our agent would get wrong, a bird or a mammal with a long name, say, let me know in the comments, and I'll try it. And if you'd like to follow along, subscribe to the channel. I hope you find this useful, and thanks for watching.