{mvGPT}
  • Episode 32
  • 24 min

Our GPT in Apple's MLX vs PyTorch on a Mac

We port our GPT from PyTorch to MLX, Apple's array library for its own chips, check that it gives the same numbers, and race the two on this Mac at writing and at training.

Watch on YouTube

In this episode, we move our GPT from PyTorch to MLX, Apple's array library for Apple silicon. We write the model in MLX, load our PyTorch weights into it by name, and check that it gives the same logits and writes the same story. Then we race the two frameworks on this Mac's GPU, writing a token at a time and training at pretrain.py's batch size, with MLX's compiler and without, train a model in MLX from scratch, and bring it back to PyTorch.

The code

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

  1. 3:01ep032/step-1Installing itBrowseChanges
  2. 3:44ep032/step-2Our GPT in MLXBrowseChanges
  3. 10:37ep032/step-3A race on this MacBrowseChanges
  4. 16:27ep032/step-4Training in MLXBrowseChanges
  5. 22:31ep032/endTraining in MLXBrowseChanges

Transcript

Intro

0:00 Welcome back to episode thirty-two, where we're going to move our GPT out of PyTorch and into MLX, the array library that Apple's machine learning researchers wrote for their own chips. Until now, nearly all the GPU work in this series on this Mac went through PyTorch's MPS backend, which translates PyTorch's operations into work for Apple's GPU. I've wondered for a while what that translation costs us, so I want to see whether MLX is faster here, and whether our code reads any differently in it. Here's the model we'll have by the end of it.

0:31 PyTorch wrote this story, but the model behind it was trained from scratch in MLX, on this Mac, and then brought back. On the way there, we'll also race the two frameworks against each other.

0:43 The project has its own website, with a page for each episode and more about the model. The code is open source on GitHub, tagged at each step, so you can check out a step and run it, and the docs get a page on MLX today. And below, you'll find the episodes, each with its chapters and its code.

1:00 Last time, we put a mixture of experts in place of each block's MLP, eight experts with two per token. Per step, it ended a little below the dense model, and per minute on this Mac, the dense model stayed ahead, partly because PyTorch on Apple's GPU handles a lot of small pieces of work slowly. That made me want to try MLX on this GPU, with the model we already have, to see how much of that slowness was PyTorch's.

1:27 We're going to look at what MLX is and how it differs from PyTorch, and then write our GPT in it, block by block, keeping the names of our PyTorch model. That lets us load PyTorch's weights into it as they are, check that it gives PyTorch's logits, and see episode three's model write PyTorch's story in MLX. Then we race the two on this Mac's GPU, writing a token at a time and training on batches of our usual size. And last, we train a model from scratch in MLX and bring it back to PyTorch, so that our other scripts can use it. Right, let's start by reading what MLX's authors say it's for.

What MLX is

2:06 Its documentation calls it a NumPy-like array framework for machine learning on Apple silicon, from Apple's machine learning research team, and its Python side follows NumPy closely. It came out in December twenty twenty-three, and next to PyTorch, two of its ideas were new to me. MLX is lazy, so when you add two arrays, it writes down that it's going to add them, and does the work once something needs the answer, like printing it or calling eval. That lets it see a whole step before it runs it. The other is unified memory, which means the CPU and the GPU on these chips share one memory, and MLX arrays live there. So there's no moving tensors to a device, as with to device in PyTorch, and operations can run on either, on one array, without copying it. Of the two, unified memory is my favourite, as our PyTorch scripts pick a device and move things onto it, and here there's nothing to pick.

Installing it

3:02 It goes in our requirements file like any other package, MLX from version zero point thirty-two. The marker after the semicolon installs it on macOS and skips it elsewhere, so that Linux and Colab, where there's no Apple GPU, don't install a library they won't use.

3:18 Then uv installs it into the environment our scripts run in, reading the requirements file again. It resolves all one hundred and twenty-five packages and finds two to install. One is MLX, at zero point thirty-two point four, and the other is MLX Metal, which holds its compiled GPU kernels for Metal, Apple's interface to its GPUs. Nothing else moves, so our PyTorch scripts keep the versions they were tested with.

Our GPT in MLX

3:45 The model goes in a new file, MLX model, next to our PyTorch one. We import Python's math module, MLX's core as m x, which is its arrays and operations, and its n n module for layers, which looks a lot like PyTorch's. This file holds episode one's blocks, with LayerNorm, GELU and a learned embedding per position, under the names our PyTorch model gives them, so that a PyTorch checkpoint's weights load by name. I'm porting the oldest version of our block on purpose. It's the one the fine-tuned model of episode three uses, and it's enough to compare the two frameworks, without porting each option we've added since. Attention comes first, as an n n Module, like in PyTorch. Its init takes the config as a plain dictionary, and makes the four projections, queries, keys, values and the output, as MLX's Linear layers. Their weights are stored outputs by inputs, as PyTorch stores them, which is what makes loading by name work without transposing anything, and then comes dropout. Where PyTorch has forward, an MLX module has the call method, so that's where the work goes. The queries are reshaped into heads and transposed, so that the axes are batch, heads, tokens and channels per head, the order our PyTorch model uses. MLX's transpose takes the whole order of the axes, zero, two, one, three, where PyTorch's swaps two of them. The keys and values are reshaped like the queries. The cache is a list for the layer, which we update in place, with the keys and values so far joined to the new ones by concatenate, and the result goes back into the list. Then it runs MLX's fast scaled dot product attention, a fused kernel like PyTorch's, which takes the mask as the word causal. Unlike PyTorch's, it has no dropout on the attention weights, so in training, our two models differ there. A single new token sees all the cached ones, so it needs no mask. The heads are put back together with a transpose and a reshape, then go through the output projection and dropout. The MLP class below it is an n n Module too. In its init, the up projection goes from the model's width to four times that, the down projection brings it back to the width, and dropout follows, as in attention. Its call goes up, through GELU, back down and through dropout. MLX's GELU is the one with the error function, like ours, and there are two approximate ones too, which would give slightly different numbers. The block is pre-norm, as in PyTorch, and the init sets up its parts in the order they run. A LayerNorm goes first, and attention after it, then a second LayerNorm with its own weights, and last, the MLP. When it's called, it adds attention's output to the residual stream, then the MLP's, and each of them reads a normalised copy of the stream. The GPT class checks the config before anything else. If it asks for rotary embeddings, RMSNorm, SwiGLU or grouped-query attention, or turns off the causal mask, as diffusion does, it stops with an error, as this file has episode one's blocks and nothing else. I want an error here, because a model that loads fine and then quietly computes something different is a mistake we might not spot for a long time. After the check, it makes the token embeddings, a vector of the model's width for each token in the vocabulary, then the position embeddings, one for each place in the context window, and dropout. The blocks are a plain Python list, which MLX registers as it does any attribute, and below the list, the final norm, applied once, after all of them. The call method gets token ids and, if we're writing, a cache. With a cache, the new tokens come after the cached ones, so the positions start where the cache ends. The embeddings go in, through each block with its layer's cache, and out through the head. Ours shares its weights with the token embeddings, and as linear multiplies by the embedding matrix, so that the two stay one tensor, as they are in PyTorch. From torch loads one of our PyTorch checkpoints, with its tokenizer, as an MLX model. It imports PyTorch and our checkpoint module when it's called, and loads the checkpoint with our usual loader. It builds an MLX GPT from the checkpoint's config, and then goes through the PyTorch model's state dict, name by name, in one list comprehension. Each tensor goes through NumPy into an MLX array, under its own name, and since the head is the embeddings, its copy is left out. Load weights then puts them into the model by name, and it raises an error for a name that doesn't match, so a slip in our naming stops the load. Generate starts an empty cache for each block, runs the prompt through the model once, and keeps the ids so far in a list. Then it goes a token at a time, and stops at the block size. It slices out the last position's logits, and greedy picks the likeliest token, and otherwise we divide by the temperature, keep the top k with a sort, setting the rest to minus infinity, and sample with random categorical. Item turns the token into a Python number, which means it waits for the GPU, as MLX is lazy and builds the work up until a value is needed. The token goes on the list, and it stops early at the end-of-text id, if it's given one. Otherwise, the new token alone goes through the model, with the cache. When the loop ends, it returns the whole list, prompt and all. For the tests, there's a new file too, test MLX. Our requirements install MLX on macOS and nowhere else, so pytest's import or skip leaves out the whole file where it's missing, and our tests still pass on Linux. After it come our checkpoint saver, the MLX model's from torch and generate, our PyTorch GPT and its config, and the word tokenizer. Tiny first seeds PyTorch, and builds a small model, two blocks of thirty-two channels, and a tokenizer for forty tokens, three reserved ones and thirty-seven made-up words. It saves them as a checkpoint, and returns the model with its path. The first test checks that MLX gives PyTorch's logits. It builds tiny, loads it in MLX with from torch, and makes a random batch of token ids. It runs the batch through the MLX model and the PyTorch one, and the largest difference has to be under a ten thousandth. The second test is about writing with the cache. It opens like the first, with tiny loaded in MLX, and starts from three token ids. MLX writes twenty tokens greedily, and PyTorch with a top k of one, both with their caches, and they have to pick identical tokens. If MLX's cache were off by one position, the first test would still pass, as it runs without a cache, and this one would fail.

10:27 We run them with pytest, and both pass, so MLX gives PyTorch's logits to a ten-thousandth, and with its cache, it writes the tokens PyTorch writes.

A race on this Mac

10:38 The race gets a file of its own, MLX bench. It imports argparse and time, MLX's core, its layers and its optimisers, NumPy and PyTorch. From our own files, it takes the checkpoint loader, the MLX model under another name, as both files call their class GPT, with from torch and generate, then PyTorch's GPT with its config and pick device, and pretrain's batch size. As with the mixture of experts last time, the contenders take turns, so that whatever else the machine is doing slows them both alike. Race needs the contenders and the number of rounds, and tracks two things for each, its fastest time and an output. First, each one runs once to warm up, as the first run of anything on a GPU pays for compiling kernels and allocating memory. The rounds come next, one turn per contender, each run timed with the performance counter, and it keeps the best time of each. To my mind, the fastest time is the fair one for a race like this, since whatever else runs on the Mac at the time slows a run down and can't speed it up. When it's done, it returns the best times, and each one's output from its last run. Writing's arguments are the checkpoint, a prompt, a number of tokens and the rounds. It loads the checkpoint into PyTorch on the GPU, in eval mode, and into MLX through from torch, and it encodes the prompt once, for both. Write torch generates with PyTorch's generate and a top k of one, which keeps the likeliest token each time, and synchronize waits for the GPU to finish before the clock stops. MLX's generate runs greedily, and race has the two of them alternate. Each picks the likeliest token, so both should write an identical story. It counts the new tokens and prints how many. Under it come the numbers, each contender's seconds and tokens a second, a line saying whether the two stories match, and the story MLX wrote, decoded back into text by the tokenizer. Training has two arguments, the number of steps in a row and the rounds. Its config has six blocks of three hundred and eighty-four, with a dropout of zero. That's episode two's model, and the batch is pretrain's size, of random tokens, as a step takes as long whatever the tokens are. Both go without dropout, as MLX's fused attention has none, so neither does work the other skips. The tokens come from NumPy's random generator, with a fixed seed. PyTorch gets its GPT on the device, and an AdamW over its parameters, with weight decay. The inputs and targets go to the device as tensors, with the targets one token ahead of the inputs. Torch steps runs our usual step a number of times: the loss, zero grad, backward, clipping to a norm of one, and the optimiser's step, with a synchronize after the last one. The MLX side builds our MLX GPT from that config, in training mode, with MLX's AdamW, and the batch as arrays. It looks different, as there's no backward call on the loss. Value and grad wraps the model and the cross entropy of its output into a function that returns the loss and the gradients together, like JAX does. I'd take that over PyTorch's way, as the gradients come back to us as values, whereas backward stores them on each parameter. After clipping, the optimiser's update applies the gradients to the model, and the step returns the loss. State gathers what the step reads and changes, the model's weights, the optimiser's moments and the random state. Compiled is MLX's compile applied to that function, which traces it once and fuses what it can into fewer GPU kernels, with that state as its inputs and outputs, so that compiling doesn't freeze them. MLX steps repeats whichever step function it gets, and since MLX is lazy, each call builds up the work without running it. Eval on the state, after each step, runs it, as a training loop would, or nothing would run at all. This race has three contenders, PyTorch, MLX, and MLX with the compiled step. It prints the batch it trains on, and then milliseconds a step and tokens a second for each, worked out from its fastest turn. Main sets up argparse, with a description of the script, for the checkpoint and four options. By default, the prompt is once upon a time, with two hundred tokens to write, five steps in a row each turn for training, and five rounds of turns. It parses them, runs the writing, and runs the training after it. The file runs main when we call it as a script.

15:04 Let's run the race, on episode three's fine-tuned model. Keep in mind that this Mac's GPU wasn't free while I recorded this, as another program was using it heavily, and that's why the contenders take turns. Writing two hundred tokens one at a time, PyTorch takes about zero point four one of a second, about four hundred and ninety tokens a second. MLX takes about zero point one six, about thirteen hundred tokens a second, so about two point six times as fast. And both write an identical story, a sun that shines over and over, which is what greedy decoding does to a model this small. For a training step, PyTorch takes about four hundred and thirty milliseconds, MLX about three hundred and sixty, and MLX with its compiled step about three hundred and ten, so about one point four times as fast as PyTorch. I expected MLX to win at writing, as a token at a time is mostly the overhead of handing work to the GPU, and MLX's is lower. I didn't expect that compiling one Python function would buy another sixteen percent on top.

16:07 Side by side, MLX pulls furthest ahead on the writing, at about two point six times PyTorch's speed. A training step is mostly large matrix multiplies, which both frameworks run on Apple's GPU through Metal, so the gap there is smaller, and compiling the step makes about two fifths of MLX's lead.

Training in MLX

16:27 A model trained in MLX has to come back to PyTorch before sample, evaluate and the rest of our scripts can use it, so MLX model gets a to torch function. Tree flatten turns the model's nested parameters into a flat list of names and arrays, which are our PyTorch names. Each array goes through NumPy into a PyTorch tensor, and the head gets the embeddings again. Our PyTorch GPT loads them by name and is saved as a checkpoint like any other, at the path we give it, with its tokenizer. For training, we write MLX pretrain, and it imports a few of Python's own modules, MLX's core, layers and optimisers, NumPy and tree flatten. Our own files give it where checkpoints go, the data folder and the tokenizer loader, and our MLX GPT with to torch. From our pretrain script, it takes the batch size, the evaluation interval, the learning rates and the warmup, so the scripts can't drift apart. It's pretrain's run in MLX: the model, the batch, the learning rate schedule and AdamW, for a number of steps. Two things differ, though, as MLX's fused attention has no dropout, and its AdamW leaves out the bias correction unless we ask for it. Get batch picks random places in the memory-mapped tokens, and takes a block of tokens from each, with the targets one token further on. It makes them MLX arrays, and the loss function is cross entropy, averaged over the batch. Main seeds NumPy and MLX with one number, loads the word tokenizer, and the config asks for six blocks of three hundred and eighty-four, with a dropout of a tenth everywhere but the attention weights. Those are episode two's settings, and here they build our MLX GPT. Then eval on the parameters, which looks odd coming from PyTorch, but MLX is lazy, so the weights exist once something asks for them, and eval makes them now. It counts the parameters with tree flatten and prints them, with the device and the number of training tokens. The learning rate is a function of the step, written this time with MLX's operations. It warms up in a straight line over the first hundred steps, as in pretrain's schedule, from a hundredth of the rate to the full rate. After that, a cosine takes it down to a tenth, by how far through the run it is. Where picks one or the other, like an if on arrays, which lets MLX compile the schedule into the step. The optimiser is two AdamWs in a multi optimiser. The first gets the weights with two or more dimensions, the matrices, with a weight decay of a tenth. The second gets the rest, the biases and the norms' gains, without decay, which is what our param groups does in PyTorch. Loss and grad is value and grad again, and state is the model's weights, the optimiser's state and the random state. The step function is compiled, with that state going in and out, and it's traced once and fused into fewer GPU kernels. Inside, it's the loss and the gradients, clipping to a length of one, and the update. The whole training step is four lines, and after the race, I wasn't going to leave the compile line off. Estimate loss puts the model in eval mode, which turns dropout off, as pretrain does. For each split, it averages the loss over twenty batches, and then puts the model back in training mode. Before the loop, it sets training mode for the run, the clock starts, and the loop makes one pass more than there are steps. Each two hundred and fifty steps, and at the last one, it estimates the loss on both splits and prints it. On that last pass, it stops there, without training. Otherwise, it runs the compiled step on a batch, and calls eval on the state, which is where the GPU does the work. On each fiftieth step, it prints the loss and the tokens a second over the last fifty. After the loop, to torch saves the model as pretrain MLX, in our checkpoints, and it prints the steps, tokens and minutes. Without an argument, it runs twelve hundred and fifty steps, which is how many episode two's ten minutes took on the laptop. The tests now import load checkpoint and to torch too, for a third test. Once more, tiny goes into MLX with from torch, and it's written back to a second checkpoint with to torch. Then it loads the first checkpoint and the second, and for each weight, by name, the two have to be equal, to the bit.

20:48 The three tests pass, the round trip among them, so a model comes back from MLX with each weight as it was. Then we start MLX pretrain, for twelve hundred and fifty steps, and as in the last episode, the GPU was busy with another program while I recorded it. So the speed you'll see is probably lower than this Mac manages with a free GPU. After a slow start, the steps settle at about thirty-seven thousand tokens a second. It finishes in about eleven minutes, with a held-out loss of about two point two nine five.

21:21 Next to episode two's run, PyTorch on the laptop for as many steps, the MLX run's held-out loss is a little higher at each evaluation, about zero point zero four at the end. I didn't expect that, as apart from the two differences we wrote down in MLX pretrain, it's our model and our recipe. Less dropout should help a run this short, if anything, and the bias correction matters for the first few dozen steps, which fall inside the warmup. So my best guess is the initialisation, which I didn't port. Our PyTorch model starts its weights with a standard deviation of zero point zero two, smaller for the two layers that add into the residual stream. MLX's layers and its embedding start from their own defaults, which are wider. I'd want to fix that, and run each a few times with different seeds, before saying either framework learns better.

22:11 The way back to PyTorch works too, as sample, our PyTorch script, loads the model MLX trained and writes two stories from once upon a time. They read like episode two's did after its ten minutes: Lily and a big red ball, a box of toys, and a few sentences that don't quite make sense, like putting the ball in her mouth and running to it.

22:32 Last, the docs get a page on MLX, with the model, the race and the run, and it goes in the docs' list and their navigation. The README gets the commands, the tests, the race and the training in MLX.

Wrap-up

22:45 We've moved our GPT into MLX today, with PyTorch's weights loaded into it by name, and it gives PyTorch's logits and writes PyTorch's tokens. Writing a token at a time, it was about two point six times as fast as PyTorch on this Mac, and a training step with its compiler was about one point four times as fast. Its own run from scratch ended a little behind episode two's, which I'd put down to the initialisation I didn't port. If I had nothing but this Mac, I'd write the next model in MLX. Our series runs on NVIDIA GPUs and in Colab too, though, so PyTorch is still our main framework, even if I found the MLX version nicer to write.

23:23 I'd like to know whether these numbers hold on other Macs, so if you've moved a model of your own to MLX, tell me in the comments how it went, and on which chip. And if you'd like to follow along, subscribe to the channel. I hope you find this useful, and thanks for watching.