opensi·si

In this tutorial you'll take a small open-weight model, an OpenEnv environment, and TRL, and run the full training pipeline end-to-end:

Train a Reasoning Model

In this tutorial you'll take a small open-weight model, an OpenEnv environment, and TRL, and run the full training pipeline end-to-end:

  1. Connect to a hosted environment.
  2. Wire it into TRL via the environment_factory pattern.
  3. Fine-tune with GRPO (Group Relative Policy Optimization).
  4. Read the reward delta from the training logs to see how much the policy improved.
  5. Publish the trained model to the Hub.

The goal is to see the whole pipeline as one coherent narrative — model, environment, training, metric — rather than three separate articles.

Why this shape

We pair GRPO with a procedural task on purpose. GRPO is a value-free RL method that ranks several rollouts of the same prompt against each other, so the only signal it needs is a per-rollout scalar reward — exactly what an environment can return after a step. Procedural means the env generates a fresh question every episode rather than serving a fixed dataset, so the model has to generalize over the family of problems instead of memorizing specific items.

What you'll use

  • Model: Qwen/Qwen3-1.7B — fits a single A100 (40 GB) at the settings below and is large enough for GRPO to move the needle. For smaller GPUs, swap to Qwen/Qwen3-0.6B.
  • Environment: reasoning_gym_env, an OpenEnv wrapper around the Reasoning Gym library. Each episode is a single Q→A.
  • Dataset: chain_sum from Reasoning Gym — chains of integer additions like Compute 17 + 4 + 22 + 9. Procedurally generated, so every rollout sees a fresh problem.
  • Trainer: TRL GRPOTrainer with environment_factory.

Note This tutorial runs through training; on a single A100 (40 GB) the recipe completes in roughly an hour at the suggested settings, peaking around ~38 GB of VRAM. T4 (16 GB) won't fit Qwen3-1.7B at these settings — see the model bullet above for the smaller-GPU swap. The exact reward numbers you see will vary with seed and budget — the point is to watch the reward curve climb and report the delta.


1. Install dependencies

This tutorial connects to sergiopaniego/reasoning_gym. For your own training runs, deploy your own copy first by running openenv push --repo-id <your-username>/reasoning_gym inside envs/reasoning_gym_env/ of the OpenEnv repo, then replace sergiopaniego with your username in the install line and the base_url= strings further down.

Install pip dependencies — keep them as separate cells (don't merge into one pip install):

!pip install -q trl
!pip install -q openenv
!pip install -q --no-deps git+https://huggingface.co/spaces/sergiopaniego/reasoning_gym
!pip install -Uq "transformers>=5.3.0"  # 5.3+ has the `environment_factory` integration TRL needs
!pip install -q trackio jmespath

2. Log in to Hugging Face

You'll need to be logged in to download the base model and (optionally) push the trained checkpoint.

from huggingface_hub import notebook_login

notebook_login()

3. Define the prompt

The model will be asked to use a single tool, answer, to submit its final number. The prompt makes that explicit. The environment wrapper below prepends it to every question.

prompt = """You are a careful arithmetic assistant.

You will be given a chain of integer additions. Compute the result and submit it as a single number.

Rules:
1. Read the question carefully.
2. Use the tool `answer` exactly once with your final number.
3. The answer must be a single integer with no units or explanation.
"""

4. Define the environment class

The environment_factory pattern asks for a Python class that the trainer can instantiate per rollout. It needs:

  • An __init__ that opens a connection to the underlying environment.
  • A reset(**kwargs) method that starts a new episode and returns the initial observation as a string (the prompt and question, in our case).
  • One or more tool methods — public methods with docstrings — that the trainer auto-discovers and exposes as tools to the model. Each call corresponds to one env.step on the underlying environment.
  • A get_reward() method that returns the episode's reward. The environment owns the reward, so no separate reward function is needed.

Because Reasoning Gym episodes are single-step (one question → one answer → done), the wrapper is small.

コード(70 行)
import random

from reasoning_gym_env import ReasoningGymAction, ReasoningGymEnv

class ReasoningGymTrainEnv:
    """Environment wrapper for GRPO training on chain_sum.

    Each rollout episode = one question → one `answer` tool call → done.
    """

    DATASET_NAME = "chain_sum"
    DATASET_SIZE = 1000
    DATASET_CONFIG = {
        "min_terms": 2,
        "max_terms": 3,
        "min_digits": 2,
        "max_digits": 2,
    }

    def __init__(self):
        # `EnvClient` subclasses are async by default; `.sync()` returns a
        # synchronous wrapper so the trainer can call our tool methods directly.
        self.client = ReasoningGymEnv(base_url="https://sergiopaniego-reasoning-gym.hf.space").sync()
        # Random seed per instance so the parallel envs the trainer creates
        # don't all iterate over the same question sequence.
        self._dataset_seed = random.randint(0, 2**31 - 1)
        self._initialized = False
        self.reward = 0.0
        self.done = False

    def reset(self, **kwargs) -> str:
        if not self._initialized:
            # First reset: configure the dataset (name + config + seed + size).
            result = self.client.reset(
                dataset_name=self.DATASET_NAME,
                dataset_config=self.DATASET_CONFIG,
                seed=self._dataset_seed,
                size=self.DATASET_SIZE,
            )
            self._initialized = True
        else:
            # Subsequent resets: no args → server returns the next question
            # from the same dataset iterator. Re-sending the config would
            # rebuild the dataset and rewind to question 0.
            result = self.client.reset()
        self.reward = 0.0
        self.done = False
        return prompt + result.observation.question

    def answer(self, answer: str) -> str:
        """Submit the final answer for the current question.

        Args:
            answer: The agent's answer (will be parsed as a number server-side).

        Returns:
            A short feedback string with the score and the correct answer.
        """
        if self.done:
            raise ValueError("Episode is already finished.")
        # The model often emits `answer` as a JSON int (e.g. `7`) even though
        # the tool schema declares string — coerce so pydantic validation on
        # `ReasoningGymAction` doesn't reject the rollout.
        result = self.client.step(ReasoningGymAction(answer=str(answer)))
        self.reward = float(result.observation.score or 0.0)
        self.done = True
        return f"score={self.reward} correct={result.observation.correct_answer}"

    def get_reward(self) -> float:
        return self.reward

Note Replace the base_url with your own deployment if you've pushed reasoning_gym_env to your own Space — the hosted versions have limited concurrency and are intended for tutorials and small experiments.

What the trainer does with this class

It helps to picture the runtime loop. The trainer keeps a pool of ReasoningGymTrainEnv instances, one per rollout in a generation batch (per_device_train_batch_size × gradient_accumulation_steps with the settings below). Instances are created on first use and reused across batches, so each one keeps its WebSocket session. Per generation batch it then does, for each rollout in parallel:

  1. env.reset(**row) starts a new episode and returns the prompt and question, which become the user message.
  2. The model generates a completion, and the trainer parses any <tool_call> blocks out of it. Each prompt is rolled out num_generations times, on separate instances.
  3. For each parsed call it dispatches to the matching tool method (here, answer(...)) and feeds the return value back to the model as a <tool_response>.
  4. When the rollout ends, the trainer calls env.get_reward() to score it.
  5. GRPO computes one advantage per completion (relative to the group's mean reward), updates the policy, and the cycle repeats.

That's why the wrapper only needs four things: a connection in __init__, a reset that returns the initial observation, one or more tool methods, and a get_reward that reads the score back.


5. No dataset needed

The environment generates every question and returns it from reset(), so GRPOTrainer doesn't need a train_dataset. Without one, max_steps sets the length of the run. When your task does come from a dataset, pass it as train_dataset: each row's columns are forwarded to reset(**row) and its prompt is prepended to what reset() returns.