{mvGPT}
  • Episode 27
  • 26 min

Speculative decoding from scratch

A draft guesses the next few tokens, and our agent checks them in the pass that writes its own, so it writes what greedy decoding writes in fewer passes. Two drafts, prompt lookup and a small model trained for thirty minutes, measured on the agent's tasks.

Watch on YouTube

Open in Colab

In this episode, our agent writes its answers word for word as before, in fewer passes of the model. A pass on the Mac's GPU costs about the same for a few tokens as for one, so a cheap draft guesses the next few tokens, and the model checks them in the pass that writes its own, keeping the guesses up to the first it disagrees with. We build speculative decoding from scratch, with two drafts: prompt lookup, which guesses what the text copies for nothing, and a small model of four layers, trained for thirty minutes on the agent's tasks. Then we measure both on episode twenty-five's held-out tasks: the passes, the guesses kept, the time, and whether the text is the same.

Topics: Inference, Performance

The code

Each step on screen is a tag in the code's repository. The code at the end of the episode is ep027/end.

  1. 1:58ep027/step-1A pass, by its tokensBrowseChanges
  2. 5:34ep027/step-2Guess, then checkBrowseChanges
  3. 10:39ep027/step-3A draft modelBrowseChanges
  4. 16:13ep027/step-4In the agentBrowseChanges
  5. 19:21ep027/step-5Measuring itBrowseChanges
  6. 23:51ep027/step-6Measuring itBrowseChanges

Transcript

Intro

0:00 Hello and welcome back to episode twenty-seven, where our agent writes its answers word for word as before, in fewer passes of the model, as a draft guesses the next few tokens. Let's begin with a quick look at where we're going to be by the end of the episode.

0:15 By the end of today, our agent writes the graph role's query for the king penguin's weight in fewer passes than tokens. Each line is one pass of the model: its own token in brackets, then the guesses of a small draft model that it checked and kept. It's about thirty-two tokens in seven passes, and the text is the one the model writes a token at a time.

0:36 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 speculative decoding today. And each episode has a page here as well, with its chapters and its code.

0:55 Now, before we get to today's work, let's quickly go over what we did last time. We changed how the agent's graph role picks its tokens, with a mask on the logits that keeps a name in a query to a list. With names copied from the task, the okapi came out right. And on episode twenty-five's tasks in the wordings it trained on, the agent went from about eighty-eight to about ninety-six percent right. Today, we keep each answer as it is, word for word, and change how many passes of the model it takes to write it.

1:28 Today, we start with what a pass of the model costs, by the number of tokens in it. That gives us speculative decoding: a cheap draft guesses the next few tokens, and the model checks them all in the pass that writes its own. The first draft costs nothing, as it guesses from the text so far. The second is a small model, which we train for thirty minutes on the agent's tasks. And we time the agent's tasks with each, against the model writing a token at a time. All right, let's get started with what a pass costs.

A pass, by its tokens

1:58 Speculative bench dot py times a forward pass by the number of new tokens in it. It imports statistics, for the median, and time, for the clock. From episode four's bench dot py, it takes sync, which waits for the GPU to finish before we read the clock, as a GPU runs what it's given in the background. It also takes the checkpoint loader, the results folder, the KV cache and pick device. New is the numbers of tokens to time, from one to sixteen, and context is the hundred tokens already in the KV cache, about the length of an agent's run, its prompt and what it has written so far. Pass ms returns the median time of a pass, and its docstring says so: a pass of new tokens, after the context in the KV cache, in milliseconds. It takes the model, the device, the number of new tokens, and forty repeats, as a GPU's timings move about from one pass to the next. Each repeat fills a fresh cache with a hundred random tokens, then times a pass of the new ones after them, with a sync before and after. The new tokens are random too, as their values don't change the time. As the comment says, the first passes on a device warm it up, so they're left out of the median. Main's parser says what the script measures, and it takes the checkpoint. It times the model on the GPU and on the CPU, or on the CPU alone, on a machine without a GPU. For each device, it loads the model, times each number of new tokens, and keeps the milliseconds a pass and a token. The milliseconds a token divide each pass's time by its tokens, which is where a pass of several tokens shows what it saves. Then it prints a table for each device, whose header names the device and the context it was timed after, then three columns: the tokens, the milliseconds, and the milliseconds a token. Each row is a number of tokens, the milliseconds a pass to one decimal place, and the milliseconds a token to two. The milliseconds a token is what a token costs when the model keeps each guess in the pass, and main saves it all to results, as speculative bench dot JSON. And at the bottom, the file runs main when it's run as a script.

4:05 We run it on episode twenty-five's agent, with nothing else running on the Mac, first on its GPU, then on its CPU, and each table is a row per number of new tokens.

4:15 On the GPU, a pass of one token takes about seven milliseconds, a pass of five about ten, and a pass of sixteen about eleven. As we saw in episode four, with a model this small, most of a pass at batch one goes into launching its operations, so the arithmetic for a few more tokens is a small part of it. On the CPU, one token takes about six milliseconds as well, two take about sixteen, and the line stays about there up to sixteen. So on the GPU, the model could check four guesses in not much more than the time of one token, and on the CPU, in a little over twice that.

Guess, then check

4:51 Speculative decoding comes from Leviathan and colleagues at Google, at the end of twenty twenty-two, and Chen and colleagues at DeepMind, early in twenty twenty-three. A draft, which is anything cheaper than the model, guesses the next few tokens. The model takes its own next token and the guesses in one pass, and its logits at each position say what it would write after it. A guess is kept while it's the token the model would write there, so we keep the guesses up to the first it disagrees with. And the model's own token at that point comes free, from the logits of the pass. With greedy decoding, the text is the one it writes a token at a time, so the draft can be as wrong as it likes: a wrong guess costs some time, and each pass still writes the model's own token.

5:35 First, the KV cache from episode four gets a method, trim, which takes how many of the newest tokens to drop. As the comment says, it drops their keys and values, the guesses speculative decoding didn't keep, and it moves the position back too, so the next token's rotary embedding is the right one. Then speculative dot py, whose comment says what it does: a cheap draft guesses the next few tokens, and the model checks them all in one forward pass. At batch one on a GPU, a pass costs about as much for a few tokens as for one, as with a model this small, most of its time goes into launching its operations. The model keeps the guesses up to the first it disagrees with, and its own token there, so the text is the one greedy decoding writes, in fewer passes. The first draft is lookup, known as prompt lookup decoding, and its docstring says how it guesses: from the text so far, what came after the last time its last few tokens were written. An answer copies names and numbers from its task and from what the tools gave back, and those it guesses for nothing. It takes k, how many tokens to guess, and longest, the longest tail of the text to look for, three tokens. Guess tries the last three tokens first, then two, then one. As the comment says, it finds the latest earlier place that tail was written, and returns the tokens after it there, up to k, or nothing, when the tail wasn't written before. The second draft is a small model with the agent's tokenizer, so each token it guesses is one the model can check, and it guesses greedily, with a KV cache of its own. Fed is the list of tokens its cache holds, so it knows what's in there. Guess first finds how much of the text the cache already has: the tokens it was fed that are still the text's. As the comment says, it keeps those, and the rest of the text goes in after them. And at least the last token goes in, even when the cache has it already, for the logits after it. So when the model turns down some guesses, the draft drops them as well, and carries on from the text the model kept. Then it writes k tokens greedily: it takes the argmax, and, for each guess but the last, feeds it back in through the small model, with its cache, for the logits after it. It returns the k guesses, and fed now holds the text and each guess but the last, which didn't go in. Passes is the decoding loop, and its docstring says how it's used: greedy decoding after the prompt, a pass at a time. Each pass yields the tokens it wrote, the model's own and the guesses it kept, and how many guesses it was given, and the caller stops when it has what it needs. The prompt goes through once, with a KV cache. Then, as the comment says, each pass starts from the model's own next token, from the logits of the pass before, and the draft's guesses at the tokens after it, as many as the context has room for. The token and the guesses go through the model in one pass. The argmax at each position is the token the model writes after it, and as the comment says, a guess is kept while it's that token. So the first guess is kept if it's what the model writes after its own token, the second if it's what it writes after the first, and so on. The guesses it didn't keep are trimmed off the cache, and the logits after the last one it kept give the next pass its token. Generate runs the passes up to the end of the text or a number of tokens, and returns the tokens and how many passes it took. Main shows a role writing up to its first call, a pass at a time. It takes the checkpoint, the task, the role, graph by default, the draft, lookup, a small model's checkpoint or none, and k, four by default. It prints each pass on a line, as the comment says: the model's own token in brackets, then the guesses it kept, up to the end of the call. At the end, it prints how many tokens took how many passes, and how many guesses were kept. The tests use tiny models of two layers. The first checks that the text is greedy decoding's, written a token at a time with no cache, with no draft, with lookup, with another tiny model as the draft, and with the model as its own draft. The second checks that the model as its own draft keeps each guess, five tokens a pass. Then lookup's guesses, and that a trimmed cache gives the logits the tokens it kept would give.

9:52 We run the tests with pytest, and all four pass, so with each draft, the text is the one greedy decoding writes.

10:00 We watch the graph role write its query for the king penguin's weight, with lookup as the draft. One guess is kept: after Y P, lookup finds cypher in the prompt's line of tools, and guesses H E R. The rest of the query isn't in the prompt, so lookup has nothing to guess, or guesses wrong. Even the name is a different token from the task's: in quotes, King starts without its space, as we saw last episode with the okapi. So it's about thirty-two tokens in thirty-one passes, with one of sixteen guesses kept. Lookup catches what an answer copies, and the query's template, written one way each time, is what a model of the agent's tasks would know.

A draft model

10:40 Draft SFT dot py trains that small model, and most of it follows episode twenty-five's graph agent SFT dot py. It imports math, for the cosine of the learning rate, prompt from agent dot py, and batches from episode twenty-one's agent SFT, which groups examples of like lengths. It imports the GPT and its config, to make a new model, and passes and the draft from speculative dot py, for the demo. From tool SFT, it takes encode, make batch and estimate loss, with the mask that leaves the prompt and the tools' results out of the loss. Run dir is checkpoints, draft, and the config is four layers of three hundred and eighty-four channels. The comment says why: a small GPT for speculative decoding, about a fifth of the agent, with its tokenizer, so each of its tokens is one the agent can check. The learning rate is one times ten to the minus three, and as the comment says, a small model from scratch takes a larger step than a fine-tune. It warms up over a hundred steps, evaluates each five hundred, and the demo is the king penguin's weight. Agreement measures the draft as a draft, and its docstring says what it is: the share of the held-out tokens the agent learned to write that the draft's likeliest token gets right. That's about the share of its guesses the agent would keep, one at a time. It runs the held-out examples through the draft in batches of thirty-two, and counts the positions where its argmax is the target, among those with a target. Main fixes the seeds, for torch and for Python's random, which shuffles the batches, so each run draws them in one order. It picks the GPU, and loads episode twenty-five's agent, as the comment says, for its tokenizer and its block size, and to check the draft's guesses in the demo. The agent comes back with its tokenizer, which the draft shares. It puts the agent in eval mode, as it isn't trained here. The draft is a new GPT with the agent's vocabulary and block size, rotary embeddings and the small config, and main prints the two models' sizes, the draft's parameters and the agent's, in millions, so the fifth shows on screen. As the comment says, it trains on episode twenty-five's training set, the agent's own tasks and its subagents', which the agent was trained to write, so the draft learns what the agent learned. Each example is encoded with its mask, the held-out set is the seen set, as in episode twenty-five, and main prints how many examples there are, and how many tokens to learn. The optimizer is AdamW, with weight decay on the matrices and none on the biases and gains, as before, and the writer logs the run for TensorBoard. Each evaluation measures the held-out loss and the agreement. Then, as the comment says, it writes the graph role's query for the demo, a pass at a time, with the draft guessing four tokens, up to the end of the query. It counts the query's tokens and passes, puts the draft back in training mode, as the demo's draft is the model being trained, in eval mode for the demo, and logs the loss and the agreement for TensorBoard. Then it prints a line with the step, the held-out loss, the agreement, and the query's tokens and passes. The budget is the minutes, in seconds, and main evaluates once at step zero, before any training. The loop runs until the budget is spent. As the comment says, the learning rate warms up, then follows a cosine down to zero as the time runs out, as the run is measured in minutes, not in steps. The warm-up is the step over a hundred, up to one, and the cosine is one at the start and zero at the end. Each step sets the rate on the optimizer's groups. The rest is the loop from episode twenty-five. When the queue runs out, batches fills it again, in a new order. A batch of like-length examples, the next off the queue, made into inputs and targets by make batch. The forward pass gives the loss, the old gradients are cleared, the backward pass makes new ones, they're clipped to a norm of one, and the optimizer takes a step. Then the counts of steps and examples seen go up. Each fifty steps, it gives the GPU's memory back on the Mac, and logs the batch's loss for TensorBoard. It prints how far it's got, the loss, the learning rate and the minutes so far, so the run can be followed from the terminal as it trains. And each five hundred steps, it runs the evaluation above. When the time is up, the loop ends, wherever the step count got to. At the end, it saves the draft to checkpoints, draft, and prints the steps, the examples and the passes through the training set. Thirty minutes is the default, when no number is given on the command line.

15:09 Then thirty minutes on the Mac, with nothing else running on it. The draft has about twenty million parameters, against the agent's one hundred and ten million, and it starts from random weights, so at step zero it agrees with none of the held-out tokens the agent learned to write. Each five hundred steps, it prints the held-out loss, the agreement, and how many passes the demo's query took with its guesses. It ends agreeing with about ninety-six percent of those tokens, from about eighty-one percent at step five hundred, and the demo's query takes seven passes. In thirty minutes, it takes about eight thousand steps, about five point five passes through the training set, as a step of the small model is much quicker than one of the agent.

15:52 The graph role's query again, with the draft model's guesses. It knows the template: after the model's M A T, it guesses the rest of match, the bracket and the S, and the model keeps them. So the query takes about seven passes for its thirty-two tokens, with twenty-six of twenty-eight guesses kept, where lookup took thirty-one.

In the agent

16:13 In the agent, the loop gets that check too, with two more things to look after: last episode's constraint, and the tools' calls. The agent takes a draft as well, next to the constraint. As the comment says, those are guesses at the next tokens, from speculative dot py, which the model checks in the pass that writes each token, along with how many it was given and kept. In run, after holds the logits for the next token, from the prompt's pass to begin with. Allowed asks the constraint for the tokens allowed after the text so far, or none, without one. Write is what the loop did with each token before, moved into a function, so that a kept guess goes through it as well. Its docstring says it: it writes a token, and runs the call the token closes, returning the tool's result's tokens, or none. It appends the token, decodes the text, and as before, notes where a call opens and runs it when it closes, with the result's tokens going on the end. It's the code from episode twenty-one, with a return where the tool's tokens used to join the new ones. Done is for a guess that ends the text. The loop picks the model's own token through the mask, as before, and stops at the end of the text. If the token closes a call, then as the comment says, it goes through the model together with the tool's result, as it did before, with no guesses. Otherwise, room is what's left of the token budget and of the context, so a pass doesn't run past either. The comment over it says what goes through the model: the draft's guesses at the tokens after the token, with it, in one pass. Kept counts the guesses it keeps, starting from zero. As the comment says, a guess is kept while it's the token the model picks after the ones before it, through the mask, so a guess that would take a name off its list is turned down. A kept end of text ends the run, and a kept guess goes through write, so if it closes a call, the call runs, and the guesses after it are dropped. As the comment says, the guesses it didn't keep come out of the cache, and a call's result goes in after the ones it did. It adds up the guesses given and kept, and the next token comes from the call's result, or from the logits after the last guess it kept. And the run's text and tokens are updated after each pass, as before. Main imports the two drafts from speculative dot py, next to last episode's two lists of names. It takes dash dash draft, for lookup or a small model's checkpoint, and dash k, the tokens to guess in each pass, four by default. Draft starts as none, for no draft at all. With lookup, the draft is a lookup of k tokens, and with a checkpoint, main loads the small model on the GPU, in eval mode, as the draft's model. The agent goes in a variable now, so that after the run, main can print how many of its guesses were kept, across the agent and its subagents. The test has a stand-in model that writes its role's script by position after its prompt, so a pass of several tokens writes what a pass of one would. It checks that with lookup and with a draft model, the run is the one with no draft, along with the math subagent's, in fewer passes.

Measuring it

19:21 Speculative eval dot py times the agent's tasks with each draft. It imports argparse, json, os and time, then the agent, and attempt from episode twenty-one's agent eval, which runs a task in a sandbox of its own and checks it. It takes the checkpoint loader, task words from last episode, the server from episode twenty-four's graph dot py, the held-out sets from episode twenty-five, the results folder, pick device, and the two drafts. The sets are episode twenty-five's held-out tasks, as the comment says: seen, phrasing and unknown, six hundred in all. Counted wraps the model, and its docstring says it: the model, counting its forward passes. It keeps the model, its config, which the agent reads, and the passes so far. Calling it adds one to the passes and calls the model, and eval and parameters pass through to the model, as the agent uses those too. Main's parser says what it compares: the agent's tasks with each draft, against greedy decoding alone. It takes the checkpoint and the draft's, and dash k, the tokens to guess in each pass, four by default. Then dash dash limit, for a quick look at the first tasks of each set, and dash dash server, for where sg serve is listening. It loads the agent on the GPU, and the small model, in eval mode, and as the comment says, the graph role copies its names from the task, as in last episode. Examples is the six hundred tasks, the three sets one after the other. The drafts are none, lookup and the small model, each made fresh for each task's agent, so the draft model's cache starts empty for each task. The results start with the model's name and k, and greedy is empty until the first draft, none, has run. It prints the number of tasks and the guesses a pass, and a header. For each draft, counted wraps the model, with its passes from zero, and agents keeps each task's agent, so we can add up their guesses after. Agent for makes an agent for a sandbox, with the counted model, the server, the constraint and a fresh draft, and keeps it. Then it times the six hundred tasks, attempted one after another, and divides by their number. It adds up the guesses given and kept across the agents, and keeps each task's trace, the tree of the agent's and its subagents' runs. With no draft, the first time round, those traces and seconds become greedy's. For each draft, it keeps the share right, the seconds a task, the model's passes a task, the guesses given and the share kept. Then the share of tasks whose trace matches greedy decoding's, each run's calls, results, last sentence and length, subagents and all, and how many times faster than greedy decoding the draft is. It prints the draft's row, each column padded to the header's width, and saves the results as speculative, then the model's name, dot JSON. And at the bottom, the file runs main when it's run as a script, like the others.

22:20 And the agent, with last episode's names copied from the task, and the draft model, asked how much heavier the okapi is than the lion. It answers about ninety-three thousand grams, as in last episode, from the calls it made then. Across the agent and its three subagents, about one hundred and twenty-two of its one hundred and seventy-six guesses were kept.

22:41 We run it on the six hundred tasks, with sg serve for the graph's queries, which takes about twenty-five minutes. Each way gets about seventy-six percent of the tasks right, and with each draft, a hundred percent of the traces match greedy decoding's: the calls, the results, the answers and the lengths, subagents and all. With no draft, a task takes about one hundred and forty-three passes of the model, across the agent and its subagents, and about one point zero second. Lookup keeps about thirty percent of its guesses, and takes a task to about one hundred and one passes. The draft model keeps about seventy-nine percent, and takes it to about forty passes, about three point five times fewer.

23:20 In seconds, a task takes about one point zero second a token at a time. With lookup, about zero point seven nine, so about one point three times faster, for nothing but a search through the text. With the draft model, about zero point six nine, about one point five times faster. The draft cuts the passes by more than three times, and the time by less. A pass with four guesses takes longer than a pass of one token, and the four guesses are four passes of the small model, whose time at batch one goes with its four layers more than with its size.

23:52 And the docs get a page on speculative decoding: what a pass costs, the check, the two drafts, and the agent's tasks with each. It goes at the end of the navigation, after last episode's page on constrained decoding, the docs' home page lists it, and the README gets the commands.

Wrap-up

24:09 Now, let's go over what's real here, and what's scaled down. Checking a draft's guesses in one pass is how serving systems such as vLLM speed up a model at small batches, and prompt lookup and small draft models are two of the drafts they offer. What's scaled down is that we decode greedily, so a guess is kept when it's the model's argmax. When a model samples, Leviathan's and Chen's papers keep a guess with a probability from the two models' probabilities. At the first one turned down, they draw the model's token from what's left of its distribution, so the text has the model's distribution, and that's a few lines more. And the draft guesses one line of tokens. Methods such as Medusa and EAGLE guess a tree of them, with small heads on the model, and check the whole tree in one pass.

24:57 So, today, we started from what a pass costs: on the Mac's GPU, about as much for a few tokens as for one. So a draft guesses the next few tokens, and the model keeps them up to the first it disagrees with, which keeps the text greedy decoding's. Lookup guesses what the text copies, for nothing. A small model of four layers, trained for thirty minutes, guesses the templates as well, and agreed with about ninety-six percent of the held-out tokens the agent was trained to write. And on episode twenty-five's tasks, the agent's traces came out as greedy decoding's in fewer passes, about one point five times faster with the draft model.

25:36 If there's a part of the agent you'd like to see made faster, or a draft you'd like to try, let me know in the comments. And if you'd like to follow along, subscribe to the channel. I hope you find this useful, and thanks for watching.