"""GridSim RL on Tinker from the SFT warm start, with the other training pages' settings: 40 steps of 32 rollouts (4
days, 8 rollouts each) from the 2,000 train days, the 200 eval days played once each at steps 0, 20 and 40, learning
rate 2e-5, temperature 1.1, up to 1,024 tokens a message and 4 messages a rollout.

    hf download earakely-scale/GridSimEnv-AgentEnv --repo-type dataset --include "bundles/gridsim-v1/*" --local-dir .
    python tinker_gridsim.py        # after tinker_gridsim_sft.py; writes runs/gridsim-qwen3-8b/
"""

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))
