# Tinker (https://www.agentenvframework.com/docs/training/tinker)

> Train using Thinking Machines' Tinker

## How a rollout runs

[Tinker](https://tinker-docs.thinkingmachines.ai/) samples from your model and trains it on its own
GPUs. [tinker-cookbook](https://github.com/thinking-machines-lab/tinker-cookbook)'s `rl.train` runs
the training loop on your machine. The helper plays each rollout there too, as an episode of one of
your bundle's tasks, with no server in between. Three pieces connect the cookbook to a bundle:

| Piece                    | What it does                                                                                                                                                     |
| ------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `AgentEnvDatasetBuilder` | `rl.train`'s dataset builder. It prepares the bundle's tasks as `agent-env run` does, and hands the cookbook each step's groups of rollouts, one task per group. |
| `EpisodeEnv`             | One rollout, as a cookbook `MessageEnv`. It starts the task as an episode, runs the model's tool calls in it, and returns the task's score as the reward.        |
| The Episode API          | Runs a task with its one prompted agent played from outside, and scores it with the task's verifiers.                                                            |

The model plays the task's prompted agent. Each prompt the task sends that agent is a turn:

1. It reads the turn's system prompt and tools, as the cookbook's renderer writes them, then the
   turn's prompt. The tools are the envs' tools, plus `bash` when the agent works in a sandbox.
2. Each message it sends is recorded on the turn. Its tool calls then run, and their results go back
   to it.
3. A message with no tool call ends the turn. The task's next turn, if it has one, comes as the next
   user message. If that turn sets a new system prompt, it's written before the prompt.
4. When the run ends, the task's verifiers score it, and the score is the reward.

## Install

You need Python 3.11 or newer, Docker running for the envs, and a Tinker API key. Tinker trains on
its own GPUs, so you need none. Install the framework into the environment that runs
tinker-cookbook:

```bash title="Terminal"
pip install tinker-cookbook 'agentenv-framework[tinker]>=0.9.1605'
export TINKER_API_KEY=<your key>
```

The `tinker` extra brings OpenEnv. tinker-cookbook, Tinker and torch are yours to pin.

## Train on a bundle

`AgentEnvDatasetBuilder` is the `dataset_builder` of `rl.train.Config`. Replace `bundles/my-bundle`
with your bundle's folder, `train` and `test` with the names of two of its evals, and `grade` with
the id of the verifier step whose score is the reward:

```python title="train.py"
import asyncio

from tinker_cookbook.rl import train
from tinker_cookbook.rl.rollout_strategy import RetryOnFailure

from agent_env.training.tinker import AgentEnvDatasetBuilder

MODEL = "Qwen/Qwen3.5-9B"
RENDERER = "qwen3_5_disable_thinking"
RUN = "my-run"

config = train.Config(
    model_name=MODEL,
    renderer_name=RENDERER,
    recipe_name="agentenv",
    log_path=f"runs/{RUN}",
    learning_rate=4e-5,
    max_tokens=4096,  # per model message
    rollout_error_tolerance=RetryOnFailure(max_retries=4, per_rollout_timeout=1200),
    dataset_builder=AgentEnvDatasetBuilder(
        bundle="bundles/my-bundle",
        run_name=RUN,
        model_name=MODEL,
        renderer_name=RENDERER,
        group_size=4,  # 32 rollouts a step: 8 tasks, 4 rollouts each
        groups_per_batch=8,
        train_split="train",
        test_split="test",
        reward="grade",
        max_turns=24,
        max_concurrent_episodes=12,
        max_trajectory_tokens=32768,
    ),
)
asyncio.run(train.main(config))
```

```bash title="Terminal"
python train.py
```

Give the builder the same `model_name` and `renderer_name` as the config: the cookbook samples and
trains with them, and the builder writes each rollout's prompts with them. The cookbook plays the test
split at the start, every `eval_every` steps (20 by default) and at the end, one rollout per task.

Two of the cookbook's settings matter here:

* **No rollout executor.** An episode lives on the event loop that started it, so every rollout runs
  on `rl.train`'s own loop. Call `train.main(config)` without a `rollout_executor`.
* **`rollout_error_tolerance`.** A failed episode raises, and `RetryOnFailure` plays the rollout again
  on a fresh episode. With the cookbook's default for most models, the first failed episode stops
  training. See [failed rollouts](#failed-rollouts).

## Train on GridSim

[GridSim](https://www.agentenvframework.com/docs/training/trl.md#train-on-gridsim) is the bundle the other training pages train on. The
model reads a day's 24 hourly power prices and submits a battery schedule. The env scores it 0.2 for
idling all day and 1 for the day's best schedule. This run follows the other pages' recipe, a short
SFT and then 40 RL steps. Tinker has no Qwen3-4B, the model they train, so this run trains Qwen3-8B.

### Download the bundle

The bundle and the SFT rows are folders in a Hugging Face dataset. The `hf` command comes with
tinker-cookbook:

```bash title="Terminal"
hf download earakely-scale/GridSimEnv-AgentEnv --repo-type dataset --include "bundles/gridsim-v1/*" --include "sft/gridsim-v1/*" --local-dir .
```

The bundle has 2,000 train days and 200 eval days. Each SFT row is a train day's prompt and its best
schedule.

### Warm start with SFT

Untrained, Qwen3-8B idles: on the 200 eval days it submits an idle schedule 92.5% of the time and
scores 0.19. A short SFT on the train days' best schedules gives RL something to build on.
[`tinker_gridsim_sft.py`](/training/tinker_gridsim_sft.py) trains one epoch with tinker-cookbook's
`supervised.train`, LoRA rank 32, at learning rate 1e-4. It writes each row the way an episode writes
its first prompt, so the model learns on the exact context it later plays from:

```python title="tinker_gridsim_sft.py (excerpt)"
def datum(row: dict, renderer, max_length: int) -> tinker.Datum:
    """A row, written as an episode's first prompt and its answer, training only the answer."""
    system, user = row["prompt"]
    answer = row["completion"][0]
    calls = [
        ToolCall(function=ToolCall.FunctionBody(name=c["function"]["name"], arguments=json.dumps(c["function"]["arguments"])),
                 id=f"call-{n}")
        for n, c in enumerate(answer["tool_calls"])
    ]
    messages = [
        *renderer.create_conversation_prefix_with_tools(tools=TOOLS, system_prompt=system["content"]),
        {"role": "user", "content": user["content"]},
        {"role": "assistant", "content": answer["content"], "tool_calls": calls},
    ]
    return conversation_to_datum(messages, renderer, max_length, TrainOnWhat.LAST_ASSISTANT_MESSAGE)
```

`TOOLS` is the env's `submit_schedule` tool, as an episode offers it. Don't use the rows' own
`tools`: they're written for TRL, with an extra `end_turn` tool.

### Train with RL

[`tinker_gridsim.py`](/training/tinker_gridsim.py) trains from the SFT checkpoint with the other
pages' settings: 32 rollouts a step (4 days, 8 rollouts each) at temperature 1.1, learning rate 2e-5,
LoRA rank 32, thinking off, and at most 4 model messages a rollout. tinker-cookbook's RL loop
compares each rollout's reward with its group's mean, as GRPO does. It plays the 200 eval days
before the first step and every 20 steps, one rollout a day.

```python title="tinker_gridsim.py"
import asyncio
import json

from tinker_cookbook.rl import train
from tinker_cookbook.rl.rollout_strategy import RetryOnFailure

from agent_env.training.tinker import AgentEnvDatasetBuilder

MODEL = "Qwen/Qwen3-8B"
RENDERER = "qwen3_disable_thinking"
RUN = "gridsim-qwen3-8b"

with open(f"runs/{RUN}-sft/checkpoints.jsonl") as f:
    sft = [json.loads(line) for line in f][-1]["state_path"]  # the SFT run's last checkpoint

config = train.Config(
    model_name=MODEL,
    renderer_name=RENDERER,
    recipe_name="agentenv-gridsim",
    log_path=f"runs/{RUN}",
    load_checkpoint_path=sft,
    learning_rate=2e-5,
    lora_rank=32,
    max_tokens=1024,  # per model message
    temperature=1.1,
    max_steps=40,
    eval_every=20,
    save_every=20,
    remove_constant_reward_groups=False,
    rollout_error_tolerance=RetryOnFailure(max_retries=4, per_rollout_timeout=600),
    dataset_builder=AgentEnvDatasetBuilder(
        bundle="bundles/gridsim-v1",
        run_name=RUN,
        model_name=MODEL,
        renderer_name=RENDERER,
        group_size=8,  # 32 rollouts a step: 4 days, 8 rollouts each
        groups_per_batch=4,
        train_split="train",
        test_split="eval",
        reward="grade",
        max_turns=4,
        max_concurrent_episodes=24,
        max_trajectory_tokens=8192,
        seed=0,
    ),
)

if __name__ == "__main__":
    asyncio.run(train.main(config))
```

Run both from the folder you downloaded into:

```bash title="Terminal"
python tinker_gridsim_sft.py
python tinker_gridsim.py
```

### What it learns

| Qwen3-8B | eval reward (200 days) |
|---|---|
| base | 0.195 |
| after SFT (GRPO step 0) | 0.645 |
| GRPO step 20 | 0.697 |
| GRPO step 40 | 0.715 |

Mean train reward of each GRPO step's 32 rollouts, by step: 1: 0.814, 2: 0.698, 3: 0.550, 4: 0.590, 5: 0.493, 6: 0.719, 7: 0.692, 8: 0.768, 9: 0.938, 10: 0.783, 11: 0.743, 12: 0.907, 13: 0.836, 14: 0.795, 15: 0.665, 16: 0.724, 17: 0.465, 18: 0.720, 19: 0.956, 20: 0.614, 21: 0.681, 22: 0.654, 23: 0.821, 24: 0.736, 25: 0.733, 26: 0.801, 27: 0.833, 28: 0.887, 29: 0.939, 30: 0.625, 31: 0.911, 32: 0.931, 33: 0.852, 34: 0.833, 35: 0.900, 36: 0.846, 37: 0.782, 38: 0.805, 39: 0.938, 40: 0.812.

| Qwen3-8B, 200 eval days | Eval reward | Beat idling | Best schedule |
| ----------------------- | ----------- | ----------- | ------------- |
| Untrained               | 0.19        | 2.5%        | 0%            |
| After SFT (step 0)      | 0.65        | 82.5%       | 12.5%         |
| After 20 steps          | 0.70        | 93%         | 9.5%          |
| After 40 steps          | 0.71        | 91.5%       | 13.5%         |

RL took the eval reward from 0.65 to 0.71 in 40 steps (standard errors about 0.02). On Qwen3-4B, the
other pages' runs score 0.51 to 0.57 after SFT and 0.57 to 0.69 after 40 steps, so their RL gains
run from 0 to 0.18. Qwen3-8B starts higher mostly because it's the larger model. Each is one run, so
read the gaps as pointers, not a ranking.

After the env accepts its schedule, the model keeps calling `submit_schedule` until it reaches the
4-message limit. The env refuses the repeats, and the reward is the first schedule's. RL didn't
change that; `max_turns=4` bounds what it costs.

Tinker sampled and trained; the 1,880 rollouts ran on a laptop's Docker, with 4 CPUs. A step took
about 70 seconds. Three took about 30 minutes, while another job shared the Docker and rollouts
stalled. `RetryOnFailure` retried 22 rollouts, 18 after a dropped connection and 4 after a timeout,
and skipped no group.

## Settings

| Setting                          | Default           | What it sets                                                                                                              |
| -------------------------------- | ----------------- | ------------------------------------------------------------------------------------------------------------------------- |
| `bundle`, `run_name`             | required          | The bundle's folder, and the name the run's rollouts are filed under.                                                     |
| `model_name`, `renderer_name`    | required          | The model and its renderer, as in `rl.train.Config`.                                                                      |
| `group_size`, `groups_per_batch` | required          | A training step plays `groups_per_batch` tasks, `group_size` times each.                                                  |
| `train_split`, `test_split`      | `all`, none       | `all`, or the name of an eval in the bundle.                                                                              |
| `test_group_size`                | 1                 | Rollouts per task of the test split.                                                                                      |
| `reward`                         | none              | The step id whose score is the reward. Needed when a task records more than one score.                                    |
| `max_turns`                      | 30                | The most messages the model sends in a rollout. At the limit, the turn ends and the verifiers score the run as it stands. |
| `max_concurrent_episodes`        | 8                 | Episodes under way at once. Each deploys its own envs; the rest wait for a slot.                                          |
| `max_trajectory_tokens`          | none              | The longest conversation, in tokens. The cookbook cuts a rollout that grows past it.                                      |
| `failed_reward`                  | 0                 | Added to the score of a rollout the cookbook cuts.                                                                        |
| `tool_timeout`                   | 60 s              | One call to an env's tool.                                                                                                |
| `turn_timeout`                   | the prompt step's | Each turn's deadline, in place of its prompt step's `timeout_seconds`.                                                    |
| `sandbox`                        | your config's     | Where episodes deploy, as `agent-env run --sandbox` sets it.                                                              |
| `epochs`, `seed`                 | 1, 0              | Passes over the train split, each shuffled anew with the seed.                                                            |

A pass over the train split takes its number of tasks divided by `groups_per_batch` steps, rounded
up: every task is played once a pass, the last step playing the tasks left over. Set more passes
with the builder's `epochs`, not the cookbook's `num_epochs`: that one replays the first pass's
batches in the same order, under the same step numbers.

## Pick a renderer

`renderer_name` names the model's chat format in the cookbook. The renderer writes the tools into
the first prompt and reads the model's tool calls, so it must support tool calling: a renderer
without it fails every rollout.

The cookbook joins a rollout's messages into one training sequence as long as each new prompt is the
last prompt plus the model's reply and the tool results. When a prompt rewrites earlier messages, the
cookbook starts a new sequence that repeats the whole conversation, which costs more to train. For
Qwen3.5, use `qwen3_5_disable_thinking`: with thinking off, every prompt within a turn extends the
last. `qwen3_5` drops the model's earlier reasoning from later prompts, so each reply after the first
starts a new sequence. A task's next turn starts a new sequence with either.

## Rewards and metrics

The reward is the task's score, the one an evaluation run records. A task that records several
scores takes one by its step id, with `reward=`. Each rollout also reports these metrics, which the
cookbook averages under `env/all/` in training and `test/env/all/` on the test split:

| Metric                                  | What it is                                                                           |
| --------------------------------------- | ------------------------------------------------------------------------------------ |
| `score/<step id>`                       | Each score the task's verifiers record.                                              |
| `cut`                                   | 1 for a rollout the cookbook cut, 0 for the rest.                                    |
| `messages`, `tool_calls`, `tool_errors` | The model's messages, its tool calls, and the calls that failed or couldn't be read. |

The cookbook cuts a rollout when a message reaches `max_tokens`, when it can't read a reply as a
message, or when the conversation passes `max_trajectory_tokens`, the first prompt included. The
helper still scores it: the open turn ends with no reply, the verifiers score where the episode got
to, and the reward is that score plus `failed_reward`. A tool call that can't be parsed doesn't cut
the rollout: the model is told, and goes on.

## Failed rollouts

An episode fails when, for instance, its envs don't deploy, a later turn offers other tools than
the first, or its run records no score. The rollout then raises instead of training as 0, and the
episode is torn down. `RetryOnFailure` plays it again on a fresh episode, and skips the group once
its `max_retries` run out. `per_rollout_timeout` ends and retries a rollout that runs longer than
that many seconds.

## Which tasks it plays

The helper plays a task's one prompted agent, so a task must prompt exactly one agent and record a
score. Before training starts, it leaves out, with a warning:

* a task that can't run as an episode, such as one that prompts no agent, or several;
* a task that gives the played agent skills, since the model isn't shown them yet.

It refuses to start when a task records no score, or records several and `reward` names none of
them, and when no task is left. For example, the shipped `hello` bundle has no task to play:

```text title="Error"
ValueError: no task can be played as an episode: {'hello': "task '…/hello/hello' prompts no agent"}
```

## Watch the rollouts

Each group's episodes are runs of their own, filed under `<run_name>/train/step-<n>`, or
`<run_name>/eval/step-<n>` for the test split, where `<n>` is the training step, such as
`step-0003`. The [explorer](https://www.agentenvframework.com/docs/getting-started.md#open-the-explorer) shows a task's runs by these
groups. Start it with the same `.agentenv/config.toml` as training, so it reads the same stores:

```bash title="Terminal"
agent-env up
```

The cookbook's own report of each step, under `log_path`, shows each rollout's messages, tool calls
and tool results, each cut at 2,000 characters. The run in the explorer keeps the full text.

## What's supported

|                  |                                                                                                                                                   |
| ---------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- |
| tinker-cookbook  | Run on 0.5.9 and 0.6.1. A CI job plays rollouts through the helper on the latest release and on main, every week, with a stand-in renderer.       |
| Models           | Trained on Tinker with Qwen3.5-9B and `qwen3_5_disable_thinking`, and with Qwen3-8B and `qwen3_disable_thinking` on [GridSim](#train-on-gridsim). |
| Multi-turn tasks | Each next turn comes as a user message; checked in CI, not yet trained on.                                                                        |
| Sandboxes        | `sandbox=` deploys every episode where `agent-env run --sandbox` would. Only local Docker has been exercised.                                     |

## Limits

* **Images in tool results** reach the model as a placeholder, `[image content]`.
* **No skills.** A task that gives the played agent skills is left out.
* **One set of tools per rollout.** The renderer writes the tools once, at the start, so a later turn
  that offers other tools fails its rollout.
* **Local Docker only, so far.** No other sandbox provider has been exercised.
* **One deploy per rollout.** Every rollout deploys its envs fresh, and the deploy counts in its time.