opensi·si

OpenEnv environments are not only useful for RL training — they are also a natural tool for collecting

Collect Rollouts for SFT

OpenEnv environments are not only useful for RL training — they are also a natural tool for collecting rollouts that become supervised training data. The environment handles episode management, automatic scoring, and reproducibility, so you get a reward-labeled dataset without writing any of that infrastructure yourself.

This tutorial shows the full pipeline:

  1. Run a strong teacher model inside an OpenEnv environment to collect rollouts.
  2. Use the environment's reward signal to filter out incorrect examples automatically.
  3. Train a smaller student model on the filtered rollouts with TRL's SFTTrainer.

As a concrete application, the resulting checkpoint is used as a warm-start for GRPO: once the student reliably produces valid tool calls, GRPO's reward_std is non-zero from the first batch and the reward curve climbs immediately.

Why use an environment to collect training data

Building a supervised dataset usually means writing a custom collection loop, a scorer, and episode bookkeeping. An OpenEnv environment gives you all three out of the box:

  • Automatic scoring — every step() returns a reward. Filter by reward == 1.0 and you have a clean, correct dataset with no manual labelling.
  • Reproducible episodes — reset(seed=42, size=N) produces the same sequence of problems every run. Anyone can regenerate the exact dataset.
  • Configurable difficulty — adjust DATASET_CONFIG to control problem complexity without changing any collection code.
  • Portable across environments — the same collect → filter → train pipeline works for any OpenEnv environment. Swap the env and the tool definition; everything else stays the same.

What you'll use

Student model Qwen/Qwen3-1.7B
Teacher model gpt-5-mini via the OpenAI API
Environment reasoning_gym_env / chain_sum
SFT trainer TRL SFTTrainer
Next step End-to-end walkthrough with GRPO

1. Install dependencies

!pip install -q openai 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"

2. Set your credentials

import getpass, os

if "OPENAI_API_KEY" not in os.environ:
    os.environ["OPENAI_API_KEY"] = getpass.getpass("OpenAI API key: ")

You'll also need a Hugging Face login to download the base model and push both the collected dataset and the fine-tuned checkpoint:

from huggingface_hub import notebook_login

notebook_login()
YOUR_HF_USERNAME = "your-username"  # replace with your Hugging Face username
assert YOUR_HF_USERNAME != "your-username", "Replace YOUR_HF_USERNAME with your Hugging Face username"

3. Define the system prompt

Use the same prompt as the GRPO tutorial so the SFT-trained model is a drop-in replacement when you continue with GRPO.

SYSTEM_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. Configure data collection

DATASET_CONFIG controls the difficulty of the chain_sum problems the environment generates: min_terms/max_terms set how many integers are added together, and min_digits/max_digits set how many digits each integer has. At these settings each problem is a sum of 2–3 two-digit numbers — easy enough for gpt-5-mini to answer correctly ~90% of the time, which gives a clean training signal after filtering.

N_EPISODES is the number of problems to collect. 300 is enough to get ~270 correct examples after filtering, which is sufficient for format compliance training.

DATASET_CONFIG = {
    "min_terms": 2,
    "max_terms": 3,
    "min_digits": 2,
    "max_digits": 2,
}

N_EPISODES = 300

5. Collect rollouts with openenv collect

openenv collect runs the teacher model inside the environment and records every episode — the environment's step() reward is written alongside the messages, so filtering by correctness requires no additional scoring code. By default it drops rollouts with a negative reward (--keep-losses keeps them). Reasoning Gym scores a wrong answer 0.0, so wrong answers are kept here and filtered in section 6.

import json, shlex

dataset_config_arg = shlex.quote(json.dumps(DATASET_CONFIG))
system_prompt_arg = shlex.quote(SYSTEM_PROMPT)
hub_repo_arg = shlex.quote(f"{YOUR_HF_USERNAME}/chain-sum-rollouts")

!openenv collect reasoning_gym:chain_sum \
  --base-url https://sergiopaniego-reasoning-gym.hf.space \
  --provider openai \
  --model gpt-5-mini \
  --num-episodes {N_EPISODES} \
  --max-tokens 1024 \
  --dataset-config {dataset_config_arg} \
  --system-prompt {system_prompt_arg} \
  --push-to-hub {hub_repo_arg} \
  --output-dir ./rollouts

To use a self-hosted teacher instead of a hosted provider, point --llm-endpoint at any OpenAI-compatible server (vLLM, TGI, Ollama) and pass the model id it serves:

openenv collect reasoning_gym:chain_sum \
  --base-url https://sergiopaniego-reasoning-gym.hf.space \
  --llm-endpoint http://localhost:8000 \
  --model Qwen/Qwen3-8B \
  --num-episodes 300 \
  --output-dir ./rollouts

The teacher drives the environment through tool calls, so the server must have tool calling enabled (for vLLM: --enable-auto-tool-choice --tool-call-parser <parser for your model>).

The command prints a live progress summary and pushes the collected episodes to the Hub as {YOUR_HF_USERNAME}/chain-sum-rollouts. Pull them back to start filtering:

from datasets import load_dataset

ds = load_dataset(f"{YOUR_HF_USERNAME}/chain-sum-rollouts", split="train")
raw_rollouts = list(ds)
print(f"Collected {len(raw_rollouts)} episodes")

The messages field stores the full conversation in standard OpenAI format (assistant messages have a tool_calls list). Convert to Qwen3's <tool_call> text format before training — GRPOTrainer produces this same format during RL, so the SFT checkpoint becomes a direct drop-in:

def to_qwen3_messages(record):
    converted = []
    for msg in record["messages"]:
        if msg["role"] == "tool":
            continue  # strip environment responses; SFT only needs the assistant turn
        if msg["role"] == "assistant" and msg.get("tool_calls"):
            tc = msg["tool_calls"][0]
            args = json.loads(tc["function"]["arguments"])
            answer_str = args.get("answer", "")
            tool_call_text = (
                "<tool_call>\n"
                + json.dumps({"name": "answer", "arguments": {"answer": answer_str}})
                + "\n</tool_call>"
            )
            converted.append({"role": "assistant", "content": tool_call_text})
        else:
            converted.append(msg)
    return {"messages": converted, "reward": record["reward"]}

rollouts = [to_qwen3_messages(r) for r in raw_rollouts]