{mvGPT}
  • Episode 35
  • 37 min

Our GPT's own GPU kernels in Mojo on a Mac

We write our GPT's writing path as GPU kernels in Mojo, call them from Python, check them against PyTorch, and make them faster in three versions, racing PyTorch and MLX on this Mac.

Watch on YouTube

In this episode, we write the part of our GPT that writes text, a token at a time, as GPU kernels in Mojo, Modular's Python-like language, and call them from Python on this Mac's GPU. We check that they give PyTorch's logits and write PyTorch's story, then race them against PyTorch and MLX. The first version, a thread for each number, is the slowest of the three. Warps of 32 threads that read side by side, and then fewer kernels a token, after measuring what a kernel launch costs, bring it most of the way to MLX.

The code

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

  1. 3:46ep035/step-1Installing itBrowseChanges
  2. 4:55ep035/step-2Our GPT as kernelsBrowseChanges
  3. 20:19ep035/step-3A raceBrowseChanges
  4. 22:54ep035/step-4WarpsBrowseChanges
  5. 28:17ep035/step-5What a launch costsBrowseChanges
  6. 30:30ep035/step-6Fewer kernelsBrowseChanges
  7. 35:21ep035/endFewer kernelsBrowseChanges

Transcript

Intro

0:00 Hi, and welcome to episode thirty-five, where we're going to write the part of our GPT that writes text as GPU kernels, in Mojo, and run them on this Mac. I've always wanted to play around with Mojo, and with this project, I have the perfect excuse. Here's a quick look at what we'll have by the end.

0:17 Episode three's model wrote this story from Python, but each token went through kernels we wrote in Mojo, on this Mac's GPU. On this first run, that's about seven hundred and thirty tokens a second, faster than PyTorch writes on this Mac.

0:32 The project has a website, with a page for each episode. The code is on GitHub, tagged at each step, so you can check out any step and run it, and the docs get a page on Mojo today. Below, you'll find the episodes, with their chapters and their code.

0:48 Last time, we went back to the tokenizer we wrote in C++ in episode eleven. Before touching it, we measured its memory and its time on web pages, and how it used its threads. Then we fixed what we found: a cache with a limit, the whole encode moved into C++, Python's lock let go while it encodes, and a heap for long chunks. All of that ran on the CPU, and today we move to the GPU, in a language I've not written before.

1:17 We'll start with what Mojo is, and how a Mojo kernel runs on a GPU. Then we write the path a token takes through our GPT as Mojo kernels that Python can call, and check them against PyTorch. In episode thirty-two, MLX wrote about two point six times as fast as PyTorch on this Mac, so we race all three. My first version loses, and then we make it faster twice, once by having threads share the reading, and once by running fewer kernels for each token. Right, let's start with what Mojo's makers say it's for.

What Mojo is

1:48 Mojo's website calls it the systems language for the AI era. It comes from Modular, the company Chris Lattner co-founded after creating LLVM and Swift. Modular showed it first in twenty twenty-three, and version one point zero came out in August twenty twenty-six. It reads a lot like Python, but it's a compiled language with types, built to run fast. And as of this year, the language is fully open source. So let's scroll down the page, to what I want to try today. We can write GPU kernels in the language we'd use for the CPU, without CUDA. And on a Mac, Mojo compiles them for Metal, Apple's interface to its GPUs. Calls between the two languages work both ways: Mojo can import Python libraries, as the page says, and Python can import Mojo files. So our model and tokenizer stay in Python, checkpoints and all, and we move the hot loop and nothing else. I want to see how well that split works on our model. In episode thirteen, we wrote flash attention as a Triton kernel, on a rented NVIDIA GPU, where each program works on a whole block of numbers. In Mojo, we write what a single thread does, and it runs on this Mac.

3:02 Before we write for a GPU, let's get a quick picture of how one runs a kernel. A kernel is a single function, written as if for one worker. The GPU runs it on thousands of threads at once, each with its own variables. Threads come in blocks, and the threads in a block can share a small, fast memory and wait for each other, which threads in different blocks can't do. Inside a block, the hardware runs them in groups of thirty-two that do one instruction together. NVIDIA calls these groups warps, and Apple calls them SIMD groups. And since they all run one function, each thread starts by asking which one it is, and picks its share of the work from that. Most of today is about how we split the work between them.

Installing it

3:46 Mojo goes in our requirements file like any Python package, in two parts. Max is Modular's library, which holds Mojo's GPU modules, and mojo is the compiler, with the piece that lets Python import Mojo files. As with MLX, the marker installs them on macOS and nowhere else, as this episode is about this Mac's GPU.

4:07 Uv installs them into the environment our scripts run in, and it resolves one hundred and thirty-nine packages in under a second. Then it warns that it can't clone files here, as its cache and our environment sit on different disks of this Mac, so it copies them instead, which is slower and changes nothing else. Max is the big one, with its compiled libraries. It installs twelve packages in all, max and mojo among them, with Mojo's compiler and its libraries, so Mojo needs no installer of its own. Mojo dash dash version prints one point two, the version this episode uses. On this Mac, I also had to download Xcode's Metal toolchain with xcodebuild, as Mojo uses it to build kernels for the GPU. I found that out from the error on the first kernel I ran.

Our GPT as kernels

4:55 The kernels go in a new file, kernels, written in Mojo, and its imports read like Python's. From Mojo's standard library, we take ceil div, which divides and rounds up, to count the blocks of threads we need, and the error function, exp and the square root, for GELU, the softmax and the norm. Unsafe stack allocation gives a block of threads memory they share. Abort, Python object and the module builder are how a Mojo file becomes a module that Python can import. The GPU's side comes from MAX: the numbers that tell a thread which one it is, and the device context and its buffers, which are how we talk to the GPU. Barrier makes a block's threads wait for each other. A comment at the top says what the file is: episode one's blocks, like the ones we ported to MLX, called from Python a token at a time, with a thread for each number a kernel writes. Comptime is Mojo's word for something worked out when the program compiles. Floats is our name for a pointer to thirty-two-bit floats that we can write through. Mojo tracks what each pointer points into, and refuses two writable pointers into one buffer in a single call, which we'll do all the time, so any origin opts out of that check. Max context is the longest context our attention holds scores for. Embed is the first kernel, and the simplest. Its arguments are the residual stream, x, the two embedding tables, the token, its position and the width. The last three are int thirty-two, and not Mojo's plain int, as Mojo won't hand a plain int to a GPU kernel, which I found out from the compiler. Global idx is the thread's number across the whole launch, so thread c writes channel c, the token's row of its table plus the position's row. The if is there because threads come in blocks of a fixed size, so the last block can have threads past the end. Unsafe offset is how we index a pointer, and it's unsafe as nothing checks that we stay inside the buffer. The tables keep a row for each token, so the token's row starts at the token times the width, and the position's row likewise. A kernel returns nothing, as thousands of threads run it at once: each one writes its part into a buffer, and that buffer is the result. Layer norm has a thread per channel too, and I wrote it the obvious way. Each thread adds up all three hundred and eighty-four channels and divides by the count, for the mean. Then it adds up the squared differences from the mean, divided by the count again, for the variance. Last, it writes its own channel: the channel minus the mean, divided by the square root of the variance plus a small epsilon, times the weight, plus the bias. So three hundred and eighty-four threads all repeat those two sums, which is wasteful, and I'm fine with that for a first version that has to be right before it's fast. Linear is y equals W x plus b, with W stored as PyTorch stores it, a row of weights for each output. Thread r takes row r, starts from the bias, and walks along the row, multiplying each weight by its input. The square brackets after the name hold parameters, gelu and add, which Mojo knows when it compiles. Comptime if on a parameter is decided then, so linear with GELU and linear without it are two kernels, and neither checks a flag while it runs. I really like this part of Mojo, and it's what Triton's constexpr did for us in episode thirteen, in plain code. The GELU is the one with the error function, like ours in PyTorch, and with add, the result goes onto what's already in y, which is how the residual stream gets attention's output and the MLP's. Attention runs a block of threads for each head, which block idx gives us, and in it, a thread for each of the head's channels. N is how many tokens there are so far, counting this one. The scores go in shared memory, from unsafe stack allocation with the shared address space. The threads share out the positions: thread d starts at position d and steps by the block's size, so with sixty-four threads, each takes one position in sixty-four. For each, it works out the dot product of the query with the cached key, divided by the square root of the head size. The score goes in shared memory at that position, where the rest of the block can read it. Barrier holds each thread until the whole block gets there, so that no thread reads a score before it's written. Then each thread finds the largest score, adds up the exponentials of the scores minus it, which is the softmax without overflowing, and sums its channel of the values, weighted by those exponentials. Its output is that sum over the total. Pointer gives us a Floats into one of our GPU buffers, to hand to the kernels. Then the GPT type, a struct, which in Mojo is like a Python class whose fields are declared and fixed. Fieldwise init writes its init from the fields for us. Movable and Writable are traits, which say what the type can do: Python needs to move it and print it. It holds the device context, a GPU buffer with all the weights, and a cache of keys and one of values. Then come the vectors a token needs on its way through: x, the residual stream, h, a normalised copy of it, the query, attention's output, the MLP's wider hidden layer and the logits. After those, the model's sizes, and read, which keeps our place as we go through the weights. Py init runs when Python calls GPT, and gets Python's arguments as Python objects: the weights as one NumPy array, then the sizes. Int with py equals turns a Python number into a Mojo one, and raises an error if it isn't a number. So we get the size of the vocabulary, the length of the context window, the number of layers, the number of heads, and the width, which is the embedding size. It refuses a context longer than attention can hold, and the device context is our handle on the GPU. Enqueue create buffer makes a buffer in the GPU's memory, and enqueue copy fills it from the NumPy array, through the address NumPy gives in C types dot data. The weights go over once, and stay there, so a token costs no copying of weights at all. Then Self builds the struct from its fields, by name. The key cache gets a row of the width for each position of each layer, six layers of two hundred and fifty-six positions for our model. So it comes to a little over two megabytes, and the value cache matches it. X, h, the query and y each hold one vector of the width, which is tiny, as we write a single token at a time. Hidden is four times wider, for the MLP, and the logits get a number for each token in the vocabulary, ten thousand of them. The sizes go in as they came, read starts at zero, and synchronize waits for the copy to finish before Python gets the object back. Write to and write repr to are how it prints, and Python's binding asks for both of them. Step is what Python calls for each token, with the token, its position and a NumPy array to write the logits into. A method we give to Python is a static method that gets the Python object, so downcast value pointer takes our GPT back out of it, and forward does the work. Next hands out the next tensor of the weights. It takes the pointer to where read has got to, moves read along by the tensor's size, and returns where the tensor starts. The weights come as one array, and forward reads them in order from the start, so we don't keep a name or an offset for each one. Run norm takes the next two tensors, the norm's weight and bias, and enqueues layer norm, with blocks of a hundred and twenty-eight threads. Run linear takes the parameters, gelu and add, in square brackets, and its arguments in round ones, and enqueues linear with those parameters. The grid dim is the number of blocks: the rows divided by a hundred and twenty-eight and rounded up, so there's a thread for each row. Run layer is the helper that forward calls. It takes a Linear layer's weights and its bias, the next two tensors, and runs it. Its parameters, gelu and add, start off, so a plain call reads like a plain Linear layer, and we name them when we want one. Forward is our GPT for one token, and it starts by giving names to the buffers it uses, as pointers. Then it sets read back to zero and takes the weights from the start. First come the token embeddings, then the zeros that mojo model puts there as the head's bias, and then the position embeddings. Embed writes this token's row plus its position's row into x, with a thread per channel. Then the loop over the layers, which looks a lot like the forward of our PyTorch block. Each layer has its own part of the two caches, which is where keys and values point. We write above them that a layer's cache holds a row of keys and a row of values for each position. Next comes the first norm, from x into h, and the query, from h. The key and the value go straight into the cache, in this token's row, so there's nothing to copy afterwards. Attention runs a block of threads for each head, reading the query and the cache, and writing y. Then the output projection adds y's projection into x, the residual stream. The second norm writes h again, the up projection widens it into hidden, with GELU, and the down projection adds it back into x. After the last block, the final norm, and then the head, whose weights are the token embeddings, as in our model, with the zeros as its bias. The copy of the logits into Python's array goes in line after all of that. The comment over it says what enqueue means: the work waits in line for the GPU, and the CPU hasn't waited on any of it. Synchronize then waits until all of it is done, which is the one moment in a token where the CPU sits and waits for the GPU. Last, there's the function Python looks for when it imports the module, named py init, then the module's name, kernels. Export makes its name visible outside the file, and A B I C makes it callable the way Python calls extensions. The C stands for the C calling convention, which is how Python's runtime calls into any compiled module, whether it's written in C, C plus plus, Rust or Mojo. Inside, the module builder makes a module called kernels. Add type adds our GPT type to it, with its init and with step as a method, and finalize hands the module to Python. If any of that fails, it aborts with the error, as a function Python calls this way can't raise one.

15:13 On the Python side, mojo model imports argparse, textwrap and time, for writing from the command line, and NumPy. Importing mojo dot importer adds Mojo's import hook. With it, the next line, import kernels, finds our Mojo file, compiles it into a Python extension, and loads it. A comment says what the file does: a checkpoint's weights go to the GPU once, and each step runs one token through. MojoGPT checks the config first, like MLX model does, and refuses anything but episode one's blocks with their biases, as those are the blocks our kernels were written for. It flattens the weights and hands them to our Mojo GPT with the sizes, and keeps one NumPy array for the logits. Step runs a token at its position through the kernels, by calling our Mojo GPT's step with that array, and it returns the array, which the next step writes over. Flatten lays the weights out in the order forward reads them. The head's weights are the token embeddings, and since it has no bias, zeros stand in for one, right after them. Then, for each block, its two norms and its six layers, a weight and then a bias each, in the order forward takes them, and after the blocks, the final norm. They're all made float thirty-two, flattened and joined into a single array of about fifty-eight megabytes for this model, which is what py init copies to the GPU. From torch imports our checkpoint module when it's called, loads one of our checkpoints with our usual loader, as MLX model's does, and returns a MojoGPT with the checkpoint's tokenizer. Generate feeds the prompt in a token at a time, which fills the cache, as our kernels take one token a step. I'd normally run the prompt through in one go, but for a few tokens of prompt, it isn't worth a second version of attention. Then it's MLX model's loop again, stopping at the context window. Greedy takes the largest logit, with arg max. Otherwise, we divide by the temperature, and keep the top k, setting the rest to minus infinity with where and sort. The softmax is the exponentials of the logits minus the largest, so that nothing overflows, and NumPy's random generator picks a token with those probabilities. The token goes on the list, it stops at the end of text, and otherwise the new token goes through the next step, at its position. Main writes a story from the command line. Its arguments are the checkpoint, the prompt, which is once upon a time unless we give one, the number of tokens, the temperature, the top k and a seed, with sample's defaults. It loads the checkpoint with from torch, which copies the weights to the GPU, then it encodes the prompt, and then it times generate with the performance counter. The seed goes into NumPy's generator, so that a run with a given seed writes one story and no other. Then it prints the story, wrapped at ninety characters, and how many new tokens it wrote, in how many seconds, and so how many a second. The compiled module lands in a folder called mojo cache, next to the file, which goes in our gitignore.

18:11 Let's have it write a story, with episode three's fine-tuned model. The first import compiles our kernels, which takes a few seconds, and then it writes. The story is about as good as this model's stories get, so the kernels compute something sensible. But about one hundred and ninety tokens a second is slow, as PyTorch wrote about four hundred and ninety on this GPU in episode thirty-two.

18:36 Before making it faster, I want tests, so that a faster version can't quietly compute something else. They go in test mojo, which imports NumPy, pytest and PyTorch. Import or skip leaves the whole file out where Mojo isn't installed, as our requirements install it on macOS and nowhere else. Then our checkpoint saver, our PyTorch GPT and its config, from torch and generate from mojo model, and the word tokenizer. Tiny is test MLX's small model, written out again here. It seeds PyTorch, builds two blocks of thirty-two channels with four heads, and a tokenizer for forty tokens, three reserved ones and thirty-seven made-up words, and saves them as a checkpoint, returning the model and its path. The first test loads tiny into our kernels with from torch. It makes sixteen random token ids, with a fixed seed, and runs them through PyTorch in one go, keeping the logits at each position. Then it runs them through our kernels a token at a time, and at each position, the largest difference from PyTorch's logits has to be under a ten-thousandth. That checks the cache too, as from the second token on, attention reads the keys and values that earlier steps wrote. The second test starts from three token ids, and writes twenty tokens greedily, with our kernels and with PyTorch's generate and a top k of one. The two lists of ids have to be equal, token for token.

20:03 We run them with pytest, and both pass, so our kernels give PyTorch's logits, position by position, and write PyTorch's tokens. The warning is Python noting that Mojo's binding gives our GPT type no module name, which doesn't change what it computes.

A race

20:19 For a fair number, we race the three in a new file, mojo bench. It imports argparse and PyTorch, our checkpoint loader, and race from MLX bench, which has the contenders take turns. From MLX model, it takes from torch and generate under names of their own, as mojo model uses those names too, then pick device from our model, and from torch and generate from mojo model. At the top, we say what the file is for: writing a story a token at a time, three ways, taking turns, so that whatever else the Mac is doing slows them all alike. Main sets up argparse, with a description of the script, and it reads the checkpoint, a prompt, which is once upon a time by default, the number of tokens, two hundred, and the rounds, five. It picks the device, which is Apple's GPU on this Mac, and loads the checkpoint three times, into PyTorch on the GPU in eval mode, into MLX, and into our kernels, and encodes the prompt once, for all three. Write torch generates with a top k of one, which keeps the likeliest token each time, and synchronizes, so that the clock waits for the GPU. Then comes the race, which is a single call. Each contender is a function that race calls and times: write torch for PyTorch, and for MLX and Mojo, lambdas that call their own generate with greedy on. The comment says why they're all greedy: the three should write an identical story. When the race is over, it counts the new tokens in our story and prints how many. Below, it prints each one's fastest time and tokens a second, whether the three stories match, and the story.

21:50 We race them over five rounds, with two hundred tokens each. PyTorch writes about five hundred tokens a second, MLX about twelve hundred, and our kernels about two hundred and ninety, last by a long way. All three wrote the story we saw in episode thirty-two, a happy sun that shines over and over.

22:09 Before changing anything, I'd guess the problem is how linear reads its weights, with each thread walking a whole row on its own. The thirty-two threads of a warp run in step, so at each moment they read thirty-two numbers, one from each of thirty-two rows, three hundred and eighty-four floats apart. The GPU's memory is fast when a warp reads numbers that sit next to each other, as it fetches them together, and this pattern wastes most of each fetch. And a layer with three hundred and eighty-four outputs gets three hundred and eighty-four threads, twelve warps, on a GPU with sixteen cores. So we flip it, and give each row a whole warp. The lanes read the row side by side, and then the warp adds up its thirty-two partial sums, which Mojo's warp sum does for us, without shared memory.

Warps

22:55 The imports get warp size from MAX's globals, which is thirty-two on this GPU, and warp, from MAX's primitives, for adding up and comparing numbers across a warp. The comment at the top changes too: the kernels now share the work out by warps, which Apple calls SIMD groups. Max head is the widest head attention will hold. Threads is two hundred and fifty-six, the block size we'll use, so warps, the number of warps in a block, is eight. Layer norm becomes a single warp of thirty-two threads for the whole vector. The old loops go, as no thread does the whole sum on its own any more. Lane is the thread's number inside the warp, from zero to thirty-one, and with a single warp in the launch, it's the thread's number too. Thirty-two threads are plenty for three hundred and eighty-four channels, twelve each, and they need no shared memory and no barrier, as they run in step. Each of the thirty-two threads adds up one channel in thirty-two, starting at its own, so together they cover the vector once: thread zero takes channels zero, thirty-two, sixty-four and so on. So each thread reads twelve channels, where before, each one read all of them, twice over. Their reads sit next to each other too, as neighbouring threads take neighbouring channels. The partial sums are then added together by warp sum, which hands each lane the total, so all of them get the mean. That replaces a loop over all the channels, which the first version ran in each of its threads. The squared differences are summed in that way too, with warp sum again, for the variance, and the standard deviation is its square root. Last, each lane writes its own channels, normalised, times the weight, plus the bias. Linear gives each output a warp of its own, and its comment says how. The row number is the thread's number divided by thirty-two, and the lane is the remainder, so thirty-two neighbouring threads share a row. Part is this lane's share of the dot product. Each lane starts at four times its lane and steps by a hundred and twenty-eight, so in each step, the warp reads a hundred and twenty-eight neighbouring numbers of the row, which the GPU fetches together. Unsafe load with a width of four reads four floats at once, as a SIMD vector, a small vector of a fixed size that a thread loads in one go, and reduce add sums its four products. I like that Mojo makes SIMD a plain type, since in most languages, it's an intrinsic with a long name. Warp sum adds the thirty-two parts into the row's dot product, the bias goes on, and GELU is as before. All thirty-two lanes now hold the answer, so lane zero alone writes it. Attention gets a block of two hundred and fifty-six threads, eight warps, for each head, and the warps share out the positions between them. Lane and group are the thread's place in its warp, and its warp's number. The memory the threads share now holds two things, the scores and each warp's share of the sums. Next to the scores, which keep their thousand and twenty-four floats, we ask for a second array in shared memory, shares. In shares, the threads leave their parts of a sum, with room for a sum per channel from each of the eight. The loop over the positions changes, and so does what each thread does inside it. Each position's key is sixty-four floats, two for each of the thirty-two threads that read it together. For the scores, warp g takes positions g, g plus eight and so on. Its lanes split the dot product of the query and that position's key across the head's sixty-four channels, warp sum gives the dot product, and lane zero writes the score. Then comes a barrier, as before, so the scores are all written. The softmax now takes two passes over the scores. First, the largest score: each thread looks at its share of the scores, warp max gives the largest in each warp, and lane zero puts it in shares. After a barrier, each thread reads the eight and keeps the largest, and a second barrier stops any thread from writing to shares while others still read them. The exponentials come next, written back over the scores, so we don't work them out twice, and their total goes through warp sum and shares like the largest score did, with a barrier on each side. The output comes in two steps, by warp and then by channel. First, each lane takes channels of the head, side by side, and its warp's positions, and sums the values, weighted by the exponentials. Each warp leaves its sums in shares, and after a barrier, a thread for each channel adds up the eight warps' shares, and divides by the total. Py init now also refuses a head wider than a hundred and twenty-eight, and a width that doesn't divide by four, as linear reads four at a time. Below, the launches change to match the kernels. Run norm launches a single warp of thirty-two threads, in a single block. Run linear launches thirty-two threads for each row, in blocks of two hundred and fifty-six, so eight rows a block, and the number of blocks is the rows times thirty-two, divided by the block size and rounded up. Further down, in forward, attention launches a block of two hundred and fifty-six threads for each head, where it had a thread for each channel.

27:56 The tests still pass, so the warps compute what the threads did. Then we run the race again, with the warps. PyTorch is at about four hundred and fifty tokens a second, MLX at about twelve hundred, and our kernels at about eight hundred and ninety. So they've passed PyTorch, and they're about three point one times as fast as the first version.

What a launch costs

28:18 Before guessing what's left, I want to measure what it costs just to start a kernel, as a token takes fifty-seven of them, and the GPU work in most of them is small. So we write a Mojo program of its own, launches, which we'll run with mojo run, without Python. It imports perf counter n s, a timer in nanoseconds from the standard library, the thread's global index, and the device context. The program measures what it costs to hand the GPU a kernel, and to wait for it. A kernel that does next to nothing goes to the GPU over and over, fifty-seven at a time, as many as a token takes now, and then thirty-two, each lot followed by a synchronize. Rounds is a thousand, the number of times we repeat each lot. Touch is that kernel, and thread zero adds one to a single number, so the GPU has almost nothing to do. Main makes the device context, a buffer of one float, and a pointer to it. A first launch compiles the kernel for the GPU, so it goes before the clock starts, and compiling isn't timed. Synchronize waits for that first one to finish. Then comes the loop over the two sizes, fifty-seven kernels and then thirty-two. For each, handing counts the nanoseconds spent handing them over, and start is when the rounds begin. In each round, queued is when the enqueues start, and the loop enqueues touch as many times as there are kernels. That's the CPU's part, which handing adds up, and then synchronize waits for the GPU to run them all. Total is the time of all the rounds. It prints the time per round in microseconds, and how much of it was handing the kernels over, in all and per kernel.

29:58 Mojo run compiles the program and runs it, in under two seconds. Fifty-seven kernels and a synchronize take about seven hundred and ten microseconds, and handing each one over costs the CPU about eight microseconds. At thirty-two kernels, it's about four hundred and ten. With the warps, a token took our kernels about eleven hundred microseconds. So starting fifty-seven near-empty kernels and waiting for them costs about sixty-three percent of that. I didn't expect the overhead to be that large a share.

Fewer kernels

30:30 So we run fewer of them, in two ways. A layer norm always comes right before a Linear layer that reads its output, so the norm can move into linear, and the layer norm kernel goes. Linear gets a third parameter, norm, next to gelu and add, and two more arguments, the norm's gain and shift. Mean starts at zero, and the comment above it says how this works. With norm on, x goes through a layer norm first, with the gain and shift, and each warp works out x's mean and standard deviation for its own row. That's two more reads of a few hundred numbers for each row, and it saves a kernel. The standard deviation, std, starts at one, next to it. Without norm, comptime if leaves all of the norm's code out of the kernel, so those two values stay as they are. With norm on, the two loops and the two warp sums are the layer norm's, moved here, one for the mean and one for the variance, and std is the square root of the variance plus epsilon. Those two reads take the GPU far less time than starting a kernel does, which costs several microseconds on its own. Further down, as each lane loads its four numbers of x, into a SIMD vector called x s, it normalises them on the way, with the gain and shift, before the multiply with the weights. The comment about the parameters now says that norm, gelu and add make a kernel for each mix of them. The second change is to the projections before attention. The query, key and value projections become one Linear layer with three times the rows. One launch replaces three, and it's a bigger one, so more of the GPU's warps get to work at once. That's eleven hundred and fifty-two rows a layer, where each of the three had three hundred and eighty-four. And this one writes its output straight to where attention will read it. So that place has a row for each position, with its query, its key and its value side by side, and attention takes that cache in place of the query, the keys and the values. R is the length of a row, three times the width. The query is in this token's row, the key of position t is in row t, after the query, and the value comes after the key. Keeping the query in the cache, where nothing needs it after this token, makes the cache half as big again. That's a little over two megabytes for this model, and it saves two launches a layer. In the struct, the cache takes the place of the keys and the values, and h and the query go, as no kernel writes them now. Py init makes the cache three times the width, and drops the buffers we no longer have. Run norm goes too, as nothing calls it. Run linear gets norm, and passes the gain and the shift through to the kernel, one argument a line. Run layer gets norm as well, which changes what it reads from the weights. Gain and shift start as a pointer to the weights. That pointer is there so that the call has something to pass, and it costs nothing, as the kernel doesn't read it without a norm. With a norm, the norm's gain and shift are the next two tensors, and the layer's weights and bias come after them. In forward, the pointers to h and the query go, with their buffers, and the loop over the layers changes more than the rest of forward. Each layer's cache is now a row of three times the width for each position, as the comment over it says. The first launch is the norm and the query, key and value, all as one Linear, which writes this token's row of the cache. Below it, attention gets this layer's cache in place of the query and the two caches, and the output projection is as before. The second norm moves into the up projection, which has norm and gelu on, and the down projection is unchanged. After the blocks, the final norm's gain and shift are the next two tensors, and the head runs with norm on. So a block takes five launches where it took nine, and a token takes thirty-two kernels. In mojo model, torch is imported now, as flatten has to lay the weights out in the new order. It stacks the query, key and value weights with torch cat, one on top of the other, and their biases one after the other, as the comment says. So the three are laid out as one layer of three times the rows.

34:38 The tests pass, so the norm inside linear and the shared cache rows give PyTorch's numbers. The last race of the day runs our kernels with fewer launches. PyTorch writes about four hundred and ninety tokens a second, MLX about twelve hundred, and our kernels about eleven hundred, which is about two point two times PyTorch's speed.

34:58 Side by side, the first version was the slowest by far. Warps, which read neighbouring numbers together, did the most for it, and fewer kernels a token did the rest. MLX is still ahead, at about one point one times our speed. I can't tell yet how much of that gap is its kernels and how much is its launches, and I'd need Metal's profiler to find out.

35:22 Last, the docs get a page on Mojo, on the kernels in their three versions and the races, and it goes in the docs' list and their navigation. The README gets four commands: the tests, a story, the race and the launches.

Wrap-up

35:36 Today we wrote the path a token takes through our GPT as Mojo kernels that Python calls, and they give PyTorch's logits and write PyTorch's story. Sharing the work out by warps made them about three point one times faster, and going from fifty-seven kernels a token to thirty-two sped them up again. They ended up past PyTorch, and still behind MLX. As for Mojo, I enjoyed writing it more than I expected. I'd miss comptime parameters and SIMD types in other languages, but I fought with the pointer origins. I wouldn't move mvGPT to it, as training needs gradients, and PyTorch gives us those for free. For one hot loop that I want to understand down to the thread, though, I'd reach for Mojo again.

36:20 If you've written GPU kernels in Mojo, or on Apple's GPUs in another way, tell me in the comments what made the biggest difference for you. And if you'd like to follow along, subscribe to the channel. I hope you find this useful, and thanks for watching.