In this episode, we give our GPT a mixture of experts: eight smaller MLPs in each block, and a router that sends each token to two of them. We write it as a loop over the experts, measure it, and then run all the experts in one batched matrix multiply. We balance the experts with Switch Transformer's loss and with DeepSeek-V3's bias, see what happens without either, train each for two thousand steps next to the dense model on this Mac, and look at which words each expert ends up with.
The code
Each step on screen is a tag in the code's repository. The code at the end of the episode is ep031/end.
- 4:09
ep031/step-1The router and the expertsBrowseChanges - 10:13
ep031/step-2Training itBrowseChanges - 16:03
ep031/step-3All the experts in one multiplyBrowseChanges - 21:23
ep031/step-4Balancing without a lossBrowseChanges - 29:27
ep031/step-5Which words each expert getsBrowseChanges - 35:42
ep031/endWhich words each expert getsBrowseChanges
Transcript
Intro
0:00 Hi, and welcome to episode thirty-one, where we're going to take the MLP out of each block of our GPT and put a mixture of experts in its place. The mixture is eight smaller MLPs, and a router that sends each token to two of them. The reason I wanted to try it is that the big open models of the last few years, Mixtral, DeepSeek-V3 and the largest Qwen3 models, are mixtures of experts, and the idea still strikes me as a bit odd. A model holds several times more weights than it uses on any one token, and that's supposed to make it better. I want to see whether it holds at our size, on this Mac. First, a quick look at what we'll have by the end.
0:41 This is a held-out story, run through our model with eight experts in each block, and each word is in the colour of the expert that the middle block sent it to first. Above it are the words each expert gets most often, and they split up by the kind of word. One expert takes he, she and they, another the full stops, and two more take mostly nouns and feelings.
1:03 All of this lives on the series' website, which has more about the project and a page per episode. The code is on GitHub, with a tag at each step, so you can check out any of them and follow along, and the docs get a page on mixtures of experts today. Further down, there's the list of episodes, with their chapters and their code.
1:22 Last time, we handed our fine-tuned model to TRL, Hugging Face's library for training after pretraining, and ran GRPO with it. With our settings, it ended within a few points of the GRPO we wrote by hand, and it was quicker, mostly because it writes all of a rollout's stories in one batch. Today, we go back inside the model, to the part of each block that we've barely touched since episode seventeen, the MLP.
1:48 We're going to write the router and its experts, first as a plain loop over the experts, and then, once we've seen how slow that is, as a single batched matrix multiply. The experts need their share of the tokens, so we'll balance them with a loss from Google's Switch Transformer paper, with a bias from DeepSeek-V3, and once with neither, to see what goes wrong. Then we train four models on this Mac, the dense model and three mixtures, for two thousand steps each, so that they all see as many tokens. And last, we write a small tool that shows which words each expert ends up with. So, let's get going, with what a mixture of experts is.
How a mixture of experts works
2:27 In our GPT, each block has attention, which mixes information between tokens, and then an MLP, which works on each token on its own: it widens the token's channels, applies a nonlinearity and narrows them back. Most of a block's weights are in that MLP. In a mixture of experts, a small linear layer called the router looks at the token first and gives each of eight experts a score. The token goes to the two experts with the highest scores, here two and five, and each of them is an MLP of its own. The other six don't run for this token at all, so it pays for two of the eight experts, plus the router. The two outputs are added up, weighted by the router's scores, and go back into the residual stream as the MLP's output did. The first mixtures of experts date from the early nineties, and this sparse kind goes back to Noam Shazeer's paper of twenty seventeen. Mixtral, from Mistral, made eight experts with two per token a common setup, while DeepSeek-V3 and the big Qwen3 models use many more, smaller ones.
3:31 Our MLP is SwiGLU, from episode seventeen, with three matrices between three hundred and eighty-four channels and a thousand and twenty-four, so about one point two million weights in each block. Our experts are going to be half as wide, five hundred and twelve channels, so each has half of that. With eight of them, a block holds four times the MLP's weights, while a token goes through two experts, which is as many weights as the MLP had. So each token costs what it cost before, and the model has four times as much to choose from in its MLPs. I wanted the experts at this size, because with the MLP's full width, a token would cost twice as much, and a lower loss could just be the extra arithmetic.
The router and the experts
4:10 We start in our model file, with three new settings in the config. N expert is the number of experts in each block, and its default of zero keeps the one MLP we've had so far, so the models of earlier episodes load as they did. Expert top k is how many of them each token goes to, two, as in Mixtral. And expert hidden is the width of one expert, which by default is the MLP's width divided by top k. If I had to pick the line that matters most today, it's that default, as it keeps a token's arithmetic where the dense model had it. The MLP used to work out its width inside its init, and now the experts need that number too, so it moves out into a function of its own, mlp hidden. It's the rule from episode seventeen, and its comment moves with it: SwiGLU has three matrices to GELU's two, so at eight thirds of the embedding size wide, it has as many weights, rounded up to a multiple of sixty-four. The MLP now takes a width, and falls back to that function when it doesn't get one. Then the new class, MoE, short for mixture of experts. It keeps the number of experts and top k, and hidden is how wide each expert is, either set in the config or worked out by default, which comes to five hundred and twelve channels for us. The arithmetic goes in a comment over it, in two parts: each expert is an MLP of its own, and each token goes through two of the eight. And then, at the MLP's width divided by top k, a token costs what it cost with one MLP, while the block holds n expert over top k times the weights. The experts are a module list of our MLPs, at that width. A module list is PyTorch's list that registers each module's weights with the model, so the optimiser finds them. The router is a linear layer from the embedding size to one score per expert, without a bias. It's tiny, about three thousand weights a block, and it decides where each token goes. Aux loss and load start out empty, and each forward pass fills them in. In forward, x comes in as batch, time and channels, and we flatten it into one row per token. From here on, each token is routed on its own, whatever sentence it's in. Softmax turns the router's scores into probabilities over the experts, and torch top k gives each token's two highest, along with their probabilities. We divide those two by their sum, so that the weights add up to one. Mixtral does it this way too, and I prefer it to the raw probabilities, because then the output stays on one scale whether the router is confident or not. Next comes getting each expert its tokens, which is the part that took me longest to get right. Flat is the list of chosen experts, two per token. Argsort gives us the order that sorts that list, so all of expert zero's pairs come first, then expert one's, and so on. In other words, we sort the token and expert pairs by expert, so each expert gets its tokens as one block of rows. Token is the token each sorted pair came from, its position divided by top k, and weight is that pair's weight, in the new order. Rows gathers the tokens' channels in that order, and bincount counts how many pairs each expert got. Out starts as zeros, one row per token, and the loop goes over the experts, with their counts. Each expert runs on its slice of the rows, from start to end, so its MLP works on the tokens it got, and on none of the others. Index add then puts the outputs back, which here means each output scaled by its weight, and added into the row of the token it came from. A token with two experts gets two additions into its row. After the loop, the balancing loss, from Google's Switch Transformer paper. Share is each expert's fraction of the pairs, and the loss is n expert times the sum, over the experts, of each one's share times the average probability the router gave it. Spread evenly, it's one, and it grows as the router favours a few experts. We keep it, and the counts, for the training loop to read, and the output goes back to batch, time and channels. Last, in the block, the MLP becomes an MoE when the config asks for experts. Then the tests, in a new file, test MoE. Tiny builds a small model, two blocks with an embedding size of thirty-two and four experts, with the modern block. The first test checks that without experts, each block keeps its plain MLP, and that there's no router anywhere, so the dense model is untouched. The second is the one I trust most, because it works out each token's answer the slow way. For each token of a small batch, it starts again from the router. Probs is the token's scores, from the router and a softmax, and best is its two highest experts, picked with top k, and their weights are those two scores divided by their sum. Expected is the weighted sum of those two experts, run on that one token. Our sorting, slicing and adding back has to give the slow answer, to a rounding error. The third test takes a block of each, the mixture's and the plain MLP, to compare their sizes. It counts one expert's weights, from its three projections, the gate, the up and the down. Then, times top k, they have to come to as many as the MLP has, which is what makes our comparison fair. And the last one checks the balancing loss, both ends of it. First, we set the router's weights to zero, so that all the scores are equal, whatever the token, and the loss has to come out at one. Then we give channel zero a value of one on each token, and the router a weight of a hundred from it to expert zero. That makes expert zero's score far higher than the others', so that it's picked for each token. The loss goes up to n expert over top k, two here, as expert zero gets half the pairs with all of the probability.
10:05 We run them with pytest, and all four pass, so the sorted version adds up the experts as the slow, token by token version does.
Training it
10:14 To train it, our pretrain script needs a few changes. Balance weight is a hundredth, the weight the Switch Transformer paper gives its balancing loss. Main gets four new arguments: the number of experts, top k, how to balance them, and a fixed length for the training. The checkpoints' folder gets the experts in its name, with the top k and the balancing when they're not the defaults, so pretrain modern MoE eight, and MoE eight none without balancing. The config gets the experts and top k, and those two are all the model needs to know, as the balancing happens in the training loop. The steps are new, as until now training was a number of minutes, and that wouldn't be fair here. I expected a mixture of experts to be slower per step on this Mac, so in ten minutes it would get through fewer batches than the dense model, and we'd be comparing two things at once. Progress is a small function inside main, giving a number from zero to one, which both the schedule and the loop read. It returns the step over the steps, when there are steps, and otherwise the time so far over the time we have. Over it, we write what it measures: how far through the run we are, by the clock or by the steps, so that runs of different speeds see as many tokens. The learning rate's schedule follows progress, the warmup and then the cosine, and the loop runs until progress reaches one, whichever way it's measured. In the loop, with experts and the balancing loss, we add the blocks' balancing losses, averaged over the blocks and weighted by the balance weight, to the next-token loss. Over that line goes where it comes from: the experts' balancing loss, averaged over the blocks, a hundredth of it on top of the loss we learn from, as in the Switch Transformer paper. Without experts, or with another kind of balancing, the backward pass gets the loss alone. The loss we print and log stays the next-token loss, so that the dense model and the mixtures are measured on that and nothing else. Each fifty steps, the line we print goes into a variable first, as it gets more on the end with experts. Shares is each expert's share of the pairs, block by block, as a table of six blocks by eight experts, moved to the CPU to read. A loop over the blocks, and another over each block's experts, sends each share to TensorBoard on its own, so we can plot any expert in any block later. Then the line gets the smallest and largest share in the table. With eight experts, an even load is twelve and a half percent each, and after that, the line is printed. At the bottom, a small option function reads a flag's value, or gives back a default when the flag isn't there. The minutes can be left out when there are steps. Dash dash MoE gives each block that many experts, each token going to dash dash top k of them, two by default. The experts are balanced with the loss we just added, unless dash dash balance is none. And dash dash steps ends the run after that many steps, instead of the minutes. Main then gets each of them through option, with loss as the default for dash dash balance, and no limit on the steps unless one is given. Before any long run, I want to know what a step costs, and timing on a Mac that's doing other things at the time is noisy. So there's a small benchmark, in a new file called MoE bench. It imports argparse, statistics for the median, and time, then PyTorch, our sync from bench, which waits for the GPU to finish its work, the model with its config, and pretrain's batch size. What it measures is a training step's time, the dense model's against a mixture of experts', on pretrain's batch. The two models take turns at it, a few steps each, so that whatever else the machine is doing slows them both down alike. Main takes three settings, through argparse: the number of experts, eight by default, so that it matches our runs. Then the rounds, ten of them, which is enough for a median to settle. And the steps in a row for each model in a round, five, as a few steps together time better than one. Each has a default, so running it without flags gives the comparison we're after. It seeds PyTorch, so each run starts from identical random weights, and picks the device, which is the Mac's GPU here. Models holds the two, each with an optimiser of its own: the dense model, with zero experts, and the mixture, both with the modern block and a vocabulary of ten thousand words. Each optimiser is AdamW with a small learning rate, as nothing here needs to learn, the weights just need updating. X and y are random tokens and targets, a batch of pretrain's size, as a step takes as long whatever the tokens are. Step is our usual training step: the loss, zero grad, backward, and the optimiser's step. Each model first takes three steps to warm up, as the first ones on a GPU pay for setting up its kernels and its memory. Then the rounds, where the two models take turns, five steps each, with a sync before the clock starts and another before it stops. Each turn's time per step goes in that model's list, in milliseconds. Once the rounds are done, it takes each model's median. It prints each model's median, with its parameters and its tokens a second, and how many times as long the mixture's step takes. I went with the median, because one turn that something else slowed down would drag a mean up with it.
15:30 Let's run the benchmark, with the experts as a loop. It takes about three minutes, as the two models take their turns. A disclaimer first: another program was loading this Mac's GPU heavily while I recorded it, so these times are about twice what a quiet Mac gives, and the ratio says more than the milliseconds. The dense model takes about eleven hundred milliseconds a step, and the mixture about twenty-five hundred, so about two point three times as long, for a step that does as much arithmetic per token. I'd guess most of that gap is the loop, with the routing around it adding the rest.
All the experts in one multiply
16:04 Per token, the loop does as much arithmetic as the dense model, so the extra time goes somewhere else. Each expert runs as its own small MLP, eight per block and forty-eight in the model, with three small matrix multiplies apiece. Python hands each of them to the GPU as a separate piece of work. A GPU is good at one large multiply, and a lot less good at many small ones. So the fix is one multiply per matrix, for all eight experts at once. In the init, we first check that the model uses SwiGLU, and raise an error if it doesn't, as the experts are about to be written out as SwiGLU MLPs, and our mixtures use the modern block anyway. Then the experts' weights become three stacked tensors. Gate is eight experts, by three hundred and eighty-four channels, by five hundred and twelve, up has that shape too, and down goes the other way, from five hundred and twelve back to three hundred and eighty-four. With the experts' weights stacked, one batched matrix multiply runs all the experts at once, instead of one small multiply per expert. N n Parameter tells PyTorch that a tensor is a weight to train. They start as random numbers with a standard deviation of zero point zero two, like our other weights, and down starts smaller, like the MLP's down proj, as it adds into the residual stream. Dropout comes over from the MLP, as the experts don't have their own anymore. Expert runs one expert on its own, the way the MLP did: the gate's projection through SiLU, times the up projection, and back down. It's there for the tests, and to read, as the forward pass won't call it. In forward, the routing and the sorting stay as they were. Expert keeps, for each sorted pair, the expert it goes to. Then slot, each pair's row within its expert's block. It's the pair's place in the sorted list, minus the place where its expert's pairs start. Cumsum gives the running totals of the counts, and taking each expert's own count away gives where it starts. Rows becomes a three-dimensional tensor of zeros, one block per expert, each as tall as the busiest expert's count, and new zeros puts it on x's device, with x's type. Rows at expert and slot gets the tokens' channels, so each expert's block holds its tokens at the top and zeros below them. Then torch bmm, for batched matrix multiply, which takes two stacks of matrices and multiplies them pair by pair, in one call. The rows times the gates and the rows times the ups give eight blocks of five hundred and twelve channels. SiLU and the product do SwiGLU's gating, and a third bmm with down brings them back to three hundred and eighty-four. The rows of zeros go through all of it too, which is wasted work. So the busier the busiest expert, the more of the multiply goes to padding. Out is now a single index add of all the pairs at once, each output read back from its expert and slot, times its weight, and the dropout goes on at the end. The test changes in two places, as the experts aren't MLPs in a list anymore. The slow version calls expert, and an expert's size is its three slices of the stacked weights.
19:11 The tests pass with the batched experts, so they add up as the loop did. Then the benchmark again, with the batched experts, on a GPU that was busier still, as the dense model's step went up too, so it's the ratio we should compare. The mixture's step takes about seventeen hundred milliseconds, about one point two times the dense model's, down from more than twice with the loop. That's better, though still more than I'd like, because the experts are just one part of a mixture's step. The rest is the routing, the softmax, the sort, the gather into blocks and the add back, along with the padding, and an optimiser that now updates two and a half times the weights. On NVIDIA GPUs, libraries like MegaBlocks run the experts with grouped kernels that skip the padding, and I've not found anything like that for Apple's GPU in plain PyTorch.
19:59 As multiples of the dense model's step, the loop took about two point three times as long on the busy GPU, and the batched experts about one point two. The long runs coming up had the GPU to themselves, and they put the batched mixture at about one point four. That's the number I trust most, as a busy GPU slows the two models in different ways and flatters the mixture here. Either way, on this Mac, a mixture costs us time at equal arithmetic, and to win by the clock, each of its steps has to learn a good deal more than the dense model's.
Balancing without a loss
20:32 DeepSeek-V3's technical report, from December twenty twenty-four, balances its experts another way. Its section on load balancing starts from the problem we just handled: without balancing, the router collapses onto a few experts, and the usual fix is an auxiliary loss, like Switch's. But a loss that's too large hurts the model, as it pulls on the router's gradients for a reason that has nothing to do with the next token. So they add a bias per expert to the scores, and use it to pick the experts and for nothing else, as the weights still come from the original scores. After each step, an expert that got more than its share has its bias lowered by a small step, gamma, and one that got less has it raised. On paper, this is the one I'd pick, since it keeps the balancing out of the loss the model learns from. They do keep a very small balancing loss per sequence as well, which we're going to leave out.
21:24 In the init, the bias is a buffer, made with register buffer. A buffer belongs to the module and goes into its checkpoints, like a weight, but the optimiser doesn't train it, and ours starts at zeros, one per expert. Putting it in the wrong place wouldn't raise any error, so we spell out its use in a comment: added to the scores to pick the experts, and nowhere else. It's DeepSeek-V3's balancing without a loss, which update bias nudges after each optimiser step, and it stays at zeros with the balancing loss. In forward, the choice of experts changes, as top k now runs on the probabilities plus the bias, and we keep its indices and nothing else. Over it, we write how the work is split now: each token's top k experts, by score with the bias, and their weights from the scores without it, scaled to add up to one. Gather does the second half, reading each chosen expert's probability from the scores without the bias, and the weights are divided by their sum, as before. Update bias is the rule from the paper. Torch no grad keeps it out of the autograd graph, as it's a plain update of a buffer, with nothing to differentiate. Load is the last batch's counts, as floats. In words, an expert that got more than its share of the last batch is picked a little less often from now on, and one that got less, a little more, by a step of rate either way. The mean load minus an expert's load is positive for an expert below its share and negative above it, and sign turns that into plus or minus one. Times the rate, a thousandth as in the paper, it's added to the bias. In the training loop, with that kind of balancing, each block's MoE calls its update right after the optimiser step. The usage comment at the bottom now says the experts are balanced by dash dash balance, which takes loss, the default, bias, or none. And it gets a test of its own, at the end of the test file. It runs on the tiny model's first block, with a random batch of three sequences of four tokens. We set expert three's bias to ten, far above any probability, so that expert three is picked for each token, and run a batch through. The test checks that expert three got all twelve tokens. Then it works out one token by hand, the first one in the batch, as a single token is enough to check the weights. Probs is its scores without any bias, and other is the second expert it picked, with the bias in. The two weights are their probabilities, divided by their sum, and expected is the weighted sum of the two experts on that token, which the output has to match. That's the line that checks the bias stays out of the weights. Then update bias runs, with a rate of a half, which makes the numbers easy to check by eye. It lowers expert three's bias to nine and a half, as it got more than its share. And it raises the bias of each expert that got less than its share, from zero to a half.
24:15 With all five passing, we know the bias moves the choice of experts and leaves their weights to the router's scores.
Four runs of 2,000 steps
24:21 Now the four runs, each of them two thousand steps of forty-eight windows of two hundred and fifty-six tokens, so about twenty-five million tokens, about one and a quarter times the size of our TinyStories training set. The dense model goes first, our modern block with one MLP each, and fourteen point six million parameters. It goes through about twenty-two thousand tokens a second on this Mac, and by the end, its sample from once upon a time is about a big, friendly dog that plays near a big tree and meets a little bird. It takes about twenty minutes, and its held-out loss ends at about one point nine zero four.
24:56 Then the mixture, with the balancing loss, which has thirty-five point eight million parameters, about two and a half times the dense model's, and a token goes through as many as before. At the end of each line, the experts' shares go from about seven to twenty percent, around the twelve and a half that would be even. So the loss keeps each expert in use, while leaving some of them a good deal busier than others. It's slower, at about sixteen thousand tokens a second, and its last sample is nearly word for word the dense model's, the friendly dog by the big tree. It takes about thirty minutes, half as long again as the dense model, though some of that is a stretch in the middle that ran slower. Its held-out loss ends at about one point eight eight three, a little below the dense model's. And I didn't expect its loss on the training batches to be about zero point zero five below its held-out loss, three times the dense model's gap. With two and a half times the weights, on a dataset this small, I think the mixture is starting to learn its stories by heart.
25:57 On a chart of the evaluations, from step two hundred and fifty, the mixture is below the dense model at each one. The gap is widest early on, at step five hundred, at about zero point zero seven, and stays near five hundredths after that. Then at the last evaluation, it narrows to about zero point zero two. I'd put that narrowing down to the memorising we just saw, though one run can't prove it. Per token, then, the extra weights do help, even at our size, which I wasn't sure of going in.
26:28 Next, the mixture without any balancing, which is lopsided from the first lines to the last: in some block, an expert gets none of the tokens at all, while another gets over forty percent. Noam Shazeer's paper already describes this collapse, where an expert that gets a few more tokens early on is trained more, scores higher, and gets picked more, and the ones left out don't recover. It's also slower than the balanced mixture, at about thirteen thousand tokens a second, which surprised me at first. The reason is our batched multiply, as each expert's block of rows is as tall as the busiest expert's, so with one expert at forty percent, a lot of the multiply is padding. After about thirty-six minutes, its held-out loss is about one point nine zero five, which is the dense model's, near enough. So without balancing, we paid for four times the weights in the MLPs, and by the last evaluation, we had nothing to show for them.
27:23 And the last run, with DeepSeek-V3's bias in place of the balancing loss. Another program was using this Mac's GPU heavily while it ran, so its speed and its minutes don't tell us much, and I'll leave them out. By the end, though, its experts are between about eleven and thirteen percent of the tokens, a lot closer to an even twelve and a half than with the loss. Its held-out loss ends at about one point eight nine zero, zero point zero one below the dense model's.
27:51 On a chart of the busiest expert's share, step by step, the run without balancing stays above forty percent from start to end. With the balancing loss, the busiest expert settles at about a fifth of the tokens. With the bias, it starts out as lopsided as the others, and gets pulled down to nearly even within a few hundred steps, as the bias builds up a thousandth at a time. The bias was already my favourite on paper, and it gets far closer to even than the loss does.
28:20 After two thousand steps, the dense model is at about one point nine zero four. The mixture with the balancing loss is the lowest, at about one point eight eight three, and the one with the bias is at about one point eight nine zero. The one without balancing is back at the dense model's, about one point nine zero five. The two balanced mixtures are within a hundredth of each other, which is about how far apart runs with different seeds landed in episode twenty-three. So I'd call it a draw between them, with both of them below the dense model at each evaluation. I'd hoped the more even split from the bias would show up in the loss, and after two thousand steps, it doesn't.
29:00 The mixtures also took longer to train, though. After the dense model's twenty minutes, the mixture with the balancing loss had reached about step fourteen hundred of two thousand, and its held-out loss there was about one point nine seven, against the dense model's one point nine zero. So by the clock on this Mac, the dense model wins, and by a good margin. Each of the mixture's steps helps a little more, but not nearly enough to make up for how many fewer of them it gets through.
Which words each expert gets
29:27 To see what the experts ended up doing, the MoE first has to keep its choices. Chosen is each token's experts from the last batch, the first choice first, as top k sorts them by score, and the forward pass stores it next to the load. Then a small tool, in a new file called experts. It imports argparse, os and re, and from collections, Counter and default dict for the counting. Then NumPy and PyTorch, and from our own files, the checkpoint loader, the data folder, pick device, and the end of text token with the tokenizer's reserved tokens. Colours is a colour for each expert, as red, green and blue values for the terminal, which takes twenty-four-bit colours in an escape code. Paint wraps a piece of text in its expert's colour, and resets the colour after it. First choices runs held-out text through the model, and the comment over it says what comes out: each token's first choice of expert, in each block, as an array of blocks by tokens. Window is the model's context, two hundred and fifty-six tokens, and windows cuts the tokens into rows that long, dropping the few left over at the end. Then it runs forty-eight windows at a time. After each batch, it reads each block's chosen experts and keeps the first column, the expert each token went to first, and stacks the six blocks into one array, on the CPU. At the end, the batches are joined along the tokens, and it all goes to NumPy for the counting. Torch no grad keeps it from building a graph we don't need. Spaced puts back the spaces our word tokenizer took out, so that a story reads normally. The result is a list it builds a word at a time, each with its space. It walks through the words, and a word is glued to the one before it when it's the first one, a full stop or a comma, or either side of an apostrophe, much as the tokenizer's detokenize does it. A word that isn't glued gets a space in front of it, and goes on the end of the list. Main reads its arguments with argparse, with a line of description for the help. It takes a checkpoint, which is the mixture we want to look at, as our pretrain script saved it at the end of a run. Then a block to look at, which is the middle one by default, and how many held-out tokens to route, a hundred thousand, enough to see each common word many times. It picks the device, and our checkpoint loader gives back the network and its tokenizer. Then eval switches it to evaluation mode, so that dropout is off. N expert and the layer come from the model's config, block three for our six. Tokens is the first hundred thousand tokens of the held-out file, read with a memory map, and first choices routes them, cut to a whole number of windows. The table's header comes before anything else, a name for each column, in its colour, padded so that the columns line up with the numbers below. Over it, we note what the table is: each expert's share of the first choices, block by block, which is one over eight each, so twelve and a half percent, when they're even. Below the header, the table gets a row per block. For each block, bincount counts how many first choices each expert got, and they're printed as shares of the tokens. Then, for the block we're looking at, it counts the words. Seen counts each word in the held-out text, for the shares. Routed keeps a counter for each expert, a default dict that makes a new counter the first time an expert comes up, and the loop adds each token to its expert's counter, one token at a time. For each expert, it takes the eight words it got most often, leaving out the reserved tokens like the end of text. Words joins them into one line, each word with the share of its uses that went to this expert. That second number is the one I care about, as it says whether a word always goes to one expert, or whether the router decides by the words around it. An expert that got nothing prints no tokens. Last comes a held-out story, from those hundred thousand tokens, so that we can see the routing on real text. Ids is the tokens as a plain list. Over it goes what we're after: the first whole held-out story, after the first end of text, each word in the colour of its expert there. Eot is the end of text token's id, which we get from the tokenizer. The story starts after the first end of text token, so that we read it from its first word, and stops at the next one, or after eighty tokens. Each word is painted in the colour of the expert it went to first in that block, so we can read the routing off the page.
33:53 We run it on the mixture with the balancing loss. In the first table, each block uses all eight experts, each with somewhere between a few percent and just over a quarter of the first choices. The words are what I was waiting for, and they split up surprisingly cleanly. In block three, expert three gets and, they, he and she, the words that start a clause, nearly all of their uses each. Expert four gets the full stops, the exclamation marks and the closing quotes, and the words that start a story, like once. Expert seven gets mostly nouns, mom, dog and bird, though big is in there too, and expert one gets the feelings, happy, sad, fun and smiled. So the experts split the work by the kind of word, which isn't what I pictured from the name, one expert for dogs and another for princesses. Mistral reported this for Mixtral too, with experts that followed syntax more than topic, and I find it neat that a model this small does it as well. In the story, it shows as colours, with the words that start a clause in one colour and the punctuation in another.
35:00 And now the mixture we trained without balancing. Its table shows the collapse, as in block two, three of the eight experts get none of the first choices, and one gets about half. In block three, expert four isn't the first choice for any token, and in training, it got almost none after the first few hundred steps. So its weights are there, trained at the start and then all but left alone. The experts that are left still split the words by kind, the names to one and the full stops to another. So the experts specialise without balancing too, while some of the weights we paid for sit there unused.
35:42 Last, the docs get a page on mixtures of experts, with the sizes, the routing, the three ways of balancing, the four runs and the words each expert ended up with. It goes in the docs' list and their navigation. And the README gets the commands, the tests, a run with eight experts and the experts tool.
Wrap-up
36:02 So, today we put a mixture of experts in place of each block's MLP: a router and eight experts, two per token, first as a loop and then as one batched multiply. Per step, the balanced mixtures ended a little below the dense model, with as much compute per token. Per minute on this Mac, the dense model stayed ahead, as the mixture's run took about half as long again. Without balancing, a few experts took over and the gain went away, and DeepSeek-V3's bias spread the tokens more evenly than the loss did. And the experts split the words by kind, with the pronouns going to one and the punctuation to another. For a model this size on a Mac, I'd keep the dense model, a little reluctantly after all the work on the experts. On a cluster of GPUs with kernels made for this, I can see why the big labs went the other way.
36:54 If you've trained a mixture of experts yourself, I'd like to know in the comments whether the balancing went as smoothly for you, and whether you'd pick the loss or the bias. And if you'd like to follow along, subscribe to the channel. I hope you find this useful, and thanks for watching.