In this episode, we hand our model to TRL, Hugging Face's library for training language models after pretraining, and train it with GRPO. We install it, save our GPT in GPT-2's format so TRL can load it, give it our instructions as a dataset and our reward as a function, and map each of our settings to TRL's config. We run it with the settings of the GRPO we wrote in episode sixteen, and with TRL's own defaults, and measure both with our own scripts, next to our own GRPO.
Topics: Reinforcement learning
The code
Each step on screen is a tag in the code's repository. The code at the end of the episode is ep030/end.
Transcript
Intro
0:00 Hello and welcome to episode thirty, where we're going to hand our model to TRL, Hugging Face's library for training language models after pretraining, and let it run GRPO in place of our own code. I think this is interesting to do because we wrote GRPO by hand in episode sixteen, so we know what each line of it does. That means we can open up a library that people use on models with billions of parameters, and see how much of it is the GRPO we wrote, and where its authors decided differently. First, a quick look at where we'll be by the end.
0:33 This is our model after about six point four minutes of GRPO in TRL. Asked for kite, river and brave, it writes about a brave little boy who flies over a river, and gets the kite in too, while brave comes back again and again. Its stories now use about forty-five percent of the words an instruction asks for, up from about twenty-seven, and we're going to measure it next to the GRPO we wrote by hand.
0:57 The series has its own website, with more about the project and a page for each episode. The code is on GitHub, tagged at each step, so you can check out any point and follow along, and the docs get a page on TRL today. Further down are all the episodes, each with its chapters and a link to its code.
1:18 A quick reminder of where we left off, first. Last time, we took attention out of our GPT and put Hyena in its place, long convolutions computed with the fast Fourier transform, between two gates. Its layer got faster than attention's once the window was long enough, while the model couldn't copy a name from earlier in a sentence, which attention does easily. Today, we leave the architecture alone and go back to reinforcement learning, with episode three's fine-tuned model and the GRPO from episode sixteen.
1:49 We're going to install TRL next to our code, and give it our fine-tuned model in the format of Hugging Face's transformers library, as a GPT-2, which our hub script has known how to write since episode five. TRL takes the instructions as a dataset and the reward as a function, and its settings go in a config, which we're going to fill in from our GRPO script, one setting at a time. Then two runs of thirty-two rollouts each, as many as episode sixteen did in its ten minutes: one with our script's choices, and one with TRL's own defaults. Last, the trained weights come back into our format, so that our evaluate script measures them, next to episode sixteen's numbers. All right, let's get started with what TRL is.
What TRL is
2:32 TRL, short for Transformers Reinforcement Learning, is Hugging Face's library for what comes after pretraining. It trains transformer language models with supervised fine-tuning, GRPO, DPO, reward models and more, and it's built on their transformers library, so a model that transformers can load, TRL can train. Further down, its trainers are sorted by kind: online and offline, along with reward models and distillation. The online ones, GRPO and RLOO, have the model write its own answers as it trains, as our GRPO did, and the offline ones, SFT, DPO and KTO, learn from text written beforehand. We've written three of them by hand in this series: SFT in episode three, DPO in episode seven and GRPO in sixteen. What surprised me is that PPO, which we wrote in episode eight, isn't in TRL one point seventeen at all, not even among the experimental trainers. My guess is that GRPO and RLOO took its place, as neither needs PPO's critic.
3:35 Each trainer has a page of its own, and the GRPO trainer's opens with a quick start that's quite short. Its data is DeepMath, about a hundred thousand maths problems on the Hugging Face Hub, each with a prompt and a solution. The script loads that dataset and gives the GRPO trainer a model by its name on the Hub, Qwen two point five, with half a billion parameters, along with a reward function that checks the answer against the solution. Then train runs the whole loop: the rollouts, the groups, the advantages and the updates we wrote by hand in episode sixteen. Our model has about fifteen million parameters and writes children's stories, so ours is going to take more lines than this, to bring our own model and our own reward to it.
Installing it
4:19 Installing it starts with a line in our requirements file, TRL from version one point seventeen, the latest as I'm recording this, at the end of the list, which we keep in alphabetical order.
4:30 Then uv installs it into the environment our scripts run in, with uv pip install dash r, which reads a requirements file. It resolves the whole file again, one hundred and twenty-three packages, and finds that it has to install fourteen of them. On the way, it warns that it copies the files instead of linking them from its cache, as the cache is on another disk, which costs a little time and nothing more. There's TRL, at one point seventeen point one, and datasets, Hugging Face's library for loading, caching and transforming data, which TRL reads its training sets from, along with the packages datasets uses to download files. It moves fsspec, which datasets reads its files through, back a few versions. What it doesn't touch is transformers or PyTorch, so our other scripts keep the versions they were tested with.
Our GPT as a GPT-2, and back
5:21 TRL trains models from Hugging Face's transformers library, and ours is a PyTorch class of our own, so it can't go in as it is. Back in episode five, our hub script learned to save our model as a GPT-2, since our blocks have GPT-2's layout, with learned positions, LayerNorm, GELU and biases. To GPT-2 renames each weight, joins q, k and v into one wide layer, and transposes the layers GPT-2 stores the other way round. That gets the model into TRL, and we also want the way back, so that our own scripts can sample and measure whatever TRL trains. That's from GPT-2, which takes a GPT-2 and our model. Theirs is the GPT-2's state dict, its weights by name, and above it goes what the function is for: the way back, a GPT-2's weights into our model, so that our scripts can sample and measure it. State is the dictionary we're going to load into our model, under our own names. The token embeddings come from w t e, the positions from w p e, and the final norm from l n f, its weight and its bias. Our head shares its weights with the token embeddings, so it gets w t e as well. Then a loop over the blocks, where b is the start of our names for block i, and h is the start of GPT-2's. GPT-2 projects the queries, keys and values with a single layer, three times as wide, and stored as inputs by outputs. So we transpose its weight and chunk it into three, which is what we write over it: the one wide layer, cut back into q, k and v. Its bias is chunked into three as well. Zip pairs each of the letters q, k and v with its weight and its bias, which go in under our names, q proj, k proj and v proj. The next loop pairs GPT-2's names with ours for the other three layers: c proj with o proj, attention's output, then c f c with up proj and c proj with down proj, the MLP's two. Their weights are transposed back as well, as GPT-2 keeps them inputs by outputs, while their biases copy over as they are. The last loop is for the two LayerNorms, l n one and l n two, which become our attention norm and MLP norm. Their weights and biases are plain vectors in both models, so they copy over unchanged. Load state dict copies it all into our model, and it raises an error for any name that's missing or left over, so a mistake in this mapping stops right there, instead of leaving a model half loaded. And it gets a test, in a new file, test hub. It imports PyTorch, our two converters from hub, our model with its config, and the word tokenizer with the list of its reserved tokens. Test GPT-2 and back seeds PyTorch and builds a tiny model, two blocks with an embedding size of eight. Its tokenizer has those reserved tokens, unknown, padding and end of text, and two words, as to GPT-2 needs the end of text and padding ids. The model goes to GPT-2, then back into another model, a fresh one, so that nothing can pass by being left as it was. Each of our weights has to come back equal, and on a random batch, the GPT-2's logits have to match ours, within a rounding error.
8:26 We run it with pytest, and it passes, so a model that goes to GPT-2 and back comes back with each of its weights as it was.
The trainer
8:34 Now the trainer, in a new file called TRL GRPO. It imports os, sys, textwrap and time, and PyTorch. From datasets, it takes the Dataset class, the table TRL reads its prompts from. From transformers, it takes the progress callback and the Trainer callback, as TRL's trainers are built on the Trainer class of transformers, and callbacks are how our code hooks into its loop. From TRL, it takes the GRPO config, which holds the settings, and the GRPO trainer, which runs the training. Then our own files: the checkpoints and runs folders, with loading and saving checkpoints, and the data folder. From DPO, the demo instruction and words rate, which measures the share of the requested words on held-out instructions, and from evaluate, load instructions and words used. From GRPO, how often it evaluates, the group of eight and the sixteen prompts. From hub, our converters both ways, and the tokenizer's, and from model, pick device. From PPO, the clip, the epochs, the learning rate and the minibatch size, then the most tokens a story gets, write from sample, instruction and parse from SFT, and the end of text token. Steps is the minibatches in a pass over a rollout: sixteen instructions times eight stories, sixteen at a time, so eight. Load prompts reads the training instructions, as load asks does, but it keeps them as text, since TRL tokenizes the prompts on its own, with the model's tokenizer. It opens the training file and splits it at each end of text token, so that each document is an instruction with its story, and parse splits each document into its fields, such as Words and Story. The rows are the instructions that ask for words and have a story, each with its prompt, laid out by instruction as the fine-tuned model saw them, and its words, as a list. The comment above them says how TRL is going to read them: a column called prompt, and the others passed to the reward, by name. Then Dataset from list turns the rows into a dataset, keeping the prompts short enough to leave two hundred tokens for the story in our window. Words reward is our reward function, and TRL calls it with the completions, the stories as text, and with each other column of the dataset under its name, so words arrives as the words each story was asked for. The keyword arguments take whatever else TRL passes, such as the prompts and the token ids, which we don't need. It returns a number per story, the words used over the words asked for, and above it, we write which reward this is: episode eight's reward, the share of the words asked for that the story uses. Report is a Trainer callback, and its init takes our model, our tokenizer and the optimiser steps in a rollout. The comment above it is why we need one: TRL runs the loop, and a callback is how our code gets a turn, a line per rollout, as our GRPO script prints. It keeps the three of them, loads the fifty held-out instructions, notes the start time, and keeps the last rollout it evaluated, none so far. Evaluate is where we measure the model that TRL is training. From GPT-2 copies TRL's weights into our model, and the line above it gives the reason: TRL's weights in our model, so that our measurement measures them. Words rate writes a story for each held-out instruction and returns the share of the words they use. It's the measurement our GRPO script printed, so that the two runs can be compared, and write gives us the demo story for rain, cake and jump. We print both as our GRPO script prints them, so that its output and this can be compared line by line, and we note the rollout. On train begin is the trainer's first call, and it evaluates the fine-tuned model, as rollout zero. On log comes each time the trainer logs its metrics, which we're going to set to once per rollout. Without a reward in them, it's the summary at the end of training, and we return. Otherwise, the rollout is the steps so far, divided by the steps in a rollout. KL is in the logs when there's a reference to measure the drift against, and we print a dash without one. Tied comes from frac reward zero std, TRL's name for the share of groups whose rewards are all equal, which we called tied, so times sixteen gives the groups. Then the line, as our script prints it, with the rollout, the reward to three decimals, the KL, the groups that tied out of sixteen, and the minutes since the start, and each ten rollouts, an evaluation. On train end evaluates the final model, unless the last rollout was evaluated already. Main takes the number of rollouts and a recipe, matched or defaults. It loads the fine-tuned model onto the GPU, Apple's on this machine, in evaluation mode. Then it loads the prompts, each with room for two hundred tokens after it in our window, and prints how many there are, with a comma for the thousands. If the recipe is matched, it uses our script's choices: a beta of zero point zero five, our KL weight, loss type GRPO, two passes over each rollout, our epochs, and bf16 and gradient checkpointing both switched off. The comment over them lists our choices: a KL penalty, each story's tokens averaged first, two passes over a rollout, and float32. It goes on with why the last two are there, as TRL would train in bfloat16 and recompute activations for the backward pass, to save memory. Otherwise, it keeps TRL's own, a beta of zero, loss type DAPO, and a single pass, with the comment: TRL's own, no penalty, all the tokens of the batch averaged together, as DAPO does, and one pass. We're going to come back to those two after the first run. Per rollout is the optimiser steps in a rollout, eight for each pass, and the run's folder is named after the recipe, under TRL in our checkpoints. Then the GRPO config, where each of our settings finds its field. Output dir is where TRL would save its own checkpoints. Num generations is eight, the stories per prompt, our group. Per device train batch size is sixteen, the stories in a minibatch, and steps per generation is eight, the minibatches in a rollout. So TRL writes eight times sixteen stories at a time, sixteen prompts by eight, and then updates in eight steps of sixteen stories, as our script did. Max completion length is our two hundred tokens, and the temperature is one, without top k, which TRL's default leaves off. Epsilon is PPO's clip of zero point two, and the learning rate is ours, kept constant, where TRL's default would decay it to zero over the run. Max steps is the rollouts times the steps per rollout, and we log once per rollout, to TensorBoard, in a folder named after the run and the time. The save strategy is no, as we save the model at the end, and the data loader's pinned memory is off, as it's meant for NVIDIA GPUs. The seed is our thirteen thirty-seven, and the recipe's choices go in last. We make the report now, so its clock starts before the trainer loads anything. The GRPO trainer takes the model, our fine-tuned model as a GPT-2, and the processing class, our tokenizer in Hugging Face's format. Reward funcs is our words reward, args is the config, the train dataset is our prompts, and callbacks is our report. We remove the progress callback, as it would print a progress bar and a dictionary of a few dozen numbers at each log. So it's our line per rollout, in place of the progress bar and its dictionaries of numbers. Then train runs the loop, rollout after rollout. After it, from GPT-2 copies the trained weights into our model, and we save it as a checkpoint in the run's folder, so that evaluate and sample load it like any of our models. Last, we print the rollouts and the minutes. The script runs thirty-two matched rollouts unless it's told otherwise.
A first run
16:25 Let's run it, with the matched recipe first. It loads the instructions that ask for words, and then it stops before the first rollout, with a long traceback. At the bottom, there's an OS error: it can't load the configuration of an empty name. Further up, the call that failed is in the GRPO trainer's init, where it makes the reference model. With a KL penalty, TRL needs a frozen copy of the model to measure the drift against. It makes that copy by loading the model again, from the name or the folder in its config, the way the quick start's model came from the Hub. Ours was built in memory, so that name is empty. It's an easy one to miss, as the trainer accepts a model object, and the run fails just when the penalty is switched on.
17:11 These are the lines where we handed the trainer the model, as an object made by to GPT-2, with the tokenizer next to it. So we give TRL the model the way it expects one, as a folder. The folder is SFT dash HF, in our checkpoints. Save pretrained writes the GPT-2 there, its config and its weights, and the tokenizer next to them, as our hub script does before it pushes to the Hub. The GRPO trainer now takes the folder's path, and loads the policy, the reference and the tokenizer from it, so the processing class goes. Above it, we write down why, for the next person who tries this: a folder, as TRL loads the reference from where the model came from, and the tokenizer with it.
Our settings, in TRL
17:58 Let's run it again, with the folder this time. The trainer loads, with its thirty-six thousand instructions that ask for words. At rollout zero, the fine-tuned model's stories use about twenty-seven point three percent of the requested words, as in episode sixteen, since it's that model, measured by that code. Then the rollouts come quickly, about seven point one seconds apart. Each line has the average reward, the KL from the reference, and the groups that tied, about six percent of them over the run. TRL logs the KL as an average per token, where our script printed a total per story, so TRL's numbers look a lot smaller, by roughly the length of a story. Each ten rollouts, the demo story for rain, cake and jump shows the change. At rollout zero, it's a girl with a pink dress, and none of the three words. By rollout ten, there's a party with a cake, a jump and even rain, and by the end, a girl called Lucy who wants to make a cake, and jumps, and jumps again. After thirty-two rollouts and about six point four minutes, the held-out stories use about forty-four point seven percent of the words.
19:03 Put on a chart next to episode sixteen's run, the two rewards climb together for the first half, and then ours pulls ahead by several points. Each rollout scores its own sixteen instructions, so both curves move up and down by several percent from one rollout to the next. Over the last five rollouts, TRL's reward averages about forty-three percent, and ours about forty-seven. I find this reassuring, as two implementations written apart, one of them by us, end up within a few points of each other.
What TRL does by default
19:32 Now, about the two recipes we set up in main. TRL's page has a section on the loss, and it's a good summary of what happened to GRPO after DeepSeek. The first formula is GRPO's loss as DeepSeekMath wrote it, and as we did: the inner sum, over a story's tokens, is divided by the story's length, and then the outer sum, over the G stories, by G. DAPO, which we read in episode sixteen, divides by the tokens of all the stories together instead. A long story then counts in proportion to its length, where GRPO's average gives each token of a long story less weight, and TRL made DAPO's loss its default. Then a paper on training like DeepSeek-R1-Zero goes a step further. It divides by a constant, the longest completion allowed, and recommends not dividing the advantages by the group's standard deviation either. So the GRPO we wrote is, by now, the one the library calls the original.
20:31 Side by side, seven of TRL's defaults differ from our script's. Two of them we keep as ours in both runs: ten to the minus six is a learning rate for fine-tuning models many times larger than ours, and two hundred tokens is what fits in our window. The defaults run takes the other five from TRL. There's no penalty, so TRL doesn't load a reference model at all, the loss is DAPO's, and each rollout gets one pass instead of two. It also trains in bfloat16, sixteen-bit numbers with float32's range and fewer digits, and recomputes the activations in the backward pass instead of keeping them, which saves memory and costs time. I think of it as the run you'd get by following TRL's docs, changing little beyond the learning rate and the length of a story.
A run with TRL's defaults
21:18 So, let's run it again, with TRL's defaults this time. With a single pass and no reference model, a rollout takes about four point five seconds, and the KL column shows a dash, as nothing is measured against. Without a penalty, the demo story drifts further. By rollout twenty, it's a big cake in a big cake, with cake in almost each sentence, and by the end, a wet day where the rain and a rainbow jump, with all three words in. After thirty-two rollouts and about four point four minutes, the held-out stories use about fifty-nine point three percent of the words.
21:54 With the defaults run on the chart too, its reward pulls ahead of the matched run within the first ten rollouts, most likely because nothing holds the model near the fine-tuned one. Over its last five rollouts, its reward is about fifty-five percent, against about forty-three with our settings.
The models, measured
22:10 Now our evaluate script, on the fine-tuned model and the two models TRL trained, each loaded from the checkpoint we saved through from GPT-2. Episode sixteen's GRPO model wasn't kept, so I can't measure it again here. The fine-tuned model, though, comes out to the digit as it did in episode sixteen, so that episode's numbers for our GRPO can sit next to these. The words used go from twenty-seven point three percent for the fine-tuned model to forty-four point seven for TRL with our settings, and fifty-seven point three with its defaults, where our GRPO reached fifty point zero. The stories that end within two hundred tokens go from forty-eight percent to forty-eight and ten, as most of the stories from TRL's defaults run on to the end of their tokens. The losses are further up the table, and they go on a chart next.
22:59 Side by side with episode sixteen's runs, the models mostly pair up. TRL with our settings uses forty-four point seven percent of the words, and our GRPO with its KL weight used fifty point zero, which is about eight words apart, out of the hundred and fifty the instructions ask for. From one run of each, I can't tell whether that gap comes from the two implementations or from the luck of the draw, and a few more seeds would settle it. TRL's defaults land right next to our GRPO without a penalty, at fifty-seven point three, against fifty-eight point zero. The losses pair up too, at two point four seven and two point four six with a penalty, and two point five three and two point five six without one. So, apart from that gap, this looks like the GRPO we wrote, behaving as it did, inside someone else's code, which is what I was hoping to see.
23:49 We give both of TRL's models the instruction from episode eight, rain, cake and jump, with the seed we used there. With our settings, it's a girl called Sarah, with rain, a jump and a cake, in a story that still reads like one. With TRL's defaults, it's a cake that jumps in the cake, with cake in nearly each sentence, and no rain. That's reward hacking, as in episode sixteen's run without a penalty: the reward counts the words, so repeating them costs nothing, and nothing pulls the model back towards the fine-tuned one.
Why TRL was quicker
24:20 I expected a library this general to be slower than our few lines of PyTorch on a model this small, and it was the other way round. To compare them fairly, I ran our GRPO script again on this Mac, for ten minutes, off camera. Between evaluations, a rollout took it about ten seconds, against about seven point one for TRL with our settings, and four point five with its defaults, which make one pass and have no reference to run. So I timed the writing on its own. Our script writes a group at a time, eight stories in a batch and sixteen batches a rollout, and that took about six point six seconds. TRL writes all hundred and twenty-eight in a single batch, padded on the left, which took transformers' generate about one point six. And our own generate, given a hundred and twenty-eight copies of one prompt, took about one point two, so the gap comes from how a rollout is batched, more than from the library. To batch ours like that, with prompts of different lengths, our generate would need the padding and the attention mask that transformers' generate already has.
What TRL did, and what we did
25:25 Looking back at the setup, what we wrote was about our model and our task: the dataset of prompts, the reward function, and the conversion to GPT-2 and back. TRL took the loop, the groups and the advantages, the clipped loss and the KL, batching the stories, and logging a few dozen metrics to TensorBoard. Its defaults follow what papers have found since DeepSeekMath, which is useful, as long as you know they're there. On a machine with NVIDIA GPUs, this script grows with a few settings: use vLLM writes the stories with vLLM, accelerate launch spreads the training over several GPUs, and a PEFT config trains LoRA adapters, as in episode nine. What it asks in return is that the model is one transformers can load, from a name or a folder. For our GPT that was easy, as its blocks are GPT-2's, and a model with a block of its own would need a class registered with transformers first.
26:20 Last, the docs get a page on TRL, with how our model goes in and comes back out, our settings next to TRL's fields and defaults, the mistake with the reference, and both runs next to our own GRPO. It goes in the list on the docs' home page and in the navigation. And the README has the two commands, the matched run and the defaults.
Wrap-up
26:40 So, today we trained our own GPT with TRL. It went in as a GPT-2, with the instructions as a dataset, the reward as a function and our settings in GRPO's config. And it had to be a folder on disk, so that TRL could load a reference from it. With our script's settings, it ended a few points below the GRPO we wrote, at about forty-five percent of the requested words against fifty, from one run of each. With TRL's defaults, and no penalty, it landed near our GRPO without one, at about fifty-seven percent, in stories that ran on and repeated the words. And it was quicker than our script, mostly because it writes all of a rollout's stories in one batch.
27:23 Let me know in the comments whether you'd reach for a library like TRL or keep writing these by hand, and which other framework you'd like to see our model trained in. And if you'd like to follow along, subscribe to the channel. I hope you find this useful, and thanks for watching.