Lecture guides›
✎

Lecture guide: Guest lecture: Dan Fu#

Lecturer: course staff · Course: Stanford CS336 Language Modeling from Scratch, Spring 2026, lecture 18 · Length: 1:12:00 Video: watch on YouTube Chapters that cite this lecture: 13. Building Your Own: A Roadmap Through the Assignments

In one sentence: Dan Fu shows what happens to a request inside a serving system, the scheduling, the caches and the bugs that appear only at scale, and argues from two research projects, megakernels for decoding and a stabilized looped transformer, that understanding inference down to the kernels opens up whole-stack innovation.

Before you watch#

The lecture is the only one in the course given from the serving side, by a guest from UC San Diego and from Together, an AI cloud company. It assumes the GPU and inference lectures: what prefill and decode are, why decoding is bound by memory bandwidth, and what a KV cache holds. The video has no chapter marks. The roadmap chapter cites it for its takeaway; the details live in this guide and in the chapters on GPUs and on inference.

The lecture, part by part#

0:00–6:00 The view from the other side: serving models#

The course is about training models; Fu talks about what comes after, serving them: turning electricity into tokens and into intelligence, and the research problems that appear from that side. Her motivation is that the field is going through a new industrial revolution: human-level text and code generation, as in Cursor, Claude Code and GPT-5.5, images and video both generated and understood, and applications in the sciences. What made this possible, and what will drive the next generation? Scale. When her doctorate began in 2018 the largest models had 100 million parameters; in 2019 GPT-2 was judged too dangerous to release, and the class could train one; today open models exceed a trillion parameters and the frontier is probably at five to ten trillion. The transition came faster than she expected, and she compares it to the horses of Manhattan: 130,000 working animals in 1902, each producing pounds of manure a day, a problem serious enough for academic conferences, one of which concluded in 1898 that nothing could be done; by 1912 cars outnumbered horses. For language models, she thinks, the 1912 moment was the previous year, when she began to write most of her code with them, as do her team and her students. The scale runs on GPUs, the new oil, with hundreds of billions of dollars behind them and sovereign wealth funds involved; and inference is the engine that turns oil into motion. Models are graphs of operations, mathematical objects in the ether; inference engines and GPU kernels are what map them onto hardware. The class wrote a FlashAttention kernel for training, but inference has a world of complexity of its own. Her one takeaway: who understands inference engines and the kernels beneath them can innovate across the whole stack. The plan is the lifetime of a token, then two research projects. She speaks for two organizations, her small lab at UC San Diego and Together, whose research background includes Liang. In this book: Building Your Own: A Roadmap Through the Assignments › What the practitioners say · Inference › Why this matters.

6:00–12:00 The lifetime of a token: an inference engine in outline#

The slides on this part are adapted from a presentation by her student Austin, drawn from his time at Together, and every slide of the talk was generated by an image model, good unless one reads the text closely. An inference engine, in outline: a request arrives and is scheduled onto GPUs, with prefill and decode possibly on different machines; it is checked against the KV cache, since the same request or a version of it may have been seen and some computation saved; the model's code then runs, and there are choices to make, such as splitting the computation across machines, across nodes or across the GPUs of a node, depending on the model's size, with more choices coming as hardware develops; at the end come tokens, and the user's end-to-end experience. What do real workloads look like? Neither like training data nor like an invented workload. Each workload has its own distribution of input and output tokens. A coding workload, as at Cursor, gives the agent a whole code base: tens of thousands of input tokens, then thinking tokens or a short answer, depending on the model. Narrative summarization, a whole book pasted into a chat and discussed, differs from a plain question. Use is turn-based and agentic: a user goes back and forth with a coding agent, and the agent itself iterates, calling tools such as a search through the code base or the web, and feeding the results back. Cadences differ too: a chat loop or a voice assistant answers quickly, an agent left to work on its own has another rhythm, and a stuck agent asking for help that nobody notices creates gaps between turns. So a workload is defined by how many new tokens arrive per turn, how many are generated, how long a session lasts, a sticky user against one who asks a single question a day, and how long the pauses are; Fu names a chat about her workouts that she revisits every other week. Targets differ as well: an interactive application wants the first tokens within a second, so that the interface can say it is thinking, and a 500-token answer should arrive fast enough to read. In this book: Building Your Own: A Roadmap Through the Assignments › What the practitioners say · Inference › 7. Run a server, not a loop.

12:00–16:00 Tokenize, look up the cache, prefill, decode#

Text arriving at the engine is tokenized first. Then comes a fairly complex scheduling regime: have these tokens been seen before, and can activations be looked up in a cache? The computation proper has two parts, prefill and decode, which are very different beasts. Prefill takes 10,000 unseen tokens and produces one: compute-bound, and close to training, the same FlashAttention kernel and training loop without the backward pass. Decode generates one token at a time: given a code base and the question of what a function does, the model processes the whole prompt and then emits tokens one by one, three or four at a time with speculative decoding. Every new token must pass back through the whole model, and the arithmetic is light: the operation is bound by memory bandwidth, because the entire model must be loaded to produce a single token. At the end of a pass a single number stands for a token and becomes a string, with a little processing: stop tokens, and perhaps a safety check on what the user is attempting. The engine runs this loop, scheduling, execution and sampling, waiting for the next request. In this book: Inference › 1. Count one decoding step · Building Your Own: A Roadmap Through the Assignments › What the practitioners say.

16:00–20:00 Continuous batching, the KV cache, and splitting a model#

With many requests at once there is continuous batching, read on a diagram where time flows downward. A long request, say the analysis of a long document, is generating tokens; another arrives and takes compute resources and memory, since its KV cache fills up as it runs; after a step the short one may finish, a new one enters, and in a later step another very long one arrives, for which there may not be enough GPU memory, so it queues until a long request ends. That is the complexity of many requests in one system. The KV cache rests on an observation: many users begin with the same greeting, and a long book need be run through prefill only once, not again at the next turn of the conversation. Caches with prefix sharing keep a plain data structure, a tree, that shows which tokens have been seen and which are new, and the activations are looked up. Once the computation reaches the GPUs it can be split in several ways. A trillion-parameter model does not fit on each of a set of 280-gigabyte GPUs: tensor parallelism splits every tensor, four ways over four GPUs, say, and today's mixture-of-experts models can be split expert by expert. These choices decide the bottlenecks, how many GPUs a model needs, and how many sessions can be served at once. In this book: Inference › 7. Run a server, not a loop · Inference › 3. Shrink the KV cache.

20:00–24:00 Prefill-decode disaggregation, and bugs at scale#

A large trend is to run prefill and decode on separate GPUs, because their characteristics differ. Prefill resembles training, heavy in FLOPs, and uses a GPU fully; decode is heavy in memory bandwidth, with little arithmetic but all the weights loaded at every step. They take different amounts of time as well: a prefill lasts much longer than one decode step, but decode runs once per generated token and prefill once per prompt. So the basic optimization, which nearly everyone has adopted, is to run prefill on one set of workers and decode on another, so that each stack is specialized. That split leaves room for innovation. One reason Fu gives for NVIDIA's purchase of Groq, a maker of inference chips, is that decode differs so much from prefill that different chips can serve it: in the next hardware generation, she says, NVIDIA plans its GPUs for prefill and Groq's chips for decode; Cerebras, partner of OpenAI, makes another chip better at decode, and SambaNova and others bet on other parts of the space. Serving trillions of tokens a day also brings nasty bugs, most of those shown from the previous year in open-source engines: what works at small scale breaks at large, in events that occur in a thousandth of a percent of cases or fewer. A kernel very slightly wrong under rare conditions turns logits into values that are not numbers halfway through a computation, and the model then repeats one token, "hi" over and over, or exclamation marks. In one engine, tool calls, the model's requests for an internet search that ordinary code then performs, stopped being processed correctly; the symptom was a jump in completion length, as the model asked for the search again and again, puzzled that nothing happened, for tens of thousands of tokens. In this book: Building Your Own: A Roadmap Through the Assignments › What the practitioners say · GPUs, TPUs and Kernels › 6. TPUs · Inference › 7. Run a server, not a loop.

24:00–30:00 Chinese characters, and where the cache lives#

One bug took out several inference providers at once and was blamed on quantization: a model would suddenly answer an English question in Chinese characters for no reason, and some suspected a Chinese model in its fine-tuning. The cause was an off-by-one error in a kernel, which occasionally read a little uninitialized GPU memory, passed it through attention, and produced a random Chinese character; the model then concluded that the user must be writing Chinese and continued in Chinese. Sometimes such behaviour is legitimate training and sometimes a bug in someone's code. More advanced stacks aim at the largest possible KV cache, so that requests of many users and sessions are held and as many sessions as possible run. It starts on the GPU, which soon fills, then goes to the CPU's memory; one reason, she says, for NVIDIA chief executive's recent attention to CPU performance is that a past generation of CPUs was slow and bottlenecked important workloads, a 500,000-dollar machine held back by its thousand-dollar CPU, and reading a KV cache back from CPU memory is one of them. Next comes the disk, and then SSD capacity matters; the rumours of OpenAI buying the world's supply of solid-state drives and memory have something to do with this. Building the engine is then a dance: entries unseen for a while are evicted to CPU, disk or some global store, and a new request waits for them to be fetched and loaded. Asked what is offloaded, since disk latency is long, she points to classic scheduling: the diagram, GPU aside, could come from an operating-systems text of the 1970s or 1980s, when too many open applications pushed memory onto disk. The image generator even printed "least recently used" as the eviction rule, a decent heuristic that some operating-systems paper probably shows to be within a factor of two of optimal. The best policy would predict the future: reopening a month-old conversation is a strong sign that a question about it is coming, so its cache could be loaded onto the GPU in advance. Short of that, heuristics serve, and the question is how much traffic to put on the GPU; she has never met anyone who wants less, within the service targets set earlier. In this book: Inference › 7. Run a server, not a loop · Building Your Own: A Roadmap Through the Assignments › What the practitioners say.

30:00–34:00 Boxes of 72 GPUs, fault tolerance, and a two-line router#

The NVL72 systems put 72 GPUs behind a fast interconnect, which raises questions: does splitting a trillion-parameter model across all 72 make sense, and what does it buy? Then fault tolerance: such systems fail often, some of it because the connectors are flimsy, plastic rather than metal, so that jamming a cable in bends them and the links turn flaky. When a model is spread over 64 GPUs and serving millions of users, what should happen when one GPU goes down? And contexts of a million tokens and more raise the question of whether to split the context across GPUs. She highlights one systems-level optimization, published a few months earlier with Together: cache-aware prefill-decode disaggregation, a routing-layer change of two lines of code. Most requests are turns of an existing conversation; if the average conversation lasts ten turns, a tenth of requests are fresh, thousands of tokens long and expensive. A new request should not run its prefill beside a short request in mid-conversation, the person who pastes a book beside the person asking why one plus one equals two. A simple router sends requests with a very low cache-hit rate to one set of prefill GPUs and warm requests to another, which made serving up to 40% faster. In her view the research is very early: in ten or twenty years these ideas will look obvious. In this book: Building Your Own: A Roadmap Through the Assignments › What the practitioners say · GPUs, TPUs and Kernels › 6. TPUs · Inference › 7. Run a server, not a loop.

34:00–40:00 Megakernels: why decode leaves a GPU idle#

The first research project, a collaboration between Stanford and Together, makes decoding faster with megakernels. The challenge of decode is that the whole model must run to produce one token: a massively parallel machine becomes, in her phrase, a glorified memory loader. It is made worse by how models are usually programmed, one operation at a time. Kernels are hard to write, as anyone who wrote FlashAttention knows, so the norm, the matrix product and the attention each get their own kernel, which is easy to program and leaves much of the GPU idle. Her cartoon, drawn from a real attention inference kernel, puts time on the horizontal axis and the GPU's streaming multiprocessors on the vertical, 132 on an H100 and about 148 on a B200; the bars are useful work and the blank space waiting for other operations. Kernel launch and teardown leave large gaps. Tail effects leave more: in a batch with a short prompt and a long one, everything waits for the long one, and the same happens inside the attention operation; across many kernels the gaps add up. No matter how well each kernel is written, the GPU idles. The megakernel answers by covering several operations with one kernel, like the fusion in FlashAttention but more aggressive. It treats the GPU as a massive distributed system: work items, some depending on others, are scheduled and distributed to maximize utilization. Applied to the attention inference kernel alone, it gives speed-ups of 30% to 70%. In this book: GPUs, TPUs and Kernels › 3. Six tricks · Building Your Own: A Roadmap Through the Assignments › What the practitioners say.

40:00–44:00 Megakernels in practice: Thunder Kittens#

The same can be done to a whole layer: one layer of a Llama model of a billion parameters runs as one kernel, and its timeline shows bars overlapped in strange ways, a weight load for the next layer starting while attention still runs, or part of a reduction beginning before attention has ended. One example: in an attention layer the query, key and value projections plus rotary position embedding come first, then attention; during decoding the KV cache can begin loading before the projections are finished, and once they are done the new query is available and the rest of attention proceeds. Another: the output projection that follows attention starts loading its weights before attention is over. Fine-grained control lets some operations start before others end. The implementation is a fairly complex CUDA framework with an instruction-level abstraction, every sub-kernel kept in a separate file and a large virtualized shared memory that orchestrates them, released as the library Thunder Kittens: something like Triton, but lower level and with finer control. The payoff is decoding close to the speed of light: the megakernel, in teal on her chart, runs far faster than competing engines, and on an H100 it reaches 72% of the available memory bandwidth, close to how fast the GPU can physically perform the operation. Her takeaway: deep control of the kernels and the hardware enables different computing paradigms, which appear only when one works with inference at that depth. In this book: GPUs, TPUs and Kernels › 5. Triton · Building Your Own: A Roadmap Through the Assignments › What the practitioners say.

44:00–48:00 Looped transformers: the promise and the instability#

The second project comes from her lab at UC San Diego, led by Hayden with Zachary and Taylor, and it asks whether scaling parameters and data is the only road to quality. It is her group's take on looped transformers, in which some blocks run in a loop: at a certain depth the activation is sent back through the same block several times instead of moving on. Two ideas hold the work up: state-space model theory to stabilize the operation, since naive training blows up, and scaling laws suggesting that the recurrence should grow with the data, so that parameters are reused. The motivation: an activation reaches the looped block and passes through the same layer again and again. The advantages: parameters stay constant while FLOPs get a dial, so if more FLOPs mean more quality, quality rises without a parameter cost; and older work, a few years old, shows greater expressivity, things a looped model can express that a model of equal size cannot. The driving question is the best intelligence per parameter and per byte of data. Early results were promising: a paper from Tom Goldstein's group at Maryland suggested that looping might beat transformers on some tasks, and a week before the release someone at OpenAI claimed that a leading Claude model was a looped language model, which Fu believes was invented and which its author later retracted in a blog post, though the claim spread widely on social media; her group had worked on looping before the fuss. The problem: looped models are fragile. Change anything in training, the learning rate by a little, and they blow up; a learning-rate sweep failed nine times in ten, with values that are not numbers and large loss spikes. In this book: Attention Alternatives and Mixture of Experts › 4. Add a state that can forget: Mamba-2 and Gated DeltaNet · Building Your Own: A Roadmap Through the Assignments › What the practitioners say.

48:00–54:00 Stability from the residual's dynamics#

Large loss spikes mean that something has gone deeply wrong, and earlier work treated them with hacks: norms in every layer, or one learning rate, two times ten to the minus four, and no other. Her group took a mathematical route in the spirit of state-space models. The looped block is too complex to analyze, full of parameters, attention, nonlinearities and rotary embeddings. Their insight was to look only at the residual, at how the activation changes from block to block, and the first empirical observation was that it changes little: each block nudges the vector. So they wrote down a dynamical system for the residual: all the nonlinear machinery goes into one box, and what remains are two matrices, one that transforms the initial vector and one, applied at every loop, that transforms the residual. Earlier looped transformers differ in ordinary choices for these matrices, the identity in one case and a fully learned matrix in another. Since the two matrices dominate the magnitudes, the nonlinear box can be dropped, and school calculus solves what is left: a closed form for the activation at any step, dominated by the loop matrix raised to the number of loops. A scalar of 2 raised to the 16th power is already very large, and that explains the spikes: the spectral radius of that matrix, a kind of norm, was above one, so earlier designs were marginally stable or unstable. The remedy constrains the two matrices so that the mathematics cannot explode: the loop matrix is made a negative diagonal matrix, whose powers vanish, and the matrix on the initial vector, applied only once, receives a simple linear norm. The spectral radius falls below one, and training is stable even at the learning rate of six times ten to the minus four that had been so harmful. The constraint also settles a conflict: an unconstrained model's activations grow to 10^19, and a model that merely applies a norm is torn between expanding its activations, to hold concepts further apart, and being pulled back to unit size, a fight that shows up as loss spikes. The same change brings quality: against an earlier looped design, the recurrent-depth model, and against strong transformer baselines of the kind tuned to learn as fast as possible, the looped and stabilized model obtains lower perplexities and better end-to-end results. In this book: Attention Alternatives and Mixture of Experts › 4. Add a state that can forget: Mamba-2 and Gated DeltaNet · Building Your Own: A Roadmap Through the Assignments › What the practitioners say.

54:00–60:00 Scaling laws for recurrence#

Is looping worth doing at scale? She recalls the compute-optimal plots of a few years ago, which answered whether to scale parameters or data. Read such a plot by the direction of its curves: down and to the right means scaling both data and parameters together, straight down means only data, flat to the right only parameters; the curves go down and to the right, which is how one arrives at a trillion-parameter model trained on 35 trillion tokens. Where does recurrence fit? One might conclude that it should never be used, or always, or sometimes. Her group's curves hold parameters fixed and increase FLOPs by adding data; each curve is one model, and the number of loops varies along it. Both models tested show the down-and-to-the-right trend again: at a fixed parameter count, more data should come with more recurrence. The recurrence follows ordinary power laws, so quality can be predicted as loops and tokens grow together. Asked about scaling everything: a hard-to-read three-dimensional figure points down and to the right and downward at once, which would mean scaling all three; what is clear is that a fixed-size model trained on more data should also loop more. That is striking, because as far as she knows no current model has any recurrence: they all sit at the far left of these curves with vast data, which suggests that something slightly better is available. The last plot puts it another way: the orange curve is a fixed-depth transformer, the blue a looping model at the same FLOP budget, with points of equal FLOPs and equal size but different data; reaching a FLOP count by increasing loops as well as data gives lower validation loss. Perhaps every large pretraining run should loop. In this book: Scaling Laws › 2. Pick a method for the trade-off · Building Your Own: A Roadmap Through the Assignments › What the practitioners say.

60:00–1:12:00 Questions#

Fu restates the takeaway: understanding inference, the kernels and all the pieces enables full-stack innovation, whether a routing algorithm that serves more traffic, kernels that run a part of the system far faster, or architectures that fit fewer parameters on fewer GPUs and need less communication. The questions that follow: is the looped model trained from scratch, or can a pretrained model be looped? Someone won a leaderboard competition, as a provocative blog post claimed, without any training, by looping two or three layers of a Qwen model, which scored better on some mathematics; her lab is looking into it, the result disturbs her, and she hopes to have the weights examined. What does looping mean for inference? Fewer parameters leave room for more KV cache or for less communication across fewer GPUs; she dreams of recurrent blocks small enough to run in a small megakernel loop, not achieved yet, though chips with only about 250 megabytes of memory are coming, and a model designed to fit in them could keep its weights resident and stream activations through. The trade-off of megakernels is, in her words, blood, sweat and tears: a talented kernel engineer might write them in a year for one hardware platform, two or three models and batch sizes from one to sixteen, and batch size seventeen means starting over; Together is building compilers to automate part of the work, and the idea has risen and fallen over decades, but done well nothing is faster. On designing a model for a known serving platform: memory constrains first, so size the model to the chip, with room for the KV cache; the quantization formats of recent Chinese models suggest attention to Huawei's chips; NVIDIA's Nemotron is trained in NVIDIA's own four-bit format, and models not meant for NVIDIA chips use MXFP4. Is looping ever compute-optimal against more parameters? Compute-optimality asks what to do within a FLOP budget, which is somewhat contrived: for more quality, raise the budget; with the model size fixed, train longer; with the size restricted, loop longer; out of data, pick the size that is trained well; and adoption and serving matter, such as what fits on a laptop. On co-design across use cases: agentic workflows need the KV cache kept hot, while batch processing that sees each document once cares less, which is where a radical compression such as DeepSeek's multi-head latent attention or a cache in eight or four bits matters; and the largest difference is causal against non-causal attention, since Google long used BERT, and probably still does, for search, where nothing needs to be generated, with T5 as an intermediate. Last, megakernels across several GPUs: early work shows that communication calls can be fused in too, though no compelling use case has appeared, since a system can be bound by the latency of the call itself; the DeepSeek team released a megakernel for a mixture-of-experts inference layer with some communication fused. Her expectation: megakernels for parts of a model, not for the whole, unless the price is paid. In this book: Building Your Own: A Roadmap Through the Assignments › What the practitioners say · Building Your Own: A Roadmap Through the Assignments › The core idea.

What to take away#

Sources#