Stage Harbor release files 105001-105427
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- .gitattributes+1
- README.mdAdded+105
- release-files.jsonAdded+3
- tasks/tasksmith-fa1a9b35ff39/tests/source/examples/scripts/async_grpo.pyAdded+76
- tasks/tasksmith-fa1a9b35ff39/tests/source/examples/scripts/bco.pyAdded+156
- tasks/tasksmith-fa1a9b35ff39/tests/source/examples/scripts/cpo.pyAdded+102
- tasks/tasksmith-fa1a9b35ff39/tests/source/examples/scripts/distillation.pyAdded+177
- tasks/tasksmith-fa1a9b35ff39/tests/source/examples/scripts/dpo.pyAdded+17
- tasks/tasksmith-fa1a9b35ff39/tests/source/examples/scripts/dpo_vlm.pyAdded+134
- tasks/tasksmith-fa1a9b35ff39/tests/source/examples/scripts/gkd.pyAdded+139
- tasks/tasksmith-fa1a9b35ff39/tests/source/examples/scripts/gold.pyAdded+152
- tasks/tasksmith-fa1a9b35ff39/tests/source/examples/scripts/grpo_2048.pyAdded+161
- tasks/tasksmith-fa1a9b35ff39/tests/source/examples/scripts/grpo_agent.pyAdded+320
- tasks/tasksmith-fa1a9b35ff39/tests/source/examples/scripts/grpo_continuous_batching.pyAdded+133
- tasks/tasksmith-fa1a9b35ff39/tests/source/examples/scripts/grpo_vlm.pyAdded+157
- tasks/tasksmith-fa1a9b35ff39/tests/source/examples/scripts/gspo.pyAdded+131
- tasks/tasksmith-fa1a9b35ff39/tests/source/examples/scripts/gspo_vlm.pyAdded+146
- tasks/tasksmith-fa1a9b35ff39/tests/source/examples/scripts/harbor/data_agent.pyAdded+131
- tasks/tasksmith-fa1a9b35ff39/tests/source/examples/scripts/harbor/harnesses/__init__.pyAdded+20
- tasks/tasksmith-fa1a9b35ff39/tests/source/examples/scripts/harbor/harnesses/bash/README.mdAdded+20
- tasks/tasksmith-fa1a9b35ff39/tests/source/examples/scripts/harbor/harnesses/bash/__init__.pyAdded+18
- tasks/tasksmith-fa1a9b35ff39/tests/source/examples/scripts/harbor/harnesses/jupyter/README.mdAdded+31
- tasks/tasksmith-fa1a9b35ff39/tests/source/examples/scripts/harbor/harnesses/jupyter/__init__.pyAdded+18
- tasks/tasksmith-fa1a9b35ff39/tests/source/examples/scripts/harbor/harnesses/jupyter/env.pyAdded+104
- tasks/tasksmith-fa1a9b35ff39/tests/source/examples/scripts/harbor/harnesses/jupyter/kernel_server.pyAdded+98
- tasks/tasksmith-fa1a9b35ff39/tests/source/examples/scripts/harbor/harnesses/jupyter/run_cell.pyAdded+61
- tasks/tasksmith-fa1a9b35ff39/tests/source/examples/scripts/harbor/harnesses/terminal_notes/README.mdAdded+40
- tasks/tasksmith-fa1a9b35ff39/tests/source/examples/scripts/harbor/harnesses/terminal_notes/__init__.pyAdded+18
- tasks/tasksmith-fa1a9b35ff39/tests/source/examples/scripts/harbor/harnesses/terminal_notes/env.pyAdded+221
- tasks/tasksmith-fa1a9b35ff39/tests/source/examples/scripts/kto.pyAdded+99
- tasks/tasksmith-fa1a9b35ff39/tests/source/examples/scripts/mpo_vlm.pyAdded+126
- tasks/tasksmith-fa1a9b35ff39/tests/source/examples/scripts/nash_md.pyAdded+130
- tasks/tasksmith-fa1a9b35ff39/tests/source/examples/scripts/online_dpo.pyAdded+137
- tasks/tasksmith-fa1a9b35ff39/tests/source/examples/scripts/online_dpo_vlm.pyAdded+203
- tasks/tasksmith-fa1a9b35ff39/tests/source/examples/scripts/openenv/browsergym.pyAdded+291
- tasks/tasksmith-fa1a9b35ff39/tests/source/examples/scripts/openenv/browsergym_llm.pyAdded+463
- tasks/tasksmith-fa1a9b35ff39/tests/source/examples/scripts/openenv/carla.pyAdded+219
- tasks/tasksmith-fa1a9b35ff39/tests/source/examples/scripts/openenv/carla_vlm.pyAdded+262
- tasks/tasksmith-fa1a9b35ff39/tests/source/examples/scripts/openenv/carla_vlm_gemma.pyAdded+278
- tasks/tasksmith-fa1a9b35ff39/tests/source/examples/scripts/openenv/catch.pyAdded+347
- tasks/tasksmith-fa1a9b35ff39/tests/source/examples/scripts/openenv/echo.pyAdded+133
- tasks/tasksmith-fa1a9b35ff39/tests/source/examples/scripts/openenv/multi_env.pyAdded+273
- tasks/tasksmith-fa1a9b35ff39/tests/source/examples/scripts/openenv/sudoku.pyAdded+669
- tasks/tasksmith-fa1a9b35ff39/tests/source/examples/scripts/openenv/sudoku_prompt.txtAdded+122
- tasks/tasksmith-fa1a9b35ff39/tests/source/examples/scripts/openenv/wordle.pyAdded+277
- tasks/tasksmith-fa1a9b35ff39/tests/source/examples/scripts/openreward/seta.pyAdded+127
- tasks/tasksmith-fa1a9b35ff39/tests/source/examples/scripts/orpo.pyAdded+102
- tasks/tasksmith-fa1a9b35ff39/tests/source/examples/scripts/ppo/ppo.pyAdded+160
- tasks/tasksmith-fa1a9b35ff39/tests/source/examples/scripts/ppo/ppo_tldr.pyAdded+168
- tasks/tasksmith-fa1a9b35ff39/tests/source/examples/scripts/prm.pyAdded+128
58 unmodified lines59606158 unmodified lines*.mp4 filter=lfs diff=lfs merge=lfs -text*.webm filter=lfs diff=lfs merge=lfs -textbundle-files.json filter=lfs diff=lfs merge=lfs -text58 unmodified lines5960616258 unmodified lines*.mp4 filter=lfs diff=lfs merge=lfs -text*.webm filter=lfs diff=lfs merge=lfs -textbundle-files.json filter=lfs diff=lfs merge=lfs -textrelease-files.json filter=lfs diff=lfs merge=lfs -text
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105---license: otherlicense_name: mixed-source-licenseslicense_link: https://huggingface.co/datasets/HuggingEnvs/HF_ML_Tasksmith/blob/main/LICENSES.mdlanguage:- entags:- reinforcement-learning- coding- harbor- repo2rlenv- tasksmithsize_categories:- n<1Kviewer: false---
[](https://huggingface.co/spaces/HuggingFaceH4/harbor-visualiser?dataset=HuggingEnvs/HF_ML_Tasksmith)
# HF ML Tasksmith
Fifty PR-derived Harbor tasks from Accelerate, Diffusers, PEFT, Transformers and TRL, including CPU and GPU tasks.
Contains **50 Harbor tasks** generated with the owned`tasksmith` recipe in [Repo2RLEnv](https://github.com/huggingface/Repo2RLEnv).Browse the complete task bundles in [Harbor Visualiser](https://huggingface.co/spaces/HuggingFaceH4/harbor-visualiser?dataset=HuggingEnvs/HF_ML_Tasksmith) or[open the task folders](https://huggingface.co/datasets/HuggingEnvs/HF_ML_Tasksmith/tree/main/tasks). Each folder is a runnable Harbor task:
```texttasks/<task_id>/├── task.toml # Harbor configuration and provenance├── instruction.md # Task shown to the coding agent├── environment/Dockerfile # Learner sandbox and its build context├── solution/solve.sh # Reference solution entry point└── tests/ ├── test.sh # Verifier entry point; writes the reward └── Dockerfile # Separate verifier sandbox, when configured```
Example: [task.toml](https://huggingface.co/datasets/HuggingEnvs/HF_ML_Tasksmith/blob/main/tasks/tasksmith-03a6a091b12f/task.toml) ·[instruction](https://huggingface.co/datasets/HuggingEnvs/HF_ML_Tasksmith/blob/main/tasks/tasksmith-03a6a091b12f/instruction.md) ·[verifier](https://huggingface.co/datasets/HuggingEnvs/HF_ML_Tasksmith/blob/main/tasks/tasksmith-03a6a091b12f/tests/test.sh) ·[oracle](https://huggingface.co/datasets/HuggingEnvs/HF_ML_Tasksmith/blob/main/tasks/tasksmith-03a6a091b12f/solution/solve.sh).
`data/tasks.jsonl` is an auxiliary metadata index. Download the task folders orarchive below to run the environments. `manifest.json` records source identity,evidence, diagnostics and measured costs. The generic tabular Hub viewer isdisabled so it does not present the index as the task dataset.
## Generation
Tasksmith explores a merged PR, bootstraps the repository, designs an instruction and deterministic verifier, packages offline assets and a reference solution, then applies bounded review, repair, baseline/oracle checks, probes and blind Sonnet rollouts. This release is an assisted practical-acceptance campaign; source PRs, execution controls and independent audit hashes are bound per task.
Implementation revision: `a8ea8fa644ec4c3980291f00d7f8190cdfb45a45`. The exact recipe, source revision,reward kinds and quality status remain in each original `task.toml`.
## Validation and limitations
Quality label counts: `{"verified": 50}`.An `exported` task is a generation artifact. Baseline/reference controls establishonly the behavior recorded in that task's evidence. They do not establish blindsolver success, difficulty, verifier completeness or resistance to reward hacking.An LLM consistency review is separate from the deterministic task reward.
- 50 assisted practical-acceptance tasks: this is not an unattended yield estimate.- Sonnet fully solved 19 tasks; 31 did not receive full reward. Solver success was not required for task acceptance.- 39 tasks request CPU only, 6 request one GPU and 5 request two GPUs; select a provider with matching resources.- Existing task metadata may reference historical local evidence paths; use the published manifest for portable acceptance summaries and evidence hashes.- Source files retain upstream repository licenses.
## Download and run
`tasks.tar.gz` preserves executable file modes and the original bundle identities:
```bashhf download HuggingEnvs/HF_ML_Tasksmith tasks.tar.gz --repo-type dataset --local-dir ./datasettar -xzf ./dataset/tasks.tar.gz -C ./datasetharbor run --path ./dataset/tasks --agent oracle --env daytona```
Configure Daytona credentials and Harbor's provider dependencies before execution.The archive includes references and private tests for the harness; the solvershould receive only the instruction and learner environment. `registry.json`pins the unpacked task paths to the immutable upload commit.
## Economics
`manifest.json` includes generation costs, failed-attempt costs and outstandingreservations when available. Cloud lifetime estimates are labeled separately fromprovider invoices. Retained task costs and new-generation costs use separate scopes.
## Credits and licensing
- https://github.com/huggingface/Repo2RLEnv/blob/a8ea8fa644ec4c3980291f00d7f8190cdfb45a45/docs/rfcs/0028-tasksmith-pr-pilot.md- https://github.com/huggingface/Repo2RLEnv/blob/a8ea8fa644ec4c3980291f00d7f8190cdfb45a45/docs/pipelines/tasksmith_campaign_retrospective.md- https://www.harborframework.com/docs/tasks- https://github.com/huggingface/transformers- https://github.com/huggingface/trl- https://github.com/huggingface/peft- https://github.com/huggingface/diffusers- https://github.com/huggingface/accelerate
See [LICENSES.md](LICENSES.md), bundled notices and per-task provenance. These areowned adaptations inspired by the credited methods, not an upstream benchmarkrelease or a claim of exact reproduction of its published results.123version https://git-lfs.github.com/spec/v1oid sha256:7b6217eea74e00d9899e230e78a42756530347ef97b82f7383e1cfb7939b23d5size 2428904512345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576# Copyright 2020-2026 The HuggingFace Team. All rights reserved.## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License.
# /// script# dependencies = [# "trl",# "math-verify",# "latex2sympy2_extended",# "trackio",# ]# ///
"""pip install math_verify
CUDA_VISIBLE_DEVICES=1 VLLM_SERVER_DEV_MODE=1 vllm serve Qwen/Qwen3-0.6B \ --max-model-len 2048 \ --logprobs-mode processed_logprobs \ --weight-transfer-config '{"backend":"nccl"}'
CUDA_VISIBLE_DEVICES=0 accelerate launch examples/scripts/async_grpo.py"""
from datasets import load_dataset
from trl.experimental.async_grpo import AsyncGRPOConfig, AsyncGRPOTrainerfrom trl.rewards import accuracy_reward
def format_sample(sample): return { "prompt": [{"role": "user", "content": sample["question"]}], "solution": sample["answer"].split("####")[-1].strip(), }
def main() -> None: dataset = load_dataset("openai/gsm8k", "main", split="train") dataset = dataset.map(format_sample, remove_columns=dataset.column_names)
config = AsyncGRPOConfig( output_dir="async_grpo_gsm8k", save_strategy="no", per_device_train_batch_size=16, gradient_accumulation_steps=2, max_completion_length=1024, chat_template_kwargs={"enable_thinking": False}, max_steps=200, learning_rate=1e-5, report_to="trackio", trackio_space_id="async-grpo-gsm8k", project="async-grpo-gsm8k", log_completions=True, ) trainer = AsyncGRPOTrainer( model="Qwen/Qwen3-0.6B", args=config, train_dataset=dataset, reward_funcs=accuracy_reward, ) trainer.train()
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156# Copyright 2020-2026 The HuggingFace Team. All rights reserved.## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License.
# /// script# dependencies = [# "trl[peft]",# "einops",# "scikit-learn",# "joblib",# "trackio",# "kernels",# ]# ///
"""Run the BCO training script with the commands below. In general, the optimal configuration for BCO will be similar to that of KTO.
# Full training:python examples/scripts/bco.py \ --model_name_or_path Qwen/Qwen2.5-0.5B-Instruct \ --trust_remote_code \ --dataset_name trl-lib/ultrafeedback-gpt-3.5-turbo-helpfulness \ --per_device_train_batch_size 16 \ --per_device_eval_batch_size 32 \ --num_train_epochs 1 \ --gradient_accumulation_steps 1 \ --eval_steps 0.2 \ --save_strategy no \ --output_dir bco-aligned-model \ --logging_first_step \ --max_length 2048 \ --max_completion_length 1024 \ --no_remove_unused_columns \ --warmup_steps 0.1
# QLoRA:python examples/scripts/bco.py \ --model_name_or_path Qwen/Qwen2.5-0.5B-Instruct \ --trust_remote_code \ --dataset_name trl-lib/ultrafeedback-gpt-3.5-turbo-helpfulness \ --per_device_train_batch_size 16 \ --per_device_eval_batch_size 32 \ --num_train_epochs 1 \ --gradient_accumulation_steps 1 \ --eval_steps 0.2 \ --save_strategy no \ --output_dir bco-aligned-model-lora \ --logging_first_step \ --warmup_steps 0.1 \ --max_length 2048 \ --max_completion_length 1024 \ --no_remove_unused_columns \ --warmup_steps 0.1 \ --use_peft \ --load_in_4bit \ --lora_target_modules all-linear \ --lora_r 16 \ --lora_alpha 16"""
from functools import partial
import torchimport torch.nn.functional as Ffrom accelerate import Acceleratorfrom datasets import load_datasetfrom transformers import AutoModel, AutoModelForCausalLM, AutoTokenizer, HfArgumentParser, PreTrainedModel
from trl import ModelConfig, ScriptArguments, get_peft_configfrom trl.experimental.bco import BCOConfig, BCOTrainer
def embed_prompt(input_ids: torch.LongTensor, attention_mask: torch.LongTensor, model: PreTrainedModel): """ Borrowed from https://huggingface.co/nomic-ai/nomic-embed-text-v1.5#transformers """
def mean_pooling(model_output, attention_mask): token_embeddings = model_output[0] input_mask_expanded = attention_mask.unsqueeze(-1).expand(token_embeddings.size()).float() return torch.sum(token_embeddings * input_mask_expanded, 1) / torch.clamp(input_mask_expanded.sum(1), min=1e-9)
with torch.no_grad(): model_output = model(input_ids=input_ids, attention_mask=attention_mask) embeddings = mean_pooling(model_output, attention_mask)
matryoshka_dim = 512 # normalize embeddings embeddings = F.normalize(embeddings, p=2, dim=1) embeddings = F.layer_norm(embeddings, normalized_shape=(embeddings.shape[1],)) embeddings = embeddings[:, :matryoshka_dim]
return embeddings
if __name__ == "__main__": parser = HfArgumentParser((ScriptArguments, BCOConfig, ModelConfig)) script_args, training_args, model_args = parser.parse_args_into_dataclasses()
training_args.gradient_checkpointing_kwargs = {"use_reentrant": True}
# Load a pretrained model model = AutoModelForCausalLM.from_pretrained(model_args.model_name_or_path) ref_model = AutoModelForCausalLM.from_pretrained(model_args.model_name_or_path)
tokenizer = AutoTokenizer.from_pretrained(model_args.model_name_or_path) if tokenizer.pad_token is None: tokenizer.pad_token = tokenizer.eos_token
dataset = load_dataset(script_args.dataset_name, name=script_args.dataset_config)
accelerator = Accelerator() embedding_model = AutoModel.from_pretrained( "nomic-ai/nomic-embed-text-v1.5", safe_serialization=True, dtype=torch.bfloat16, device_map="auto", ) embedding_model = accelerator.prepare_model(embedding_model) embedding_tokenizer = AutoTokenizer.from_pretrained("bert-base-uncased") embedding_func = partial( embed_prompt, model=embedding_model, )
# Initialize the BCO trainer trainer = BCOTrainer( model, ref_model, args=training_args, train_dataset=dataset[script_args.dataset_train_split], eval_dataset=dataset[script_args.dataset_test_split] if training_args.eval_strategy != "no" else None, processing_class=tokenizer, peft_config=get_peft_config(model_args), embedding_func=embedding_func, embedding_tokenizer=embedding_tokenizer, )
# Train and push the model to the Hub trainer.train()
# Save and push to hub trainer.save_model(training_args.output_dir) if training_args.push_to_hub: trainer.push_to_hub(dataset_name=script_args.dataset_name)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102# Copyright 2020-2026 The HuggingFace Team. All rights reserved.## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License.
# /// script# dependencies = [# "trl[peft]",# "trackio",# "kernels",# ]# ///
"""Run the CPO training script with the following command with some example arguments.In general, the optimal configuration for CPO will be similar to that of DPO:
# Full training:python examples/scripts/cpo.py \ --dataset_name trl-lib/ultrafeedback_binarized \ --model_name_or_path gpt2 \ --per_device_train_batch_size 4 \ --max_steps 1000 \ --learning_rate 8e-6 \ --gradient_accumulation_steps 1 \ --eval_steps 500 \ --output_dir "gpt2-aligned-cpo" \ --warmup_steps 150 \ --logging_first_step \ --no_remove_unused_columns
# QLoRA:python examples/scripts/cpo.py \ --dataset_name trl-lib/ultrafeedback_binarized \ --model_name_or_path gpt2 \ --per_device_train_batch_size 4 \ --max_steps 1000 \ --learning_rate 8e-5 \ --gradient_accumulation_steps 1 \ --eval_steps 500 \ --output_dir "gpt2-lora-aligned-cpo" \ --optim rmsprop \ --warmup_steps 150 \ --logging_first_step \ --no_remove_unused_columns \ --use_peft \ --lora_r 16 \ --lora_alpha 16"""
from datasets import load_datasetfrom transformers import AutoModelForCausalLM, AutoTokenizer, HfArgumentParser
from trl import ModelConfig, ScriptArguments, get_peft_configfrom trl.experimental.cpo import CPOConfig, CPOTrainer
if __name__ == "__main__": parser = HfArgumentParser((ScriptArguments, CPOConfig, ModelConfig)) script_args, training_args, model_args = parser.parse_args_into_dataclasses()
################ # Model & Tokenizer ################ model = AutoModelForCausalLM.from_pretrained(model_args.model_name_or_path) tokenizer = AutoTokenizer.from_pretrained(model_args.model_name_or_path) if tokenizer.pad_token is None: tokenizer.pad_token = tokenizer.eos_token
################ # Dataset ################ dataset = load_dataset(script_args.dataset_name, name=script_args.dataset_config)
################ # Training ################ trainer = CPOTrainer( model, args=training_args, train_dataset=dataset[script_args.dataset_train_split], eval_dataset=dataset[script_args.dataset_test_split] if training_args.eval_strategy != "no" else None, processing_class=tokenizer, peft_config=get_peft_config(model_args), )
# train and save the model trainer.train()
# Save and push to hub trainer.save_model(training_args.output_dir) if training_args.push_to_hub: trainer.push_to_hub(dataset_name=script_args.dataset_name)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177# Copyright 2020-2026 The HuggingFace Team. All rights reserved.## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License.
# /// script# dependencies = [# "trl",# "peft",# "trackio",# "kernels",# ]# ///
# docstyle-ignore"""# Full training (off-policy only, lmbda=0):```python examples/scripts/distillation.py \ --model_name_or_path Qwen/Qwen2.5-0.5B-Instruct \ --teacher_model_name_or_path Qwen/Qwen2.5-1.5B-Instruct \ --dataset_name trl-lib/chatbot_arena_completions \ --learning_rate 2e-5 \ --per_device_train_batch_size 4 \ --gradient_accumulation_steps 8 \ --lmbda 0.0 \ --output_dir distilled-model \ --num_train_epochs 1```
# Mixed on/off-policy (lmbda=0.5):```python examples/scripts/distillation.py \ --model_name_or_path Qwen/Qwen2.5-0.5B-Instruct \ --teacher_model_name_or_path Qwen/Qwen2.5-1.5B-Instruct \ --dataset_name trl-lib/chatbot_arena_completions \ --learning_rate 2e-5 \ --per_device_train_batch_size 4 \ --gradient_accumulation_steps 8 \ --lmbda 0.5 \ --beta 0.5 \ --output_dir distilled-model \ --num_train_epochs 1```
# LoRA:```python examples/scripts/distillation.py \ --model_name_or_path Qwen/Qwen2.5-0.5B-Instruct \ --teacher_model_name_or_path Qwen/Qwen2.5-1.5B-Instruct \ --dataset_name trl-lib/chatbot_arena_completions \ --learning_rate 2e-4 \ --per_device_train_batch_size 4 \ --gradient_accumulation_steps 8 \ --lmbda 0.0 \ --output_dir distilled-model \ --num_train_epochs 1 \ --use_peft \ --lora_r 64 \ --lora_alpha 16```"""
import argparseimport os
# Enable logging in a Hugging Face Spaceos.environ.setdefault("TRACKIO_SPACE_ID", "trl-trackio")
def main(script_args, training_args, model_args): from datasets import load_dataset from transformers import GenerationConfig
from trl import ( LogCompletionsCallback, get_kbit_device_map, get_peft_config, get_quantization_config, ) from trl.experimental.distillation import DistillationTrainer
################ # Model init kwargs ################ quantization_config = get_quantization_config(model_args) model_kwargs = dict( revision=model_args.model_revision, attn_implementation=model_args.attn_implementation, dtype=model_args.dtype, use_cache=False if training_args.gradient_checkpointing else True, device_map=get_kbit_device_map() if quantization_config is not None else None, quantization_config=quantization_config, ) training_args.model_init_kwargs = model_kwargs
teacher_model_kwargs = dict( revision=training_args.teacher_model_revision, attn_implementation=model_args.attn_implementation, dtype=model_args.dtype, use_cache=True, device_map=get_kbit_device_map() if quantization_config is not None else None, quantization_config=quantization_config, ) if training_args.teacher_model_init_kwargs is not None: teacher_model_kwargs.update(training_args.teacher_model_init_kwargs) training_args.teacher_model_init_kwargs = teacher_model_kwargs
################ # Dataset ################ dataset = load_dataset(script_args.dataset_name, name=script_args.dataset_config)
################ # Training ################ eval_dataset = None if training_args.eval_strategy != "no": if script_args.dataset_test_split in dataset: eval_dataset = dataset[script_args.dataset_test_split] elif "validation" in dataset: eval_dataset = dataset["validation"] elif "dev" in dataset: eval_dataset = dataset["dev"]
trainer = DistillationTrainer( model=model_args.model_name_or_path, teacher_model=training_args.teacher_model_name_or_path, args=training_args, train_dataset=dataset[script_args.dataset_train_split], eval_dataset=eval_dataset, peft_config=get_peft_config(model_args), )
if training_args.eval_strategy != "no": generation_config = GenerationConfig( max_new_tokens=training_args.max_completion_length, do_sample=True, temperature=training_args.temperature ) completions_callback = LogCompletionsCallback(trainer, generation_config, num_prompts=8) trainer.add_callback(completions_callback)
trainer.train()
# Save and push to Hub trainer.save_model(training_args.output_dir) if training_args.push_to_hub: trainer.push_to_hub(dataset_name=script_args.dataset_name)
def make_parser(subparsers: argparse._SubParsersAction | None = None, prog: str | None = None): from trl import ModelConfig, ScriptArguments, TrlParser from trl.experimental.distillation import DistillationConfig
dataclass_types = (ScriptArguments, DistillationConfig, ModelConfig) if subparsers is not None: parser = subparsers.add_parser( "distillation", help="Run the distillation training script", dataclass_types=dataclass_types ) else: parser = TrlParser(dataclass_types, prog=prog) return parser
if __name__ == "__main__": parser = make_parser() script_args, training_args, model_args = parser.parse_args_and_config(fail_with_unknown_args=False) main(script_args, training_args, model_args)1234567891011121314151617# Copyright 2020-2026 The HuggingFace Team. All rights reserved.## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License.
################################################################################################ This file has been moved to https://github.com/huggingface/trl/blob/main/trl/scripts/dpo.py ################################################################################################123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134# Copyright 2020-2026 The HuggingFace Team. All rights reserved.## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License.
# /// script# dependencies = [# "trl[peft]",# "Pillow>=9.4.0",# "torchvision",# "trackio",# "kernels",# ]# ///
"""Without dataset streaming:
```accelerate launch examples/scripts/dpo_vlm.py \ --dataset_name HuggingFaceH4/rlaif-v_formatted \ --model_name_or_path Qwen/Qwen2.5-VL-3B-Instruct \ --per_device_train_batch_size 2 \ --gradient_accumulation_steps 32 \ --dataset_num_proc 32 \ --output_dir dpo_qwen_2_5_rlaif-v \ --dtype bfloat16 \ --use_peft \ --lora_target_modules all-linear```
With dataset streaming:
```accelerate launch examples/scripts/dpo_vlm.py \ --dataset_name HuggingFaceH4/rlaif-v_formatted \ --dataset_streaming \ --model_name_or_path Qwen/Qwen2.5-VL-3B-Instruct \ --per_device_train_batch_size 2 \ --max_steps 100 \ --gradient_accumulation_steps 32 \ --dataset_num_proc 32 \ --output_dir dpo_qwen_2_5_rlaif-v \ --dtype bfloat16 \ --use_peft \ --lora_target_modules all-linear```"""
import torchfrom datasets import load_datasetfrom transformers import AutoModelForImageTextToText, AutoProcessor
from trl import ( DPOConfig, DPOTrainer, ModelConfig, ScriptArguments, TrlParser, get_kbit_device_map, get_peft_config, get_quantization_config,)
if __name__ == "__main__": parser = TrlParser((ScriptArguments, DPOConfig, ModelConfig)) script_args, training_args, model_args = parser.parse_args_and_config()
################ # Model & Processor ################ dtype = model_args.dtype if model_args.dtype in ["auto", None] else getattr(torch, model_args.dtype)
model_kwargs = dict( revision=model_args.model_revision, attn_implementation=model_args.attn_implementation, dtype=dtype, ) quantization_config = get_quantization_config(model_args) if quantization_config is not None: # Passing None would not be treated the same as omitting the argument, so we include it only when valid. model_kwargs["device_map"] = get_kbit_device_map() model_kwargs["quantization_config"] = quantization_config
model = AutoModelForImageTextToText.from_pretrained( model_args.model_name_or_path, **model_kwargs, ) peft_config = get_peft_config(model_args)
processor = AutoProcessor.from_pretrained(model_args.model_name_or_path, do_image_splitting=False)
if script_args.ignore_bias_buffers: # torch distributed hack model._ddp_params_and_buffers_to_ignore = [ name for name, buffer in model.named_buffers() if buffer.dtype == torch.bool ]
################ # Dataset ################ dataset = load_dataset( script_args.dataset_name, name=script_args.dataset_config, streaming=script_args.dataset_streaming, )
################ # Training ################ trainer = DPOTrainer( model, args=training_args, train_dataset=dataset[script_args.dataset_train_split], eval_dataset=dataset[script_args.dataset_test_split] if training_args.eval_strategy != "no" else None, peft_config=peft_config, )
trainer.train()
# Save and push to hub trainer.save_model(training_args.output_dir) if training_args.push_to_hub: trainer.push_to_hub(dataset_name=script_args.dataset_name)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139# Copyright 2020-2026 The HuggingFace Team. All rights reserved.## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License.
# /// script# dependencies = [# "trl[peft]",# "trackio",# "kernels",# ]# ///
"""# Full training:python examples/scripts/gkd.py \ --model_name_or_path Qwen/Qwen2-0.5B-Instruct \ --teacher_model_name_or_path Qwen/Qwen2-1.5B-Instruct \ --dataset_name trl-lib/chatbot_arena_completions \ --learning_rate 2e-5 \ --per_device_train_batch_size 4 \ --gradient_accumulation_steps 8 \ --output_dir gkd-model \ --num_train_epochs 1 \ --push_to_hub
# LoRA:python examples/scripts/gkd.py \ --model_name_or_path Qwen/Qwen2-0.5B-Instruct \ --teacher_model_name_or_path Qwen/Qwen2-1.5B-Instruct \ --dataset_name trl-lib/chatbot_arena_completions \ --learning_rate 2e-4 \ --per_device_train_batch_size 4 \ --gradient_accumulation_steps 8 \ --output_dir gkd-model \ --num_train_epochs 1 \ --push_to_hub \ --use_peft \ --lora_r 64 \ --lora_alpha 16"""
from datasets import load_datasetfrom transformers import AutoTokenizer, GenerationConfig
from trl import ( LogCompletionsCallback, ModelConfig, ScriptArguments, TrlParser, get_kbit_device_map, get_peft_config, get_quantization_config,)from trl.experimental.gkd import GKDConfig, GKDTrainer
if __name__ == "__main__": parser = TrlParser((ScriptArguments, GKDConfig, ModelConfig)) script_args, training_args, model_args = parser.parse_args_and_config()
################ # Model & Tokenizer ################ model_kwargs = dict( revision=model_args.model_revision, attn_implementation=model_args.attn_implementation, dtype=model_args.dtype, use_cache=False if training_args.gradient_checkpointing else True, ) quantization_config = get_quantization_config(model_args) if quantization_config is not None: # Passing None would not be treated the same as omitting the argument, so we include it only when valid. model_kwargs["device_map"] = get_kbit_device_map() model_kwargs["quantization_config"] = quantization_config
training_args.model_init_kwargs = model_kwargs
teacher_model_kwargs = dict( revision=model_args.model_revision, attn_implementation=model_args.attn_implementation, dtype=model_args.dtype, use_cache=True, ) if quantization_config is not None: # Passing None would not be treated the same as omitting the argument, so we include it only when valid. model_kwargs["device_map"] = get_kbit_device_map() model_kwargs["quantization_config"] = quantization_config
training_args.teacher_model_init_kwargs = teacher_model_kwargs
tokenizer = AutoTokenizer.from_pretrained( model_args.model_name_or_path, revision=model_args.model_revision, padding_side="left", ) if tokenizer.pad_token is None: tokenizer.pad_token = tokenizer.eos_token
################ # Dataset ################ dataset = load_dataset(script_args.dataset_name, name=script_args.dataset_config)
################ # Training ################ trainer = GKDTrainer( model=model_args.model_name_or_path, teacher_model=training_args.teacher_model_name_or_path, args=training_args, train_dataset=dataset[script_args.dataset_train_split], eval_dataset=dataset[script_args.dataset_test_split] if training_args.eval_strategy != "no" else None, processing_class=tokenizer, peft_config=get_peft_config(model_args), )
if training_args.eval_strategy != "no": generation_config = GenerationConfig( max_new_tokens=training_args.max_new_tokens, do_sample=True, temperature=training_args.temperature ) completions_callback = LogCompletionsCallback(trainer, generation_config, num_prompts=8) trainer.add_callback(completions_callback)
trainer.train()
# Save and push to hub trainer.save_model(training_args.output_dir) if training_args.push_to_hub: trainer.push_to_hub(dataset_name=script_args.dataset_name)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152# Copyright 2020-2026 The HuggingFace Team. All rights reserved.## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License.
# /// script# dependencies = [# "trl @ git+https://github.com/huggingface/trl.git",# "peft",# "trackio",# ]# ///
# docstyle-ignore"""# Full training:python examples/scripts/gold.py \ --model_name_or_path meta-llama/Llama-3.2-1B-Instruct \ --teacher_model_name_or_path Qwen/Qwen2-1.5B-Instruct \ --dataset_name trl-lib/chatbot_arena_completions \ --learning_rate 2e-5 \ --per_device_train_batch_size 4 \ --gradient_accumulation_steps 8 \ --output_dir gold-model \ --num_train_epochs 1 \ --push_to_hub
# LoRA:python examples/scripts/gold.py \ --model_name_or_path meta-llama/Llama-3.2-1B-Instruct \ --teacher_model_name_or_path Qwen/Qwen2-1.5B-Instruct \ --dataset_name trl-lib/chatbot_arena_completions \ --learning_rate 2e-4 \ --per_device_train_batch_size 4 \ --gradient_accumulation_steps 8 \ --output_dir gold-model \ --num_train_epochs 1 \ --push_to_hub \ --use_peft \ --lora_r 64 \ --lora_alpha 16"""
import logging
from datasets import load_datasetfrom transformers import AutoTokenizer, GenerationConfig
from trl import ( LogCompletionsCallback, ModelConfig, ScriptArguments, TrlParser, get_kbit_device_map, get_peft_config, get_quantization_config,)from trl.experimental.gold.gold_config import GOLDConfigfrom trl.experimental.gold.gold_trainer import GOLDTrainer
logger = logging.getLogger(__name__)
if __name__ == "__main__": parser = TrlParser((ScriptArguments, GOLDConfig, ModelConfig)) script_args, training_args, model_args = parser.parse_args_and_config()
################ # Model & Tokenizer ################ quantization_config = get_quantization_config(model_args) model_kwargs = dict( revision=model_args.model_revision, attn_implementation=model_args.attn_implementation, dtype=model_args.dtype, use_cache=False if training_args.gradient_checkpointing else True, device_map=get_kbit_device_map() if quantization_config is not None else None, quantization_config=quantization_config, ) training_args.model_init_kwargs = model_kwargs
if training_args.teacher_tokenizer_name_or_path is None and training_args.use_uld_loss: training_args.teacher_tokenizer_name_or_path = training_args.teacher_model_name_or_path teacher_model_kwargs = dict( revision=training_args.teacher_model_revision, attn_implementation=model_args.attn_implementation, dtype=model_args.dtype, use_cache=True, device_map=get_kbit_device_map() if quantization_config is not None else None, quantization_config=quantization_config, ) if training_args.teacher_model_init_kwargs is not None: teacher_model_kwargs.update(training_args.teacher_model_init_kwargs) training_args.teacher_model_init_kwargs = teacher_model_kwargs
tokenizer = AutoTokenizer.from_pretrained( model_args.model_name_or_path, revision=model_args.model_revision, ) if tokenizer.pad_token is None: tokenizer.pad_token = tokenizer.eos_token
################ # Dataset ################ dataset = load_dataset(script_args.dataset_name, name=script_args.dataset_config)
################ # Training ################ eval_dataset = None if training_args.eval_strategy != "no": if script_args.dataset_test_split in dataset: eval_dataset = dataset[script_args.dataset_test_split] elif "validation" in dataset: eval_dataset = dataset["validation"] elif "dev" in dataset: eval_dataset = dataset["dev"]
trainer = GOLDTrainer( model=model_args.model_name_or_path, teacher_model=training_args.teacher_model_name_or_path, args=training_args, train_dataset=dataset[script_args.dataset_train_split], eval_dataset=eval_dataset, processing_class=tokenizer, peft_config=get_peft_config(model_args), )
if training_args.eval_strategy != "no": generation_config = GenerationConfig( max_new_tokens=training_args.max_completion_length, do_sample=True, temperature=training_args.temperature ) completions_callback = LogCompletionsCallback(trainer, generation_config, num_prompts=8) trainer.add_callback(completions_callback)
trainer.train()
# Save and push to hub trainer.save_model(training_args.output_dir) if training_args.push_to_hub: trainer.push_to_hub(dataset_name=script_args.dataset_name)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161# Copyright 2020-2026 The HuggingFace Team. All rights reserved.## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License.
# /// script# dependencies = [# "trl[peft]",# ]# ///
import random
from datasets import Datasetfrom peft import LoraConfig
from trl import GRPOConfig, GRPOTrainer
PROMPT = "Play 2048 on a 4x4 board. Use the tool `move` with one of: up, down, left, right. Maximize the score."
class Game2048Env: def reset(self, **kwargs) -> str: self.board = [[0] * 4 for _ in range(4)] self.score = 0.0 self.done = False self._spawn() self._spawn() return f"score={self.score}\n{self._render()}\ndone={self.done}"
def move(self, direction: str) -> str: """ Play one move in 2048.
Args: direction: One of "up", "down", "left", "right".
Returns: Environment feedback after the move. """ if self.done: raise ValueError("Game over.") moved, gained = self._apply_move(direction.strip().lower()) if moved: self.score += gained self._spawn() self.done = not self._can_move() return f"score={self.score}\n{self._render()}\ndone={self.done}"
def _spawn(self) -> None: empty = [(r, c) for r in range(4) for c in range(4) if self.board[r][c] == 0] if not empty: return r, c = random.choice(empty) self.board[r][c] = 4 if random.random() < 0.1 else 2
@staticmethod def _merge_line(line: list[int]) -> tuple[list[int], int]: vals = [x for x in line if x] out = [] gained = 0 i = 0 while i < len(vals): if i + 1 < len(vals) and vals[i] == vals[i + 1]: v = vals[i] * 2 out.append(v) gained += v i += 2 else: out.append(vals[i]) i += 1 out += [0] * (4 - len(out)) return out, gained
def _apply_move(self, direction: str) -> tuple[bool, int]: if direction not in {"up", "down", "left", "right"}: return False, 0
before = [row[:] for row in self.board] gained_total = 0
if direction in {"left", "right"}: for r in range(4): row = self.board[r][:] if direction == "right": row.reverse() merged, gained = self._merge_line(row) if direction == "right": merged.reverse() self.board[r] = merged gained_total += gained else: for c in range(4): col = [self.board[r][c] for r in range(4)] if direction == "down": col.reverse() merged, gained = self._merge_line(col) if direction == "down": merged.reverse() for r in range(4): self.board[r][c] = merged[r] gained_total += gained
moved = self.board != before return moved, gained_total
def _can_move(self) -> bool: if any(0 in row for row in self.board): return True for r in range(4): for c in range(4): if r + 1 < 4 and self.board[r][c] == self.board[r + 1][c]: return True if c + 1 < 4 and self.board[r][c] == self.board[r][c + 1]: return True return False
def _render(self) -> str: return "\n".join(" ".join(f"{v:3d}" for v in row) for row in self.board)
def reward_score(environments, **kwargs): return [env.score for env in environments]
def main() -> None: dataset = Dataset.from_dict({"prompt": [[{"role": "user", "content": PROMPT}] for _ in range(1000)]})
trainer = GRPOTrainer( model="Qwen/Qwen3-4B", train_dataset=dataset, reward_funcs=reward_score, args=GRPOConfig( chat_template_kwargs={"enable_thinking": False}, logging_steps=1, log_completions=True, num_completions_to_print=2, report_to="trackio", trackio_space_id="trl-2048", max_completion_length=2048, per_device_train_batch_size=4, gradient_accumulation_steps=2, ), environment_factory=Game2048Env, peft_config=LoraConfig(), ) trainer.train()
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320# Copyright 2020-2026 The HuggingFace Team. All rights reserved.## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License.
# /// script# dependencies = [# "trl[peft]",# "trackio",# "kernels",# ]# ///
"""# Full training```python examples/scripts/grpo_agent.py \ --model_name_or_path Qwen/Qwen3-1.7B \ --output_dir grpo_biogrid_qwen_3g-1.7b \ --push_to_hub True \ --use_vllm True \ --vllm_mode colocate \ --max_completion_length 1024 \ --report_to trackio \ --log_completions True \ --max_steps 400```"""
import reimport signalimport sqlite3import textwrapfrom contextlib import contextmanager
from datasets import load_dataset
from trl import GRPOConfig, GRPOTrainer, ModelConfig, ScriptArguments, TrlParser
def query_reward(completions, answer, **kwargs): """ Reward query strategy: - Penalize more than 2 queries - Penalize generic queries (LIMIT 1 / PRAGMA) - Reward usage of WHERE - Reward evidence supporting the final answer """ rewards = []
for completion, ans in zip(completions, answer, strict=False): reward = 0.0 sql_queries = [] tool_results = []
# collect all SQL queries and tool results for turn in completion: if turn.get("tool_calls"): for call in turn["tool_calls"]: sql = call["function"]["arguments"].get("sql_command", "").lower() sql_queries.append(sql) if turn.get("role") == "tool" and turn.get("content"): tool_results.append(turn["content"])
# --- penalize too many queries --- if len(sql_queries) > 3: reward -= 1.5
# --- check query quality --- where_count = 0 for q in sql_queries: if "limit 1" in q: reward -= 1.0 if " where " not in q: reward -= 0.5 else: where_count += 1 reward += min(where_count, 3) * 0.4 # small bonus for WHERE usage
# --- evidence check: do queries support the answer? --- combined_results = [] error_detected = False
for res in tool_results: if isinstance(res, dict) and "error" in res: error_detected = True elif isinstance(res, list): combined_results.extend(res)
# if error detected, penalize heavily if error_detected: reward -= 2.0 elif len(sql_queries) == 0: reward -= 1.5 else: has_hits = len(combined_results) > 0 correct_answer = ans.lower() if (has_hits and correct_answer == "yes") or (not has_hits and correct_answer == "no"): reward += 2.0 else: reward -= 1.5
rewards.append(reward)
return rewards
def correctness_reward(completions, answer, **kwargs): """ Reward Yes/No correctness. Model must provide final answer enclosed in stars — *yes* or *no*. Does not reward informal yes/no buried in text. """ rewards = [] for completion, ans in zip(completions, answer, strict=False): raw = completion[-1]["content"].lower()
# detect form *yes* or *no* match = re.search(r"\*(yes|no)\*", raw) guess = match.group(1) if match else None
reward = 0.0
if guess is None: reward -= 0.5 # invalid format elif guess == ans.lower(): reward += 0.6 # correct under required format else: reward -= 1.0 # wrong answer
rewards.append(reward)
return rewards
def structure_reward(completions, **kwargs): """ Reward proper assistant structure. Encourages a logical sequence: tool call + response + optional extra content. """ rewards = []
for completion in completions: has_call = False has_response = False has_other = False
for turn in completion: role = turn.get("role") if role == "assistant" and turn.get("tool_calls"): has_call = True elif role == "tool": has_response = True else: content = turn.get("content") if content and content.strip() not in ["", "<think>"]: has_other = True
# Reward sequences if has_call and has_response: if has_other: reward = 0.1 else: reward = 0.05 # still positive even without extra text elif has_call and not has_response: reward = -0.15 else: reward = 0.0 # neutral if no call
rewards.append(reward)
return rewards
# ------------------------# Database tool function# ------------------------class TimeoutError(Exception): """Raised when a function call times out."""
pass
@contextmanagerdef timeout(seconds): """Context manager that raises TimeoutError if execution exceeds time limit."""
def timeout_handler(signum, frame): raise TimeoutError(f"Operation timed out after {seconds} seconds")
signal.signal(signal.SIGALRM, timeout_handler) signal.alarm(seconds) try: yield finally: signal.alarm(0)
def query_biogrid(sql_command: str) -> list[tuple]: """ Execute a read-only SQL command on the BioGRID database.
BioGRID is a curated biological database that compiles protein, genetic, and chemical interactions from multiple organisms. It provides researchers with experimentally verified interaction data to support studies in systems biology and functional genomics.
Args: sql_command: The SQL command to execute.
Returns: A list of tuples containing the query results. """ with timeout(5): conn = sqlite3.connect("file:biogrid.db?mode=ro", uri=True) cursor = conn.cursor() try: cursor.execute(sql_command) results = cursor.fetchall() finally: conn.close() return results
# ------------------------# Dataset formatting# ------------------------def format_example(example): question = example["question"] preamble = textwrap.dedent("""\ You have access to the BioGRID SQLite database. Use SQL queries to retrieve only the information needed to answer the question.
Genes may appear in the database in columns `Alt_IDs_Interactor_A` `Alt_IDs_Interactor_B`, `Aliases_Interactor_A` and `Aliases_Interactor_B`, and each entry can contain multiple gene names or synonyms separated by '|', for example: 'entrez gene/locuslink:JNKK(gene name synonym)|entrez gene/locuslink:MAPKK4(gene name synonym)|...' So a gene like 'JNKK' or 'MAPKK4' may appear inside one of these strings.
If the database schema is unclear or you are unsure about column names: - First inspect the schema with `PRAGMA table_info(interactions);` - Or preview a few rows with `SELECT * FROM interactions LIMIT 1;`
Otherwise, directly query the required data.
Final answer must be enclosed in stars, e.g. *Yes* or *No*. Facts: - The NCBI Taxonomy identifier for humans is taxid:9606. """) content = f"{preamble}\nQuestion: {question}" prompt = [{"role": "user", "content": content}] return {"prompt": prompt}
# ------------------------# Main# ------------------------if __name__ == "__main__": parser = TrlParser((ScriptArguments, GRPOConfig, ModelConfig)) script_args, training_args, model_args = parser.parse_args_and_config()
# ------------------------ # Create DB # ------------------------ print("Creating biogrid.db...") # Load dataset biogrid_dataset = load_dataset("qgallouedec/biogrid", split="train") df = biogrid_dataset.to_pandas()
# Normalize column names: remove spaces, replace with underscores df.columns = [c.replace(" ", "_") for c in df.columns] conn = sqlite3.connect("biogrid.db") try: df.to_sql("interactions", conn, if_exists="replace", index=False) print(f"biogrid.db created. Rows stored: {len(df)}") finally: conn.close()
# ------------------------ # Load and format dataset # ------------------------ dataset = load_dataset("qgallouedec/biogrid_qa", split="train") dataset = dataset.filter( lambda example: example["question"].startswith("Does the gene ") ) # keep only simple questions for example dataset = dataset.map(format_example, remove_columns=["question"])
train_dataset = dataset eval_dataset = None # No eval by default, can be added if needed
training_args.chat_template_kwargs = {"enable_thinking": False}
# ------------------------ # Initialize trainer # ------------------------ trainer = GRPOTrainer( model=model_args.model_name_or_path, train_dataset=train_dataset, eval_dataset=eval_dataset, tools=[query_biogrid], reward_funcs=[correctness_reward, structure_reward, query_reward], args=training_args, )
# ------------------------ # Train # ------------------------ trainer.train()
# ------------------------ # Save and push # ------------------------ trainer.save_model(training_args.output_dir) if training_args.push_to_hub: trainer.push_to_hub(dataset_name=script_args.dataset_name)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133# Copyright 2020-2026 The HuggingFace Team. All rights reserved.## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License.
# /// script# dependencies = [# "trl[peft]",# "kernels",# ]# ///
"""GRPO training on GSM8K using transformers' continuous batching engine instead of the defaultgenerate(). Continuous batching removes finished sequences from the batch immediately rather thanwaiting for the slowest one, which yields faster generation and lower VRAM than default generate()for tasks with variable completion lengths (N≥32).
The key config parameter is `max_memory_percent` in `transformers_continuous_batching_config`,which caps the paged KV cache as a fraction of free VRAM. TRL defaults to 0.5; tune it down to0.3-0.4 for large generation batches to leave room for the training backward pass.
python examples/scripts/grpo_continuous_batching.py \ --model_name_or_path Qwen/Qwen3-1.7B \ --output_dir grpo-gsm8k-continuous-batching \ --num_generations 32 \ --max_completion_length 1024 \ --use_peft \ --log_completions
accelerate launch --config_file examples/accelerate_configs/deepspeed_zero3.yaml \ examples/scripts/grpo_continuous_batching.py \ --model_name_or_path Qwen/Qwen3-1.7B \ --output_dir grpo-gsm8k-continuous-batching \ --num_generations 32 \ --max_completion_length 1024 \ --use_peft \ --log_completions"""
import loggingimport re
import torchfrom datasets import load_dataset
from trl import GRPOConfig, GRPOTrainer, ModelConfig, ScriptArguments, TrlParser, get_peft_config
logging.getLogger("ContinuousBatchingLogger").setLevel(logging.ERROR)
SYSTEM_PROMPT = ( "You are a helpful math tutor. Solve the problem step by step, then provide the final " "numeric answer on the last line in the format: #### <number>")
def extract_answer(text: str) -> str | None: match = re.search(r"####\s*([\d,]+)", text) return match.group(1).replace(",", "") if match else None
def correctness_reward(completions, reference_answer, **kwargs): rewards = [] for completion, ref in zip(completions, reference_answer, strict=False): predicted = extract_answer(completion if isinstance(completion, str) else completion[-1]["content"]) rewards.append(1.0 if predicted is not None and predicted == ref else 0.0) return rewards
if __name__ == "__main__": parser = TrlParser((ScriptArguments, GRPOConfig, ModelConfig)) script_args, training_args, model_args = parser.parse_args_and_config()
################ # Model ################ dtype = model_args.dtype if model_args.dtype in ["auto", None] else getattr(torch, model_args.dtype) training_args.model_init_kwargs = dict( revision=model_args.model_revision, attn_implementation=model_args.attn_implementation, dtype=dtype, )
################ # Dataset ################ dataset = load_dataset( script_args.dataset_name or "openai/gsm8k", script_args.dataset_config or "main", split=script_args.dataset_train_split, )
def make_conversation(example): return { "prompt": [ {"role": "system", "content": SYSTEM_PROMPT}, {"role": "user", "content": example["question"]}, ], "reference_answer": example["answer"].split("####")[-1].strip().replace(",", ""), }
dataset = dataset.map(make_conversation, remove_columns=dataset.column_names)
################ # Training ################ training_args.use_transformers_continuous_batching = True if training_args.transformers_continuous_batching_config is None: training_args.transformers_continuous_batching_config = {"use_cuda_graph": False}
trainer = GRPOTrainer( model=model_args.model_name_or_path, reward_funcs=correctness_reward, args=training_args, train_dataset=dataset, peft_config=get_peft_config(model_args), )
trainer.train()
trainer.save_model(training_args.output_dir) if training_args.push_to_hub: trainer.push_to_hub(dataset_name=script_args.dataset_name)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157# Copyright 2020-2026 The HuggingFace Team. All rights reserved.## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License.
# /// script# dependencies = [# "trl[peft]",# "Pillow",# "math-verify",# "latex2sympy2_extended",# "torchvision",# "trackio",# "kernels",# ]# ///
"""pip install math_verify
# For Qwen/Qwen2.5-VL-3B-Instructaccelerate launch \ --config_file examples/accelerate_configs/deepspeed_zero3.yaml \ examples/scripts/grpo_vlm.py \ --model_name_or_path Qwen/Qwen2.5-VL-3B-Instruct \ --output_dir grpo-Qwen2.5-VL-3B-Instruct \ --learning_rate 1e-5 \ --dtype bfloat16 \ --max_completion_length 1024 \ --use_vllm \ --vllm_mode colocate \ --use_peft \ --lora_target_modules "q_proj", "v_proj" \ --log_completions
# For HuggingFaceTB/SmolVLM2-2.2B-Instructpip install num2words==0.5.14
accelerate launch \ --config_file examples/accelerate_configs/deepspeed_zero3.yaml \ examples/scripts/grpo_vlm.py \ --model_name_or_path HuggingFaceTB/SmolVLM2-2.2B-Instruct \ --output_dir grpo-SmolVLM2-2.2B-Instruct \ --learning_rate 1e-5 \ --dtype bfloat16 \ --max_completion_length 1024 \ --use_peft \ --lora_target_modules "q_proj", "v_proj" \ --log_completions \ --per_device_train_batch_size 1 \ --gradient_accumulation_steps 2 \ --num_generations 2
"""
import torchfrom datasets import load_dataset
from trl import ( GRPOConfig, GRPOTrainer, ModelConfig, ScriptArguments, TrlParser, get_kbit_device_map, get_peft_config, get_quantization_config,)from trl.rewards import accuracy_reward, think_format_reward
if __name__ == "__main__": parser = TrlParser((ScriptArguments, GRPOConfig, ModelConfig)) script_args, training_args, model_args = parser.parse_args_and_config() ################ # Model ################ dtype = model_args.dtype if model_args.dtype in ["auto", None] else getattr(torch, model_args.dtype) training_args.model_init_kwargs = dict( revision=model_args.model_revision, attn_implementation=model_args.attn_implementation, dtype=dtype, ) quantization_config = get_quantization_config(model_args) if quantization_config is not None: # Passing None would not be treated the same as omitting the argument, so we include it only when valid. training_args.model_init_kwargs["device_map"] = get_kbit_device_map() training_args.model_init_kwargs["quantization_config"] = quantization_config
################ # Dataset ################ dataset = load_dataset("lmms-lab/multimodal-open-r1-8k-verified", split="train") dataset = dataset.train_test_split(test_size=100, seed=42)
SYSTEM_PROMPT = ( "A conversation between user and assistant. The user asks a question, and the assistant solves it. The " "assistant first thinks about the reasoning process in the mind and then provides the user with the answer. " "The reasoning process and answer are enclosed within <think></think> tags, i.e., <think>\nThis is my " "reasoning.\n</think>\nThis is my answer." )
def make_conversation(example): prompt = [ {"role": "system", "content": SYSTEM_PROMPT}, {"role": "user", "content": example["problem"]}, ] return {"prompt": prompt}
dataset = dataset.map(make_conversation)
# Filter have big images def filter_big_images(example): image = example["image"] return image.size[0] < 512 and image.size[1] < 512
dataset = dataset.filter(filter_big_images)
def convert_to_rgb(example): image = example["image"] if image.mode != "RGB": image = image.convert("RGB") example["image"] = image return example
dataset = dataset.map(convert_to_rgb)
train_dataset = dataset["train"] eval_dataset = dataset["test"] if training_args.eval_strategy != "no" else None
################ # Training ################ trainer = GRPOTrainer( model=model_args.model_name_or_path, args=training_args, reward_funcs=[think_format_reward, accuracy_reward], train_dataset=train_dataset, eval_dataset=eval_dataset, peft_config=get_peft_config(model_args), )
trainer.train()
# Save and push to hub trainer.save_model(training_args.output_dir) if training_args.push_to_hub: trainer.push_to_hub(dataset_name=script_args.dataset_name)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131# Copyright 2020-2026 The HuggingFace Team. All rights reserved.## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License.
# /// script# dependencies = [# "trl[peft]",# "math-verify",# "latex2sympy2_extended",# "trackio",# "kernels",# ]# ///
"""pip install math_verify
# For Qwen/Qwen3-0.6Bpip install num2words==0.5.14
accelerate launch \ --config_file examples/accelerate_configs/deepspeed_zero3.yaml \ examples/scripts/gspo.py \ --model_name_or_path Qwen/Qwen3-0.6B \ --output_dir gspo-Qwen3-0.6B \ --learning_rate 1e-5 \ --dtype bfloat16 \ --max_completion_length 1024 \ --use_peft \ --lora_target_modules "q_proj", "v_proj" \ --log_completions \ --per_device_train_batch_size 8 \ --num_generations 8 \ --importance_sampling_level sequence \ --epsilon 3e-4 \ --epsilon_high 4e-4 \ --beta 0.0 \ --loss_type grpo \ --gradient_accumulation_steps 2 \ --steps_per_generation 8
"""
import torchfrom datasets import load_dataset
from trl import ( GRPOConfig, GRPOTrainer, ModelConfig, ScriptArguments, TrlParser, get_kbit_device_map, get_peft_config, get_quantization_config,)from trl.rewards import accuracy_reward, think_format_reward
if __name__ == "__main__": parser = TrlParser((ScriptArguments, GRPOConfig, ModelConfig)) script_args, training_args, model_args = parser.parse_args_and_config() ################ # Model & Processor ################ dtype = model_args.dtype if model_args.dtype in ["auto", None] else getattr(torch, model_args.dtype) training_args.model_init_kwargs = dict( revision=model_args.model_revision, attn_implementation=model_args.attn_implementation, dtype=dtype, ) quantization_config = get_quantization_config(model_args) if quantization_config is not None: # Passing None would not be treated the same as omitting the argument, so we include it only when valid. training_args.model_init_kwargs["device_map"] = get_kbit_device_map() training_args.model_init_kwargs["quantization_config"] = quantization_config
################ # Dataset ################ train_dataset, eval_dataset = load_dataset("AI-MO/NuminaMath-TIR", split=["train[:5%]", "test[:5%]"])
SYSTEM_PROMPT = ( "A conversation between user and assistant. The user asks a question, and the assistant solves it. The " "assistant first thinks about the reasoning process in the mind and then provides the user with the answer. " "The reasoning process and answer are enclosed within <think></think> tags, i.e., <think>\nThis is my " "reasoning.\n</think>\nThis is my answer." )
def make_conversation(example): return { "prompt": [ {"role": "system", "content": SYSTEM_PROMPT}, {"role": "user", "content": example["problem"]}, ], }
train_dataset = train_dataset.map(make_conversation) eval_dataset = eval_dataset.map(make_conversation)
train_dataset = train_dataset.remove_columns(["messages", "problem"]) eval_dataset = eval_dataset.remove_columns(["messages", "problem"])
################ # Training ################ trainer = GRPOTrainer( model=model_args.model_name_or_path, args=training_args, reward_funcs=[think_format_reward, accuracy_reward], train_dataset=train_dataset, eval_dataset=eval_dataset, peft_config=get_peft_config(model_args), )
trainer.train()
# Save and push to hub trainer.save_model(training_args.output_dir) if training_args.push_to_hub: trainer.push_to_hub(dataset_name=script_args.dataset_name)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146# Copyright 2020-2026 The HuggingFace Team. All rights reserved.## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License.
# /// script# dependencies = [# "trl[peft]",# "Pillow",# "math-verify",# "latex2sympy2_extended",# "torchvision",# "trackio",# "kernels",# ]# ///
"""pip install math_verify
# For Qwen/Qwen2.5-VL-3B-Instructaccelerate launch \ --config_file examples/accelerate_configs/deepspeed_zero3.yaml \ examples/scripts/gspo_vlm.py \ --model_name_or_path Qwen/Qwen2.5-VL-3B-Instruct \ --output_dir gspo-Qwen2.5-VL-3B-Instruct \ --learning_rate 1e-5 \ --dtype bfloat16 \ --max_completion_length 1024 \ --use_peft \ --lora_target_modules "q_proj", "v_proj" \ --log_completions \ --per_device_train_batch_size 8 \ --num_generations 8 \ --importance_sampling_level sequence \ --epsilon 3e-4 \ --epsilon_high 4e-4 \ --beta 0.0 \ --loss_type grpo \ --gradient_accumulation_steps 2 \ --steps_per_generation 8
"""
import torchfrom datasets import load_dataset
from trl import ( GRPOConfig, GRPOTrainer, ModelConfig, ScriptArguments, TrlParser, get_kbit_device_map, get_peft_config, get_quantization_config,)from trl.rewards import accuracy_reward, think_format_reward
if __name__ == "__main__": parser = TrlParser((ScriptArguments, GRPOConfig, ModelConfig)) script_args, training_args, model_args = parser.parse_args_and_config() ################ # Model ################ dtype = model_args.dtype if model_args.dtype in ["auto", None] else getattr(torch, model_args.dtype) training_args.model_init_kwargs = dict( revision=model_args.model_revision, attn_implementation=model_args.attn_implementation, dtype=dtype, ) quantization_config = get_quantization_config(model_args) if quantization_config is not None: # Passing None would not be treated the same as omitting the argument, so we include it only when valid. training_args.model_init_kwargs["device_map"] = get_kbit_device_map() training_args.model_init_kwargs["quantization_config"] = quantization_config
################ # Dataset ################ dataset = load_dataset("lmms-lab/multimodal-open-r1-8k-verified", split="train") dataset = dataset.train_test_split(test_size=100, seed=42)
SYSTEM_PROMPT = ( "A conversation between user and assistant. The user asks a question, and the assistant solves it. The " "assistant first thinks about the reasoning process in the mind and then provides the user with the answer. " "The reasoning process and answer are enclosed within <think></think> tags, i.e., <think>\nThis is my " "reasoning.\n</think>\nThis is my answer." )
def make_conversation(example): prompt = [ {"role": "system", "content": SYSTEM_PROMPT}, {"role": "user", "content": example["problem"]}, ] return {"prompt": prompt}
dataset = dataset.map(make_conversation)
# Filter have big images def filter_big_images(example): image = example["image"] return image.size[0] < 512 and image.size[1] < 512
dataset = dataset.filter(filter_big_images)
def convert_to_rgb(example): image = example["image"] if image.mode != "RGB": image = image.convert("RGB") example["image"] = image return example
dataset = dataset.map(convert_to_rgb)
train_dataset = dataset["train"] eval_dataset = dataset["test"] if training_args.eval_strategy != "no" else None
################ # Training ################ trainer = GRPOTrainer( model=model_args.model_name_or_path, args=training_args, reward_funcs=[think_format_reward, accuracy_reward], train_dataset=train_dataset, eval_dataset=eval_dataset, peft_config=get_peft_config(model_args), )
trainer.train()
# Save and push to hub trainer.save_model(training_args.output_dir) if training_args.push_to_hub: trainer.push_to_hub(dataset_name=script_args.dataset_name)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131# Copyright 2020-2026 The HuggingFace Team. All rights reserved.## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License.
# /// script# dependencies = ["trl[vllm,harbor]", "harbor[e2b]"] # harbor[e2b]: the --env e2b backend (swap per --env)# ///
"""GRPO training against a Harbor task suite.
One ``HarborSpec`` fans out into TRL's three slots — ``.train_dataset`` / ``.environment_factory`` /``.reward_funcs``. The base agent (harness) is selected with ``--agent``: the built-in ``"bash"``, oran import/file path to a custom ``HarborEnv`` subclass. Harbor runs in-process, so install with``trl[harbor]`` (Python >= 3.12) plus the chosen sandbox backend's extra (``pip install "harbor[e2b]"``for the recommended ``--env e2b``; the ``docker`` backend just needs a reachable Docker daemon).
Usage (server vLLM, single-node 2+2 GPU split):
```sh# Terminal 1 — vLLMCUDA_VISIBLE_DEVICES=2,3 trl vllm-serve --model Qwen/Qwen3-4B --tensor-parallel-size 2 --port 8000
# Terminal 2 — trainingCUDA_VISIBLE_DEVICES=0,1 accelerate launch \ --config_file examples/accelerate_configs/deepspeed_zero2.yaml --num_processes 2 \ examples/scripts/harbor/data_agent.py \ --vllm-mode server --vllm-server-base-url http://localhost:8000 --env e2b```"""
import argparse
from trl import GRPOConfig, GRPOTrainerfrom trl.experimental.harbor import HarborSpec
def parse_args() -> argparse.Namespace: parser = argparse.ArgumentParser(description="GRPO training against a Harbor task suite.")
parser.add_argument("--model", type=str, default="Qwen/Qwen3-4B") parser.add_argument( "--dataset", type=str, default="AdithyaSK/data_agent_rl_environment_train", help="HF dataset repo id with a Harbor task tree, or a local path containing a tasks/ subtree.", ) parser.add_argument( "--agent", type=str, default="bash", help="Base agent/harness: built-in name ('bash'), import path 'pkg.mod:Class', or file 'path.py:Class'.", ) parser.add_argument( "--env", dest="environment_type", type=str, default="docker", help="Harbor sandbox backend (docker, e2b, daytona, gke, modal, runloop, ...).", ) parser.add_argument("--num-tasks", type=int, default=64)
parser.add_argument("--learning-rate", type=float, default=1e-6) parser.add_argument("--per-device-train-batch-size", type=int, default=8) parser.add_argument("--num-generations", type=int, default=8) parser.add_argument("--max-completion-length", type=int, default=2048) parser.add_argument("--max-steps", type=int, default=50) parser.add_argument("--max-tool-calling-iterations", type=int, default=25)
parser.add_argument("--vllm-mode", choices=("colocate", "server"), default="colocate") parser.add_argument("--vllm-server-base-url", type=str, default="http://localhost:8000") parser.add_argument("--vllm-gpu-memory-utilization", type=float, default=0.3)
parser.add_argument("--output-dir", type=str, default=None) parser.add_argument("--report-to", type=str, default="none")
return parser.parse_args()
def main() -> None: args = parse_args()
# One spec object — fans out into TRL's three slots. spec = HarborSpec( args.dataset, agent=args.agent, environment_type=args.environment_type, num_tasks=args.num_tasks, )
config_kwargs: dict = dict( learning_rate=args.learning_rate, per_device_train_batch_size=args.per_device_train_batch_size, num_generations=args.num_generations, max_completion_length=args.max_completion_length, max_steps=args.max_steps, max_tool_calling_iterations=args.max_tool_calling_iterations, chat_template_kwargs={"enable_thinking": False}, log_completions=True, use_vllm=True, vllm_mode=args.vllm_mode, report_to=[s.strip() for s in args.report_to.split(",") if s.strip() and s.strip() != "none"] or "none", ) if args.output_dir: config_kwargs["output_dir"] = args.output_dir if args.vllm_mode == "colocate": config_kwargs["vllm_gpu_memory_utilization"] = args.vllm_gpu_memory_utilization else: config_kwargs["vllm_server_base_url"] = args.vllm_server_base_url
trainer = GRPOTrainer( model=args.model, args=GRPOConfig(**config_kwargs), train_dataset=spec.train_dataset, environment_factory=spec.environment_factory, reward_funcs=spec.reward_funcs, ) trainer.train()
if __name__ == "__main__": main()1234567891011121314151617181920# Copyright 2020-2026 The HuggingFace Team. All rights reserved.## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License.
from .bash import BashEnvfrom .jupyter import JupyterEnvfrom .terminal_notes import TerminalNotesEnv
__all__ = ["BashEnv", "JupyterEnv", "TerminalNotesEnv"]1234567891011121314151617181920# `bash` harness
The minimal harness: a single shell tool. This is the **built-in** [`HarborBashEnv`](../../../../../trl/experimental/harbor/_env.py) (`trl.experimental.harbor.HarborBashEnv`); this folder just documents it and re-exports it as `BashEnv`.
## Tools
| Tool | Signature | What it does ||---|---|---|| `bash` | `bash(command: str) -> str` | Run a shell command in the sandbox; returns combined stdout+stderr (truncated to 8k). Non-stateful between calls. |
## Submission
No submit tool — write the answer to `/workdir/answer.txt`, e.g. `echo -n "<value>" > /workdir/answer.txt`. The task's verifier reads that file.
## Use it
```pythonfrom trl.experimental.harbor import HarborSpecspec = HarborSpec(dataset, agent="bash") # built-in name```123456789101112131415161718# Copyright 2020-2026 The HuggingFace Team. All rights reserved.## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License.
from trl.experimental.harbor import HarborBashEnv as BashEnv # the built-in bash harness
__all__ = ["BashEnv"]12345678910111213141516171819202122232425262728293031# `jupyter` harness
A **stateful Python kernel** harness. Variables, imports, and side-effects persist across cells, so themodel builds up state like a notebook. Implemented by `JupyterEnv` in [`env.py`](env.py).
## How it works
On `reset`, the harness (`_setup`) uploads two helpers into the sandbox and starts a tiny kernel server:
- [`kernel_server.py`](kernel_server.py) — a local HTTP server (`127.0.0.1:8765`) holding one persistent Python kernel.- [`run_cell.py`](run_cell.py) — sends a base64-encoded cell to the kernel server and prints its JSON result.
Each `add_and_execute_code_cell` call runs `python3 /opt/run_cell.py` against that kernel.
## Tools
| Tool | Signature | What it does ||---|---|---|| `add_and_execute_code_cell` | `add_and_execute_code_cell(code: str) -> str` | Execute Python in the **stateful** kernel; state persists across calls. Use for all computation. || `execute_shell_command` | `execute_shell_command(command: str) -> str` | Run a shell command (pip install, ls, …). **Not** stateful with the Python kernel. |
## Submission
Write the answer to `/workdir/answer.txt` — e.g. `add_and_execute_code_cell(code="open('/workdir/answer.txt','w').write(str(ans))")`.
## Use it
```pythonfrom trl.experimental.harbor import HarborSpecspec = HarborSpec(dataset, agent="examples/scripts/harbor/harnesses/jupyter/env.py:JupyterEnv")```123456789101112131415161718# Copyright 2020-2026 The HuggingFace Team. All rights reserved.## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License.
from .env import JupyterEnv
__all__ = ["JupyterEnv"]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104# Copyright 2020-2026 The HuggingFace Team. All rights reserved.## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License.
"""Jupyter-style base agent — a stateful-kernel Harbor harness.
A custom [`~trl.experimental.harbor.HarborEnv`] subclass exposing a stateful Python kernel(variables/imports persist across cells) plus a shell tool. Point a trainer at it with``HarborSpec(dataset, agent="examples/scripts/harbor/harnesses/jupyter/env.py:JupyterEnv")``.
The kernel is a tiny HTTP server (`kernel_server.py`, uploaded to /opt/ and started in `_setup`); eachcell runs via `python3 /opt/run_cell.py` (see `run_cell.py`). Submission is by writing``/workdir/answer.txt`` (same verifier as the bash harness)."""
import asyncioimport base64import jsonimport shlexfrom pathlib import Path
from trl.experimental.harbor import HarborEnv
_HERE = Path(__file__).parent
_JUPYTER_PROMPT_SUFFIX = ( "\n\nYou are a data-analysis agent with a **stateful Python kernel**: variables, imports, and " "side-effects persist across `add_and_execute_code_cell` calls. Dataset files are in " "/home/user/input/. Use `execute_shell_command` for shell (pip install, ls). **Submit your final " "answer by writing it to /workdir/answer.txt** (e.g. " "`add_and_execute_code_cell(code=\"open('/workdir/answer.txt','w').write(str(ans))\")`). Keep it " "short; do not end your turn without submitting.")
class JupyterEnv(HarborEnv): """Stateful-Jupyter-kernel harness over a Harbor sandbox."""
PROMPT_SUFFIX = _JUPYTER_PROMPT_SUFFIX
async def _setup(self) -> None: # Upload the kernel server + cell runner, ensure curl, start the kernel, wait for it to bind. await self._env.upload_file(_HERE / "kernel_server.py", "/opt/kernel_server.py") await self._env.upload_file(_HERE / "run_cell.py", "/opt/run_cell.py") await self._env.exec("which curl >/dev/null 2>&1 || apt-get install -y curl", timeout_sec=120) await self._env.exec( "nohup setsid python3 /opt/kernel_server.py >/tmp/kernel.log 2>&1 < /dev/null &", timeout_sec=30 ) for _ in range(30): r = await self._env.exec("curl -s -o /dev/null -w '%{http_code}' http://127.0.0.1:8765/", timeout_sec=5) if (r.stdout or "").strip() == "200": return await asyncio.sleep(0.5) log = await self._env.exec("cat /tmp/kernel.log", timeout_sec=5) raise RuntimeError(f"kernel_server failed to bind 127.0.0.1:8765\n--- kernel.log ---\n{log.stdout}")
def _run_cell(self, code: str) -> str: b64 = base64.b64encode(code.encode()).decode() result = self._loop.run_until_complete( self._env.exec(f"python3 /opt/run_cell.py --code-b64 {shlex.quote(b64)}", timeout_sec=180) ) raw = (result.stdout or "").strip() if not raw: return f"[run_cell empty stdout, rc={result.return_code}, stderr={result.stderr or ''}]" try: return str(json.loads(raw).get("output", "")) except json.JSONDecodeError: return f"[run_cell unparseable: {raw[:500]}]"
def add_and_execute_code_cell(self, code: str) -> str: """ Execute Python code in the stateful kernel. Variables, imports, and side-effects persist across calls. Use this for all computation.
Args: code: The Python code to execute.
Returns: The textual output of the executed cell. """ return self._run_cell(code)
def execute_shell_command(self, command: str) -> str: """ Run a shell command in the sandbox (pip install, ls, etc.). Not stateful with the Python kernel.
Args: command: The shell command to run.
Returns: The command's combined stdout and stderr. """ return self._exec(command)1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798# Copyright 2020-2026 The HuggingFace Team. All rights reserved.## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License.
"""Tiny stateful Python execution server.
Uploaded by JupyterToolAgent into the Harbor container at /opt/kernel_server.pyand started in the background. Listens on 127.0.0.1:8765 and accepts:
POST / Content-Type: application/json Body: {"code": "..."} Reply: {"output": "<stdout+stderr+traceback>", "ok": true|false}
A single persistent globals dict survives across requests — that's the"stateful kernel" the agent's `add_and_execute_code_cell` tool relies on.No IPython, no jupyter_client. Just compile(...) + exec(...)."""
from __future__ import annotations
import contextlibimport ioimport jsonimport tracebackfrom http.server import BaseHTTPRequestHandler, HTTPServer
PORT = 8765G: dict = {"__name__": "__main__"}
def _exec(code: str) -> tuple[str, bool]: out = io.StringIO() err = io.StringIO() ok = True try: # Try "single" mode first so a bare expression auto-prints (mimics Jupyter). try: compiled = compile(code, "<cell>", "single") except SyntaxError: compiled = compile(code, "<cell>", "exec") with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err): exec(compiled, G) except SystemExit: pass except BaseException: ok = False err.write(traceback.format_exc()) return out.getvalue() + err.getvalue(), ok
class Handler(BaseHTTPRequestHandler): def do_POST(self): try: n = int(self.headers.get("Content-Length", "0")) body = self.rfile.read(n).decode("utf-8", errors="replace") payload = json.loads(body) code = payload.get("code", "") output, ok = _exec(code) except Exception: output, ok = traceback.format_exc(), False # Cap to keep the per-cell response small. if len(output) > 8000: output = output[:8000] + f"\n... [truncated {len(output) - 8000} chars]" body_out = json.dumps({"output": output, "ok": ok}).encode() self.send_response(200) self.send_header("Content-Type", "application/json") self.send_header("Content-Length", str(len(body_out))) self.end_headers() self.wfile.write(body_out)
def do_GET(self): # Health check. msg = b'{"ready": true}' self.send_response(200) self.send_header("Content-Type", "application/json") self.send_header("Content-Length", str(len(msg))) self.end_headers() self.wfile.write(msg)
def log_message(self, *a, **k): # Quiet — Harbor agent's exec captures stdout/stderr. pass
if __name__ == "__main__": print(f"[kernel_server] starting on 127.0.0.1:{PORT}", flush=True) HTTPServer(("127.0.0.1", PORT), Handler).serve_forever()12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061# Copyright 2020-2026 The HuggingFace Team. All rights reserved.## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License.
"""CLI client for the kernel_server, invoked by the Harbor agent via env.exec.
Usage (inside the container): python3 /opt/run_cell.py --code-b64 <base64-encoded-python-source>
Writes the kernel server's response payload (already JSON-encoded) to stdout.The agent base64-decodes it on the host side. Base64 sidesteps shell escapingfor code containing quotes, newlines, etc."""
from __future__ import annotations
import argparseimport base64import jsonimport sysimport urllib.request
PORT = 8765
def main() -> int: p = argparse.ArgumentParser() p.add_argument("--code-b64", required=True) p.add_argument("--timeout", type=int, default=120) args = p.parse_args()
code = base64.b64decode(args.code_b64).decode("utf-8") payload = json.dumps({"code": code}).encode() req = urllib.request.Request( f"http://127.0.0.1:{PORT}", data=payload, method="POST", headers={"Content-Type": "application/json"}, ) try: with urllib.request.urlopen(req, timeout=args.timeout) as r: sys.stdout.write(r.read().decode("utf-8", errors="replace")) return 0 except Exception as exc: sys.stdout.write(json.dumps({"output": f"[run_cell err] {exc}", "ok": False})) return 1
if __name__ == "__main__": raise SystemExit(main())12345678910111213141516171819202122232425262728293031323334353637383940# `terminal_notes` harness
A richer shell harness: **6 shell tools** (including background processes) plus a **4-tool persistentnote toolkit**. Implemented by `TerminalNotesEnv` in [`env.py`](env.py).
## Tools
### Shell (backed by the sandbox)
| Tool | Signature | What it does ||---|---|---|| `shell_exec` | `shell_exec(command: str, blocking: bool = True) -> str` | Run a command. Blocking → combined stdout+stderr; non-blocking → detach and return a PID. || `shell_write_content_to_file` | `shell_write_content_to_file(path: str, content: str) -> str` | Write `content` to `path` (used to commit `/workdir/answer.txt`). || `shell_write_to_process` | `shell_write_to_process(pid: str, content: str) -> str` | Write to a background process's stdin. || `shell_view` | `shell_view(pid: str) -> str` | Read the captured stdout of a background process. || `shell_wait` | `shell_wait(pid: str) -> str` | Wait (≤5 min) for a background process to exit, then return its output. || `shell_kill_process` | `shell_kill_process(pid: str) -> str` | SIGKILL a background process. |
### Notes (in-env state, persist across turns of a rollout)
| Tool | Signature | What it does ||---|---|---|| `create_note` | `create_note(title: str, content: str) -> str` | Create a note. || `append_note` | `append_note(title: str, content: str) -> str` | Append to an existing note. || `read_note` | `read_note(title: str) -> str` | Read a note's content. || `list_note` | `list_note() -> str` | List note titles + sizes. |
> Unlike the original SETA agent, notes are **not** auto-injected into the prompt each turn (TRL owns the> prompt under `environment_factory`); recall them on demand with `read_note` / `list_note`.
## Submission
Write the answer to `/workdir/answer.txt`, e.g. `shell_write_content_to_file(path="/workdir/answer.txt", content="<value>")`.
## Use it
```pythonfrom trl.experimental.harbor import HarborSpecspec = HarborSpec(dataset, agent="examples/scripts/harbor/harnesses/terminal_notes/env.py:TerminalNotesEnv")```123456789101112131415161718# Copyright 2020-2026 The HuggingFace Team. All rights reserved.## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License.
from .env import TerminalNotesEnv
__all__ = ["TerminalNotesEnv"]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221# Copyright 2020-2026 The HuggingFace Team. All rights reserved.## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License.
"""Shell + notes base agent — a 10-tool Harbor harness (6 shell + 4 notes).
A custom [`~trl.experimental.harbor.HarborEnv`] subclass with a richer toolset than the bash harness:six shell tools (including background processes) and a persistent note-taking toolkit. Point a trainerat it with ``HarborSpec(dataset, agent="examples/scripts/harbor/harnesses/terminal_notes/env.py:TerminalNotesEnv")``.Submission is by writing ``/workdir/answer.txt`` (same verifier as the bash harness).
Notes live in-env (a dict) and survive across turns of the same rollout. They're recalled on demand via``read_note`` / ``list_note`` (TRL owns the prompt under ``environment_factory``, so the env can'tinject them automatically each turn)."""
import base64import shleximport uuid
from trl.experimental.harbor import HarborEnv
_PROMPT_SUFFIX = ( "\n\nYou are an autonomous data-analysis agent in a sandboxed Linux container (Python preinstalled). " "Dataset files are in /home/user/input/. You have shell tools (shell_exec, " "shell_write_content_to_file, shell_view/wait/kill for background procs) and a persistent note system " "(create_note, append_note, read_note, list_note) — use notes as a scratchpad and read them back. " "**Submit your final answer by writing it to /workdir/answer.txt via a shell tool** (e.g. " "shell_write_content_to_file(path='/workdir/answer.txt', content=<answer>)). Keep it short; do not " "end your turn without submitting.")
class TerminalNotesEnv(HarborEnv): """10-tool harness (6 shell + 4 notes) over a Harbor sandbox."""
PROMPT_SUFFIX = _PROMPT_SUFFIX
def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self._notes: dict[str, str] = {} self._bg: dict[str, dict] = {}
def reset(self, task_dir=None, **kwargs) -> str: self._notes.clear() self._bg.clear() return super().reset(task_dir=task_dir, **kwargs)
# ── shell toolkit ───────────────────────────────────────────────────────
def shell_exec(self, command: str, blocking: bool = True) -> str: """ Execute a shell command in the sandbox. If `blocking` (default), run synchronously and return combined stdout+stderr; otherwise detach into the background and return the new PID.
Args: command: The shell command to run. blocking: Run synchronously (True) or in the background (False).
Returns: Combined stdout+stderr (blocking) or the background PID. """ if blocking: return self._exec(command) token = uuid.uuid4().hex[:8] log, pipe = f"/tmp/sh_{token}.log", f"/tmp/sh_{token}.in" out = self._exec( f"mkfifo {pipe} 2>/dev/null; ( nohup setsid bash -c {shlex.quote(command)} <{pipe} >{log} 2>&1 ) & echo $!", timeout=15, ) pid = out.strip().split()[-1] if out.strip() else "" if not pid.isdigit(): return f"[shell_exec bg] failed to spawn: {out}" self._bg[pid] = {"log": log, "pipe": pipe} return f"Started background process PID={pid} log={log}"
def shell_write_content_to_file(self, path: str, content: str) -> str: """ Write `content` to `path` in the sandbox (overwrites). Use to commit the final answer to /workdir/answer.txt.
Args: path: Destination path in the sandbox. content: File contents.
Returns: A confirmation string. """ b64 = base64.b64encode(content.encode()).decode() out = self._exec( f"mkdir -p $(dirname {shlex.quote(path)}) && echo {b64} | base64 -d > {shlex.quote(path)}", timeout=30 ) return f"Wrote {len(content)} bytes to {path}" if "rc=" not in out else f"[write_file] {out}"
def shell_write_to_process(self, pid: str, content: str) -> str: """ Send `content` (with a trailing newline) to the stdin of a background process.
Args: pid: PID returned by shell_exec(blocking=False). content: Text to write to stdin.
Returns: A confirmation string. """ proc = self._bg.get(pid) if proc is None: return f"Unknown PID={pid}. Started: {list(self._bg)}" b64 = base64.b64encode((content + "\n").encode()).decode() self._exec(f"echo {b64} | base64 -d > {shlex.quote(proc['pipe'])}", timeout=30) return f"Wrote {len(content)} bytes to PID={pid} stdin"
def shell_view(self, pid: str) -> str: """ Return the current captured stdout of a background process.
Args: pid: PID returned by shell_exec(blocking=False).
Returns: The captured stdout so far. """ proc = self._bg.get(pid) return self._exec(f"tail -c 4000 {shlex.quote(proc['log'])} 2>/dev/null") if proc else f"Unknown PID={pid}"
def shell_wait(self, pid: str) -> str: """ Wait (up to ~5 min) for a background process to terminate, then return its captured stdout.
Args: pid: PID returned by shell_exec(blocking=False).
Returns: The process output after it exits. """ proc = self._bg.get(pid) if proc is None: return f"Unknown PID={pid}" return self._exec( f"for i in $(seq 1 300); do [ ! -d /proc/{pid} ] && break; sleep 1; done; " f"echo '--- exited ---'; tail -c 4000 {shlex.quote(proc['log'])} 2>/dev/null", timeout=320, )
def shell_kill_process(self, pid: str) -> str: """ Send SIGKILL to a background process.
Args: pid: PID returned by shell_exec(blocking=False).
Returns: A confirmation string. """ if pid not in self._bg: return f"Unknown PID={pid}" return f"Sent SIGKILL to PID={pid}: {self._exec(f'kill -9 {pid} 2>&1', timeout=10)}"
# ── note toolkit (in-env state) ──────────────────────────────────────────
def create_note(self, title: str, content: str) -> str: """ Create a persistent note (recall it later with read_note/list_note).
Args: title: Note title. content: Note body.
Returns: A confirmation string. """ self._notes[title] = content return f"Note '{title}' created ({len(content)} chars). Total: {len(self._notes)}."
def append_note(self, title: str, content: str) -> str: """ Append `content` (on a new line) to an existing note.
Args: title: Note title. content: Text to append.
Returns: A confirmation string. """ if title not in self._notes: return f"Note '{title}' not found. Use create_note first." self._notes[title] += "\n" + content return f"Note '{title}' updated -> {len(self._notes[title])} chars."
def read_note(self, title: str) -> str: """ Return the full content of a note.
Args: title: Note title.
Returns: The note content, or a not-found message. """ return self._notes.get(title, f"Note '{title}' not found.")
def list_note(self) -> str: """ List all note titles with their character counts.
Returns: One line per note, or a message if there are none. """ return "\n".join(f"- {t} ({len(c)} chars)" for t, c in self._notes.items()) or "(no notes yet)"123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899# Copyright 2020-2026 The HuggingFace Team. All rights reserved.## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License.
# /// script# dependencies = [# "trl[peft]",# "trackio",# "kernels",# ]# ///
"""Run the KTO training script with the commands below. In general, the optimal configuration for KTO will be similar to that of DPO.
# Full training:python trl/scripts/kto.py \ --dataset_name trl-lib/kto-mix-14k \ --model_name_or_path trl-lib/qwen1.5-1.8b-sft \ --per_device_train_batch_size 16 \ --num_train_epochs 1 \ --learning_rate 5e-7 \ --lr_scheduler_type cosine \ --gradient_accumulation_steps 1 \ --eval_steps 500 \ --output_dir kto-aligned-model \ --warmup_steps 0.1 \ --logging_first_step
# QLoRA:python trl/scripts/kto.py \ --dataset_name trl-lib/kto-mix-14k \ --model_name_or_path trl-lib/qwen1.5-1.8b-sft \ --per_device_train_batch_size 8 \ --num_train_epochs 1 \ --learning_rate 5e-7 \ --lr_scheduler_type cosine \ --gradient_accumulation_steps 1 \ --eval_steps 500 \ --output_dir kto-aligned-model-lora \ --warmup_steps 0.1 \ --logging_first_step \ --use_peft \ --load_in_4bit \ --lora_target_modules all-linear \ --lora_r 16 \ --lora_alpha 16"""
from datasets import load_datasetfrom transformers import AutoModelForCausalLM, AutoTokenizer, HfArgumentParser
from trl import ModelConfig, ScriptArguments, get_peft_configfrom trl.experimental.kto import KTOConfig, KTOTrainer
if __name__ == "__main__": parser = HfArgumentParser((ScriptArguments, KTOConfig, ModelConfig)) script_args, training_args, model_args = parser.parse_args_into_dataclasses()
# Load a pretrained model model = AutoModelForCausalLM.from_pretrained(model_args.model_name_or_path) ref_model = AutoModelForCausalLM.from_pretrained(model_args.model_name_or_path)
tokenizer = AutoTokenizer.from_pretrained(model_args.model_name_or_path) if tokenizer.pad_token is None: tokenizer.pad_token = tokenizer.eos_token
# Load the dataset dataset = load_dataset(script_args.dataset_name, name=script_args.dataset_config)
# Initialize the KTO trainer trainer = KTOTrainer( model, ref_model, args=training_args, train_dataset=dataset[script_args.dataset_train_split], eval_dataset=dataset[script_args.dataset_test_split] if training_args.eval_strategy != "no" else None, processing_class=tokenizer, peft_config=get_peft_config(model_args), )
# Train and push the model to the Hub trainer.train()
# Save and push to hub trainer.save_model(training_args.output_dir) if training_args.push_to_hub: trainer.push_to_hub(dataset_name=script_args.dataset_name)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126# Copyright 2020-2026 The HuggingFace Team. All rights reserved.## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License.
# /// script# dependencies = [# "trl[peft]",# "Pillow",# "torchvision",# "trackio",# "kernels",# ]# ///
"""python examples/scripts/mpo_vlm.py \ --dataset_name HuggingFaceH4/rlaif-v_formatted \ --model_name_or_path Qwen/Qwen2.5-VL-3B-Instruct \ --per_device_train_batch_size 4 \ --per_device_eval_batch_size 4 \ --num_train_epochs 1 \ --gradient_accumulation_steps 8 \ --dataset_num_proc 1 \ --output_dir dpo_idefics_rlaif-v \ --dtype bfloat16 \ --use_peft \ --lora_target_modules down_proj, o_proj, k_proj, q_proj, gate_proj, up_proj, v_proj \ --loss_type sigmoid bco_pair sft \ --loss_weights 0.8 0.2 1.0"""
import torchfrom datasets import load_datasetfrom PIL import Imagefrom transformers import AutoModelForImageTextToText
from trl import ( DPOConfig, DPOTrainer, ModelConfig, ScriptArguments, TrlParser, get_kbit_device_map, get_peft_config, get_quantization_config,)
if __name__ == "__main__": parser = TrlParser((ScriptArguments, DPOConfig, ModelConfig)) script_args, training_args, model_args = parser.parse_args_and_config()
################ # Model & Processor ################ dtype = model_args.dtype if model_args.dtype in ["auto", None] else getattr(torch, model_args.dtype)
model_kwargs = dict( revision=model_args.model_revision, attn_implementation=model_args.attn_implementation, dtype=dtype, ) quantization_config = get_quantization_config(model_args) if quantization_config is not None: # Passing None would not be treated the same as omitting the argument, so we include it only when valid. model_kwargs["device_map"] = get_kbit_device_map() model_kwargs["quantization_config"] = quantization_config
model = AutoModelForImageTextToText.from_pretrained( model_args.model_name_or_path, **model_kwargs, ) peft_config = get_peft_config(model_args)
################ # Dataset ################ dataset = load_dataset( script_args.dataset_name, name=script_args.dataset_config, streaming=script_args.dataset_streaming, ) train_dataset = dataset[script_args.dataset_train_split] test_dataset = dataset[script_args.dataset_test_split] if training_args.eval_strategy != "no" else None
def ensure_rgb(example): # Convert the image to RGB if it's not already image = example["images"][0] if isinstance(image, Image.Image): if image.mode != "RGB": image = image.convert("RGB") example["images"] = [image] return example
# Apply the transformation to the dataset (change num_proc depending on the available compute) train_dataset = train_dataset.map(ensure_rgb, num_proc=training_args.dataset_num_proc) if test_dataset is not None: test_dataset = test_dataset.map(ensure_rgb, num_proc=training_args.dataset_num_proc)
################ # Training ################ trainer = DPOTrainer( model=model, args=training_args, train_dataset=train_dataset, eval_dataset=test_dataset, peft_config=peft_config, )
trainer.train()
# Save and push to hub trainer.save_model(training_args.output_dir) if training_args.push_to_hub: trainer.push_to_hub(dataset_name=script_args.dataset_name)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130# Copyright 2020-2026 The HuggingFace Team. All rights reserved.## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License.
# /// script# dependencies = [# "trl",# "trackio",# "kernels",# ]# ///
"""Usage:
python examples/scripts/nash_md.py \ --model_name_or_path trl-lib/pythia-1b-deduped-tldr-sft \ --reward_model_path trl-lib/pythia-1b-deduped-tldr-rm \ --dataset_name trl-lib/tldr \ --learning_rate 5.0e-7 \ --output_dir pythia-1b-tldr-nash-md \ --per_device_train_batch_size 4 \ --gradient_accumulation_steps 32 \ --num_train_epochs 3 \ --max_new_tokens 64 \ --warmup_steps 0.1 \ --missing_eos_penalty 1.0 \ --push_to_hub
accelerate launch --config_file examples/accelerate_configs/deepspeed_zero2.yaml \ examples/scripts/nash_md.py \ --model_name_or_path trl-lib/pythia-1b-deduped-tldr-sft \ --reward_model_path trl-lib/pythia-1b-deduped-tldr-rm \ --dataset_name trl-lib/tldr \ --learning_rate 5.0e-7 \ --output_dir pythia-1b-tldr-nash-md \ --per_device_train_batch_size 4 \ --gradient_accumulation_steps 32 \ --num_train_epochs 3 \ --max_new_tokens 64 \ --warmup_steps 0.1 \ --missing_eos_penalty 1.0 \ --push_to_hub"""
import torchfrom datasets import load_datasetfrom transformers import AutoModelForCausalLM, AutoModelForSequenceClassification, AutoTokenizer, GenerationConfig
from trl import ( LogCompletionsCallback, ModelConfig, ScriptArguments, TrlParser, get_kbit_device_map, get_quantization_config,)from trl.experimental.nash_md import NashMDConfig, NashMDTrainer
if __name__ == "__main__": parser = TrlParser((ScriptArguments, NashMDConfig, ModelConfig)) script_args, training_args, model_args = parser.parse_args_and_config() training_args.gradient_checkpointing_kwargs = {"use_reentrant": True}
dtype = model_args.dtype if model_args.dtype in ["auto", None] else getattr(torch, model_args.dtype) model_kwargs = dict( revision=model_args.model_revision, attn_implementation=model_args.attn_implementation, dtype=dtype, use_cache=False if training_args.gradient_checkpointing else True, ) quantization_config = get_quantization_config(model_args) if quantization_config is not None: # Passing None would not be treated the same as omitting the argument, so we include it only when valid. model_kwargs["device_map"] = get_kbit_device_map() model_kwargs["quantization_config"] = quantization_config
model = AutoModelForCausalLM.from_pretrained(model_args.model_name_or_path, **model_kwargs) ref_model = AutoModelForCausalLM.from_pretrained(model_args.model_name_or_path, **model_kwargs)
if training_args.reward_model_path is not None: reward_model = AutoModelForSequenceClassification.from_pretrained( training_args.reward_model_path, num_labels=1, **model_kwargs, ) else: reward_model = None
tokenizer = AutoTokenizer.from_pretrained(model_args.model_name_or_path, padding_side="left") if tokenizer.pad_token is None: tokenizer.pad_token = tokenizer.eos_token
dataset = load_dataset(script_args.dataset_name, name=script_args.dataset_config)
trainer = NashMDTrainer( model=model, ref_model=ref_model, reward_funcs=reward_model, args=training_args, train_dataset=dataset[script_args.dataset_train_split], eval_dataset=dataset[script_args.dataset_test_split] if training_args.eval_strategy != "no" else None, processing_class=tokenizer, )
if training_args.eval_strategy != "no": generation_config = GenerationConfig( max_new_tokens=training_args.max_new_tokens, do_sample=True, temperature=training_args.temperature ) completions_callback = LogCompletionsCallback(trainer, generation_config, num_prompts=8) trainer.add_callback(completions_callback)
trainer.train()
# Save and push to hub trainer.save_model(training_args.output_dir) if training_args.push_to_hub: trainer.push_to_hub(dataset_name=script_args.dataset_name)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137# Copyright 2020-2026 The HuggingFace Team. All rights reserved.## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License.
# /// script# dependencies = [# "trl[peft]",# "trackio",# "kernels",# ]# ///
"""Usage:
python examples/scripts/online_dpo.py \ --model_name_or_path trl-lib/pythia-1b-deduped-tldr-sft \ --reward_model_path trl-lib/pythia-1b-deduped-tldr-rm \ --dataset_name trl-lib/tldr \ --learning_rate 5.0e-7 \ --output_dir pythia-1b-tldr-online-dpo \ --per_device_train_batch_size 8 \ --gradient_accumulation_steps 16 \ --warmup_steps 0.1 \ --missing_eos_penalty 1.0
With LoRA:python examples/scripts/online_dpo.py \ --model_name_or_path trl-lib/pythia-1b-deduped-tldr-sft \ --reward_model_path trl-lib/pythia-1b-deduped-tldr-rm \ --dataset_name trl-lib/tldr \ --learning_rate 5.0e-6 \ --output_dir pythia-1b-tldr-online-dpo \ --per_device_train_batch_size 16 \ --gradient_accumulation_steps 8 \ --warmup_steps 0.1 \ --missing_eos_penalty 1.0 \ --use_peft"""
import torchfrom datasets import load_datasetfrom transformers import AutoModelForCausalLM, AutoModelForSequenceClassification, AutoTokenizer, GenerationConfig
from trl import ( LogCompletionsCallback, ModelConfig, ScriptArguments, TrlParser, get_kbit_device_map, get_peft_config, get_quantization_config,)from trl.experimental.online_dpo import OnlineDPOConfig, OnlineDPOTrainer
if __name__ == "__main__": parser = TrlParser((ScriptArguments, OnlineDPOConfig, ModelConfig)) script_args, training_args, model_args = parser.parse_args_and_config() training_args.gradient_checkpointing_kwargs = {"use_reentrant": True}
dtype = model_args.dtype if model_args.dtype in ["auto", None] else getattr(torch, model_args.dtype) model_kwargs = dict( revision=model_args.model_revision, attn_implementation=model_args.attn_implementation, dtype=dtype, use_cache=False if training_args.gradient_checkpointing else True, ) quantization_config = get_quantization_config(model_args) if quantization_config is not None: # Passing None would not be treated the same as omitting the argument, so we include it only when valid. model_kwargs["device_map"] = get_kbit_device_map() model_kwargs["quantization_config"] = quantization_config
model = AutoModelForCausalLM.from_pretrained(model_args.model_name_or_path, **model_kwargs)
if training_args.reward_model_path is not None: reward_model = AutoModelForSequenceClassification.from_pretrained( training_args.reward_model_path, num_labels=1, **model_kwargs, ) reward_tokenizer = AutoTokenizer.from_pretrained( training_args.reward_model_path, truncation=True, truncation_side="left", # since we judge the completion, truncating left is more appropriate ) if reward_tokenizer.pad_token_id is None: reward_tokenizer.pad_token = reward_tokenizer.eos_token else: reward_model = None reward_tokenizer = None
tokenizer = AutoTokenizer.from_pretrained( model_args.model_name_or_path, padding_side="left", **model_kwargs, ) if tokenizer.pad_token_id is None: tokenizer.pad_token = tokenizer.eos_token
dataset = load_dataset(script_args.dataset_name, name=script_args.dataset_config)
trainer = OnlineDPOTrainer( model=model, reward_funcs=reward_model, args=training_args, train_dataset=dataset[script_args.dataset_train_split], eval_dataset=dataset[script_args.dataset_test_split] if training_args.eval_strategy != "no" else None, processing_class=tokenizer, reward_processing_classes=reward_tokenizer, peft_config=get_peft_config(model_args), )
if training_args.eval_strategy != "no": generation_config = GenerationConfig( max_new_tokens=training_args.max_new_tokens, do_sample=True, temperature=training_args.temperature ) completions_callback = LogCompletionsCallback(trainer, generation_config, num_prompts=8) trainer.add_callback(completions_callback)
trainer.train()
# Save and push to hub trainer.save_model(training_args.output_dir) if training_args.push_to_hub: trainer.push_to_hub(dataset_name=script_args.dataset_name)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203# Copyright 2020-2026 The HuggingFace Team. All rights reserved.## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License.
# /// script# dependencies = [# "trl[peft]",# "math-verify",# "latex2sympy2_extended",# "trackio",# "torchvision",# "kernels",# ]# ///
"""pip install math_verify
# For Qwen/Qwen2.5-VL-3B-Instructaccelerate launch \ --config_file examples/accelerate_configs/deepspeed_zero3.yaml \ examples/scripts/online_dpo_vlm.py \ --model_name_or_path Qwen/Qwen2.5-VL-3B-Instruct \ --reward_model_path Qwen/Qwen2.5-VL-3B-Instruct \ --output_dir online-dpo-Qwen2.5-VL-3B-Instruct \ --learning_rate 1e-5 \ --dtype bfloat16 \ --max_length 1536 \ --max_new_tokens 1024 \ --use_vllm \ --vllm_mode server \ --use_peft \ --lora_target_modules "q_proj", "v_proj" \ --per_device_train_batch_size 1 \ --gradient_accumulation_steps 2
# For HuggingFaceTB/SmolVLM2-2.2B-Instructpip install num2words==0.5.14
accelerate launch \ --config_file examples/accelerate_configs/deepspeed_zero3.yaml \ examples/scripts/online_dpo_vlm.py \ --model_name_or_path HuggingFaceTB/SmolVLM2-2.2B-Instruct \ --reward_model_path HuggingFaceTB/SmolVLM2-2.2B-Instruct \ --output_dir online-dpo-SmolVLM2-2.2B-Instruct \ --learning_rate 1e-5 \ --dtype bfloat16 \ --max_length 1536 \ --max_new_tokens 1024 \ --use_peft \ --lora_target_modules "q_proj", "v_proj" \ --per_device_train_batch_size 1 \ --gradient_accumulation_steps 2
# Single GPU test command:python examples/scripts/online_dpo_vlm.py \ --model_name_or_path HuggingFaceTB/SmolVLM2-2.2B-Instruct \ --reward_model_path HuggingFaceTB/SmolVLM2-2.2B-Instruct \ --output_dir online-dpo-SmolVLM2-2.2B-Instruct-test \ --learning_rate 1e-5 \ --dtype bfloat16 \ --max_length 1536 \ --max_new_tokens 128 \ --use_peft \ --lora_target_modules "q_proj", "v_proj" \ --per_device_train_batch_size 1 \ --gradient_accumulation_steps 1 \ --max_steps 2 \ --logging_steps 1 \ --trust_remote_code"""
import torchimport transformersfrom datasets import load_datasetfrom transformers import AutoConfig, AutoProcessor, GenerationConfig
from trl import ( LogCompletionsCallback, ModelConfig, ScriptArguments, TrlParser, get_kbit_device_map, get_peft_config, get_quantization_config,)from trl.experimental.online_dpo import OnlineDPOConfig, OnlineDPOTrainerfrom trl.rewards import accuracy_reward, think_format_reward
if __name__ == "__main__": parser = TrlParser((ScriptArguments, OnlineDPOConfig, ModelConfig)) script_args, training_args, model_args = parser.parse_args_and_config() training_args.gradient_checkpointing_kwargs = {"use_reentrant": True}
dtype = model_args.dtype if model_args.dtype in ["auto", None] else getattr(torch, model_args.dtype) model_kwargs = dict( revision=model_args.model_revision, attn_implementation=model_args.attn_implementation, dtype=dtype, use_cache=False if training_args.gradient_checkpointing else True, ) quantization_config = get_quantization_config(model_args) if quantization_config is not None: # Passing None would not be treated the same as omitting the argument, so we include it only when valid. model_kwargs["device_map"] = get_kbit_device_map() model_kwargs["quantization_config"] = quantization_config
# Load the VLM model using correct architecture (from GRPO pattern) config = AutoConfig.from_pretrained(model_args.model_name_or_path) architecture = getattr(transformers, config.architectures[0]) model = architecture.from_pretrained(model_args.model_name_or_path, **model_kwargs)
# For VLM online DPO, using a reward model is complex because it needs images reward_model = None reward_processor = None
# Load processor for main model processor = AutoProcessor.from_pretrained(model_args.model_name_or_path) if hasattr(processor, "tokenizer"): processor.tokenizer.padding_side = "left" if processor.tokenizer.pad_token_id is None: processor.tokenizer.pad_token = processor.tokenizer.eos_token
################ # Dataset ################ dataset = load_dataset("lmms-lab/multimodal-open-r1-8k-verified", split="train") dataset = dataset.train_test_split(test_size=100, seed=42)
SYSTEM_PROMPT = ( "A conversation between user and assistant. The user asks a question, and the assistant solves it. The " "assistant first thinks about the reasoning process in the mind and then provides the user with the answer. " "The reasoning process and answer are enclosed within <think></think> tags, i.e., <think>\nThis is my " "reasoning.\n</think>\nThis is my answer." )
def make_conversation(example): # Create conversational format that OnlineDPOTrainer expects prompt = [ {"role": "system", "content": SYSTEM_PROMPT}, {"role": "user", "content": example["problem"]}, ] return {"prompt": prompt, "image": example["image"]}
dataset = dataset.map(make_conversation)
# Filter big images (from GRPO pattern) def filter_big_images(example): image = example["image"] return image.size[0] < 512 and image.size[1] < 512
dataset = dataset.filter(filter_big_images)
def convert_to_rgb(example): image = example["image"] if image.mode != "RGB": image = image.convert("RGB") example["image"] = image return example
dataset = dataset.map(convert_to_rgb)
train_dataset = dataset["train"] eval_dataset = dataset["test"] if training_args.eval_strategy != "no" else None
################ # Training ################ trainer = OnlineDPOTrainer( model=model, reward_funcs=[think_format_reward, accuracy_reward], # Use same reward functions as GRPO VLM args=training_args, train_dataset=train_dataset, eval_dataset=eval_dataset, processing_class=processor, peft_config=get_peft_config(model_args), )
# Add completion logging callback (from online DPO pattern) if training_args.eval_strategy != "no": generation_config = GenerationConfig( max_new_tokens=training_args.max_new_tokens, do_sample=True, temperature=training_args.temperature ) completions_callback = LogCompletionsCallback(trainer, generation_config, num_prompts=8) trainer.add_callback(completions_callback)
trainer.train()
# Save and push to hub trainer.save_model(training_args.output_dir) if training_args.push_to_hub: trainer.push_to_hub(dataset_name="lmms-lab/multimodal-open-r1-8k-verified")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291# Copyright 2020-2026 The HuggingFace Team. All rights reserved.## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License.
# /// script# dependencies = [# "trl[vllm,peft]",# "trackio",# "kernels",# "openenv-browsergym-env @ git+https://huggingface.co/spaces/openenv/browsergym_env",# ]# ///
"""GRPO training with OpenEnv's BrowserGym environment for VLMs (Vision Language Models).
This script uses `environment_factory` with multimodal tool responses: each tool actionreturns a screenshot (PIL Image) alongside the accessibility tree text, allowing the VLMto see the page visually after each action.
Setup:```shpip install "openenv-browsergym-env @ git+https://huggingface.co/spaces/openenv/browsergym_env"```
Usage:```sh# Without vLLM (default, 1 GPU)python examples/scripts/openenv/browsergym.py
# With vLLM colocate (1 GPU, requires vLLM support for the model)python examples/scripts/openenv/browsergym.py --use-vllm
# With vLLM server (2 GPUs)CUDA_VISIBLE_DEVICES=0 trl vllm-serve --model Qwen/Qwen3.5-2B --host 0.0.0.0 --port 8000CUDA_VISIBLE_DEVICES=1 python examples/scripts/openenv/browsergym.py --use-vllm --vllm-mode server```"""
from __future__ import annotations
import argparsefrom datetime import datetimefrom pathlib import Path
import numpy as npfrom browsergym_env import BrowserGymAction, BrowserGymEnvfrom datasets import Datasetfrom PIL import Image
from trl import GRPOConfig, GRPOTrainer
def parse_args() -> argparse.Namespace: parser = argparse.ArgumentParser(description="GRPO training with BrowserGym VLM environment.") parser.add_argument("--model-id", default="Qwen/Qwen3.5-2B") parser.add_argument("--space-url", default="https://openenv-browsergym-env.hf.space") parser.add_argument("--task-name", default="click-test", help="BrowserGym task name to pass to reset().") parser.add_argument("--dataset-prompt", default="Complete the web task successfully.") parser.add_argument("--dataset-size", type=int, default=1000) parser.add_argument("--max-steps", type=int, default=10) parser.add_argument("--max-completion-length", type=int, default=1024) parser.add_argument("--image-size", type=int, default=512, help="Resize screenshots to this size. 0 to disable.") parser.add_argument("--num-generations", type=int, default=4) parser.add_argument("--gradient-accumulation-steps", type=int, default=32) parser.add_argument("--learning-rate", type=float, default=5e-6) parser.add_argument("--num-epochs", type=int, default=1) parser.add_argument("--logging-steps", type=int, default=1) parser.add_argument("--output-dir", default=None) parser.add_argument("--use-vllm", action="store_true", default=False, help="Enable vLLM for generation.") parser.add_argument("--vllm-mode", choices=("colocate", "server"), default="colocate") parser.add_argument("--vllm-server-url", default="http://localhost:8000") return parser.parse_args()
def sanitize_name(name: str) -> str: return name.replace("/", "-")
SYSTEM_PROMPT = """You control a web browser to complete tasks.
The page structure shows elements as: [bid] element_type 'element_text'For example: [13] button 'Click Me!' means the element has bid='13'.
You will see a screenshot of the page after each action. Use the visual informationalong with the page structure to decide your next action.
Use the available tools to interact with the page:- click: Click an element by its bid- fill: Fill an input field with text- send_keys: Send keyboard input- scroll: Scroll the page- noop: Do nothing
Complete the given task as efficiently as possible."""
def reward_completion(completions, environments, **kwargs) -> list[float]: return [env.reward for env in environments]
def main() -> None: args = parse_args()
space_url = args.space_url max_steps = args.max_steps image_size = args.image_size
dataset = Dataset.from_dict( { "prompt": [ [ {"role": "system", "content": SYSTEM_PROMPT}, {"role": "user", "content": args.dataset_prompt}, ] ] * args.dataset_size } )
class BrowserGymVLMEnv: def __init__(self): self.client = BrowserGymEnv(base_url=space_url) self.reward = 0.0 self.done = False self._step_count = 0
def reset(self, **kwargs) -> str | None: self.reward = 0.0 self.done = False self._step_count = 0 result = self.client.reset(task_name=args.task_name) self.done = result.done return self._format_observation(result.observation)
def click(self, bid: str) -> list: """Click an element on the page.
Args: bid: The BrowserGym ID of the element to click.
Returns: The updated page observation with screenshot. """ return self._do_action(f"click('{bid}')")
def fill(self, bid: str, text: str) -> list: """Fill an input field with text.
Args: bid: The BrowserGym ID of the input field. text: The text to type into the field.
Returns: The updated page observation with screenshot. """ return self._do_action(f"fill('{bid}', '{text}')")
def send_keys(self, text: str) -> list: """Send keyboard input to the page.
Args: text: The keyboard input to send.
Returns: The updated page observation with screenshot. """ return self._do_action(f"send_keys('{text}')")
def scroll(self, direction: str) -> list: """Scroll the page.
Args: direction: Direction to scroll, either 'up' or 'down'.
Returns: The updated page observation with screenshot. """ return self._do_action(f"scroll('{direction}')")
def noop(self) -> list: """Do nothing and observe the current page state.
Returns: The current page observation with screenshot. """ return self._do_action("noop()")
def _do_action(self, action_str: str) -> list: if self.done: raise ValueError("Episode is done.")
self._step_count += 1 result = self.client.step(BrowserGymAction(action_str=action_str)) observation = result.observation step_reward = float(result.reward or 0.0) self.done = result.done
if self.done and step_reward > 0: self.reward = 1.0 elif self.done: self.reward = 0.0 else: self.reward = step_reward
if self._step_count >= max_steps: self.done = True
return self._format_observation_multimodal(observation)
def _format_observation(self, observation) -> str: """Format initial observation as text (for reset, appended to prompt).""" parts = [] if observation.goal: parts.append(f"Goal: {observation.goal}") if observation.axtree_txt: axtree = observation.axtree_txt if len(axtree) > 2000: axtree = axtree[:2000] + "..." parts.append(f"Page structure:\n{axtree}") return "\n\n".join(parts) if parts else "No observation available."
def _format_observation_multimodal(self, observation) -> list: """Format observation as multimodal content blocks (screenshot + text).""" content = []
# Add screenshot if available if observation.screenshot is not None: screenshot_array = np.array(observation.screenshot, dtype=np.uint8) screenshot_image = Image.fromarray(screenshot_array) if image_size > 0: screenshot_image.thumbnail((image_size, image_size), Image.LANCZOS) content.append({"type": "image", "image": screenshot_image})
# Add text observation parts = [] if observation.goal: parts.append(f"Goal: {observation.goal}") if observation.last_action_error and observation.error: parts.append(f"Error: {observation.error}") if observation.axtree_txt: axtree = observation.axtree_txt if len(axtree) > 2000: axtree = axtree[:2000] + "..." parts.append(f"Page structure:\n{axtree}") text = "\n\n".join(parts) if parts else "No observation available." content.append({"type": "text", "text": text})
return content
timestamp = datetime.now().strftime("%Y-%m-%d_%H-%M-%S") default_output_dir = Path("outputs") / f"browsergym-vlm-grpo-{sanitize_name(args.model_id)}-{timestamp}" output_dir = Path(args.output_dir or default_output_dir)
trainer = GRPOTrainer( model=args.model_id, reward_funcs=reward_completion, train_dataset=dataset, args=GRPOConfig( use_vllm=args.use_vllm, vllm_mode=args.vllm_mode if args.use_vllm else "colocate", vllm_server_base_url=args.vllm_server_url if args.use_vllm and args.vllm_mode == "server" else None, output_dir=str(output_dir), num_train_epochs=args.num_epochs, learning_rate=args.learning_rate, gradient_accumulation_steps=args.gradient_accumulation_steps, num_generations=args.num_generations, max_completion_length=args.max_completion_length, logging_steps=args.logging_steps, log_completions=True, report_to="trackio", trackio_space_id=f"browsergym-vlm-grpo-{sanitize_name(args.model_id)}", chat_template_kwargs={"enable_thinking": False}, ), environment_factory=BrowserGymVLMEnv, ) trainer.train()
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463# Copyright 2020-2026 The HuggingFace Team. All rights reserved.## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License.
# /// script# dependencies = [# "trl[vllm,peft]",# "trackio",# "kernels",# "openenv-browsergym-env @ git+https://huggingface.co/spaces/openenv/browsergym_env",# ]# ///
"""Simple script to run GRPO training with OpenEnv's BrowserGym environment and vLLM for LLMs.
This script is optimized for text-only Language Models (LLMs). It uses the accessibilitytree text from BrowserGym, making it memory-efficient.
The environment runs on a Hugging Face Space by default.
Setup (Option A - Install from HF Space, recommended):
```shuv pip install git+https://huggingface.co/spaces/openenv/browsergym_env```
Setup (Option B - Clone OpenEnv repo, for development):
```shgit clone https://github.com/huggingface/OpenEnv.gitcd OpenEnv/envs/browsergym_envuv pip install -e .```
# Option 1: HF Spaces + Colocated vLLM (1 GPU required)```shpython examples/scripts/openenv/browsergym_llm.py --vllm-mode colocate```
# Option 2: HF Spaces + Separate vLLM server (2 GPUs required)
# Spin up vLLM server (Terminal 1)```shCUDA_VISIBLE_DEVICES=0 trl vllm-serve --model Qwen/Qwen3-0.6B --host 0.0.0.0 --port 8001```
# Run training (Terminal 2)```shCUDA_VISIBLE_DEVICES=1 python examples/scripts/openenv/browsergym_llm.py --vllm-mode server --vllm-server-url http://localhost:8001```"""
from __future__ import annotations
import argparsefrom datetime import datetimefrom pathlib import Path
from browsergym_env import BrowserGymAction, BrowserGymEnvfrom datasets import Dataset
from trl import GRPOConfig, GRPOTrainer
def parse_args() -> argparse.Namespace: parser = argparse.ArgumentParser(description="Run GRPO training for BrowserGym MiniWoB using OpenEnv environment.") parser.add_argument( "--model-id", default="Qwen/Qwen3-0.6B", help="Model identifier passed to GRPOTrainer for fine-tuning.", ) parser.add_argument( "--space-url", type=str, default="https://openenv-browsergym-env.hf.space", help="URL for the Hugging Face Space running the BrowserGym environment.", ) parser.add_argument( "--benchmark", default="miniwob", help="BrowserGym benchmark to use (miniwob, webarena, etc.).", ) parser.add_argument( "--task-name", default="click-test", help="Specific task within the benchmark (e.g., click-test, click-button).", ) parser.add_argument( "--dataset-prompt", default="Complete the web task successfully.", help="Prompt text used to seed the training dataset.", ) parser.add_argument( "--dataset-size", type=int, default=1000, help="Number of entries to include in the synthetic training dataset.", ) parser.add_argument( "--max-steps", type=int, default=10, help="Maximum number of steps per episode.", ) parser.add_argument( "--max-completion-length", type=int, default=1024, help="Maximum completion length in tokens for tool-calling generation.", ) parser.add_argument( "--temperature", type=float, default=0.7, help="Sampling temperature used during rollout generation.", ) parser.add_argument( "--top-k", type=int, default=50, help="Top-k sampling parameter forwarded to vLLM.", ) parser.add_argument( "--top-p", type=float, default=None, help="Optional top-p sampling parameter forwarded to vLLM.", ) parser.add_argument( "--learning-rate", type=float, default=5e-6, help="Learning rate for GRPO training.", ) parser.add_argument( "--weight-decay", type=float, default=0.0, help="Weight decay applied during optimization.", ) parser.add_argument( "--gradient-accumulation-steps", type=int, default=32, help="Gradient accumulation steps for GRPO training.", ) parser.add_argument( "--warmup-steps", type=int, default=10, help="Warmup steps for the scheduler.", ) parser.add_argument( "--per-device-batch-size", type=int, default=1, help="Per-device train batch size.", ) parser.add_argument( "--num-generations", type=int, default=4, help="Number of rollout generations per dataset prompt.", ) parser.add_argument( "--num-epochs", type=int, default=1, help="Number of training epochs.", ) parser.add_argument( "--save-interval", type=int, default=50, help="Interval (in steps) between checkpoint saves.", ) parser.add_argument( "--save-total-limit", type=int, default=None, help="Maximum number of checkpoints to keep.", ) parser.add_argument( "--output-dir", default=None, help="Directory where training outputs and checkpoints are stored.", ) parser.add_argument( "--run-name", default=None, help="Optional run name for logging systems.", ) parser.add_argument( "--project", default=None, help="Optional project identifier for logging systems.", ) parser.add_argument( "--vllm-mode", choices=("colocate", "server"), default="colocate", help="vLLM execution mode: 'colocate' or 'server'.", ) parser.add_argument( "--vllm-server-url", type=str, default="http://localhost:8001", help="URL for the vLLM server (only used when --vllm-mode=server).", ) parser.add_argument( "--logging-steps", type=int, default=1, help="Frequency of logging steps for GRPO training.", ) return parser.parse_args()
def sanitize_name(name: str) -> str: return name.replace("/", "-")
# ---------------------------------------------------------------------------# System Prompt# ---------------------------------------------------------------------------
SYSTEM_PROMPT = """You control a web browser to complete tasks.
The page structure shows elements as: [bid] element_type 'element_text'For example: [13] button 'Click Me!' means the element has bid='13'.
Use the available tools to interact with the page:- click: Click an element by its bid- fill: Fill an input field with text- send_keys: Send keyboard input- scroll: Scroll the page- noop: Do nothing
Complete the given task as efficiently as possible."""
# ---------------------------------------------------------------------------# Reward# ---------------------------------------------------------------------------
def reward_completion(environments, **kwargs) -> list[float]: """Reward for task completion.""" return [env.reward for env in environments]
# ---------------------------------------------------------------------------# Main entrypoint# ---------------------------------------------------------------------------
def main() -> None: args = parse_args()
space_url = args.space_url max_steps = args.max_steps
dataset = Dataset.from_dict( { "prompt": [ [ {"role": "system", "content": SYSTEM_PROMPT}, {"role": "user", "content": args.dataset_prompt}, ] ] * args.dataset_size } )
class BrowserGymLLMEnv: def __init__(self): self.client = BrowserGymEnv(base_url=space_url) self.reward = 0.0 self._done = False self._step_count = 0
def _ensure_large_max_size(self): """Raise WebSocket max message size for large observations (e.g. accessibility trees).
openenv-core<=0.2.1 does not pass max_size to ws_connect, so the websockets library defaults to 1MB. We force a connection and patch it to 100MB before any messages are sent. """ self.client.connect() ws = self.client._ws if ws is not None and hasattr(ws, "protocol"): proto = ws.protocol # websockets <16: max_size; websockets >=16: max_message_size attr = "max_size" if hasattr(proto, "max_size") else "max_message_size" if getattr(proto, attr) == 2**20: setattr(proto, attr, 100 * 1024 * 1024)
def reset(self, **kwargs) -> str: self.reward = 0.0 self._done = False self._step_count = 0 self._ensure_large_max_size() result = self.client.reset(task_name=args.task_name) self._done = result.done return self._format_observation(result.observation)
def click(self, bid: str) -> str: """Click an element on the page.
Args: bid: The BrowserGym ID of the element to click.
Returns: The updated page observation. """ return self._do_action(f"click({bid!r})")
def fill(self, bid: str, text: str) -> str: """Fill an input field with text.
Args: bid: The BrowserGym ID of the input field. text: The text to type into the field.
Returns: The updated page observation. """ return self._do_action(f"fill({bid!r}, {text!r})")
def send_keys(self, text: str) -> str: """Send keyboard input to the page.
Args: text: The keyboard input to send.
Returns: The updated page observation. """ return self._do_action(f"send_keys({text!r})")
def scroll(self, direction: str) -> str: """Scroll the page.
Args: direction: Direction to scroll, either 'up' or 'down'.
Returns: The updated page observation. """ return self._do_action(f"scroll({direction!r})")
def noop(self) -> str: """Do nothing and observe the current page state.
Returns: The current page observation. """ return self._do_action("noop()")
def _do_action(self, action_str: str) -> str: if self._done: raise ValueError("Episode is done.")
self._step_count += 1 result = self.client.step(BrowserGymAction(action_str=action_str)) observation = result.observation step_reward = float(result.reward or 0.0) self._done = result.done
# Reward shaping: binary success/failure on completion if self._done and step_reward > 0: self.reward = 1.0 elif self._done: self.reward = 0.0 else: self.reward = step_reward
# Enforce max steps if self._step_count >= max_steps: self._done = True
return self._format_observation(observation)
def _format_observation(self, observation) -> str: parts = [] if observation.goal: parts.append(f"Goal: {observation.goal}") if observation.last_action_error and observation.error: parts.append(f"Error: {observation.error}") if observation.axtree_txt: axtree = observation.axtree_txt if len(axtree) > 2000: axtree = axtree[:2000] + "..." parts.append(f"Page structure:\n{axtree}") return "\n\n".join(parts) if parts else "No observation available."
timestamp = datetime.now().strftime("%Y-%m-%d_%H-%M-%S") default_output_dir = Path("outputs") / f"browsergym-grpo-{sanitize_name(args.model_id)}-{timestamp}" output_dir = Path(args.output_dir or default_output_dir)
grpo_config = GRPOConfig( use_vllm=True, vllm_mode=args.vllm_mode, vllm_server_base_url=args.vllm_server_url if args.vllm_mode == "server" else None, vllm_gpu_memory_utilization=0.4, output_dir=str(output_dir), num_train_epochs=args.num_epochs, learning_rate=args.learning_rate, weight_decay=args.weight_decay, gradient_accumulation_steps=args.gradient_accumulation_steps, per_device_train_batch_size=args.per_device_batch_size, warmup_steps=args.warmup_steps, num_generations=args.num_generations, generation_batch_size=args.num_generations, max_completion_length=args.max_completion_length, logging_steps=args.logging_steps, report_to="trackio", trackio_space_id=f"browsergym-grpo-{sanitize_name(args.model_id)}-{timestamp}", save_strategy="steps", save_steps=args.save_interval, save_total_limit=args.save_total_limit, temperature=args.temperature, top_k=args.top_k, top_p=args.top_p, chat_template_kwargs={"enable_thinking": False}, )
grpo_config.run_name = args.run_name or f"run-{timestamp}" grpo_config.project = args.project or f"group-{sanitize_name(args.model_id)}"
trainer = GRPOTrainer( model=args.model_id, reward_funcs=[reward_completion], train_dataset=dataset, args=grpo_config, environment_factory=BrowserGymLLMEnv, )
print("=" * 80) print("Starting GRPO training with BrowserGym environment (LLM mode)") print(f"Benchmark: {args.benchmark}") print(f"Task: {args.task_name}") print(f"Model: {args.model_id}") print("Mode: LLM (text-only, using accessibility tree)") print(f"Using {args.num_generations} rollouts per dataset prompt") print(f"Output directory: {output_dir}") print("=" * 80)
trainer.train()
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219# Copyright 2020-2026 The HuggingFace Team. All rights reserved.## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License.
# /// script# dependencies = [# "trl",# "openenv-carla-env @ git+https://huggingface.co/spaces/sergiopaniego/carla_env",# ]# ///
"""Simple script to run GRPO training with OpenEnv's CARLA environment. The environment simulates an emergencydriving scenario where pedestrians are ahead and the model must learn to observe the scene and take thecorrect action (e.g., swerve to an empty lane) to minimize casualties.
Setup (Option A - Install from HF Space, recommended):
```shuv pip install git+https://huggingface.co/spaces/sergiopaniego/carla_env```
Setup (Option B - Clone OpenEnv repo, for development):
```shgit clone https://github.com/huggingface/OpenEnv.gitcd OpenEnv/envs/carla_envuv pip install -e .```
Usage:
```shpython examples/scripts/openenv/carla.pypython examples/scripts/openenv/carla.py --model Qwen/Qwen3-1.7B --env-urls https://server1.hf.space https://server2.hf.space```"""
import argparse
from carla_env import CarlaAction, CarlaEnvfrom datasets import Dataset
from trl import GRPOConfig, GRPOTrainer
def parse_args(): parser = argparse.ArgumentParser(description="Run GRPO training with CARLA environment.") parser.add_argument( "--model", type=str, default="Qwen/Qwen3-0.6B", help="Model to use for training.", ) parser.add_argument( "--env-urls", type=str, nargs="+", default=["https://sergiopaniego-carla-env.hf.space"], help="URLs for the CARLA environment servers (one per environment instance).", ) parser.add_argument( "--trackio-space-id", type=str, default="carla-grpo-trolley", help="Trackio space identifier.", ) parser.add_argument( "--hub-model-id", type=str, default=None, help="Hub model ID to push the trained model to (e.g., sergiopaniego/Qwen3-0.6B-carla-trolley-escape).", ) parser.add_argument( "--run-name", type=str, default=None, help="Run name for tracking.", ) return parser.parse_args()
PROMPT = """You control an autonomous vehicle in an emergency. There are pedestrians ahead and you must \decide what to do immediately.
You have the following tools available:- `observe`: Advance time and get a new observation of the scene.- `emergency_stop`: Apply maximum braking to stop the vehicle.- `lane_change(direction)`: Change lane to the left or right. Direction must be "left" or "right".
Observe the scene first, then decide the best course of action to minimize harm."""
SIM_TICKS = 10 # Number of simulation steps to advance after each action
class CarlaGRPOEnv: _env_url_iter = None
def __init__(self): url = next(CarlaGRPOEnv._env_url_iter) self.client = CarlaEnv(base_url=url, connect_timeout_s=30, message_timeout_s=120)
@staticmethod def _describe(obs) -> str: """Build a text description from the observation fields.""" parts = [] parts.append(f"Speed: {obs.speed_kmh:.1f} km/h.") if obs.nearby_actors: for actor in obs.nearby_actors: parts.append(f"- {actor.get('type', 'actor')} at {actor.get('distance', '?')}m") else: parts.append("No nearby actors detected.") if obs.collision_detected: parts.append(f"COLLISION detected with {obs.collided_with or 'unknown'}!") return "\n".join(parts)
def _advance(self, ticks: int = SIM_TICKS): """Advance the simulation by calling observe repeatedly, return the last result.""" result = None for _ in range(ticks): result = self.client.step(CarlaAction(action_type="observe")) if result.done: break return result
def reset(self, **kwargs) -> str | None: result = self.client.reset(scenario_name="trolley_micro_escape_exists") self.reward = 0.0 return self._describe(result.observation)
def observe(self) -> str: """ Get the current scene description without taking any action.
Returns: The scene description with vehicle state and nearby actors. """ result = self._advance() self.reward = result.observation.rubric_reward or 0.0 return self._describe(result.observation)
def emergency_stop(self) -> str: """ Apply maximum braking to stop the vehicle.
Returns: The scene description after braking. """ self.client.step(CarlaAction(action_type="emergency_stop")) result = self._advance() self.reward = result.observation.rubric_reward or 0.0 return self._describe(result.observation)
def lane_change(self, direction: str) -> str: """ Change lane to avoid obstacles.
Args: direction: Direction to change lane, either "left" or "right".
Returns: The scene description after changing lane. """ self.client.step(CarlaAction(action_type="lane_change", lane_direction=direction)) result = self._advance() self.reward = result.observation.rubric_reward or 0.0 return self._describe(result.observation)
def reward_func(environments, **kwargs): return [environment.reward for environment in environments]
def main(): args = parse_args() CarlaGRPOEnv._env_url_iter = iter(args.env_urls)
dataset = Dataset.from_dict({"prompt": [[{"role": "user", "content": PROMPT}] for _ in range(1000)]})
trainer = GRPOTrainer( model=args.model, train_dataset=dataset, reward_funcs=reward_func, args=GRPOConfig( chat_template_kwargs={"enable_thinking": False}, log_completions=True, logging_steps=2, num_completions_to_print=1, max_completion_length=1024, per_device_train_batch_size=len(args.env_urls), steps_per_generation=1, num_generations=len(args.env_urls), gradient_accumulation_steps=16, max_steps=50, push_to_hub=args.hub_model_id is not None, hub_model_id=args.hub_model_id, run_name=args.run_name, report_to="trackio", trackio_space_id=args.trackio_space_id, ), environment_factory=CarlaGRPOEnv, ) trainer.train()
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262# Copyright 2020-2026 The HuggingFace Team. All rights reserved.## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License.
# /// script# dependencies = [# "trl",# "openenv-carla-env @ git+https://huggingface.co/spaces/sergiopaniego/carla_env",# ]# ///
"""GRPO training with OpenEnv's CARLA environment for VLMs (Vision Language Models).
VLM adaptation of `carla.py`: each tool call returns a camera image alongside the textscene description, so the model sees the driving scene after each action.
Setup:
```shuv pip install git+https://huggingface.co/spaces/sergiopaniego/carla_env```
Usage (requires at least 2 CARLA Spaces, each supports only 1 concurrent connection):
```shpython examples/scripts/openenv/carla_vlm.py \ --model Qwen/Qwen3.5-0.8B \ --env-urls https://server1.hf.space https://server2.hf.space```"""
import argparseimport base64from io import BytesIO
from carla_env import CarlaAction, CarlaEnvfrom datasets import Datasetfrom PIL import Image
from trl import GRPOConfig, GRPOTrainer
def parse_args(): parser = argparse.ArgumentParser(description="Run GRPO VLM training with CARLA environment.") parser.add_argument( "--model", type=str, default="Qwen/Qwen3.5-0.8B", help="Model to use for training.", ) parser.add_argument( "--env-urls", type=str, nargs="+", default=["https://sergiopaniego-carla-env.hf.space"], help="URLs for the CARLA environment servers (one per environment instance).", ) parser.add_argument( "--image-size", type=int, default=256, help="Resize camera images to this size. 0 to disable.", ) parser.add_argument( "--max-completion-length", type=int, default=1024, help="Maximum number of tokens in the generated completion.", ) parser.add_argument( "--gradient-accumulation-steps", type=int, default=16, help="Number of steps to accumulate gradients over before updating.", ) parser.add_argument( "--max-steps", type=int, default=50, help="Number of training steps to run.", ) parser.add_argument( "--trackio-space-id", type=str, default="carla-grpo-trolley-vlm", help="Trackio space identifier.", ) parser.add_argument( "--hub-model-id", type=str, default=None, help="Hub model ID to push the trained model to.", ) parser.add_argument( "--run-name", type=str, default=None, help="Run name for tracking.", ) return parser.parse_args()
PROMPT = """You control an autonomous vehicle in an emergency. There are pedestrians ahead and you must \decide what to do immediately.
You will see a camera image from the vehicle after each action. Use the visual informationalong with the scene description to decide your next action.
You have the following tools available:- `observe`: Advance time and get a new observation of the scene with a camera image.- `emergency_stop`: Apply maximum braking to stop the vehicle.- `lane_change(direction)`: Change lane to the left or right. Direction must be "left" or "right".
Observe the scene first, then decide the best course of action to minimize harm."""
SIM_TICKS = 10 # Number of simulation steps to advance after each action
class CarlaGRPOEnv: _env_url_iter = None _image_size = 256
def __init__(self): url = next(CarlaGRPOEnv._env_url_iter) self.client = CarlaEnv(base_url=url, connect_timeout_s=30, message_timeout_s=120)
@staticmethod def _describe(obs) -> str: """Build a text description from the observation fields.""" parts = [f"Speed: {obs.speed_kmh:.1f} km/h."] if obs.nearby_actors: for actor in obs.nearby_actors: parts.append(f"- {actor.get('type', 'actor')} at {actor.get('distance', '?')}m") else: parts.append("No nearby actors detected.") if obs.collision_detected: parts.append(f"COLLISION detected with {obs.collided_with or 'unknown'}!") return "\n".join(parts)
@staticmethod def _decode_image(camera_image_b64, target_size): """Decode base64 JPEG image and optionally resize.""" img = Image.open(BytesIO(base64.b64decode(camera_image_b64))) if target_size > 0: img.thumbnail((target_size, target_size), Image.LANCZOS) return img
def _format_multimodal(self, obs) -> list: """Format observation as multimodal content blocks (camera image + text).""" content = [] if obs.camera_image is not None: content.append({"type": "image", "image": self._decode_image(obs.camera_image, CarlaGRPOEnv._image_size)}) content.append({"type": "text", "text": self._describe(obs)}) return content
def _advance_and_capture(self, ticks: int = SIM_TICKS): """Advance the simulation, then capture an image of the current state.""" result = None for _ in range(ticks): result = self.client.step(CarlaAction(action_type="observe")) if result.done: break capture_result = self.client.step(CarlaAction(action_type="capture_image")) result.observation.camera_image = capture_result.observation.camera_image return result
def reset(self, **kwargs) -> str | None: result = self.client.reset(scenario_name="trolley_micro_escape_exists") self.reward = 0.0 return self._describe(result.observation)
def observe(self) -> list: """ Get the current scene with a camera image and description.
Returns: The camera image and scene description with vehicle state and nearby actors. """ result = self._advance_and_capture() self.reward = result.observation.rubric_reward or 0.0 return self._format_multimodal(result.observation)
def emergency_stop(self) -> list: """ Apply maximum braking to stop the vehicle.
Returns: The camera image and scene description after braking. """ self.client.step(CarlaAction(action_type="emergency_stop")) result = self._advance_and_capture() self.reward = result.observation.rubric_reward or 0.0 return self._format_multimodal(result.observation)
def lane_change(self, direction: str) -> list: """ Change lane to avoid obstacles.
Args: direction: Direction to change lane, either "left" or "right".
Returns: The camera image and scene description after changing lane. """ self.client.step(CarlaAction(action_type="lane_change", lane_direction=direction)) result = self._advance_and_capture() self.reward = result.observation.rubric_reward or 0.0 return self._format_multimodal(result.observation)
def reward_func(environments, **kwargs): return [environment.reward for environment in environments]
def main(): args = parse_args() CarlaGRPOEnv._env_url_iter = iter(args.env_urls) CarlaGRPOEnv._image_size = args.image_size
dataset = Dataset.from_dict({"prompt": [[{"role": "user", "content": PROMPT}] for _ in range(1000)]})
trainer = GRPOTrainer( model=args.model, train_dataset=dataset, reward_funcs=reward_func, args=GRPOConfig( chat_template_kwargs={"enable_thinking": False}, log_completions=True, logging_steps=2, num_completions_to_print=1, max_completion_length=args.max_completion_length, per_device_train_batch_size=len(args.env_urls), steps_per_generation=1, num_generations=len(args.env_urls), gradient_accumulation_steps=args.gradient_accumulation_steps, max_steps=args.max_steps, push_to_hub=args.hub_model_id is not None, hub_model_id=args.hub_model_id, run_name=args.run_name, report_to="trackio", trackio_space_id=args.trackio_space_id, ), environment_factory=CarlaGRPOEnv, ) trainer.train()
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278# Copyright 2020-2026 The HuggingFace Team. All rights reserved.## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License.
# /// script# dependencies = [# "trl",# "openenv-carla-env @ git+https://huggingface.co/spaces/sergiopaniego/carla_env",# ]# ///
"""GRPO training with OpenEnv's CARLA environment for Gemma VLMs.
Gemma-specific variant of `carla_vlm.py` with LoRA support (memory-efficient trainingby excluding the vision encoder from adapter targets) and a tuned learning rate.
Setup:
```shuv pip install git+https://huggingface.co/spaces/sergiopaniego/carla_env```
Usage (requires at least 2 CARLA Spaces, each supports only 1 concurrent connection):
```shpython examples/scripts/openenv/carla_vlm_gemma.py \ --env-urls https://server1.hf.space https://server2.hf.space \ --use-lora```"""
import argparseimport base64from io import BytesIO
from carla_env import CarlaAction, CarlaEnvfrom datasets import Datasetfrom PIL import Image
from trl import GRPOConfig, GRPOTrainer
def parse_args(): parser = argparse.ArgumentParser(description="Run GRPO VLM training with CARLA environment.") parser.add_argument("--model", type=str, default="google/gemma-4-E2B-it") parser.add_argument( "--env-urls", type=str, nargs="+", required=True, help="URLs for CARLA environment servers. At least 2 required (1 Space = 1 connection).", ) parser.add_argument("--dataset-size", type=int, default=1000) parser.add_argument("--max-completion-length", type=int, default=3072) parser.add_argument("--per-device-train-batch-size", type=int, default=None, help="Defaults to len(env-urls).") parser.add_argument("--gradient-accumulation-steps", type=int, default=16) parser.add_argument("--max-steps", type=int, default=100) parser.add_argument("--image-size", type=int, default=256, help="Resize camera images to this size. 0 to disable.") parser.add_argument("--trackio-space-id", type=str, default=None, help="Trackio Space ID for logging.") parser.add_argument("--use-lora", action="store_true", help="Use LoRA for memory-efficient training.") parser.add_argument("--lora-r", type=int, default=128, help="LoRA rank.") parser.add_argument("--lora-alpha", type=int, default=256, help="LoRA alpha.") parser.add_argument( "--lora-target-modules", type=str, default="llm-only", help="LoRA target modules. Use 'llm-only' to skip vision encoder, 'all-linear' for all.", ) parser.add_argument( "--learning-rate", type=float, default=5e-6, help="Learning rate. Default 5e-6 (good for LoRA r=128)." ) parser.add_argument("--hub-model-id", type=str, default=None) parser.add_argument("--run-name", type=str, default=None) parser.add_argument("--report-to", type=str, default="trackio", help="Logging backend: wandb, trackio, none.") return parser.parse_args()
PROMPT = """\You control an autonomous vehicle in an emergency. There are pedestrians ahead and you must \decide what to do immediately.
You will see a camera image from the vehicle after each action. Use the visual informationalong with the scene description to decide your next action.
You have the following tools available:- `observe`: Advance time and get a new observation of the scene with a camera image.- `emergency_stop`: Apply maximum braking to stop the vehicle.- `lane_change(direction)`: Change lane to the left or right. Direction must be "left" or "right".
Make one tool call at a time, wait for the result, then decide your next action.Observe the scene first, then decide the best course of action to minimize harm.Consider all available actions - sometimes avoiding the obstacle by changing lanes \is safer than stopping in its path."""
SIM_TICKS = 10 # Number of simulation steps to advance after each action
class CarlaVLMEnv: _env_url_iter = None _image_size = 256
def __init__(self): self.url = next(CarlaVLMEnv._env_url_iter) self.client = CarlaEnv(base_url=self.url, connect_timeout_s=30, message_timeout_s=120) self.reward = 0.0
@staticmethod def _describe(obs) -> str: parts = [f"Speed: {obs.speed_kmh:.1f} km/h."] if obs.nearby_actors: for actor in obs.nearby_actors: parts.append(f"- {actor.get('type', 'actor')} at {actor.get('distance', '?')}m") else: parts.append("No nearby actors detected.") if obs.collision_detected: parts.append(f"COLLISION detected with {obs.collided_with or 'unknown'}!") return "\n".join(parts)
@staticmethod def _decode_image(camera_image_b64, target_size): """Decode base64 JPEG image and optionally resize.""" img = Image.open(BytesIO(base64.b64decode(camera_image_b64))) if target_size > 0: img.thumbnail((target_size, target_size), Image.LANCZOS) return img
def _format_multimodal(self, obs) -> list: """Format observation as multimodal content blocks (camera image + text).""" content = [] if obs.camera_image is not None: content.append({"type": "image", "image": self._decode_image(obs.camera_image, CarlaVLMEnv._image_size)}) content.append({"type": "text", "text": self._describe(obs)}) return content
def _advance_and_capture(self, ticks: int = SIM_TICKS): """Advance the simulation, then capture an image of the current state.""" result = None for _ in range(ticks): result = self.client.step(CarlaAction(action_type="observe")) if result.done: break capture_result = self.client.step(CarlaAction(action_type="capture_image")) result.observation.camera_image = capture_result.observation.camera_image return result
def reset(self, **kwargs) -> str | None: for attempt in range(3): try: result = self.client.reset(scenario_name="trolley_micro_escape_exists") self.reward = 0.0 return self._describe(result.observation) except Exception as e: if attempt == 2: raise print(f"[WARN] reset failed (attempt {attempt + 1}/3): {e}. Reconnecting...") self.client = CarlaEnv(base_url=self.url, connect_timeout_s=30, message_timeout_s=120)
def observe(self) -> list: """ Get the current scene with a camera image and description.
Returns: The camera image and scene description with vehicle state and nearby actors. """ result = self._advance_and_capture() self.reward = result.observation.rubric_reward or 0.0 return self._format_multimodal(result.observation)
def emergency_stop(self) -> list: """ Apply maximum braking to stop the vehicle.
Returns: The camera image and scene description after braking. """ self.client.step(CarlaAction(action_type="emergency_stop")) result = self._advance_and_capture() self.reward = result.observation.rubric_reward or 0.0 print(f"[DEBUG env] emergency_stop: done={result.done}, reward={self.reward}") return self._format_multimodal(result.observation)
def lane_change(self, direction: str) -> list: """ Change lane to avoid obstacles.
Args: direction: Direction to change lane, either "left" or "right".
Returns: The camera image and scene description after changing lane. """ self.client.step(CarlaAction(action_type="lane_change", lane_direction=direction)) result = self._advance_and_capture() self.reward = result.observation.rubric_reward or 0.0 print(f"[DEBUG env] lane_change({direction}): done={result.done}, reward={self.reward}") return self._format_multimodal(result.observation)
def reward_func(completions, environments, **kwargs): rewards = [env.reward for env in environments] for i, (comp, env) in enumerate(zip(completions, environments, strict=False)): tools = [ msg["tool_calls"][0]["function"]["name"] for msg in comp if isinstance(msg, dict) and msg.get("tool_calls") ] print(f"[DEBUG reward] gen={i} tools={tools} env_reward={env.reward}") return rewards
def main(): args = parse_args() CarlaVLMEnv._env_url_iter = iter(args.env_urls) CarlaVLMEnv._image_size = args.image_size
dataset = Dataset.from_dict({"prompt": [[{"role": "user", "content": PROMPT}] for _ in range(args.dataset_size)]})
peft_config = None if args.use_lora: from peft import LoraConfig
if args.lora_target_modules == "llm-only": target_modules = "all-linear" exclude_modules = ["vision_tower", "multi_modal_projector"] else: target_modules = args.lora_target_modules exclude_modules = None
peft_config = LoraConfig( r=args.lora_r, lora_alpha=args.lora_alpha, target_modules=target_modules, exclude_modules=exclude_modules, task_type="CAUSAL_LM", )
trainer = GRPOTrainer( model=args.model, train_dataset=dataset, reward_funcs=reward_func, peft_config=peft_config, args=GRPOConfig( chat_template_kwargs={"enable_thinking": False}, log_completions=True, logging_steps=2, num_completions_to_print=1, max_completion_length=args.max_completion_length, per_device_train_batch_size=args.per_device_train_batch_size or len(args.env_urls), steps_per_generation=1, num_generations=len(args.env_urls), max_tool_calling_iterations=10, learning_rate=args.learning_rate, gradient_accumulation_steps=args.gradient_accumulation_steps, max_steps=args.max_steps, push_to_hub=args.hub_model_id is not None, hub_model_id=args.hub_model_id, run_name=args.run_name, report_to=args.report_to, trackio_space_id=args.trackio_space_id, ), environment_factory=CarlaVLMEnv, ) trainer.train()
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347# Copyright 2020-2026 The HuggingFace Team. All rights reserved.## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License.
# /// script# dependencies = [# "trl[vllm,peft]",# "trackio",# "kernels",# "openenv-openspiel-env @ git+https://huggingface.co/spaces/openenv/openspiel_env",# ]# ///
"""Simple script to run GRPO training with OpenEnv's Catch environment (OpenSpiel) and vLLM. The reward functionis based on the catch game where the agent tries to catch falling balls.
Setup (Option A - Install from HF Space, recommended):
```shuv pip install git+https://huggingface.co/spaces/openenv/openspiel_env```
Setup (Option B - Clone OpenEnv repo, for development):
```shgit clone https://github.com/huggingface/OpenEnv.gitcd OpenEnv/envs/openspiel_envuv pip install -e .```
# Option 1: HF Spaces + Colocated vLLM (1 GPU required)```shpython examples/scripts/openenv/catch.py --env-mode space --env-host https://openenv-openspiel-env.hf.space --vllm-mode colocate```
# Option 2: HF Spaces + Separate vLLM server (2 GPUs required)
# Spin up vLLM server (Terminal 1)```shCUDA_VISIBLE_DEVICES=0 trl vllm-serve --model Qwen/Qwen2.5-0.5B-Instruct --host 0.0.0.0 --port 8000```
# Run training (Terminal 2)```shCUDA_VISIBLE_DEVICES=1 python examples/scripts/openenv/catch.py --env-mode space --env-host https://openenv-openspiel-env.hf.space --vllm-mode server --vllm-server-url http://localhost:8000```
# Option 3: Local + Colocated vLLM (1 GPU required)
# Start the environment only if using --env-mode docker-local```shdocker run -d -p 8001:8001 registry.hf.space/openenv-openspiel-env:latest```
```shpython examples/scripts/openenv/catch.py --env-mode docker-local --vllm-mode colocate```"""
# ruff: noqa: T201import argparseimport osimport subprocessimport sysimport timefrom pathlib import Path
import requestsfrom datasets import Datasetfrom openspiel_env import OpenSpielEnvfrom openspiel_env.models import OpenSpielAction
from trl import GRPOConfig, GRPOTrainer, RichProgressCallback
def parse_args(): parser = argparse.ArgumentParser(description="Run GRPO training with OpenSpiel Catch environment and vLLM.")
# --- Environment settings --- parser.add_argument("--env-host", type=str, default="0.0.0.0", help="Host for the environment server.") parser.add_argument("--env-port", type=int, default=8001, help="Port for the environment server.") parser.add_argument( "--env-mode", choices=["local", "docker-local", "docker-image", "docker-hub", "space"], default="docker-image", help="Where to run the environment: 'local' to launch it, 'docker-local' if already running locally, 'docker-image' to run from a Docker image, 'docker-hub' to run from Docker Hub, or 'space' to use a remote Space URL.", ) # --- Generation and model config --- parser.add_argument( "--model", type=str, default="Qwen/Qwen2.5-0.5B-Instruct", help="Model name or path.", ) parser.add_argument( "--dataset-size", type=int, default=1000, help="Number of prompts to use for training dataset.", ) parser.add_argument( "--env-image", type=str, default="openspiel-env:latest", help="Docker image for the OpenSpiel environment." ) parser.add_argument( "--vllm-mode", choices=["colocate", "server"], default="colocate", help="vLLM execution mode: 'colocate' or 'server'.", ) parser.add_argument( "--vllm-server-url", type=str, default="http://localhost:8000", help="URL for the vLLM server (only used when --vllm-mode=server).", )
return parser.parse_args()
def start_env_server(env_host: str, env_port: int): """Launch the OpenSpiel Catch environment locally via uvicorn.""" env_url = f"http://{env_host}:{env_port}" print(f"⚡ Starting FastAPI server for OpenSpiel Catch Environment on {env_url}...")
work_dir = str(Path.cwd().parent.absolute()) process = subprocess.Popen( [ sys.executable, "-m", "uvicorn", "envs.openspiel_env.server.app:app", "--host", env_host, "--port", str(env_port), ], env={**os.environ, "PYTHONPATH": f"{work_dir}/src"}, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, cwd=work_dir, )
print("⏳ Waiting for server to start...") time.sleep(5)
try: requests.get(f"{env_url}/health", timeout=2) print("\n✅ OpenSpiel Catch Environment server is running!") except Exception as e: print(f"\n❌ Server failed to start: {e}") if process.stderr: print(process.stderr.read()) raise
return process
BASE_PROMPT = """You are an AI agent playing the game **Catch**.
### Game Description- The game is played on a **10×5 grid**.- There is one **falling ball** and one **paddle** that you control at the bottom.- The objective is to **move the paddle left or right to catch the ball** as it falls.- The episode ends when the ball reaches the bottom row: - You get **+1 reward** if you catch it. - You get **–1 reward** if you miss it.
### Observation FormatEach observation is a flattened 10x5 grid (list of 50 floats).- 1.0 → occupied (ball or paddle)- 0.0 → empty cell
You have the following tools available:- `move(direction)`: Move the paddle left or right. Direction must be "left" or "right".- `stay`: Do nothing and let the ball fall one step.
Observe the grid, determine where the ball is relative to the paddle, then move accordingly."""
def reward_from_env(environments, **kwargs): rewards = [] for env in environments: if env.done: # Catch gives +1 for catching, -1 for missing. Clamp to [0, 1] for GRPO advantage estimation. rewards.append(max(env.reward, 0.0)) else: rewards.append(0.0) # Incomplete episode return rewards
def main(): args = parse_args()
# Select environment mode — all modes resolve to env_url if args.env_mode == "local": env_url = f"http://{args.env_host}:{args.env_port}" server_process = start_env_server(args.env_host, args.env_port) elif args.env_mode == "docker-local": env_url = f"http://{args.env_host}:{args.env_port}" server_process = None print(f"🌍 Using existing OpenSpiel Environment (Docker) at: {env_url}") elif args.env_mode == "docker-image": _bootstrap = OpenSpielEnv.from_docker_image(args.env_image) env_url = _bootstrap.base_url server_process = None print("🌍 Using OpenSpiel Environment (Docker) from local Image") elif args.env_mode == "docker-hub": _bootstrap = OpenSpielEnv.from_hub(args.env_image) env_url = _bootstrap.base_url server_process = None print("🌍 Using existing OpenSpiel Environment (Docker) from Hub Image") elif args.env_mode == "space": env_url = args.env_host server_process = None print(f"🌍 Using Hugging Face Space environment at: {env_url}") else: raise ValueError(f"Unknown environment mode: {args.env_mode}")
dataset = Dataset.from_dict({"prompt": [[{"role": "user", "content": BASE_PROMPT}]] * args.dataset_size})
class CatchEnv: ROWS = 10 COLS = 5
def __init__(self): self.client = OpenSpielEnv(base_url=env_url) self.reward = 0.0 self.done = False
@staticmethod def _format_obs(info_state: list[float]) -> str: """Convert the flat 50-float observation into a readable text description.""" rows, cols = CatchEnv.ROWS, CatchEnv.COLS ball_row = ball_col = paddle_col = None for idx, val in enumerate(info_state): if val == 1.0: r, c = divmod(idx, cols) if r < rows - 1: ball_row, ball_col = r + 1, c + 1 else: paddle_col = c + 1 parts = [] if ball_row is not None and ball_col is not None: parts.append(f"Ball: row {ball_row}/{rows}, column {ball_col}/{cols}") if paddle_col is not None: parts.append(f"Paddle: column {paddle_col}/{cols}") if ball_col is not None and paddle_col is not None: diff = ball_col - paddle_col if diff < 0: parts.append(f"The ball is {abs(diff)} column(s) to the LEFT of the paddle.") elif diff > 0: parts.append(f"The ball is {diff} column(s) to the RIGHT of the paddle.") else: parts.append("The ball is directly above the paddle.") return "\n".join(parts)
def reset(self, **kwargs) -> str: env_result = self.client.reset() self.reward = 0.0 self.done = env_result.observation.done return self._format_obs(env_result.observation.info_state)
def _do_action(self, action_id: int) -> str: if self.done: raise ValueError("Episode is done.") env_result = self.client.step(OpenSpielAction(action_id=action_id, game_name="catch")) self.reward = env_result.reward or 0.0 self.done = env_result.observation.done return self._format_obs(env_result.observation.info_state)
def move(self, direction: str) -> str: """Move the paddle left or right.
Args: direction: Direction to move, either "left" or "right".
Returns: The observation after moving. """ if direction == "left": action_id = 0 elif direction == "right": action_id = 2 else: raise ValueError(f"Invalid direction {direction!r}: must be 'left' or 'right'.") return self._do_action(action_id)
def stay(self) -> str: """Do nothing and let the ball fall one step.
Returns: The observation after staying. """ return self._do_action(1)
training_args = GRPOConfig( output_dir=f"{args.model.split('/')[-1]}-GRPO-Catch", use_vllm=True, vllm_mode=args.vllm_mode, vllm_server_base_url=args.vllm_server_url if args.vllm_mode == "server" else None, vllm_gpu_memory_utilization=0.2, logging_steps=1, log_completions=True, report_to="trackio", trackio_space_id=f"{args.model.split('/')[-1]}-GRPO-Catch", num_train_epochs=1, per_device_train_batch_size=2, num_generations=8, max_completion_length=4096, gradient_accumulation_steps=16, chat_template_kwargs={"enable_thinking": False}, )
trainer = GRPOTrainer( model=args.model, reward_funcs=reward_from_env, args=training_args, train_dataset=dataset, environment_factory=CatchEnv, callbacks=[RichProgressCallback()], )
try: trainer.train() finally: if server_process: print("🛑 Terminating environment server...") server_process.terminate() server_process.wait()
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133# Copyright 2020-2026 The HuggingFace Team. All rights reserved.## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License.
# /// script# dependencies = [# "trl",# "openenv-echo-env @ git+https://huggingface.co/spaces/qgallouedec/echo_env",# ]# ///
"""Simple script to run GRPO training with OpenEnv's Echo environment. The environment echoes back the messagesent to it and rewards longer completions.
Setup (Option A - Install from HF Space, recommended):
```shuv pip install git+https://huggingface.co/spaces/qgallouedec/echo_env```
Setup (Option B - Clone OpenEnv repo, for development):
```shgit clone https://github.com/huggingface/OpenEnv.gitcd OpenEnv/envs/echo_envuv pip install -e .```
Usage:
```shpython examples/scripts/openenv/echo.pypython examples/scripts/openenv/echo.py --model Qwen/Qwen2.5-0.5B-Instruct --env-host https://qgallouedec-echo-env.hf.space```"""
import argparse
from datasets import Datasetfrom echo_env import EchoEnvfrom echo_env.models import EchoAction
from trl import GRPOConfig, GRPOTrainer
def parse_args(): parser = argparse.ArgumentParser(description="Run GRPO training with Echo environment.") parser.add_argument( "--model", type=str, default="Qwen/Qwen3-0.6B", help="Model to use for training.", ) parser.add_argument( "--env-host", type=str, default="https://qgallouedec-echo-env.hf.space", help="URL for the Echo environment HF Space.", ) return parser.parse_args()
def reward_func(environments, **kwargs): return [env.reward for env in environments]
def main(): args = parse_args()
dataset = Dataset.from_dict( { "prompt": [ [{"role": "user", "content": "Try to echo 'Hello World!' in the environment."}], [{"role": "user", "content": "Make the environment echo 'Goodbye World!'"}], [{"role": "user", "content": "Can you ask the environment to echo 'TRL is great!'?"}], [{"role": "user", "content": "What happens if you ask the environment to echo 'I love RLHF!'?"}], [{"role": "user", "content": "Try to make the environment echo 'OpenEnv is awesome!'"}], ], } )
class EchoToolEnv: def __init__(self): self.env = EchoEnv(base_url=args.env_host) self.reward = 0.0
def reset(self, **kwargs) -> None | str: self.reward = 0.0 return None
def echo(self, message: str) -> str: """ Echo the message back from the environment.
Args: message: The message to echo
Returns: The echoed message. """ observation = self.env.step(EchoAction(message=message)) self.reward = observation.observation.reward return observation.observation.echoed_message
trainer = GRPOTrainer( model=args.model, train_dataset=dataset, reward_funcs=reward_func, args=GRPOConfig( chat_template_kwargs={"enable_thinking": False}, log_completions=True, logging_steps=2, num_completions_to_print=1, ), environment_factory=EchoToolEnv, ) trainer.train()
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273# Copyright 2020-2026 The HuggingFace Team. All rights reserved.## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License.
# /// script# dependencies = [# "trl",# "trackio",# "openenv-textarena @ git+https://huggingface.co/spaces/openenv/wordle",# "openenv-openspiel-env @ git+https://huggingface.co/spaces/openenv/openspiel_env",# ]# ///
"""Multi-environment GRPO training with OpenEnv: Wordle + Catch in the same training run.
Demonstrates how to wrap multiple environments in a single `environment_factory` class. The datasetcontains an "env" column that routes each sample to the correct environment at `reset()` time.
Usage: python examples/scripts/openenv/multi_env.py \\ --wordle-url https://openenv-wordle.hf.space \\ --catch-url https://openenv-openspiel-env.hf.space"""
import argparse
from datasets import Datasetfrom openspiel_env import OpenSpielEnvfrom openspiel_env.models import OpenSpielActionfrom textarena_env import TextArenaAction, TextArenaEnv
from trl import GRPOConfig, GRPOTrainer
wordle_prompt = """You are an expert Wordle solver with deep knowledge of English vocabulary, letter frequency patterns, and optimal guessing strategies.
Follow these rules to play Wordle:
1. The target is a 5-letter English word2. You have 6 attempts to guess the correct word3. After each guess, you receive color-coded feedback: - GREEN (G): Letter is correct and in the correct position - YELLOW (Y): Letter is in the word but in the wrong position - GRAY (X): Letter is not in the word at all4. All guesses must be valid 5-letter English words5. You cannot reuse a word you've already guessed6. Use the tool `guess` to make a guess."""
catch_prompt = """You are an AI agent playing the game **Catch**.
### Game Description- The game is played on a **10×5 grid**.- There is one **falling ball** and one **paddle** that you control at the bottom.- The objective is to **move the paddle left or right to catch the ball** as it falls.- The episode ends when the ball reaches the bottom row: - You get **+1 reward** if you catch it. - You get **–1 reward** if you miss it.
### Observation FormatEach observation is a flattened 10x5 grid (list of 50 floats).- 1.0 → occupied (ball or paddle)- 0.0 → empty cell
You have the following tools available:- `move(direction)`: Move the paddle left or right. Direction must be "left" or "right".- `stay`: Do nothing and let the ball fall one step.
Observe the grid, determine where the ball is relative to the paddle, then move accordingly."""
DEFAULT_WORDLE_URL = "https://openenv-wordle.hf.space"DEFAULT_CATCH_URL = "https://openenv-openspiel-env.hf.space"
CATCH_ROWS = 10CATCH_COLS = 5
def _format_catch_obs(info_state: list[float]) -> str: """Convert the flat 50-float observation into a readable text description.""" ball_row = ball_col = paddle_col = None for idx, val in enumerate(info_state): if val == 1.0: r, c = divmod(idx, CATCH_COLS) if r < CATCH_ROWS - 1: ball_row, ball_col = r + 1, c + 1 else: paddle_col = c + 1 parts = [] if ball_row is not None and ball_col is not None: parts.append(f"Ball: row {ball_row}/{CATCH_ROWS}, column {ball_col}/{CATCH_COLS}") if paddle_col is not None: parts.append(f"Paddle: column {paddle_col}/{CATCH_COLS}") if ball_col is not None and paddle_col is not None: diff = ball_col - paddle_col if diff < 0: parts.append(f"The ball is {abs(diff)} column(s) to the LEFT of the paddle.") elif diff > 0: parts.append(f"The ball is {diff} column(s) to the RIGHT of the paddle.") else: parts.append("The ball is directly above the paddle.") return "\n".join(parts)
class MultiEnv: wordle_url = DEFAULT_WORDLE_URL catch_url = DEFAULT_CATCH_URL
def __init__(self): self._wordle_client = None self._catch_client = None self.active = None self.reward = 0.0 self.done = False
def reset(self, **kwargs) -> str | None: self.active = kwargs.get("env", "wordle") self.reward = 0.0 self.done = False
if self.active == "wordle": if self._wordle_client is not None: try: self._wordle_client.close() except Exception: pass self._wordle_client = TextArenaEnv(base_url=MultiEnv.wordle_url) result = self._wordle_client.reset() self._last_full_feedback = result.observation.messages[0].content self.reward = 0.0 return self._last_full_feedback elif self.active == "catch": if self._catch_client is not None: try: self._catch_client.close() except Exception: pass self._catch_client = OpenSpielEnv(base_url=MultiEnv.catch_url) result = self._catch_client.reset() self.done = result.observation.done return _format_catch_obs(result.observation.info_state) else: raise ValueError(f"Unknown environment: {self.active}")
def guess(self, guess: str) -> str: """ Make a guess in the Wordle environment.
Args: guess: The guessed word, formatted as '[abcde]'
Returns: The feedback message from the environment. """ if self.active != "wordle": raise ValueError("guess is only available in Wordle") if self.done: raise ValueError("Game over.") result = self._wordle_client.step(TextArenaAction(message=guess)) _full_feedback = result.observation.messages[0].content feedback = _full_feedback[len(self._last_full_feedback) :] self._last_full_feedback = _full_feedback if "You attempted an invalid move" in feedback: self.reward = 0.0 else: self.reward = result.reward self.done = result.done return feedback
def _catch_action(self, action_id: int) -> str: if self.done: raise ValueError("Episode is done.") result = self._catch_client.step(OpenSpielAction(action_id=action_id, game_name="catch")) self.reward = result.reward or 0.0 self.done = result.observation.done return _format_catch_obs(result.observation.info_state)
def move(self, direction: str) -> str: """Move the paddle left or right.
Args: direction: Direction to move, either "left" or "right".
Returns: The observation after moving. """ if self.active != "catch": raise ValueError("move is only available in Catch") if direction == "left": action_id = 0 elif direction == "right": action_id = 2 else: raise ValueError(f"Invalid direction {direction!r}: must be 'left' or 'right'.") return self._catch_action(action_id)
def stay(self) -> str: """Do nothing and let the ball fall one step.
Returns: The observation after staying. """ if self.active != "catch": raise ValueError("stay is only available in Catch") return self._catch_action(1)
def wordle_reward(environments, **kwargs) -> list[float | None]: return [env.reward if env.active == "wordle" else None for env in environments]
def catch_reward(environments, **kwargs) -> list[float | None]: rewards = [] for env in environments: if env.active != "catch": rewards.append(None) elif env.done: # Catch gives +1 for catching, -1 for missing. Clamp to [0, 1] for GRPO advantage estimation. rewards.append(max(env.reward, 0.0)) else: rewards.append(0.0) # Incomplete episode return rewards
def main() -> None: parser = argparse.ArgumentParser(description="Multi-environment GRPO training") parser.add_argument("--wordle-url", default=DEFAULT_WORDLE_URL, help="Wordle environment URL") parser.add_argument("--catch-url", default=DEFAULT_CATCH_URL, help="Catch environment URL") args, remaining = parser.parse_known_args()
MultiEnv.wordle_url = args.wordle_url MultiEnv.catch_url = args.catch_url
n = 500 # samples per environment dataset = Dataset.from_dict( { "prompt": ( [[{"role": "user", "content": wordle_prompt}]] * n + [[{"role": "user", "content": catch_prompt}]] * n ), "env": ["wordle"] * n + ["catch"] * n, } )
trainer = GRPOTrainer( model="Qwen/Qwen3-1.7B", reward_funcs=[wordle_reward, catch_reward], train_dataset=dataset, args=GRPOConfig( report_to="wandb", log_completions=True, num_completions_to_print=2, logging_steps=1, chat_template_kwargs={"enable_thinking": False}, max_completion_length=1024, ), environment_factory=MultiEnv, ) trainer.train()
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669# Copyright 2020-2026 The HuggingFace Team. All rights reserved.## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License.
# /// script# dependencies = [# "trl[vllm,peft]",# "trackio",# "kernels",# "openenv-textarena @ git+https://huggingface.co/spaces/openenv/sudoku",# ]# ///
"""GRPO training for Sudoku with TextArena environment.
Setup (Option A - Install from HF Space, recommended):
```shuv pip install git+https://huggingface.co/spaces/openenv/sudoku```
Setup (Option B - Clone OpenEnv repo, for development):
```shgit clone https://github.com/huggingface/OpenEnv.gitcd OpenEnv/envs/textarena_envuv pip install -e .```
# Option 1: HF Spaces + Colocated vLLM (1 GPU required)```shpython examples/scripts/openenv/sudoku.py --vllm-mode colocate```
# Option 2: HF Spaces + Separate vLLM server (2 GPUs required)
# Spin up vLLM server (Terminal 1)```shCUDA_VISIBLE_DEVICES=0 trl vllm-serve --model Qwen/Qwen3-1.7B --host 0.0.0.0 --port 8000```
# Run training (Terminal 2)```shCUDA_VISIBLE_DEVICES=1 python examples/scripts/openenv/sudoku.py --vllm-mode server --vllm-server-url http://localhost:8000```
# Option 3: Local + Colocated vLLM (1 GPU required)
# Start the environment only if using --env-mode docker-local```shdocker run -d -p 8001:8001 registry.hf.space/openenv-sudoku:latest```
```shpython examples/scripts/openenv/sudoku.py --env-mode docker-local --vllm-mode colocate```
# Full example with all flags:```shpython examples/scripts/openenv/sudoku.py \ --vllm-mode colocate \ --env-mode space \ --env-host https://openenv-sudoku.hf.space \ --num-generations 8 \ --per-device-batch-size 1 \ --max-turns 100 \ --gradient-accumulation-steps 8 \ --difficulty easy \ --dataset-size 100```"""
from __future__ import annotations
# ruff: noqa: T201import argparseimport sysimport timefrom collections import defaultdictfrom datetime import datetimefrom pathlib import Path
from datasets import Dataset
from trl import GRPOConfig, GRPOTrainer, RichProgressCallback
# Ensure src/ is on the pathsys.path.insert(0, str(Path(__file__).parent / "src"))
from textarena_env import TextArenaAction, TextArenaEnv
# ---------------------------------------------------------------------------# Argument parsing# ---------------------------------------------------------------------------
def parse_args() -> argparse.Namespace: parser = argparse.ArgumentParser(description="GRPO training for Sudoku")
# Model parser.add_argument("--model-id", default="Qwen/Qwen3-1.7B")
# Environment parser.add_argument("--env-host", type=str, default="https://openenv-sudoku.hf.space") parser.add_argument("--env-port", type=int, default=8001) parser.add_argument("--env-mode", choices=["docker-local", "docker-image", "docker-hub", "space"], default="space") parser.add_argument("--env-image", type=str, default="textarena-env:latest")
# Prompts parser.add_argument("--system-prompt-path", default="sudoku_prompt.txt") parser.add_argument("--dataset-prompt", default="Play Sudoku like an expert.") parser.add_argument("--dataset-size", type=int, default=1000)
# Game settings parser.add_argument("--max-turns", type=int, default=100) parser.add_argument( "--difficulty", type=str, choices=["easy", "medium", "hard"], default="easy", help="Training difficulty: easy=guaranteed+options, medium=only options, hard=no hints", ) parser.add_argument( "--api-delay", type=float, default=0.0, help="Delay in seconds between API calls to avoid rate limiting" )
# Sampling parser.add_argument("--temperature", type=float, default=0.8) parser.add_argument("--top-k", type=int, default=10) parser.add_argument("--top-p", type=float, default=None, help="Top-p sampling parameter")
# Training parser.add_argument("--learning-rate", type=float, default=5e-6) parser.add_argument("--weight-decay", type=float, default=0.0) parser.add_argument("--gradient-accumulation-steps", type=int, default=64) parser.add_argument("--warmup-steps", type=int, default=20) parser.add_argument("--per-device-batch-size", type=int, default=1) parser.add_argument("--num-generations", type=int, default=8) parser.add_argument("--num-epochs", type=int, default=1) parser.add_argument("--max-completion-length", type=int, default=16384)
# Checkpoints parser.add_argument("--save-interval", type=int, default=10) parser.add_argument("--save-total-limit", type=int, default=None) parser.add_argument("--output-dir", default=None)
# Logging parser.add_argument("--run-name", default=None) parser.add_argument("--project", default=None) parser.add_argument("--trackio-space-id", default="Sudoku-GRPO") parser.add_argument("--logging-steps", type=int, default=1) parser.add_argument( "--gradient-checkpointing", action=argparse.BooleanOptionalAction, default=True, help="Enable gradient checkpointing to save memory", )
# LoRA / PEFT parser.add_argument( "--use-lora", action="store_true", default=False, help="Use LoRA for memory-efficient training" ) parser.add_argument("--lora-r", type=int, default=16, help="LoRA rank") parser.add_argument("--lora-alpha", type=int, default=32, help="LoRA alpha")
# vLLM parser.add_argument("--vllm-mode", choices=("colocate", "server"), default="colocate") parser.add_argument("--vllm-server-url", type=str, default="http://localhost:8000") parser.add_argument("--vllm-gpu-memory-utilization", type=float, default=0.15)
return parser.parse_args()
# ---------------------------------------------------------------------------# Helper functions# ---------------------------------------------------------------------------
def resolve_system_prompt(path: str) -> str: prompt_path = Path(path) if not prompt_path.is_file(): prompt_path = Path(__file__).parent / path return prompt_path.read_text()
def sanitize_name(name: str) -> str: return name.replace("/", "-")
def is_valid_board_state(board_str: str) -> bool: """Check if the string contains an actual Sudoku board.""" return "R1" in board_str and "R9" in board_str and "|" in board_str
def parse_board(board_str: str) -> list[list[int]]: """Parse board string into 9x9 grid (0 = empty).""" grid = [[0] * 9 for _ in range(9)] if not is_valid_board_state(board_str): return grid
for line in board_str.split("\n"): line_stripped = line.strip() if line_stripped and line_stripped[0] == "R" and len(line_stripped) > 1 and line_stripped[1].isdigit(): row = int(line_stripped[1]) - 1 # 0-indexed cell_part = line_stripped[2:] col = 0 for char in cell_part: if char == ".": grid[row][col] = 0 col += 1 elif char.isdigit(): grid[row][col] = int(char) col += 1 return grid
def count_filled_cells(board_str: str) -> int: """Count the number of filled cells in the board.""" if not is_valid_board_state(board_str): return 0 grid = parse_board(board_str) return sum(1 for row in grid for cell in row if cell != 0)
def get_valid_numbers(grid: list[list[int]], row: int, col: int) -> set[int]: """Get valid numbers for a cell based on Sudoku rules.""" if grid[row][col] != 0: return set()
used = set()
# Check row for c in range(9): if grid[row][c] != 0: used.add(grid[row][c])
# Check column for r in range(9): if grid[r][col] != 0: used.add(grid[r][col])
# Check 3x3 box box_row, box_col = 3 * (row // 3), 3 * (col // 3) for r in range(box_row, box_row + 3): for c in range(box_col, box_col + 3): if grid[r][c] != 0: used.add(grid[r][c])
return set(range(1, 10)) - used
def extract_empty_cells_with_candidates( board_str: str, sort_by_difficulty: bool = True) -> list[tuple[int, int, set[int]]]: """Extract empty cells with their valid candidate numbers.
Args: sort_by_difficulty: If True, sort by number of candidates (easiest first). If False, keep natural order (top-left to bottom-right). """ grid = parse_board(board_str) cells_with_candidates = []
for row in range(9): for col in range(9): if grid[row][col] == 0: candidates = get_valid_numbers(grid, row, col) cells_with_candidates.append((row + 1, col + 1, candidates)) # 1-indexed
if sort_by_difficulty: # Sort by number of candidates (easiest first = naked singles) cells_with_candidates.sort(key=lambda x: len(x[2]))
return cells_with_candidates
def extract_empty_cells(board_str: str) -> list[tuple[int, int]]: """Extract list of empty cells (row, col) from board string.""" empty_cells = [] if not is_valid_board_state(board_str): return empty_cells
for line in board_str.split("\n"): line_stripped = line.strip() if line_stripped and line_stripped[0] == "R" and len(line_stripped) > 1 and line_stripped[1].isdigit(): row = int(line_stripped[1]) cell_part = line_stripped[2:] col = 0 for char in cell_part: if char == ".": col += 1 empty_cells.append((row, col)) elif char.isdigit(): col += 1 return empty_cells
def extract_board_only(text: str) -> str: """Extract just the Sudoku grid from a message.""" if not text: return ""
lines = text.split("\n") board_lines = [] in_board = False
for line in lines: stripped = line.strip() if stripped.startswith("C1") or ( stripped and stripped[0] == "R" and len(stripped) > 1 and stripped[1].isdigit() ): in_board = True if in_board and (stripped.startswith("-") or stripped.startswith("R") or stripped.startswith("C1")): board_lines.append(line) elif ( in_board and stripped and not stripped.startswith("-") and not (stripped[0] == "R" and len(stripped) > 1 and stripped[1].isdigit()) ): break
return "\n".join(board_lines) if board_lines else ""
# ---------------------------------------------------------------------------# Reward functions# ---------------------------------------------------------------------------
def reward_empty_cell(environments, **kwargs) -> list[float]: """Reward for targeting empty cells (learn to pick valid positions first).""" return [env.empty_cell_reward for env in environments]
def reward_valid_moves(environments, **kwargs) -> list[float]: """Reward for making valid moves.""" return [env.valid_move_reward for env in environments]
def reward_correct(environments, **kwargs) -> list[float]: """Reward for solving the puzzle.""" return [env.correct_reward for env in environments]
def reward_repetition(environments, **kwargs) -> list[float]: """Penalty for repeating moves.""" return [env.repetition_reward for env in environments]
def reward_progress(environments, **kwargs) -> list[float]: """Reward for filling more cells in the board.""" return [env.progress_reward for env in environments]
# ---------------------------------------------------------------------------# Main# ---------------------------------------------------------------------------
def main() -> None: args = parse_args()
# Setup environment — all modes resolve to env_url if args.env_mode == "docker-local": env_url = f"http://{args.env_host}:{args.env_port}" elif args.env_mode == "docker-image": _bootstrap = TextArenaEnv.from_docker_image(args.env_image) env_url = _bootstrap.base_url elif args.env_mode == "docker-hub": _bootstrap = TextArenaEnv.from_hub(args.env_image) env_url = _bootstrap.base_url elif args.env_mode == "space": env_url = args.env_host else: raise ValueError(f"Unknown environment mode: {args.env_mode}")
print(f"Environment: {args.env_mode} ({env_url})")
system_prompt = resolve_system_prompt(args.system_prompt_path) dataset = Dataset.from_dict( { "prompt": [ [ {"role": "system", "content": system_prompt}, {"role": "user", "content": args.dataset_prompt}, ] ] * args.dataset_size } )
# Capture args for use in the environment class closure difficulty = args.difficulty max_turns = args.max_turns api_delay = args.api_delay
class SudokuEnv: def __init__(self): self.client = TextArenaEnv(base_url=env_url) self._difficulty = difficulty self._max_turns = max_turns self._api_delay = api_delay self._reset_state()
def _reset_state(self): self._move_counts: defaultdict[str, int] = defaultdict(int) self._successful_moves: list[str] = [] self._failed_moves: list[str] = [] self._valid_move_scores: list[float] = [] self._empty_cell_scores: list[float] = [] self._correct_scores: list[float] = [] self._repetition_scores: list[float] = [] self._last_board_state = "" self._initial_filled = 0 self._max_filled = 0 self._turn = 0 self._done = False
def reset(self, **kwargs) -> str: self._reset_state() result = self.client.reset() time.sleep(self._api_delay) observation = result.observation self._done = result.done
# Store full message content for diffing (messages are cumulative) self._last_full_content = observation.messages[0].content if observation.messages else ""
if is_valid_board_state(self._last_full_content): self._last_board_state = self._last_full_content self._initial_filled = count_filled_cells(self._last_board_state) self._max_filled = self._initial_filled
board = extract_board_only(self._last_board_state) if self._last_board_state else "No board available." hints = self._format_hints() return f"Step 0. Progress: 0 cells filled.\n\nBoard:\n{board}{hints}"
def place(self, row: int, col: int, number: int) -> str: """Place a number on the Sudoku board.
Args: row: Row number (1-9). col: Column number (1-9). number: Number to place (1-9).
Returns: The result of the move and updated board state. """ if self._done: raise ValueError("Game is over. No more moves allowed.")
self._turn += 1 move = f"[{row} {col} {number}]"
# Step environment result = self.client.step(TextArenaAction(message=move)) time.sleep(self._api_delay) observation = result.observation correct_score = float(result.reward or 0.0) self._done = result.done
# Only check the NEW content for feedback (messages are cumulative) full_content = observation.messages[0].content if observation.messages else "" new_content = full_content[len(self._last_full_content) :] self._last_full_content = full_content
new_content_lower = new_content.lower() env_says_invalid = any( kw in new_content_lower for kw in ["invalid", "error", "cannot", "already", "violation", "lost"] ) got_warning = "please resubmit" in new_content_lower or "avoid penalties" in new_content_lower
# Also verify against our own board state: placing on a non-empty cell is always invalid if self._last_board_state: empty_cells = extract_empty_cells(self._last_board_state) targets_empty = (row, col) in empty_cells else: empty_cells = [] targets_empty = True # Can't verify, assume valid
is_valid = not env_says_invalid and targets_empty
# Empty cell score: did the model target an empty cell? empty_cell_score = 1.0 if targets_empty else -1.0
# Repetition tracking is_new_move = self._move_counts[move] == 0 repetition_count = self._move_counts[move] self._move_counts[move] += 1 repetition_score = -min(2 ** (repetition_count - 1), 10.0) if repetition_count > 0 else 0.0
# Valid move score if is_valid and is_new_move: valid_move_score = 1.0 self._successful_moves.append(move) elif got_warning: valid_move_score = -0.5 self._failed_moves.append(move) else: valid_move_score = 0.0
# Update board state from new content if is_valid and is_valid_board_state(new_content): self._last_board_state = new_content current_filled = count_filled_cells(self._last_board_state) if current_filled > self._max_filled: self._max_filled = current_filled
self._valid_move_scores.append(valid_move_score) self._empty_cell_scores.append(empty_cell_score) self._correct_scores.append(correct_score) self._repetition_scores.append(repetition_score)
# Enforce max turns if self._turn >= self._max_turns: self._done = True
# Build response board = extract_board_only(self._last_board_state) if self._last_board_state else "No board available." status = "valid" if is_valid else "invalid" cells_filled = len(self._successful_moves) progress = f"Step {self._turn}. Progress: {cells_filled} cells filled." hints = self._format_hints()
if self._done: return f"Move {move}: {status}. Game over.\n{progress}\n\nFinal board:\n{board}" return f"Move {move}: {status}\n{progress}\n\nBoard:\n{board}{hints}"
def _format_hints(self) -> str: parts = []
# Already tried moves (avoid repetitions) all_tried = self._successful_moves + self._failed_moves if all_tried: parts.append(f"\nMOVES ALREADY TRIED (do not repeat): {', '.join(all_tried)}")
if not self._last_board_state: return "\n".join(parts)
if self._difficulty == "easy": cells = extract_empty_cells_with_candidates(self._last_board_state, sort_by_difficulty=True) if cells: guaranteed = [] other = [] for r, c, candidates in cells[:10]: if len(candidates) == 1: guaranteed.append(f"[{r} {c} {list(candidates)[0]}]") elif len(candidates) <= 3: nums = ",".join(str(n) for n in sorted(candidates)) other.append(f"({r},{c})->{nums}") if guaranteed: parts.append(f"\nGUARANTEED MOVES: {', '.join(guaranteed[:5])}") if other: parts.append(f"Other options: {' | '.join(other[:5])}")
elif self._difficulty == "medium": cells = extract_empty_cells_with_candidates(self._last_board_state, sort_by_difficulty=False) if cells: cell_hints = [] for r, c, candidates in cells[:10]: nums = ",".join(str(n) for n in sorted(candidates)) cell_hints.append(f"({r},{c})->{nums}") parts.append(f"\nEmpty cells: {' | '.join(cell_hints)}")
return "\n".join(parts)
# Reward properties — properties are not detected by inspect.ismethod, # so they won't be exposed as tools.
@property def correct_reward(self) -> float: return self._correct_scores[-1] if self._correct_scores else 0.0
@property def valid_move_reward(self) -> float: return sum(self._valid_move_scores) / len(self._valid_move_scores) if self._valid_move_scores else 0.0
@property def empty_cell_reward(self) -> float: return sum(self._empty_cell_scores) / len(self._empty_cell_scores) if self._empty_cell_scores else 0.0
@property def repetition_reward(self) -> float: return sum(self._repetition_scores) / len(self._repetition_scores) if self._repetition_scores else 0.0
@property def progress_reward(self) -> float: remaining = 81 - self._initial_filled if remaining > 0: return (self._max_filled - self._initial_filled) / remaining return 1.0
timestamp = datetime.now().strftime("%Y-%m-%d_%H-%M-%S") output_dir = Path(args.output_dir or f"outputs/sudoku-grpo-{sanitize_name(args.model_id)}-{timestamp}")
grpo_config = GRPOConfig( use_vllm=True, vllm_mode=args.vllm_mode, vllm_server_base_url=args.vllm_server_url if args.vllm_mode == "server" else None, vllm_gpu_memory_utilization=args.vllm_gpu_memory_utilization or 0.2, output_dir=str(output_dir), num_train_epochs=args.num_epochs, learning_rate=args.learning_rate, weight_decay=args.weight_decay, gradient_accumulation_steps=args.gradient_accumulation_steps, per_device_train_batch_size=args.per_device_batch_size, warmup_steps=args.warmup_steps, num_generations=args.num_generations, max_completion_length=args.max_completion_length, logging_steps=args.logging_steps, save_strategy="steps", save_steps=args.save_interval, save_total_limit=args.save_total_limit, temperature=args.temperature, top_k=args.top_k, top_p=args.top_p, report_to="trackio", log_completions=True, num_completions_to_print=1, chat_template_kwargs={"enable_thinking": False}, )
grpo_config.run_name = args.run_name or f"run-{timestamp}" grpo_config.project = args.project or f"group-{sanitize_name(args.model_id)}" grpo_config.trackio_space_id = args.trackio_space_id grpo_config.gradient_checkpointing = args.gradient_checkpointing
peft_config = None if args.use_lora: from peft import LoraConfig
peft_config = LoraConfig(r=args.lora_r, lora_alpha=args.lora_alpha, task_type="CAUSAL_LM")
trainer = GRPOTrainer( model=args.model_id, reward_funcs=[ reward_empty_cell, # Learn to pick empty cells reward_valid_moves, # Learn valid numbers reward_repetition, # Penalize repeating moves reward_progress, # Reward filling more cells reward_correct, # Solve the puzzle ], peft_config=peft_config, train_dataset=dataset, args=grpo_config, environment_factory=SudokuEnv, callbacks=[RichProgressCallback()], )
print(f"Starting GRPO training: {args.num_generations} generations, {args.max_turns} max turns") trainer.train()
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122You are an expert Sudoku player with deep knowledge of logical deduction strategies and number placement techniques.
## GAME RULES
1. The puzzle is a 9x9 grid divided into nine 3x3 subgrids (boxes)2. Some cells are pre-filled with numbers 1-93. You must fill in the empty cells (shown as '.') with numbers 1-94. Each row must contain numbers 1-9 without repetition5. Each column must contain numbers 1-9 without repetition6. Each 3x3 subgrid must contain numbers 1-9 without repetition7. You cannot overwrite pre-filled cells8. Invalid moves result in penalties (-1 reward)
## HOW TO PLAY
Use the `place` tool to make moves. The tool takes three arguments:- `row`: Row number (1-9)- `col`: Column number (1-9)- `number`: Number to place (1-9)
## STRATEGIC APPROACH
Do not repeat the same move twice.
### Basic Strategies- **Naked Singles**: If a cell has only one possible candidate, fill it in immediately.- **Hidden Singles**: If a number can only go in one cell within a row, column, or box, place it there.- **Scanning**: Look at each row, column, and box to find where specific numbers can go.
### Intermediate Strategies- **Naked Pairs/Triples**: When two/three cells in a unit contain only the same candidates, eliminate those from other cells.- **Hidden Pairs/Triples**: When numbers only appear in specific cells within a unit, those cells can only contain those numbers.- **Pointing Pairs**: When a candidate in a box is restricted to a single row/column, eliminate it elsewhere.
### Solving Process1. Start by scanning the entire grid to identify easy fills (cells with few candidates)2. Look for rows, columns, or boxes with many numbers already placed3. Fill all naked singles first4. Then look for hidden singles in each row, column, and box5. Apply more advanced techniques as needed
### Common Pitfalls to Avoid- Don't guess randomly - Sudoku is pure logic- Don't overlook any constraint (row, column, or box)- Don't try to overwrite pre-filled cells- Don't place invalid numbers (must be 1-9)- Don't use invalid coordinates (must be 1-9)- Don't repeat a move that was already made
## EXAMPLES
### Example 1: Naked SingleIf row 3, column 4 can only contain the number 5:→ call `place(row=3, col=4, number=5)`
### Example 2: Hidden SingleIf the number 8 can only go in one cell in row 1:→ call `place(row=1, col=7, number=8)`
### Example 3: Row AnalysisRow 2 is missing only value 5, and column 8 is the empty cell:→ call `place(row=2, col=8, number=5)`
### Example 4: Box AnalysisIn the center box, only one cell can contain 9:→ call `place(row=5, col=5, number=9)`
## BOARD READING
The board is displayed as a 9x9 grid:- Numbers 1-9 are pre-filled or already placed- Empty cells are shown as '.'- Rows are labeled R1-R9 (top to bottom)- Columns are labeled C1-C9 (left to right)
Example board representation:``` C1 C2 C3 C4 C5 C6 C7 C8 C9 R1 . 8 9 | 1 . . | . 3 7R2 2 7 1 | 9 4 3 | 6 . 8R3 . 6 5 | . 2 7 | 4 9 . - - - - - - - - - - - - - - - - R4 . . . | 7 8 . | 9 2 3R5 . 9 2 | . 5 6 | . . 4R6 7 3 8 | . . 2 | 1 . . - - - - - - - - - - - - - - - - R7 8 4 . | . . 9 | 5 . .R8 5 . . | 6 . 8 | 3 4 9R9 9 . 6 | 5 3 4 | 8 7 2```
## COORDINATE REFERENCE
Row indices (top to bottom): 1, 2, 3, 4, 5, 6, 7, 8, 9Column indices (left to right): 1, 2, 3, 4, 5, 6, 7, 8, 9
Subgrid layout:```Subgrid 1 | Subgrid 2 | Subgrid 3 (R1-R3) (R1-R3) (R1-R3) (C1-C3) (C4-C6) (C7-C9)----------+-----------+----------Subgrid 4 | Subgrid 5 | Subgrid 6 (R4-R6) (R4-R6) (R4-R6) (C1-C3) (C4-C6) (C7-C9)----------+-----------+----------Subgrid 7 | Subgrid 8 | Subgrid 9 (R7-R9) (R7-R9) (R7-R9) (C1-C3) (C4-C6) (C7-C9)```
## IMPORTANT CONSTRAINTS
- Coordinates are 1-indexed (1-9 for both row and column)- Numbers must be 1-9- One move per tool call- Must be a valid move (no rule violations)- Never repeat a previous move
## YOUR GOAL
Use ONLY the `place` tool to fill in empty cells one at a time. No explanation, no reasoning, just the `place`.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277# Copyright 2020-2026 The HuggingFace Team. All rights reserved.## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License.
# /// script# dependencies = [# "trl",# "trackio",# "openenv-textarena @ git+https://huggingface.co/spaces/openenv/wordle",# ]# ///
"""Simple script to run GRPO training with OpenEnv's Wordle environment and vLLM.
Setup (Option A - Install from HF Space, recommended):
```shuv pip install git+https://huggingface.co/spaces/openenv/wordle```
# Option 1: HF Spaces + Colocated vLLM (1 GPU required)```shpython examples/scripts/openenv/wordle.py --vllm-mode colocate```
# Option 2: HF Spaces + Separate vLLM server (2 GPUs required)
# Spin up vLLM server (Terminal 1)```shCUDA_VISIBLE_DEVICES=0 trl vllm-serve --model Qwen/Qwen3-1.7B --host 0.0.0.0 --port 8000```
# Run training (Terminal 2)```shCUDA_VISIBLE_DEVICES=1 python examples/scripts/openenv/wordle.py --vllm-mode server --vllm-server-url http://localhost:8000```
# Option 3: Local Environment + Colocated vLLM (1 GPU required)
To run the Wordle environment locally, you have several options:
## Option 3a: Using Docker Image (Recommended)
First, build the Docker image from the textarena_env directory:```shcd 3rd_party/OpenEnv/envs/textarena_envdocker build -t textarena-env:latest -f server/Dockerfile .```
Then run the environment server:```shdocker run -d -p 8001:8001 textarena-env:latest```
Finally, run training pointing to local server:```shpython examples/scripts/openenv/wordle.py --vllm-mode colocate --env-url http://localhost:8001```
## Option 3b: Running Server Directly
From the textarena_env directory:```shcd 3rd_party/OpenEnv/envs/textarena_envuv venv && source .venv/bin/activateuv pip install -e .python -m uvicorn server.app:app --reload --port 8001```
Then in another terminal, run training:```shpython examples/scripts/openenv/wordle.py --vllm-mode colocate --env-url http://localhost:8001```
## Option 3c: Using Pre-built HF Space Image
```shdocker run -d -p 8001:8001 registry.hf.space/burtenshaw-wordle:latestpython examples/scripts/openenv/wordle.py --vllm-mode colocate --env-url http://localhost:8001```"""
import argparse
from datasets import Datasetfrom textarena_env import TextArenaAction, TextArenaEnv
from trl import GRPOConfig, GRPOTrainer, RichProgressCallback
def parse_args() -> argparse.Namespace: parser = argparse.ArgumentParser( description="Run GRPO training for Wordle using the TextArena OpenEnv environment." ) parser.add_argument( "--model", type=str, default="Qwen/Qwen3-1.7B", help="Model identifier passed to GRPOTrainer for fine-tuning.", ) parser.add_argument( "--env-url", type=str, default="https://openenv-wordle.hf.space", help="URL for the environment server.", ) parser.add_argument( "--dataset-size", type=int, default=1000, help="Number of entries to include in the synthetic training dataset.", ) parser.add_argument( "--num-generations", type=int, default=4, help="Number of rollout generations per dataset prompt.", ) parser.add_argument( "--num-epochs", type=int, default=1, help="Number of training epochs.", ) parser.add_argument( "--learning-rate", type=float, default=1e-6, help="Learning rate for GRPO training.", ) parser.add_argument( "--gradient-accumulation-steps", type=int, default=64, help="Gradient accumulation steps for GRPO training.", ) parser.add_argument( "--logging-steps", type=int, default=1, help="Frequency of logging steps for GRPO training.", ) parser.add_argument( "--output-dir", type=str, default=None, help="Directory where training outputs and checkpoints are stored.", ) parser.add_argument( "--trackio-space-id", type=str, default="wordle-grpo", help="Trackio space identifier.", ) parser.add_argument( "--vllm-mode", choices=("colocate", "server"), default="colocate", help="vLLM execution mode: 'colocate' or 'server'.", ) parser.add_argument( "--vllm-server-url", type=str, default="http://localhost:8000", help="URL for the vLLM server (only used when --vllm-mode=server).", ) return parser.parse_args()
prompt = """You are an expert Wordle solver with deep knowledge of English vocabulary, letter frequency patterns, and optimal guessing strategies.
Follow these rules to play Wordle:
1. The target is a 5-letter English word2. You have 6 attempts to guess the correct word3. After each guess, you receive color-coded feedback: - GREEN (G): Letter is correct and in the correct position - YELLOW (Y): Letter is in the word but in the wrong position - GRAY (X): Letter is not in the word at all4. All guesses must be valid 5-letter English words5. You cannot reuse a word you've already guessed6. Use the tool `guess` to make a guess."""
def reward_func(environments, **kwargs) -> list[float]: return [env.reward for env in environments]
def main() -> None: args = parse_args()
env_url = args.env_url
class WordleEnv: def __init__(self): self.client = TextArenaEnv(base_url=env_url)
def reset(self, **kwargs) -> str | None: result = self.client.reset() # The game returns cumulative feedback each turn (new text appended at the end), so # we store the previous full response and slice out only the newly appended part. self._last_full_feedback = result.observation.messages[0].content self.reward = 0.0 self.done = False return self._last_full_feedback
def guess(self, guess: str) -> str: """ Make a guess in the Wordle environment.
Args: guess: The guessed word, formatted as '[abcde]'
Returns: The feedback message from the environment. """ if self.done: raise ValueError("Game over.") result = self.client.step(TextArenaAction(message=guess)) _full_feedback = result.observation.messages[0].content # Just take the new feedback since the last guess, which is the part appended to the end of the full feedback feedback = _full_feedback[len(self._last_full_feedback) :] self._last_full_feedback = _full_feedback # For some reason, the environment doesn't penalize invalid moves and just returns the last reward. # We check the feedback for the invalid move message and penalize it if found. if "You attempted an invalid move" in feedback: self.reward = 0.0 else: self.reward = result.reward self.done = result.done return feedback
output_dir = args.output_dir or f"{args.model.split('/')[-1]}-wordle-GRPO" dataset = Dataset.from_dict({"prompt": [[{"role": "user", "content": prompt}] for _ in range(args.dataset_size)]})
trainer = GRPOTrainer( model=args.model, reward_funcs=reward_func, train_dataset=dataset, args=GRPOConfig( output_dir=output_dir, use_vllm=True, vllm_mode=args.vllm_mode, vllm_server_base_url=args.vllm_server_url if args.vllm_mode == "server" else None, report_to="trackio", trackio_space_id=args.trackio_space_id, log_completions=True, num_completions_to_print=2, logging_steps=args.logging_steps, num_train_epochs=args.num_epochs, num_generations=args.num_generations, learning_rate=args.learning_rate, gradient_accumulation_steps=args.gradient_accumulation_steps, chat_template_kwargs={"enable_thinking": False}, max_completion_length=1024, ), environment_factory=WordleEnv, callbacks=[RichProgressCallback()], ) trainer.train()
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127# Copyright 2020-2026 The HuggingFace Team. All rights reserved.## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License.
# /// script# dependencies = ["trl[vllm,openreward]"]# ///
"""GRPO training against the SETA ORS environment.
Defaults target ``Eigent/SETA`` on the openreward.ai catalog (requires``OPENREWARD_API_KEY``). Pass ``--target https://...hf.space`` to pointat a self-hosted Space.
Usage (colocate vLLM, single-node):
```shaccelerate launch \ --config_file examples/accelerate_configs/deepspeed_zero2.yaml \ --num_processes 4 \ examples/scripts/openreward/seta.py \ --vllm-mode colocate```
Usage (server vLLM, single-node 2+2 GPU split):
```sh# Terminal 1 — vLLMCUDA_VISIBLE_DEVICES=2,3 trl vllm-serve --model Qwen/Qwen3-4B \ --tensor-parallel-size 2 --port 8000
# Terminal 2 — trainingCUDA_VISIBLE_DEVICES=0,1 accelerate launch \ --config_file examples/accelerate_configs/deepspeed_zero2.yaml \ --num_processes 2 \ examples/scripts/openreward/seta.py \ --vllm-mode server --vllm-server-base-url http://localhost:8000```"""
import argparse
from trl import GRPOConfig, GRPOTrainerfrom trl.experimental.openreward import OpenRewardSpec
def parse_args() -> argparse.Namespace: parser = argparse.ArgumentParser(description="GRPO training against the SETA ORS environment.")
parser.add_argument("--model", type=str, default="Qwen/Qwen3-4B") parser.add_argument( "--target", type=str, default="Eigent/SETA", help="ORS env target — either a catalog name (e.g. 'Eigent/SETA') or a URL " "(e.g. 'https://you-seta.hf.space').", ) parser.add_argument("--split", type=str, default="train") parser.add_argument("--num-tasks", type=int, default=64)
parser.add_argument("--learning-rate", type=float, default=5e-7) parser.add_argument("--per-device-train-batch-size", type=int, default=1) parser.add_argument("--gradient-accumulation-steps", type=int, default=1) parser.add_argument("--num-generations", type=int, default=2) parser.add_argument("--max-completion-length", type=int, default=2048) parser.add_argument("--max-steps", type=int, default=5) parser.add_argument("--max-tool-calling-iterations", type=int, default=20)
parser.add_argument("--vllm-mode", choices=("colocate", "server"), default="colocate") parser.add_argument("--vllm-server-base-url", type=str, default="http://localhost:8000") parser.add_argument("--vllm-gpu-memory-utilization", type=float, default=0.3)
parser.add_argument("--output-dir", type=str, default=None) parser.add_argument("--report-to", type=str, default="none")
return parser.parse_args()
def main() -> None: args = parse_args()
# One spec object — fans out into TRL's three slots. spec = OpenRewardSpec(args.target, num_tasks=args.num_tasks, split=args.split)
config_kwargs: dict = dict( learning_rate=args.learning_rate, per_device_train_batch_size=args.per_device_train_batch_size, gradient_accumulation_steps=args.gradient_accumulation_steps, num_generations=args.num_generations, max_completion_length=args.max_completion_length, max_steps=args.max_steps, max_tool_calling_iterations=args.max_tool_calling_iterations, chat_template_kwargs={"enable_thinking": False}, log_completions=True, use_vllm=True, vllm_mode=args.vllm_mode, report_to=[s.strip() for s in args.report_to.split(",") if s.strip() and s.strip() != "none"] or "none", ) if args.output_dir: config_kwargs["output_dir"] = args.output_dir if args.vllm_mode == "colocate": config_kwargs["vllm_gpu_memory_utilization"] = args.vllm_gpu_memory_utilization else: config_kwargs["vllm_server_base_url"] = args.vllm_server_base_url
trainer = GRPOTrainer( model=args.model, args=GRPOConfig(**config_kwargs), train_dataset=spec.train_dataset, environment_factory=spec.environment_factory, reward_funcs=spec.reward_funcs, ) trainer.train()
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102# Copyright 2020-2026 The HuggingFace Team. All rights reserved.## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License.
# /// script# dependencies = [# "trl[peft]",# "trackio",# "kernels",# ]# ///
"""Run the ORPO training script with the following command with some example arguments.In general, the optimal configuration for ORPO will be similar to that of DPO without the need for a reference model:
# regular:python examples/scripts/orpo.py \ --dataset_name trl-internal-testing/hh-rlhf-helpful-base-trl-style \ --model_name_or_path gpt2 \ --per_device_train_batch_size 4 \ --max_steps 1000 \ --learning_rate 8e-6 \ --gradient_accumulation_steps 1 \ --eval_steps 500 \ --output_dir "gpt2-aligned-orpo" \ --warmup_steps 150 \ --logging_first_step \ --no_remove_unused_columns
# peft:python examples/scripts/orpo.py \ --dataset_name trl-internal-testing/hh-rlhf-helpful-base-trl-style \ --model_name_or_path gpt2 \ --per_device_train_batch_size 4 \ --max_steps 1000 \ --learning_rate 8e-5 \ --gradient_accumulation_steps 1 \ --eval_steps 500 \ --output_dir "gpt2-lora-aligned-orpo" \ --optim rmsprop \ --warmup_steps 150 \ --logging_first_step \ --no_remove_unused_columns \ --use_peft \ --lora_r 16 \ --lora_alpha 16"""
from datasets import load_datasetfrom transformers import AutoModelForCausalLM, AutoTokenizer, HfArgumentParser
from trl import ModelConfig, ScriptArguments, get_peft_configfrom trl.experimental.orpo import ORPOConfig, ORPOTrainer
if __name__ == "__main__": parser = HfArgumentParser((ScriptArguments, ORPOConfig, ModelConfig)) script_args, training_args, model_args = parser.parse_args_into_dataclasses()
################ # Model & Tokenizer ################ model = AutoModelForCausalLM.from_pretrained(model_args.model_name_or_path) tokenizer = AutoTokenizer.from_pretrained(model_args.model_name_or_path) if tokenizer.pad_token is None: tokenizer.pad_token = tokenizer.eos_token
################ # Dataset ################ dataset = load_dataset(script_args.dataset_name, name=script_args.dataset_config)
################ # Training ################ trainer = ORPOTrainer( model, args=training_args, train_dataset=dataset[script_args.dataset_train_split], eval_dataset=dataset[script_args.dataset_test_split] if training_args.eval_strategy != "no" else None, processing_class=tokenizer, peft_config=get_peft_config(model_args), )
# train and save the model trainer.train()
# Save and push to hub trainer.save_model(training_args.output_dir) if training_args.push_to_hub: trainer.push_to_hub(dataset_name=script_args.dataset_name)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160# Copyright 2020-2026 The HuggingFace Team. All rights reserved.## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License.
# /// script# dependencies = [# "trl[peft]",# "trackio",# "kernels",# ]# ///
import shutil
import torchfrom accelerate import PartialStatefrom datasets import load_datasetfrom transformers import ( AutoModelForCausalLM, AutoModelForSequenceClassification, AutoTokenizer, HfArgumentParser,)
from trl import ModelConfig, ScriptArguments, get_kbit_device_map, get_peft_config, get_quantization_configfrom trl.experimental.ppo import PPOConfig, PPOTrainer
"""python -i examples/scripts/ppo/ppo.py \ --dataset_name trl-internal-testing/descriptiveness-sentiment-trl-style \ --dataset_train_split descriptiveness \ --output_dir pythia-1b-deduped-descriptiveness-sentiment-trl-style-ppo \ --per_device_train_batch_size 64 \ --gradient_accumulation_steps 1 \ --total_episodes 10000 \ --model_name_or_path EleutherAI/pythia-1b-deduped \ --missing_eos_penalty 1.0
accelerate launch --config_file examples/accelerate_configs/deepspeed_zero3.yaml \ examples/scripts/ppo/ppo.py \ --dataset_name trl-internal-testing/descriptiveness-sentiment-trl-style \ --dataset_train_split descriptiveness \ --output_dir pythia-1b-deduped-descriptiveness-sentiment-trl-style-ppo \ --num_ppo_epochs 1 \ --num_mini_batches 1 \ --per_device_train_batch_size 1 \ --gradient_accumulation_steps 16 \ --total_episodes 10000 \ --model_name_or_path EleutherAI/pythia-1b-deduped \ --sft_model_path EleutherAI/pythia-1b-deduped \ --reward_model_path EleutherAI/pythia-1b-deduped \ --local_rollout_forward_batch_size 1 \ --missing_eos_penalty 1.0"""
if __name__ == "__main__": parser = HfArgumentParser((ScriptArguments, PPOConfig, ModelConfig)) script_args, training_args, model_args = parser.parse_args_into_dataclasses() # remove output_dir if exists shutil.rmtree(training_args.output_dir, ignore_errors=True)
################ # Model & Tokenizer ################ dtype = model_args.dtype if model_args.dtype in ["auto", None] else getattr(torch, model_args.dtype) model_kwargs = dict( revision=model_args.model_revision, attn_implementation=model_args.attn_implementation, dtype=dtype, ) quantization_config = get_quantization_config(model_args) if quantization_config is not None: # Passing None would not be treated the same as omitting the argument, so we include it only when valid. model_kwargs["device_map"] = get_kbit_device_map() model_kwargs["quantization_config"] = quantization_config
tokenizer = AutoTokenizer.from_pretrained(model_args.model_name_or_path, padding_side="left") tokenizer.add_special_tokens({"pad_token": "[PAD]"}) value_model = AutoModelForSequenceClassification.from_pretrained( training_args.reward_model_path, num_labels=1, **model_kwargs ) reward_model = AutoModelForSequenceClassification.from_pretrained( training_args.reward_model_path, num_labels=1, **model_kwargs ) policy = AutoModelForCausalLM.from_pretrained(training_args.sft_model_path, **model_kwargs)
peft_config = get_peft_config(model_args) if peft_config is None: ref_policy = AutoModelForCausalLM.from_pretrained(training_args.sft_model_path, **model_kwargs) else: ref_policy = None
################ # Dataset ################ dataset = load_dataset( script_args.dataset_name, name=script_args.dataset_config, split=script_args.dataset_train_split ) eval_samples = 100 train_dataset = dataset.select(range(len(dataset) - eval_samples)) eval_dataset = dataset.select(range(len(dataset) - eval_samples, len(dataset))) dataset_text_field = "prompt"
def prepare_dataset(dataset, tokenizer): """pre-tokenize the dataset before training; only collate during training"""
def tokenize(element): outputs = tokenizer( element[dataset_text_field], padding=False, ) return {"input_ids": outputs["input_ids"]}
return dataset.map( tokenize, batched=True, remove_columns=dataset.column_names, num_proc=training_args.dataset_num_proc, )
# Compute that only on the main process for faster data processing. # see: https://github.com/huggingface/trl/pull/1255 with PartialState().local_main_process_first(): train_dataset = prepare_dataset(train_dataset, tokenizer) eval_dataset = prepare_dataset(eval_dataset, tokenizer)
################ # Training ################ trainer = PPOTrainer( args=training_args, processing_class=tokenizer, model=policy, ref_model=ref_policy, reward_model=reward_model, value_model=value_model, train_dataset=train_dataset, eval_dataset=eval_dataset, peft_config=peft_config, ) trainer.train()
# Save and push to hub trainer.save_model(training_args.output_dir) if training_args.push_to_hub: trainer.push_to_hub(dataset_name=script_args.dataset_name)
trainer.generate_completions()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168# Copyright 2020-2026 The HuggingFace Team. All rights reserved.## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License.
# /// script# dependencies = [# "trl[peft]",# "trackio",# "kernels",# ]# ///
import shutil
import torchfrom accelerate import PartialStatefrom datasets import load_datasetfrom transformers import ( AutoModelForCausalLM, AutoModelForSequenceClassification, AutoTokenizer, HfArgumentParser,)
from trl import ModelConfig, ScriptArguments, get_kbit_device_map, get_peft_config, get_quantization_configfrom trl.experimental.ppo import PPOConfig, PPOTrainer
"""python examples/scripts/ppo/ppo_tldr.py \ --dataset_name trl-lib/tldr \ --dataset_test_split validation \ --output_dir pythia-1b-deduped-tldr-preference-sft-trl-style-ppo \ --per_device_train_batch_size 1 \ --gradient_accumulation_steps 64 \ --total_episodes 30000 \ --model_name_or_path EleutherAI/pythia-1b-deduped \ --sft_model_path cleanrl/EleutherAI_pythia-1b-deduped__sft__tldr \ --reward_model_path cleanrl/EleutherAI_pythia-1b-deduped__reward__tldr \ --missing_eos_penalty 1.0 \ --stop_token eos \ --response_length 53 \ --eval_strategy steps \ --eval_steps 100
accelerate launch --config_file examples/accelerate_configs/deepspeed_zero2.yaml \ examples/scripts/ppo/ppo_tldr.py \ --dataset_name trl-lib/tldr \ --dataset_test_split validation \ --output_dir pythia-1b-deduped-tldr-preference-sft-trl-style-ppo \ --per_device_train_batch_size 16 \ --gradient_accumulation_steps 4 \ --total_episodes 1000000 \ --model_name_or_path EleutherAI/pythia-1b-deduped \ --sft_model_path cleanrl/EleutherAI_pythia-1b-deduped__sft__tldr \ --reward_model_path cleanrl/EleutherAI_pythia-1b-deduped__reward__tldr \ --local_rollout_forward_batch_size 16 \ --missing_eos_penalty 1.0 \ --stop_token eos \ --eval_strategy steps \ --eval_steps 100"""
if __name__ == "__main__": parser = HfArgumentParser((ScriptArguments, PPOConfig, ModelConfig)) script_args, training_args, model_args = parser.parse_args_into_dataclasses() # remove output_dir if exists shutil.rmtree(training_args.output_dir, ignore_errors=True)
################ # Model & Tokenizer ################ dtype = model_args.dtype if model_args.dtype in ["auto", None] else getattr(torch, model_args.dtype) model_kwargs = dict( revision=model_args.model_revision, attn_implementation=model_args.attn_implementation, dtype=dtype, ) quantization_config = get_quantization_config(model_args) if quantization_config is not None: # Passing None would not be treated the same as omitting the argument, so we include it only when valid. model_kwargs["device_map"] = get_kbit_device_map() model_kwargs["quantization_config"] = quantization_config
tokenizer = AutoTokenizer.from_pretrained(model_args.model_name_or_path, padding_side="left") tokenizer.add_special_tokens({"pad_token": "[PAD]"}) value_model = AutoModelForSequenceClassification.from_pretrained( training_args.reward_model_path, num_labels=1, **model_kwargs ) reward_model = AutoModelForSequenceClassification.from_pretrained( training_args.reward_model_path, num_labels=1, **model_kwargs, ) policy = AutoModelForCausalLM.from_pretrained(training_args.sft_model_path, **model_kwargs)
peft_config = get_peft_config(model_args) if peft_config is None: ref_policy = AutoModelForCausalLM.from_pretrained(training_args.sft_model_path, **model_kwargs) else: ref_policy = None
################ # Dataset ################ dataset = load_dataset(script_args.dataset_name, name=script_args.dataset_config) train_dataset = dataset[script_args.dataset_train_split] eval_dataset = dataset[script_args.dataset_test_split] if training_args.eval_strategy != "no" else None
def prepare_dataset(dataset, tokenizer): """pre-tokenize the dataset before training; only collate during training"""
def tokenize(element): input_ids = tokenizer(element["prompt"], padding=False)["input_ids"] return {"input_ids": input_ids, "lengths": len(input_ids)}
return dataset.map( tokenize, remove_columns=dataset.column_names, num_proc=training_args.dataset_num_proc, )
# Compute that only on the main process for faster data processing. # see: https://github.com/huggingface/trl/pull/1255 with PartialState().local_main_process_first(): train_dataset = prepare_dataset(train_dataset, tokenizer) if eval_dataset is not None: eval_dataset = prepare_dataset(eval_dataset, tokenizer) # filtering train_dataset = train_dataset.filter(lambda x: x["lengths"] <= 512, num_proc=training_args.dataset_num_proc) if eval_dataset is not None: eval_dataset = eval_dataset.filter(lambda x: x["lengths"] <= 512, num_proc=training_args.dataset_num_proc)
assert train_dataset[0]["input_ids"][-1] != tokenizer.eos_token_id, "The last token should not be an EOS token"
################ # Training ################ trainer = PPOTrainer( args=training_args, processing_class=tokenizer, model=policy, ref_model=ref_policy, reward_model=reward_model, value_model=value_model, train_dataset=train_dataset, eval_dataset=eval_dataset, peft_config=peft_config, ) trainer.train()
# Save and push to hub trainer.save_model(training_args.output_dir) if training_args.push_to_hub: trainer.push_to_hub(dataset_name=script_args.dataset_name)
trainer.generate_completions()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128# Copyright 2020-2026 The HuggingFace Team. All rights reserved.## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License.
# /// script# dependencies = [# "trl",# "trackio",# "kernels",# ]# ///
"""Full training:python examples/scripts/prm.py \ --model_name_or_path Qwen/Qwen2-0.5B-Instruct \ --dataset_name trl-lib/prm800k \ --output_dir Qwen2-0.5B-Reward \ --per_device_train_batch_size 8 \ --num_train_epochs 1 \ --learning_rate 1.0e-5 \ --eval_strategy steps \ --eval_steps 50
LoRA:python examples/scripts/prm.py \ --model_name_or_path Qwen/Qwen2-0.5B-Instruct \ --dataset_name trl-lib/prm800k \ --output_dir Qwen2-0.5B-Reward-LoRA \ --per_device_train_batch_size 8 \ --num_train_epochs 1 \ --learning_rate 1.0e-4 \ --eval_strategy steps \ --eval_steps 50 --use_peft \ --lora_r 32 \ --lora_alpha 16"""
import torchfrom accelerate import loggingfrom datasets import load_datasetfrom transformers import AutoModelForTokenClassification, AutoTokenizer, HfArgumentParser
from trl import ( ModelConfig, ScriptArguments, get_kbit_device_map, get_peft_config, get_quantization_config,)from trl.experimental.prm import PRMConfig, PRMTrainer
logger = logging.get_logger(__name__)
if __name__ == "__main__": parser = HfArgumentParser((ScriptArguments, PRMConfig, ModelConfig)) script_args, training_args, model_args = parser.parse_args_into_dataclasses()
################ # Model & Tokenizer ################ dtype = model_args.dtype if model_args.dtype in ["auto", None] else getattr(torch, model_args.dtype) model_kwargs = dict( revision=model_args.model_revision, use_cache=False if training_args.gradient_checkpointing else True, ) quantization_config = get_quantization_config(model_args) if quantization_config is not None: # Passing None would not be treated the same as omitting the argument, so we include it only when valid. model_kwargs["device_map"] = get_kbit_device_map() model_kwargs["quantization_config"] = quantization_config
tokenizer = AutoTokenizer.from_pretrained(model_args.model_name_or_path, use_fast=True) model = AutoModelForTokenClassification.from_pretrained( model_args.model_name_or_path, num_labels=2, **model_kwargs )
if model_args.use_peft and model_args.lora_task_type != "TOKEN_CLS": logger.warning( "You are using a `task_type` that is different than `TOKEN_CLS` for PEFT. This will lead to silent bugs" " Make sure to pass --lora_task_type TOKEN_CLS when using this script with PEFT.", )
############## # Load dataset ############## dataset = load_dataset(script_args.dataset_name, name=script_args.dataset_config)
dataset = dataset.filter(lambda x: len(x["completions"]) > 0)
########## # Training ########## trainer = PRMTrainer( model=model, processing_class=tokenizer, args=training_args, train_dataset=dataset[script_args.dataset_train_split], eval_dataset=dataset[script_args.dataset_test_split], peft_config=get_peft_config(model_args), ) trainer.train()
############################ # Save model and push to Hub ############################ trainer.save_model(training_args.output_dir) metrics = trainer.evaluate() trainer.log_metrics("eval", metrics) trainer.save_metrics("eval", metrics)
# Save and push to hub trainer.save_model(training_args.output_dir) if training_args.push_to_hub: trainer.push_to_hub(dataset_name=script_args.dataset_name).gitattributes+1
README.mdAdded+105
release-files.jsonAdded+3
tasks/tasksmith-fa1a9b35ff39/tests/source/examples/scripts/async_grpo.pyAdded+76
tasks/tasksmith-fa1a9b35ff39/tests/source/examples/scripts/bco.pyAdded+156
tasks/tasksmith-fa1a9b35ff39/tests/source/examples/scripts/cpo.pyAdded+102
tasks/tasksmith-fa1a9b35ff39/tests/source/examples/scripts/distillation.pyAdded+177
tasks/tasksmith-fa1a9b35ff39/tests/source/examples/scripts/dpo.pyAdded+17
tasks/tasksmith-fa1a9b35ff39/tests/source/examples/scripts/dpo_vlm.pyAdded+134
tasks/tasksmith-fa1a9b35ff39/tests/source/examples/scripts/gkd.pyAdded+139
tasks/tasksmith-fa1a9b35ff39/tests/source/examples/scripts/gold.pyAdded+152
tasks/tasksmith-fa1a9b35ff39/tests/source/examples/scripts/grpo_2048.pyAdded+161
tasks/tasksmith-fa1a9b35ff39/tests/source/examples/scripts/grpo_agent.pyAdded+320
tasks/tasksmith-fa1a9b35ff39/tests/source/examples/scripts/grpo_continuous_batching.pyAdded+133
tasks/tasksmith-fa1a9b35ff39/tests/source/examples/scripts/grpo_vlm.pyAdded+157
tasks/tasksmith-fa1a9b35ff39/tests/source/examples/scripts/gspo.pyAdded+131
tasks/tasksmith-fa1a9b35ff39/tests/source/examples/scripts/gspo_vlm.pyAdded+146
tasks/tasksmith-fa1a9b35ff39/tests/source/examples/scripts/harbor/data_agent.pyAdded+131
tasks/tasksmith-fa1a9b35ff39/tests/source/examples/scripts/harbor/harnesses/__init__.pyAdded+20
tasks/tasksmith-fa1a9b35ff39/tests/source/examples/scripts/harbor/harnesses/bash/README.mdAdded+20
tasks/tasksmith-fa1a9b35ff39/tests/source/examples/scripts/harbor/harnesses/bash/__init__.pyAdded+18
tasks/tasksmith-fa1a9b35ff39/tests/source/examples/scripts/harbor/harnesses/jupyter/README.mdAdded+31
tasks/tasksmith-fa1a9b35ff39/tests/source/examples/scripts/harbor/harnesses/jupyter/__init__.pyAdded+18
tasks/tasksmith-fa1a9b35ff39/tests/source/examples/scripts/harbor/harnesses/jupyter/env.pyAdded+104
tasks/tasksmith-fa1a9b35ff39/tests/source/examples/scripts/harbor/harnesses/jupyter/kernel_server.pyAdded+98
tasks/tasksmith-fa1a9b35ff39/tests/source/examples/scripts/harbor/harnesses/jupyter/run_cell.pyAdded+61
tasks/tasksmith-fa1a9b35ff39/tests/source/examples/scripts/harbor/harnesses/terminal_notes/README.mdAdded+40
tasks/tasksmith-fa1a9b35ff39/tests/source/examples/scripts/harbor/harnesses/terminal_notes/__init__.pyAdded+18
tasks/tasksmith-fa1a9b35ff39/tests/source/examples/scripts/harbor/harnesses/terminal_notes/env.pyAdded+221
tasks/tasksmith-fa1a9b35ff39/tests/source/examples/scripts/kto.pyAdded+99
tasks/tasksmith-fa1a9b35ff39/tests/source/examples/scripts/mpo_vlm.pyAdded+126
tasks/tasksmith-fa1a9b35ff39/tests/source/examples/scripts/nash_md.pyAdded+130
tasks/tasksmith-fa1a9b35ff39/tests/source/examples/scripts/online_dpo.pyAdded+137
tasks/tasksmith-fa1a9b35ff39/tests/source/examples/scripts/online_dpo_vlm.pyAdded+203
tasks/tasksmith-fa1a9b35ff39/tests/source/examples/scripts/openenv/browsergym.pyAdded+291
tasks/tasksmith-fa1a9b35ff39/tests/source/examples/scripts/openenv/browsergym_llm.pyAdded+463
tasks/tasksmith-fa1a9b35ff39/tests/source/examples/scripts/openenv/carla.pyAdded+219
tasks/tasksmith-fa1a9b35ff39/tests/source/examples/scripts/openenv/carla_vlm.pyAdded+262
tasks/tasksmith-fa1a9b35ff39/tests/source/examples/scripts/openenv/carla_vlm_gemma.pyAdded+278
tasks/tasksmith-fa1a9b35ff39/tests/source/examples/scripts/openenv/catch.pyAdded+347
tasks/tasksmith-fa1a9b35ff39/tests/source/examples/scripts/openenv/echo.pyAdded+133
tasks/tasksmith-fa1a9b35ff39/tests/source/examples/scripts/openenv/multi_env.pyAdded+273
tasks/tasksmith-fa1a9b35ff39/tests/source/examples/scripts/openenv/sudoku.pyAdded+669
tasks/tasksmith-fa1a9b35ff39/tests/source/examples/scripts/openenv/sudoku_prompt.txtAdded+122
tasks/tasksmith-fa1a9b35ff39/tests/source/examples/scripts/openenv/wordle.pyAdded+277
tasks/tasksmith-fa1a9b35ff39/tests/source/examples/scripts/openreward/seta.pyAdded+127
tasks/tasksmith-fa1a9b35ff39/tests/source/examples/scripts/orpo.pyAdded+102
tasks/tasksmith-fa1a9b35ff39/tests/source/examples/scripts/ppo/ppo.pyAdded+160
tasks/tasksmith-fa1a9b35ff39/tests/source/examples/scripts/ppo/ppo_tldr.pyAdded+168
tasks/tasksmith-fa1a9b35ff39/tests/source/examples/scripts/prm.pyAdded+128