← All AI Engineer talks

AI Engineer Europe 2026

Let LLMs Wander: Engineering RL Environments — Stefano Fiorucci

Read the talk

Let LLMs Wander: Building Environments That Teach Models Through Play

A tic-tac-toe experiment shows how parsers, rewards, opponent curricula, and controlled randomness turn an evaluation harness into a training environment for a small language model.

From a talk by Stefano Fiorucci

Before you start: Basic familiarity with Python and language-model prompting is helpful; reinforcement learning concepts are introduced as they are needed.

Can a small model learn by playing?

How do you turn a small language model that barely plays tic-tac-toe against a random opponent into a strong player? Giving it examples is one starting point. Giving it a game engine, opportunities to explore, and feedback on its decisions opens another route. Stefano Fiorucci, who develops Haystack at deepset and experiments with small models outside that work, uses this problem to explore reinforcement learning environments.

An environment gives an agent somewhere to use tools, execute code, and attempt tasks that take multiple steps. Its responses make the consequences of those actions available for evaluation and learning. Fiorucci places this work in a growing ecosystem of environment startups working with major AI labs, and cites DeepSeek and MiniMax reports describing training across thousands of environments. Tic-tac-toe makes the engineering questions small enough to inspect: what can the model do, what changes when it acts, and what should count as success?

0:070:27
Suggest correction

This note stays in this page until you copy or download it. Nothing is submitted; reloading clears the draft.

0:07 · section reference included

State, action, reward, repeat

The basic reinforcement learning loop has two participants: an agent and an environment. The agent observes the current state and chooses an action. The environment changes in response and returns a numerical reward indicating how good or bad the outcome is.

Diagram of an agent above an environment, connected by arrows labeled Action, State, and Reward.
The reinforcement learning loop connects agent actions with environment state and reward.

The objective is to maximize cumulative reward. That requires balancing exploration, trying actions that might reveal better strategies, with exploitation, choosing actions already known to work. The resulting sequence of states, actions, and rewards is a trajectory, also called a rollout. Here, those terms mean a complete episode—for example, one whole game, rather than one move.

2:172:33
Suggest correction

This note stays in this page until you copy or download it. Nothing is submitted; reloading clears the draft.

2:17 · section reference included

From imitating answers to rewarding outcomes

A language model takes a prompt and generates a completion. Fiorucci introduces its conventional training recipe in three stages:

StageTraining signalIntended result
PretrainingLarge amounts of textBroad knowledge and text completion
Supervised fine-tuning, or SFTCurated conversational examplesInstruction following and task behavior
Reinforcement learningRewards, including preference-based signalsBetter alignment with desired behavior

PPO, or proximal policy optimization, is one technique used in the third stage. The distinguishing feature of SFT is statistical imitation: given prompt–response pairs, the model learns to produce responses resembling those examples.

The motivation for reasoning-oriented RL comes from the limits of that recipe. Fiorucci invokes Ilya Sutskever’s NeurIPS 2024 discussion of diminishing returns from pretraining, then points to OpenAI o1. OpenAI described improvements from both more reinforcement learning during training and more time spent thinking at inference. The slide illustrates those two compute axes with AIME accuracy plots, although the release disclosed relatively little about the training procedure.

Two scatter plots under “o1 improves with more compute” show AIME accuracy rising with train-time compute and test-time compute, each on a logarithmic horizontal scale.
o1 accuracy increases with training compute and test-time compute.

DeepSeek-R1 offered a more concrete route. Reasoning traces can improve answers, but producing enough curated reasoning examples for SFT is expensive. DeepSeek used reinforcement learning with verifiable rewards, together with GRPO, group relative policy optimization, which offers a lighter training setup than PPO.

In the simplest verifiable-reward task, a model generates a reasoning trace and an answer. A checker compares the answer with known ground truth, then supplies a reward for training. The same principle extends to a won game or a successful tool call: an automatically checkable outcome can become a learning signal. SFT draws behavior toward the examples supplied; RL samples alternative trajectories from the model’s existing capabilities and reinforces those that score better. That creates room to discover strategies beyond the demonstrations.

The language model now occupies the agent’s place in the loop. Its environment includes the dataset, interaction harness, and scoring rules—everything needed to run and judge the task. Once the model can call a weather API or use a terminal, that environment becomes a dynamic software system. In tic-tac-toe, the model’s action is a text response specifying a move. The engine constructs prompts, tracks the board, generates opponent moves, and decides when the game ends. A simple reward might assign +1 to a win and 0 to a loss. Through repeated play, the model can discover useful strategies without a human-written example for every position. Fiorucci invokes Andrej Karpathy’s description of environments as opportunities to take actions and see outcomes, extending learning beyond expert imitation.

3:323:44
Suggest correction

This note stays in this page until you copy or download it. Nothing is submitted; reloading clears the draft.

3:32 · section reference included

Build a single-turn environment with Verifiers

Verifiers, from Prime Intellect, packages these environments as installable, distributable Python packages. It supplies base classes for single-turn, multi-turn, and tool interactions, plus abstractions for response parsing and reward functions. The same environment can serve evaluation and training.

Model serving sits behind an OpenAI-compatible endpoint, allowing the environment to work with OpenAI, OpenRouter, or a local model served through vLLM. Verifiers handles asynchronous interactions and parallel trajectories. The workflow presented also includes a trainer and integrations with Prime RL, Tinker, and SkyRL, so the environment author can concentrate on task behavior and rewards.

The first example is Reverse Text. Its load_environment entry point assembles a dataset, parser, reward rubric, and SingleTurnEnv. The default dataset contains 1,000 paragraphs in a prompt column. Mapping creates a question containing the original paragraph and an answer containing its reversal.

An XMLParser extracts the response from the requested reversed-text tags. A reward function then compares that text with the reference answer. Although the spoken explanation calls the score a longest-common-subsequence ratio, the companion implementation uses difflib.SequenceMatcher(...).ratio(). The core transformation and comparison can be expressed directly in Python:

python

from difflib import SequenceMatcher


def prepare_example(row: dict[str, str]) -> dict[str, str]:
    text = row["prompt"]
    return {"question": text, "answer": text[::-1]}


def score_reversal(parsed_answer: str, answer: str) -> float:
    return SequenceMatcher(None, parsed_answer, answer).ratio()


example = prepare_example({"prompt": "Hello"})
score = score_reversal("olleH", example["answer"])

Parsing keeps output extraction separate from scoring. A rubric collects weighted reward functions; the environment bundles that rubric with the dataset and interaction setup.

Evaluation makes the assembled environment concrete:

  1. Invoke load_environment and select five dataset examples.
  2. Sample three rollouts for each example, producing fifteen conversations. Repeated questions can yield different completions because model sampling is stochastic.
  3. Send the system prompt and question to the model.
  4. Parse the response, calculate its reward, and save the result.
  5. Aggregate summary statistics and the reward distribution.

Training uses the same interaction and scoring machinery, then adds parameter updates. This shared path is what makes an evaluation environment useful as a training artifact.

10:1910:28
Suggest correction

This note stays in this page until you copy or download it. Nothing is submitted; reloading clears the draft.

10:19 · section reference included

Add state, tools, and reusable interaction loops

The DoubleCheck environment adds another exchange. The model answers a math question; the environment replies, “Are you sure?” The rollout continues so that the model can reconsider. MultiTurnEnv introduces a state dictionary for information maintained throughout the episode. A setup_state method can initialize it, although this particular example does not need that hook.

env_response returns a list of messages. Here the reply is fixed, but a richer environment can generate its response from the current state. A method marked with @vf.stop, the decorator shown in the companion code, is checked on each turn. When it returns true, the rollout ends. Underneath, the model and environment alternate messages and update shared state until a stopping condition is satisfied; the completed trajectory can then be evaluated.

MultiTurnEnv supplies the core single-agent rollout loop for the environment types presented. ToolEnv adds Python functions as callable tools. A model response can request a tool, the environment executes it, and the returned result becomes input for the next model response. This continues until the model responds without tool calls. Fiorucci points to wiki-search as a more realistic example of that pattern.

Other abstractions extend the same foundation:

  • MCP environments connect to Model Context Protocol servers and expose their tools.
  • StatefulToolEnv keeps per-rollout resources such as a database connection or session ID.
  • Recursive language model environments let a model decompose and recursively inspect input through a REPL. The strategy addresses context that need not fit into one model prompt; it does not make a single context window infinite.
  • Third-party integrations connect Verifiers with other environment libraries.

Each abstraction changes what the agent can interact with while retaining the need to track an episode and judge its outcome.

The Environments Hub adds a distribution layer: a community space for sharing environments, tightly integrated with Verifiers. This matters because an environment tied to one training stack is difficult to reuse elsewhere. As a market for closed environments develops, open packages provide another route to the tasks and feedback that open models need for training. They also make other people’s experiments available to inspect and extend.

14:3214:55
Suggest correction

This note stays in this page until you copy or download it. Nothing is submitted; reloading clears the draft.

14:32 · section reference included

Start with a playable tic-tac-toe environment

Tic-tac-toe has a small state space and a deterministic solution, yet small language models can struggle with it. Its multi-turn dynamics also make it awkward to capture fully in a static dataset. The practical starting point is a minimal environment that can run an evaluation before any training complexity is added.

The first version gives the model a narrow contract: play as X, go first, and return a cell number from 0 through 8 inside <move> tags. The opponent chooses random legal moves. load_environment creates examples containing the initial user message, and setup_state initializes per-game information such as the board and winner.

env_response implements the game’s transition:

  1. Parse the model’s latest move and check whether it is legal.
  2. End the game as a loss if the move is invalid.
  3. Apply a valid move, generate the opponent’s random move when play can continue, and check for a win or draw.
  4. If the game remains active, return the current board and ask for the next move.

The rubric combines a win reward with weight 1 and an XML-format reward with weight 0.2. This separates two requirements: learning useful game behavior and producing a response the engine can interpret.

18:5219:09
Suggest correction

This note stays in this page until you copy or download it. Nothing is submitted; reloading clears the draft.

18:52 · section reference included

Make difficulty adjustable and comparisons fair

The next version varies whether the model starts, then introduces an optimal opponent using minimax. Against optimal play, a draw is the best achievable result. But an opponent that is perfect from the beginning can deprive a weak model of wins and useful learning signals. The environment therefore lets the opponent sometimes choose a random move instead of an optimal one.

min_random_move_prob and max_random_move_prob define the range of opponent randomness across games:

Parameter settingOpponent behavior
Both 0Always optimal
Both 1Always random
A range between 0 and 1Adjustable mixture of optimal and random moves

Rollouts derived from the same dataset example share the same random-move probability. They therefore face the same difficulty setting even when the sampled model behavior differs.

The response contract also grows to include a thinking trace before the move. A regular-expression reward checks for <think> tags as well as the move format. Invalid outputs need a gentler treatment too: malformed responses and occupied-cell choices were common enough that immediate losses could cut off useful experience. The revised rule lets play continue with a flat −0.1 penalty and an eight-turn cap in the walkthrough.

Group-based RL needs reward differences to reflect the model’s decisions. If two rollouts start from the same example but receive different opponent luck, their scores become harder to compare. Fiorucci assigns an example seed that controls the starting player, then derives each turn’s seed from the example seed and the board state. Within that example, reaching the same board position produces the same opponent response. The model can still explore different moves, but a repeated position no longer receives an unrelated random continuation.

There is a second source of noise across batches. Batch size here counts the games used before a weight update. When opponent difficulty varies, a small batch can accidentally contain mostly easy opponents or mostly hard ones. The average reward then fluctuates with the sampled curriculum. Stratified sampling forces each batch to contain a balanced spread of difficulties across the configured range. Seeding controls comparisons within a rollout group; stratification controls the difficulty mix across an update. The repository contains the detailed sampling implementation.

Slide lists varying who starts, stronger opponents, making models think, handling invalid moves, seeds for group-based RL, and stratified sampling across batches.
Tic-tac-toe environment improvements cover opponents, reasoning, invalid moves, and sampling noise.
21:1521:35
Suggest correction

This note stays in this page until you copy or download it. Nothing is submitted; reloading clears the draft.

21:15 · section reference included

Use SFT to make the small model ready to learn

Baseline evaluation compares GPT-5 Mini with Liquid AI’s LFM2-2.6B, the small open model identified in Fiorucci’s companion repository. GPT-5 Mini follows the format well and plays competently, though imperfectly. LFM2 struggles with both formatting and legal moves: it sometimes wins against a random opponent but rarely survives an optimal one. These are sampled evaluations, so some variation is expected.

LFM2 is nevertheless a promising starting point: it is small, fast, and already instruction-tuned. The proposed division of labor is to use SFT for the output contract and valid-move syntax, then RL for stronger strategic behavior. An environment that already generates and scores trajectories can also supply the synthetic demonstrations for that warm-up.

Fiorucci generates 200 examples with GPT-5 Mini and filters out losing games before SFT. The teacher’s reliable formatting makes it useful even though its game strategy is imperfect. Prime RL runs the supervised fine-tuning stage; Fiorucci reports that it takes a few minutes on his 96 GB GPU, with smaller hardware also possible. Afterward, formatting is almost perfect, invalid moves are less frequent, and game performance improves, but substantial strategic weaknesses remain.

25:4226:07
Suggest correction

This note stays in this page until you copy or download it. Nothing is submitted; reloading clears the draft.

25:42 · section reference included

Update the policy from groups of games

Applied to tic-tac-toe, the group-relative training loop is straightforward:

  1. Sample several complete games from the same initial board.
  2. Score each rollout with deterministic win, format, and invalid-move reward functions.
  3. Calculate the group’s average reward and compare each rollout with that baseline to obtain its advantage.
  4. Update the model to favor trajectories that performed better than the group baseline.

The comparison is relative to other attempts at the same starting task. That is why shared opponent difficulty and controlled environment randomness matter: they make the baseline more informative about the model’s play.

The experiment uses CISPO, introduced in MiniMax-M1, which clips importance-sampling weights. Fiorucci presents it as an improvement over GRPO for this training setup. Training runs through the Verifiers RL simple trainer, with one GPU for inference and another for updates. This is the historical vf.RLTrainer workflow: the companion training chapter now labels it legacy, pins verifiers[rl]==0.1.9.post3 for reproduction, and recommends Prime RL for new projects.

The first RL run samples opponent random-move probabilities from 20% to 70%. It excludes both purely random and perfectly optimal opponents, creating opportunities to learn attack and defense. num_groups configures the stratified sampling. The remaining trainer settings must balance stable learning with GPU utilization and memory limits; the repository supplies the detailed memory guidance.

Fiorucci observed unstable training and model collapse with batch sizes below 256 games in this environment. His explanation is that too few games per update expose the model to too narrow a set of matches and opponent types, allowing a locally successful but poor strategy to dominate the update. Batch size therefore affects the quality of the learning signal as well as resource use.

28:1928:29
Suggest correction

This note stays in this page until you copy or download it. Nothing is submitted; reloading clears the draft.

28:19 · section reference included

Good rewards still leave strategic failures

The first training run looks healthy: win reward and total reward rise, formatting remains near perfect, and the invalid-move penalty converges toward zero. A separate evaluation is still needed to find out whether those trends translate into stronger play.

After the first RL run, Fiorucci reports an 85% draw rate against an optimal opponent in a 100-game evaluation, with one rollout per example and opponent random-move probability set to zero. The model also dominates random opponents, and invalid moves fall to near zero. A draw is the strongest possible outcome against optimal play, so the remaining losses identify room for improvement.

Inspecting the rollouts reveals a recurring weakness: fork traps. An opponent creates two winning paths, and the model can block only one. The final move may look sensible in isolation, but the decisive mistake occurred earlier, when the model allowed the fork to form. The three-board sequence makes that delayed consequence visible. Improving further requires changing the strategies explored during training, rather than merely polishing the last response.

“Possible improvements” slide with three tic-tac-toe boards linked by arrows, red X marks, green O marks, and text identifying fork traps.
A three-board sequence illustrates the model falling into a fork trap.
30:5531:03
Suggest correction

This note stays in this page until you copy or download it. Nothing is submitted; reloading clears the draft.

30:55 · section reference included

Increase difficulty without losing the ability to attack

For the next run, Fiorucci uses larger GPUs to iterate faster, while noting that they are probably unnecessary. He raises opponent strength by narrowing the random-move probability to 0%–25%. Training exclusively against perfect opponents had produced an unwanted result: an overly defensive model that failed to exploit mistakes when tested against random players. Keeping some imperfect play in the curriculum preserves opportunities to learn how to win.

A stronger opponent alone does not guarantee escape from an established strategy. After several unsuccessful attempts to improve, Fiorucci adjusts sampling temperature to encourage exploration. Higher temperature increases behavioral variety, but too much can cause incoherent output. In this run, win reward and total reward initially fall. Fiorucci interprets that dip as exploration of new, initially worse strategies; the rewards later recover and reach new highs. Formatting and invalid-move rewards also dip briefly but remain near their best values overall.

After evaluation, Fiorucci calls the result a tic-tac-toe master and tries a game against it. He deliberately makes an imperfect move, then has to block the model repeatedly and eventually loses. The interaction tests a practical question that reward plots cannot answer by themselves: will the model exploit a human opponent’s mistake?

The final comparison returns to GPT-5 Mini, the teacher that supplied the SFT examples. Fiorucci reports similar performance against random opponents and better performance from the trained LFM2 against an optimal opponent. The spoken comparison gives no exact final percentages. Its significance is task-specific: the demonstrations established useful behavior, and subsequent environment-driven training improved the student beyond its teacher on this game.

32:3232:43
Suggest correction

This note stays in this page until you copy or download it. Nothing is submitted; reloading clears the draft.

32:32 · section reference included

Inspect what the environment actually teaches

The successful runs followed several failures. Larger batches appeared to learn slowly but offered more stable updates. Small batches drawn from diverse games and opponent strengths could reinforce suboptimal strategies and lead to collapse. The relevant unit is the collection of experiences behind each update, not simply how quickly the next point appears on a chart.

A more subtle failure came from an earlier minimax implementation that Fiorucci had delegated to Claude. When several moves had the same optimal score, it always chose the first free position among them. Evaluation scores looked excellent, yet the trained model was ineffective when Fiorucci played against it. The opponent was optimal in score but narrow in behavior, and the model had memorized that particular player. An optimal opponent can still contain a training bias.

Starting-model choice introduces another tradeoff. A model already trained for reasoning may generate long thinking traces. With a tight completion limit and limited GPU resources, many early completions can be truncated, wasting budget and potentially damaging useful behavior during training. An instruct model can instead acquire reasoning tailored to the task. Very small models may still lack enough capacity, so evaluate the base model and inspect several completions for promising behavior before committing to a run.

Continue inspecting rollouts as training progresses, and try the actual task after programmatic evaluation. Aggregate rewards reveal trends; individual trajectories reveal which strategies produced them. At the beginning of a run, watch for out-of-memory failures and instability. Once the run is healthy, give it time. Constantly watching slow progress can invite premature stopping or unnecessary parameter changes. As Fiorucci puts it: “start training and go for a walk.”

35:3035:47
Suggest correction

This note stays in this page until you copy or download it. Nothing is submitted; reloading clears the draft.

35:30 · section reference included

Take the same method to a few useful tools

SFT and reinforcement learning play complementary roles in this experiment. Demonstrations teach an initial response contract; interaction supplies a space to practice, and rewards guide which behaviors to retain. Fiorucci’s broader proposal is to use a clear reward signal to train a small specialist that can outperform a larger closed model on a particular task. He also suggests a cost advantage, though this experiment supplies no comparable total-cost measurement.

The LLM RL Environments Lil Course contains the environment and training walkthroughs, while the Environments Hub offers other tasks to explore. A concrete next project is to train a small model on two or three tools you use frequently and test whether it can outperform a larger model on that specific workflow. Fiorucci recommends the wiki-search example in the Prime RL repository as a starting point. The next environment can be a small, useful task whose actions and outcomes are clear enough to check.

“What you can do next?” slide recommends a course, exploring the Environments Hub, and training a small language model on two or three tools, with a Wiki Search example link.
Next steps include an RL environments course, the Environments Hub, and a small-model tool experiment.
38:4039:04
Suggest correction

This note stays in this page until you copy or download it. Nothing is submitted; reloading clears the draft.

38:40 · section reference included

Resources

From the talk

Read the complete timestamped transcript
  1. 0:07

    Hello everybody, and welcome to Let LLMs Wander: Engineering Reinforcement Learning Environments. A few words about me. I am Stefano Fiorucci, AI and software engineer. By day, I work on AI orchestration at Deepset, where I develop Haystack, an open source LLM framework.

  2. 0:27

    By night, I love tinkering with small language models, fine-tuning, and reinforcement learning.

  3. 0:34

    Today, I'm going to talk about reinforcement learning environments for language models evaluation and training. This has been a hot topic over the past year, and I find it fascinating for several reasons.

  4. 0:46

    These environments let models learn by interacting, exploring, and improving from feedback. They are natural gyms for LLM agents that can use tools, run code, and solve multi-step tasks. In addition, startups building RL environments are getting major funding and working directly with big AI labs.

  5. 1:10

    Recent technical reports by DeepSeek and MiniMax show that they are effectively using thousands of reinforcement learning environments to improve model performance on challenging tasks and scale intelligence.

  6. 1:26

    Don't worry if you know nothing about RL environments. I'll cover that soon.

  7. 1:33

    Here is the agenda for the talk. We'll first review classic reinforcement learning concept and see how they map to the language models domain. We'll then introduce Verifiers, an open source library to build environments as software artifacts, and explore some common patterns to implement them.

  8. 1:53

    Finally, I'll walk you through an experiment where we take a small model that can barely play tic-tac-toe against a random player and transform it into a master using a reinforcement learning environment.

  9. 2:07

    Let's start. First, a quick refresher on reinforcement learning.

  10. 2:17

    In reinforcement learning, there are two main characters, the agent and the environment. The environment is the world the agent interacts with. At each step, the agent sees the current state of the world and takes an action.

  11. 2:33

    The state of the environment then changes in response to that action. The agent also receives a reward from the environment, number indicating how good or bad the state is.

  12. 2:46

    The agent's goal is to maximize its cumulative reward over time, and to do this, it has to balance exploration, so trying new actions to discover better strategies, and exploitation, using actions known to work.

  13. 3:03

    By interacting with the environment, the agent learns from experience and improves its behavior.

  14. 3:10

    A trajectory or rollout is the sequence of states, actions, and rewards that the agent goes through while interacting with the environment. It's a record of the experience. In this presentation, I'll use trajectory to mean a complete episode, like one entire game.

  15. 3:32

    Let's take a look at LLMs training. Language model is a statistical model that given some text, the prompt returns a text completion.

  16. 3:44

    The standard training recipe is divided into three phases.

  17. 3:49

    First, pre-training on a massive amount of internet text. Here, the model learns to create text completions. The base model is knowledgeable, but can't follow instructions and is hardly usable in applications.

  18. 4:05

    During supervised fine-tuning on conversational examples, the model is trained to follow instruction and can learn new tasks.

  19. 4:14

    In the third step, reinforcement learning is often used with techniques like proximal policy optimization to align the model with human preferences.

  20. 4:26

    It's worth showing an example of supervised fine-tuning data, as later we'll frequently compare supervised fine-tuning learning with new reinforcement learning approaches. As you can see, we have pairs of prompt and responses, and during this phase, the model learns by statistical imitation.

  21. 4:47

    It's essentially trying to mimic the examples provided.

  22. 4:54

    You might remember Ilyas Tatkiver talk at NeurIPS twenty twenty-four. He pointed out that the LLM training paradigm we just saw is starting showing its limits. In particular, pre-training no longer seems to be enough to keep improving model quality at the same rate.

  23. 5:15

    We needed a new way to scale. Then OpenAI published its o1 models series.

  24. 5:27

    In their release blog post, they mentioned the reinforcement learning training to make models use chain-of-thought effectively. They also underlined that the performance of o1 consistently improved with more reinforcement learning, train-time compute, and with more time spent thinking, test-time compute.

  25. 5:48

    Unfortunately, they did not share many details on how this model was actually trained.

  26. 5:56

    The release of DeepSeek-R1 shed some light on how you can possibly achieve- Those results. First, they recognized that reasoning and chain-of-thought can improve the performance of models. But teaching this behavior to models using supervised fine-tuning requires curated data that is too expensive to produce at scale.

  27. 6:20

    They used reinforcement learning with verifiable rewards, which we'll see in a moment.

  28. 6:26

    And DeepSeek also used GRPO, a new reinforcement learning algorithm that offers a simple, lighter setup compared to techniques like PPO.

  29. 6:39

    So what is reinforcement learning with verifiable rewards?

  30. 6:44

    In this paradigm, the model is asked the question and generates both a reasoning trace and an answer. The answer is then checked against a known correct answer. The reward is used for reinforcement learning training.

  31. 7:01

    The underlying idea is more general. Any task where the outcome can be verified automatically, like a correct answer, a won game, a successful tool call, can serve as a training signal.

  32. 7:16

    And this is fundamentally different from supervised fine-tuning. In SFT, the model learns from curated examples, and its completions tend to stay close to the distribution of those examples. In reinforcement learning with verifiable rewards, the model explores different trajectories from its pretraining and learns to favor the ones that

  33. 7:40

    maximize rewards. And this is exciting because the model is no longer limited by the quality of human examples. Through trial and error, it can discover more efficient reasoning strategies.

  34. 7:58

    We can finally map the classic reinforcement learning concepts to LLMs. The language model acts as the agent.

  35. 8:08

    The environment for any task included data, harnesses, and scoring rules, everything needed to check and possibly train the model on the task.

  36. 8:21

    From a software perspective, this marks a shift from supervised fine-tuning to reinforcement learning with verifiable rewards. While SFT mainly relies on conversational datasets, this new paradigm usually requires an environment, a dynamic system that the model can interact with.

  37. 8:41

    The definition of an agent is also expanding. Language models can now be given tools from a weather API to a terminal, and this makes environments for training and evaluation more complex and critical.

  38. 8:55

    To make this more concrete, consider teaching a model to play tic-tac-toe. The agent is the language model. Its action is generating a text response with a specific move.

  39. 9:08

    The environment acts as the game engine. It handles prompting the model, tracking the board status, generating the opponent's moves, and deciding when the game is over. The reward is the signal from the environment.

  40. 9:23

    For example, plus one for a win and zero for a loss. This reward guides the model to find winning strategies through trial and error.

  41. 9:34

    This setup allows the agent to discover strategies that maximize its score without needing preexisting human examples.

  42. 9:47

    You have probably understood that I am enthusiastic about this topic, but let's also use Andrej Karpathy's words to describe the environments. "They give the LLM an opportunity to actually interact, take actions, see outcomes.

  43. 10:04

    This means you can hope to do a lot better than statistical expert imitation."

  44. 10:11

    Now, let's see how to build these environments.

  45. 10:19

    To build the environments as software artifacts, we can use Verifiers, an open source library by Prime Intellect.

  46. 10:28

    Verifiers provides modular components to create reinforcement learning environments for LLM agents. This can be used for both evaluation and training.

  47. 10:40

    Environments are Python packages that can be easily installed and distributed. The library provides base classes for several setups: single-turn environments with just one interaction between the model and the end, multi-turn environments, tool environments where the model is equipped with tools, and several others.

  48. 11:03

    It also includes abstractions for parsing model responses and defining reward functions.

  49. 11:09

    Verifier abstracts model serving. It accepts an OpenAI-compatible API endpoint, so you can plug in OpenAI, open router, or local models via vLLM. It handles async interaction and parallel trajectories, so you focus on the environment logic.

  50. 11:31

    For training, Verifiers come with its own trainer. It integrates with other frameworks such as Prime RL, Tinker, and Sky RL. In short, Verifiers lets us focus on the task and the rewards rather than the infrastructure.

  51. 11:52

    Let's start with a single-turn environment. Reverse Text is a simple environment to evaluate or train language models on their ability to reverse a string of text.

  52. 12:07

    What's going on here? load_environment is the entry point for every Verifiers environment. It contains all the setup logic. First, a dataset is loaded and mapped. The default dataset contains a thousand text paragraphs stored in the prompt column.

  53. 12:27

    During the mapping step, we transform the original dataset. Question is the text paragraph, while answer is the reversing text.

  54. 12:38

    Next, XML parser is initialized. It extracts the text inside the reversing text, text as specified in the system prompt. We then define the reward function. This compares the model's output to the ground truth and returns a longest common subsequence ratio.

  55. 13:00

    Finally, we bundle this into a rubric, a collection of weighted rewards, and initialize the single term env.

  56. 13:13

    But how does this come to life? Let me show you an evaluation run.

  57. 13:24

    Here is what happens under the hood. load_environment is invoked. Five examples are taken from the dataset, and each example is used three times for three rollouts. Each rollout gets the same question, but may produce different completions due to model randomness.

  58. 13:44

    We have fifteen rollouts in total. For each rollout, a conversation is prepared with the system prompt and the question. The conversation is sent to the model. The model generates a response.

  59. 13:57

    The response is parsed, extracting the answer. The reward is computed, and results are saved. At the end of the evaluation, you get summary statistics and additional info about reward distribution.

  60. 14:16

    Training follows the same core mechanism with the additional step of updating model parameters. We'll look at that in more detail later.

  61. 14:32

    Let's look at the different example from Verifiers, the double-check environment. Here, the model answers a math question, and the environment then asks, "Are you sure?" This is a multi-term environment, similar in spirit to tic-tac-toe, in which each trajectory involves multiple interaction between the model and the environment.

  62. 14:55

    Let's look at what multi-turn env introduces. State makes its first appearance here. It's a dictionary that tracks information during a rollout. We can set the initial state through the setup state method not used in this example.

  63. 15:15

    And response. Instead of the interaction ending after one turn, the environment can reply with a list of messages. Here, it just says, "Are you sure?" In more complex environments, the response can be dynamically generated based on the state.

  64. 15:35

    The the_if_stop decorator marks a method as a stopping condition. This method runs at every turn of the agent environment interaction. Once it returns true, the rollout terminates. Under the hood, Verifiers runs a loop in which the model and the environment take turns exchanging messages, updating shared state until a

  65. 16:00

    stopping condition is met, and the full trajectory can be evaluated.

  66. 16:09

    Another interesting type of environment is the tool environment. All environment types in Verifiers are built on multi-turn env, which implements the core single agent rollout loop. Tool env adds tool calling to this foundation.

  67. 16:27

    As you can see, tools are defined as Python function. During rollouts, the model can call tools, receive results, and continue reasoning until it produces a response without tool calls.

  68. 16:40

    Each turn consists of a model response followed by the environment's tool execution.

  69. 16:48

    For a more realistic example, I recommend checking out the wiki-search environment.

  70. 17:00

    Beyond the fundamental environments I just showed, Verifiers provides more abstraction to build environments. The NCP environment automatically connects to model context protocol servers to expose their tools.

  71. 17:18

    Stateful tool env is for tools that need per rollout persisted state, like database connection or session ID.

  72. 17:28

    There is also a class implementing recursive language models, a novel idea you might have heard of. It's an inference strategy where language models can decompose and recursively interact with input context or unbounded length through REPL environments.

  73. 17:49

    Verifiers also plays well with others, integrating with several third-party environment libraries.

  74. 18:01

    Verifiers is tightly integrated with the Environments Hub, a community space for sharing these RL environments. Verifiers and the Environments Hub are different phases of the same intent. They aim to fight environment fragmentation.

  75. 18:19

    Too often, environments are locked into specific training stack, making them difficult to reuse. And as a market for closed source environments emerges, these open initiatives ensure we have a robust alternative.

  76. 18:35

    We don't want open source models to lag behind just because they lack the right playground training. Plus, beyond the serious side, it's just fun to explore the hub and see what people are building.

  77. 18:52

    Now, let's move on. Tic-tac-toe. We'll use verifiers to create a tic-tac-toe environment for training and evaluating language models on this game. Now, why tic-tac-toe?

  78. 19:09

    It's a simple game, but requires multi-turn interaction, and capturing its dynamics with a static dataset is challenging. Despite its small state space and deterministic solution, small language models often struggle with it.

  79. 19:25

    Let's see if reinforcement learning can help bridge that gap.

  80. 19:37

    It's best to start with a simple version, run evaluation to verify it works, and then iterate. To start, we make a few assumptions. The model always plays as X and goes first.

  81. 19:51

    It must output a number between zero and eight inside move tags, and the opponent just plays randomly.

  82. 20:02

    In load environment, we create the dataset containing the initial user message that starts each game.

  83. 20:11

    For each rollout, setup state populates the state dictionary with information used and updating during the game, such as the board and the winner.

  84. 20:24

    Env response contains the core game logic. It parses the model last move,

  85. 20:32

    check if it's valid. Invalid moves are an immediate loss for now, and applies it to the board. Then it applies a random opponent move and checks for a win or draw.

  86. 20:44

    If the game isn't finished, it returns a user message with the current board state and asks for the next move. We use two reward function: win reward function with weight one and format reward function with weight zero point two, which rewards the model for respecting the XML format.

  87. 21:15

    We can now make our environment more flexible, realistic, and suitable for both evaluation and training. I made some of these improvements gradually while it evolves during training. First, we want the model to sometimes play first and sometime play second.

  88. 21:35

    Let's now address opponent skill. Always playing against a random opponent isn't realistic. So we introduce an optimal opponent using the minimax algorithm. Against this opponent, a draw is the best achievable outcome.

  89. 21:51

    However, for training, we want the opponent's skill to be controllable. If the opponent is too perfect too early, the model might never see a win and fail to learn.

  90. 22:02

    We can do so by introducing a probability for the opponent to choose a random move instead of the optimal one. In load environment, we introduce min random move prob and max random move prob varying from zero to one.

  91. 22:17

    If we set both to zero, all games will be against an optimal opponent. If we set both to one, all games will be against a random opponent. Using these parameters allows us to control the opponent's skill across all games.

  92. 22:35

    For different rollouts originating from the same dataset example, the opponent will always have the same probability of choosing random moves, ensuring fair comparison.

  93. 22:48

    Now, about reasoning. It's common to ask models to produce a thinking trace before the final answer. It can improve performance at inference time, but it's also instrumental to make models better during training.

  94. 23:01

    We define a new format reward function using a regular expression to also check the presence of think tags.

  95. 23:12

    Let's now cover invalid moves. When experimenting with small open models, I observed many of them. Sometimes the output format was incorrect. Other times, the chosen cell was occupied. Ending the game immediately is harsh.

  96. 23:28

    It might stop smaller models from getting a useful learning signal. Instead, we now let the game continue and apply a flat minus zero point one penalty, capping the turns at eight.

  97. 23:45

    Let's discuss reducing noise in group-based reinforcement learning. In GRPO learning, we compare several rollouts from the same starting point to see which ones to reinforce based on rewards. For this to work, differences in rewards should come from how the model plays, not from environment randomness.

  98. 24:08

    And how can we reduce noise in this setup?

  99. 24:13

    First, we set an example seed for each example in the dataset. To select the starting player. Then for each turn, we derive a specific turn seed based on the example seed and board state.

  100. 24:27

    This guarantees that if two rollouts reach the same board position, the opponent will always respond the same way.

  101. 24:37

    Last point, reducing noise across batches. For our training, the batch size is the number of games taken into consideration before the models were, are updated.

  102. 24:51

    In our setup, the opponent's skill varies across the dataset according to mean random move prob and max random move prob. If we train with a small batch size and the random move probability is not fixed, we might sample a batch in which many opponents are hard or many are easy.

  103. 25:11

    This causes the average reward to fluctuate a lot, making training unstable. To fight this, I added the stratified sampling. This forces every batch to contain a perfectly balanced mix of opponent difficult spanning the chosen range.

  104. 25:30

    I know this slide is dense, but you can find our code and more details in the GitHub repository.

  105. 25:42

    Time to evaluate existing models. We choose GPT-5 Mini and LFM 2 by Liquid AI, a small fast open model. Using verifiers evaluating models just requires a few commands. Allowing for some statistical variability, GPT-5 Mini is excellent at following format and is a good tic-tac-toe player, but not perfect.

  106. 26:07

    The small open model by Liquid AI struggles to follow format and to make valid moves. It's a weak tic-tac-toe player, sometimes winning against a random opponent, but rarely surviving against an optimal one.

  107. 26:21

    There is a significant gap. We decide to train LFM 2 for some reasons.

  108. 26:37

    It's a good model for its size, and it's an instruct model, ideal for transforming it into a reasoning model. How can we improve it? We saw that this model struggles to follow format and often provides invalid moves.

  109. 26:53

    We can use supervised fine-tuning for a warm-up phase where we teach the model the format and valid move syntax. We can then use reinforcement learning to build deeper capabilities.

  110. 27:05

    The first step is generating synthetic data for supervised fine-tuning.

  111. 27:12

    Once you have the good environment, generating data requires a single command.

  112. 27:18

    Here we use GPT-5 Mini since it followed format perfectly, and we don't need many examples. We generate two hundred and filter out losing games to avoid backing in suboptimal strategies.

  113. 27:36

    With the synthetic data at hand, we can clearly spin up a supervised fine-tuning run using Prime RL. In this example, I am using a ninety-six gigabytes GPU, but you can use a smaller one.

  114. 27:52

    Training requires only a few minutes. Time to evaluate our fine-tuned model. Compared to the original model, it learned format almost perfectly and reduced the number of invalid moves.

  115. 28:10

    It also improved the game performance, but there is still significant work to do.

  116. 28:19

    Before jumping into RL training, let's do a quick recap of group relative policy optimization applied to tic-tac-toe.

  117. 28:29

    Rollouts. Starting from the same initial board, the model plays several games via LLM sampling.

  118. 28:38

    Each rollout is evaluated using deterministic reward function, in our case, win format and invalid moves rewards.

  119. 28:50

    An average score is calculated across the group of rollouts, and each rollout is then compared against this average advantage computation.

  120. 29:03

    The model is updated to favor trajectories that did better than the group baseline.

  121. 29:12

    We'll use CISPO, which is an improvement over GRPO.

  122. 29:20

    For reinforcement learning training, I used Verifiers RL simple trainer. Here we use a GPU for inference and a GPU for training. Let's comment some parameters in the training configuration.

  123. 29:34

    In this training run, random move probability is ranging from twenty to seventy percent. No purely random players and no optimal players. It's a good playground to get signal and learn both attack and defense.

  124. 29:49

    The num groups parameter is used to set up stratified sampling. When it comes to trainer arguments, we want our model to learn stably while fully utilizing our GPUs without crashing.

  125. 30:02

    For tips on how to use the GPU without going out of memory, I recommend checking out the GitHub repo. Here, I want to stress that reinforcement learning training is sensitive to either parameters and can be unstable I learned the hard way that batch size is a key parameter.

  126. 30:22

    In this environment, I observed unstable training and model collapse and experimented with values lower than two hundred fifty-six. The explanation is intuitive. Batch size is the number of games used to update the model's weights.

  127. 30:39

    If this number is low, this means learning to play from a very small number of matches and opponent types at once, and this likely leads to suboptimal strategies.

  128. 30:55

    Let's take a look at training plots. Win reward function and the total reward constantly improved.

  129. 31:03

    Format reward function was already near perfect and did not change significantly. Invalid move penalty function started well and converged to zero towards the end of training. It seems a good training run, but let's run proper evaluation.

  130. 31:26

    Impressive. Thanks to reinforcement learning, our model has become a very competent tic-tac-toe player. It dominates random players and draws eighty-five percent of the time against an optimal opponent. Invalid moves have dropped to near zero.

  131. 31:45

    These results are already satisfying, and one can say there's not much more we can learn from this example.

  132. 31:57

    I am a perfectionist, and I'd like a perfect AI player. Inspecting the rollouts, I found some recurrent failure modes. In particular, our model sometimes falls into four traps. This example shows the end of the game.

  133. 32:13

    Our model is not playing badly here, but it had already lost the game by allowing the opponent to have two winning paths.

  134. 32:24

    Is it possible to use our RL environment to push our model further toward perfection?

  135. 32:32

    Let's try. We have to make some changes. In this run, I used bigger GPUs just to experiment quickly. It's probably not required.

  136. 32:43

    First, let's discuss opponent skill. We increase opponent skill by setting the probability of a random move to range from zero percent to twenty-five percent. I also tried making the model play ag- against perfect opponents only, but it didn't work.

  137. 33:01

    The model became overly defensive and failed to exploit errors when testing against random players.

  138. 33:10

    But how to make our model explore beyond learned strategies? I made several experiment where this model failed to improve and forget the suboptimal strategies. We want the model to experiment with new approaches, and temperature is the right parameter to tweak.

  139. 33:29

    But this is a bit risky. If the temperature is too high, the model can start generating gibberish. Let's train.

  140. 33:40

    Things get really interesting. There was a significant initial drop in win reward function and total reward. I interpret this as an exploratory phase where the model tried new and random strategies, which hurt performance at first.

  141. 33:56

    But over time, it recovered and improved to new highs. Also, format reward function and invalid move penalty function had an initial drop, but overall always stayed around their maximum values.

  142. 34:11

    Let's move to proper evaluation. Oh, we finally got tic-tac-toe master, but why not playing a game against it?

  143. 34:25

    Okay, let's make, uh, not a perfect move.

  144. 34:32

    Hmm, we now need to block the model.

  145. 34:38

    Hmm, let's block it again. Oh, no, we lost.

  146. 34:47

    It could be interesting now to compare our model performance with GPT-5-mini, the teacher model we used to generate our synthetic data.

  147. 35:00

    Hmm, against a random opponent, performance is very similar.

  148. 35:07

    Let's see against an optimal opponent. Oh, in this case, our model is superior. This is a very nice achievement.

  149. 35:30

    To get these results, I went through several failed experiments, and I'd like to share the findings with you. First of all, batch size. If this value is large, yes, your model apparently learns slowly, but in exchange you get stable training.

  150. 35:47

    If the batch size is small and your environment produces diverse matches and opponent skill, the model will learn from a small number of games at once. This can reinforce suboptimal strategies, and you may observe unstable training or model collapse.

  151. 36:04

    Second lesson, watch for hidden biases in environments. Let me explain. In a previous experiment, I used a different minimax algorithm for the optimal opponent. I thought this was an implementation detail and let Claude handle it.

  152. 36:20

    I got great benchmark results, but then playing against the model, I realized it was too ruthless. Looking better at minimax, these are the bias. If multiple moves have the same optimal scores, the first free position was always selected.

  153. 36:36

    I basically was training my model against a specific type of optimal player. Over many games, the model simply memorized it.

  154. 36:47

    Now about model choice. You can start from a model which is already trained for reasoning, but they tend to output long thinking traces. If you have limited GPU resources and time, you may end up truncating most of the longer completion at the beginning to fit the short limits.

  155. 37:06

    This means wasted budget and also the risk of damaging the model's intelligence. It might make more sense to start from an instruct model and transform it to-- into a reasoning model for your task.

  156. 37:20

    Another point about models, it could be hard to push very small models to competency. This of course depends on the task. What I recommend, evaluate the base model in your environment, look at a few completions, choose a model that shows promising behaviors, even if the numbers are not satisfying yet.

  157. 37:45

    In general, it is always a good idea to inspect some rollouts to see the model evolve. Also, after training, do not stop at programmatic evaluation. Try the model in the real task.

  158. 37:58

    The final recommendation, it's natural to watch your logs and plots when you start training to identify early out-of-memory errors or instability. It's difficult for me too, but once training begins well, I suggest stopping staring at plots for a while.

  159. 38:16

    Reinforcement learning is slow and takes time to see progress. If you continually monitor it, you risk the temptation to stop it and tweak something prematurely, while a slowly progressing run can be surprisingly well given enough time.

  160. 38:31

    So start training and go for a walk.

  161. 38:40

    During this presentation, we mapped the reinforcement learning concept to the language models domain. Then I introduced Verifiers, an open source library to build environments as software artifacts. Finally, I walked you through my experiments where I took a small model and turned it into a tic-tac-toe master using supervised fine-tuning and reinforcement learning with verifiable

  162. 39:04

    rewards. We did not just show the model how to play. We gave it a space to play and guided it through rewards.

  163. 39:14

    Nowadays, reinforcement learning complements supervised fine-tuning in language models post-training. You can do this at home too. If you can define a clear reward signal, you can build an environment and train a small specialized model to beat a large closed model on a specific task at a fraction of the cost.

  164. 39:37

    I want to leave you with a few ideas and resources on this topic. All what I shared today can be found in my free LLM RL environment link course, where I go deep at explaining the detail.

  165. 39:50

    Take a look and give a star. To figure out what others are building, explore the Environments Hub. And what to build next? Something I'm very excited about is this.

  166. 40:04

    Train a small language models on two, three tools you often use and try to outperform a large model in that specific task. I recommend the wiki-search example in the prime-rl repository as a starting point.

  167. 40:21

    Thank you.