Stage Harbor release files 105001-105427
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- .gitattributes +1 -0
- README.md +105 -0
- release-files.json +3 -0
- tasks/tasksmith-fa1a9b35ff39/tests/source/examples/scripts/async_grpo.py +76 -0
- tasks/tasksmith-fa1a9b35ff39/tests/source/examples/scripts/bco.py +156 -0
- tasks/tasksmith-fa1a9b35ff39/tests/source/examples/scripts/cpo.py +102 -0
- tasks/tasksmith-fa1a9b35ff39/tests/source/examples/scripts/distillation.py +177 -0
- tasks/tasksmith-fa1a9b35ff39/tests/source/examples/scripts/dpo.py +17 -0
- tasks/tasksmith-fa1a9b35ff39/tests/source/examples/scripts/dpo_vlm.py +134 -0
- tasks/tasksmith-fa1a9b35ff39/tests/source/examples/scripts/gkd.py +139 -0
- tasks/tasksmith-fa1a9b35ff39/tests/source/examples/scripts/gold.py +152 -0
- tasks/tasksmith-fa1a9b35ff39/tests/source/examples/scripts/grpo_2048.py +161 -0
- tasks/tasksmith-fa1a9b35ff39/tests/source/examples/scripts/grpo_agent.py +320 -0
- tasks/tasksmith-fa1a9b35ff39/tests/source/examples/scripts/grpo_continuous_batching.py +133 -0
- tasks/tasksmith-fa1a9b35ff39/tests/source/examples/scripts/grpo_vlm.py +157 -0
- tasks/tasksmith-fa1a9b35ff39/tests/source/examples/scripts/gspo.py +131 -0
- tasks/tasksmith-fa1a9b35ff39/tests/source/examples/scripts/gspo_vlm.py +146 -0
- tasks/tasksmith-fa1a9b35ff39/tests/source/examples/scripts/harbor/data_agent.py +131 -0
- tasks/tasksmith-fa1a9b35ff39/tests/source/examples/scripts/harbor/harnesses/__init__.py +20 -0
- tasks/tasksmith-fa1a9b35ff39/tests/source/examples/scripts/harbor/harnesses/bash/README.md +20 -0
- tasks/tasksmith-fa1a9b35ff39/tests/source/examples/scripts/harbor/harnesses/bash/__init__.py +18 -0
- tasks/tasksmith-fa1a9b35ff39/tests/source/examples/scripts/harbor/harnesses/jupyter/README.md +31 -0
- tasks/tasksmith-fa1a9b35ff39/tests/source/examples/scripts/harbor/harnesses/jupyter/__init__.py +18 -0
- tasks/tasksmith-fa1a9b35ff39/tests/source/examples/scripts/harbor/harnesses/jupyter/env.py +104 -0
- tasks/tasksmith-fa1a9b35ff39/tests/source/examples/scripts/harbor/harnesses/jupyter/kernel_server.py +98 -0
- tasks/tasksmith-fa1a9b35ff39/tests/source/examples/scripts/harbor/harnesses/jupyter/run_cell.py +61 -0
- tasks/tasksmith-fa1a9b35ff39/tests/source/examples/scripts/harbor/harnesses/terminal_notes/README.md +40 -0
- tasks/tasksmith-fa1a9b35ff39/tests/source/examples/scripts/harbor/harnesses/terminal_notes/__init__.py +18 -0
- tasks/tasksmith-fa1a9b35ff39/tests/source/examples/scripts/harbor/harnesses/terminal_notes/env.py +221 -0
- tasks/tasksmith-fa1a9b35ff39/tests/source/examples/scripts/kto.py +99 -0
- tasks/tasksmith-fa1a9b35ff39/tests/source/examples/scripts/mpo_vlm.py +126 -0
- tasks/tasksmith-fa1a9b35ff39/tests/source/examples/scripts/nash_md.py +130 -0
- tasks/tasksmith-fa1a9b35ff39/tests/source/examples/scripts/online_dpo.py +137 -0
- tasks/tasksmith-fa1a9b35ff39/tests/source/examples/scripts/online_dpo_vlm.py +203 -0
- tasks/tasksmith-fa1a9b35ff39/tests/source/examples/scripts/openenv/browsergym.py +291 -0
- tasks/tasksmith-fa1a9b35ff39/tests/source/examples/scripts/openenv/browsergym_llm.py +463 -0
- tasks/tasksmith-fa1a9b35ff39/tests/source/examples/scripts/openenv/carla.py +219 -0
- tasks/tasksmith-fa1a9b35ff39/tests/source/examples/scripts/openenv/carla_vlm.py +262 -0
- tasks/tasksmith-fa1a9b35ff39/tests/source/examples/scripts/openenv/carla_vlm_gemma.py +278 -0
- tasks/tasksmith-fa1a9b35ff39/tests/source/examples/scripts/openenv/catch.py +347 -0
- tasks/tasksmith-fa1a9b35ff39/tests/source/examples/scripts/openenv/echo.py +133 -0
- tasks/tasksmith-fa1a9b35ff39/tests/source/examples/scripts/openenv/multi_env.py +273 -0
- tasks/tasksmith-fa1a9b35ff39/tests/source/examples/scripts/openenv/sudoku.py +669 -0
- tasks/tasksmith-fa1a9b35ff39/tests/source/examples/scripts/openenv/sudoku_prompt.txt +122 -0
- tasks/tasksmith-fa1a9b35ff39/tests/source/examples/scripts/openenv/wordle.py +277 -0
- tasks/tasksmith-fa1a9b35ff39/tests/source/examples/scripts/openreward/seta.py +127 -0
- tasks/tasksmith-fa1a9b35ff39/tests/source/examples/scripts/orpo.py +102 -0
- tasks/tasksmith-fa1a9b35ff39/tests/source/examples/scripts/ppo/ppo.py +160 -0
- tasks/tasksmith-fa1a9b35ff39/tests/source/examples/scripts/ppo/ppo_tldr.py +168 -0
- tasks/tasksmith-fa1a9b35ff39/tests/source/examples/scripts/prm.py +128 -0
.gitattributes
CHANGED
|
@@ -59,3 +59,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
|
| 59 |
*.mp4 filter=lfs diff=lfs merge=lfs -text
|
| 60 |
*.webm filter=lfs diff=lfs merge=lfs -text
|
| 61 |
bundle-files.json filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
| 59 |
*.mp4 filter=lfs diff=lfs merge=lfs -text
|
| 60 |
*.webm filter=lfs diff=lfs merge=lfs -text
|
| 61 |
bundle-files.json filter=lfs diff=lfs merge=lfs -text
|
| 62 |
+
release-files.json filter=lfs diff=lfs merge=lfs -text
|
README.md
ADDED
|
@@ -0,0 +1,105 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
license: other
|
| 3 |
+
license_name: mixed-source-licenses
|
| 4 |
+
license_link: https://huggingface.co/datasets/HuggingEnvs/HF_ML_Tasksmith/blob/main/LICENSES.md
|
| 5 |
+
language:
|
| 6 |
+
- en
|
| 7 |
+
tags:
|
| 8 |
+
- reinforcement-learning
|
| 9 |
+
- coding
|
| 10 |
+
- harbor
|
| 11 |
+
- repo2rlenv
|
| 12 |
+
- tasksmith
|
| 13 |
+
size_categories:
|
| 14 |
+
- n<1K
|
| 15 |
+
viewer: false
|
| 16 |
+
---
|
| 17 |
+
|
| 18 |
+
[](https://huggingface.co/spaces/HuggingFaceH4/harbor-visualiser?dataset=HuggingEnvs/HF_ML_Tasksmith)
|
| 19 |
+
|
| 20 |
+
# HF ML Tasksmith
|
| 21 |
+
|
| 22 |
+
Fifty PR-derived Harbor tasks from Accelerate, Diffusers, PEFT, Transformers and TRL, including CPU and GPU tasks.
|
| 23 |
+
|
| 24 |
+
Contains **50 Harbor tasks** generated with the owned
|
| 25 |
+
`tasksmith` recipe in [Repo2RLEnv](https://github.com/huggingface/Repo2RLEnv).
|
| 26 |
+
Browse the complete task bundles in [Harbor Visualiser](https://huggingface.co/spaces/HuggingFaceH4/harbor-visualiser?dataset=HuggingEnvs/HF_ML_Tasksmith) or
|
| 27 |
+
[open the task folders](https://huggingface.co/datasets/HuggingEnvs/HF_ML_Tasksmith/tree/main/tasks). Each folder is a runnable Harbor task:
|
| 28 |
+
|
| 29 |
+
```text
|
| 30 |
+
tasks/<task_id>/
|
| 31 |
+
├── task.toml # Harbor configuration and provenance
|
| 32 |
+
├── instruction.md # Task shown to the coding agent
|
| 33 |
+
├── environment/Dockerfile # Learner sandbox and its build context
|
| 34 |
+
├── solution/solve.sh # Reference solution entry point
|
| 35 |
+
└── tests/
|
| 36 |
+
├── test.sh # Verifier entry point; writes the reward
|
| 37 |
+
└── Dockerfile # Separate verifier sandbox, when configured
|
| 38 |
+
```
|
| 39 |
+
|
| 40 |
+
Example: [task.toml](https://huggingface.co/datasets/HuggingEnvs/HF_ML_Tasksmith/blob/main/tasks/tasksmith-03a6a091b12f/task.toml) ·
|
| 41 |
+
[instruction](https://huggingface.co/datasets/HuggingEnvs/HF_ML_Tasksmith/blob/main/tasks/tasksmith-03a6a091b12f/instruction.md) ·
|
| 42 |
+
[verifier](https://huggingface.co/datasets/HuggingEnvs/HF_ML_Tasksmith/blob/main/tasks/tasksmith-03a6a091b12f/tests/test.sh) ·
|
| 43 |
+
[oracle](https://huggingface.co/datasets/HuggingEnvs/HF_ML_Tasksmith/blob/main/tasks/tasksmith-03a6a091b12f/solution/solve.sh).
|
| 44 |
+
|
| 45 |
+
`data/tasks.jsonl` is an auxiliary metadata index. Download the task folders or
|
| 46 |
+
archive below to run the environments. `manifest.json` records source identity,
|
| 47 |
+
evidence, diagnostics and measured costs. The generic tabular Hub viewer is
|
| 48 |
+
disabled so it does not present the index as the task dataset.
|
| 49 |
+
|
| 50 |
+
## Generation
|
| 51 |
+
|
| 52 |
+
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.
|
| 53 |
+
|
| 54 |
+
Implementation revision: `a8ea8fa644ec4c3980291f00d7f8190cdfb45a45`. The exact recipe, source revision,
|
| 55 |
+
reward kinds and quality status remain in each original `task.toml`.
|
| 56 |
+
|
| 57 |
+
## Validation and limitations
|
| 58 |
+
|
| 59 |
+
Quality label counts: `{"verified": 50}`.
|
| 60 |
+
An `exported` task is a generation artifact. Baseline/reference controls establish
|
| 61 |
+
only the behavior recorded in that task's evidence. They do not establish blind
|
| 62 |
+
solver success, difficulty, verifier completeness or resistance to reward hacking.
|
| 63 |
+
An LLM consistency review is separate from the deterministic task reward.
|
| 64 |
+
|
| 65 |
+
- 50 assisted practical-acceptance tasks: this is not an unattended yield estimate.
|
| 66 |
+
- Sonnet fully solved 19 tasks; 31 did not receive full reward. Solver success was not required for task acceptance.
|
| 67 |
+
- 39 tasks request CPU only, 6 request one GPU and 5 request two GPUs; select a provider with matching resources.
|
| 68 |
+
- Existing task metadata may reference historical local evidence paths; use the published manifest for portable acceptance summaries and evidence hashes.
|
| 69 |
+
- Source files retain upstream repository licenses.
|
| 70 |
+
|
| 71 |
+
## Download and run
|
| 72 |
+
|
| 73 |
+
`tasks.tar.gz` preserves executable file modes and the original bundle identities:
|
| 74 |
+
|
| 75 |
+
```bash
|
| 76 |
+
hf download HuggingEnvs/HF_ML_Tasksmith tasks.tar.gz --repo-type dataset --local-dir ./dataset
|
| 77 |
+
tar -xzf ./dataset/tasks.tar.gz -C ./dataset
|
| 78 |
+
harbor run --path ./dataset/tasks --agent oracle --env daytona
|
| 79 |
+
```
|
| 80 |
+
|
| 81 |
+
Configure Daytona credentials and Harbor's provider dependencies before execution.
|
| 82 |
+
The archive includes references and private tests for the harness; the solver
|
| 83 |
+
should receive only the instruction and learner environment. `registry.json`
|
| 84 |
+
pins the unpacked task paths to the immutable upload commit.
|
| 85 |
+
|
| 86 |
+
## Economics
|
| 87 |
+
|
| 88 |
+
`manifest.json` includes generation costs, failed-attempt costs and outstanding
|
| 89 |
+
reservations when available. Cloud lifetime estimates are labeled separately from
|
| 90 |
+
provider invoices. Retained task costs and new-generation costs use separate scopes.
|
| 91 |
+
|
| 92 |
+
## Credits and licensing
|
| 93 |
+
|
| 94 |
+
- https://github.com/huggingface/Repo2RLEnv/blob/a8ea8fa644ec4c3980291f00d7f8190cdfb45a45/docs/rfcs/0028-tasksmith-pr-pilot.md
|
| 95 |
+
- https://github.com/huggingface/Repo2RLEnv/blob/a8ea8fa644ec4c3980291f00d7f8190cdfb45a45/docs/pipelines/tasksmith_campaign_retrospective.md
|
| 96 |
+
- https://www.harborframework.com/docs/tasks
|
| 97 |
+
- https://github.com/huggingface/transformers
|
| 98 |
+
- https://github.com/huggingface/trl
|
| 99 |
+
- https://github.com/huggingface/peft
|
| 100 |
+
- https://github.com/huggingface/diffusers
|
| 101 |
+
- https://github.com/huggingface/accelerate
|
| 102 |
+
|
| 103 |
+
See [LICENSES.md](LICENSES.md), bundled notices and per-task provenance. These are
|
| 104 |
+
owned adaptations inspired by the credited methods, not an upstream benchmark
|
| 105 |
+
release or a claim of exact reproduction of its published results.
|
release-files.json
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:7b6217eea74e00d9899e230e78a42756530347ef97b82f7383e1cfb7939b23d5
|
| 3 |
+
size 24289045
|
tasks/tasksmith-fa1a9b35ff39/tests/source/examples/scripts/async_grpo.py
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2020-2026 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
# /// script
|
| 16 |
+
# dependencies = [
|
| 17 |
+
# "trl",
|
| 18 |
+
# "math-verify",
|
| 19 |
+
# "latex2sympy2_extended",
|
| 20 |
+
# "trackio",
|
| 21 |
+
# ]
|
| 22 |
+
# ///
|
| 23 |
+
|
| 24 |
+
"""
|
| 25 |
+
pip install math_verify
|
| 26 |
+
|
| 27 |
+
CUDA_VISIBLE_DEVICES=1 VLLM_SERVER_DEV_MODE=1 vllm serve Qwen/Qwen3-0.6B \
|
| 28 |
+
--max-model-len 2048 \
|
| 29 |
+
--logprobs-mode processed_logprobs \
|
| 30 |
+
--weight-transfer-config '{"backend":"nccl"}'
|
| 31 |
+
|
| 32 |
+
CUDA_VISIBLE_DEVICES=0 accelerate launch examples/scripts/async_grpo.py
|
| 33 |
+
"""
|
| 34 |
+
|
| 35 |
+
from datasets import load_dataset
|
| 36 |
+
|
| 37 |
+
from trl.experimental.async_grpo import AsyncGRPOConfig, AsyncGRPOTrainer
|
| 38 |
+
from trl.rewards import accuracy_reward
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def format_sample(sample):
|
| 42 |
+
return {
|
| 43 |
+
"prompt": [{"role": "user", "content": sample["question"]}],
|
| 44 |
+
"solution": sample["answer"].split("####")[-1].strip(),
|
| 45 |
+
}
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def main() -> None:
|
| 49 |
+
dataset = load_dataset("openai/gsm8k", "main", split="train")
|
| 50 |
+
dataset = dataset.map(format_sample, remove_columns=dataset.column_names)
|
| 51 |
+
|
| 52 |
+
config = AsyncGRPOConfig(
|
| 53 |
+
output_dir="async_grpo_gsm8k",
|
| 54 |
+
save_strategy="no",
|
| 55 |
+
per_device_train_batch_size=16,
|
| 56 |
+
gradient_accumulation_steps=2,
|
| 57 |
+
max_completion_length=1024,
|
| 58 |
+
chat_template_kwargs={"enable_thinking": False},
|
| 59 |
+
max_steps=200,
|
| 60 |
+
learning_rate=1e-5,
|
| 61 |
+
report_to="trackio",
|
| 62 |
+
trackio_space_id="async-grpo-gsm8k",
|
| 63 |
+
project="async-grpo-gsm8k",
|
| 64 |
+
log_completions=True,
|
| 65 |
+
)
|
| 66 |
+
trainer = AsyncGRPOTrainer(
|
| 67 |
+
model="Qwen/Qwen3-0.6B",
|
| 68 |
+
args=config,
|
| 69 |
+
train_dataset=dataset,
|
| 70 |
+
reward_funcs=accuracy_reward,
|
| 71 |
+
)
|
| 72 |
+
trainer.train()
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
if __name__ == "__main__":
|
| 76 |
+
main()
|
tasks/tasksmith-fa1a9b35ff39/tests/source/examples/scripts/bco.py
ADDED
|
@@ -0,0 +1,156 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2020-2026 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
# /// script
|
| 16 |
+
# dependencies = [
|
| 17 |
+
# "trl[peft]",
|
| 18 |
+
# "einops",
|
| 19 |
+
# "scikit-learn",
|
| 20 |
+
# "joblib",
|
| 21 |
+
# "trackio",
|
| 22 |
+
# "kernels",
|
| 23 |
+
# ]
|
| 24 |
+
# ///
|
| 25 |
+
|
| 26 |
+
"""
|
| 27 |
+
Run the BCO training script with the commands below. In general, the optimal configuration for BCO will be similar to that of KTO.
|
| 28 |
+
|
| 29 |
+
# Full training:
|
| 30 |
+
python examples/scripts/bco.py \
|
| 31 |
+
--model_name_or_path Qwen/Qwen2.5-0.5B-Instruct \
|
| 32 |
+
--trust_remote_code \
|
| 33 |
+
--dataset_name trl-lib/ultrafeedback-gpt-3.5-turbo-helpfulness \
|
| 34 |
+
--per_device_train_batch_size 16 \
|
| 35 |
+
--per_device_eval_batch_size 32 \
|
| 36 |
+
--num_train_epochs 1 \
|
| 37 |
+
--gradient_accumulation_steps 1 \
|
| 38 |
+
--eval_steps 0.2 \
|
| 39 |
+
--save_strategy no \
|
| 40 |
+
--output_dir bco-aligned-model \
|
| 41 |
+
--logging_first_step \
|
| 42 |
+
--max_length 2048 \
|
| 43 |
+
--max_completion_length 1024 \
|
| 44 |
+
--no_remove_unused_columns \
|
| 45 |
+
--warmup_steps 0.1
|
| 46 |
+
|
| 47 |
+
# QLoRA:
|
| 48 |
+
python examples/scripts/bco.py \
|
| 49 |
+
--model_name_or_path Qwen/Qwen2.5-0.5B-Instruct \
|
| 50 |
+
--trust_remote_code \
|
| 51 |
+
--dataset_name trl-lib/ultrafeedback-gpt-3.5-turbo-helpfulness \
|
| 52 |
+
--per_device_train_batch_size 16 \
|
| 53 |
+
--per_device_eval_batch_size 32 \
|
| 54 |
+
--num_train_epochs 1 \
|
| 55 |
+
--gradient_accumulation_steps 1 \
|
| 56 |
+
--eval_steps 0.2 \
|
| 57 |
+
--save_strategy no \
|
| 58 |
+
--output_dir bco-aligned-model-lora \
|
| 59 |
+
--logging_first_step \
|
| 60 |
+
--warmup_steps 0.1 \
|
| 61 |
+
--max_length 2048 \
|
| 62 |
+
--max_completion_length 1024 \
|
| 63 |
+
--no_remove_unused_columns \
|
| 64 |
+
--warmup_steps 0.1 \
|
| 65 |
+
--use_peft \
|
| 66 |
+
--load_in_4bit \
|
| 67 |
+
--lora_target_modules all-linear \
|
| 68 |
+
--lora_r 16 \
|
| 69 |
+
--lora_alpha 16
|
| 70 |
+
"""
|
| 71 |
+
|
| 72 |
+
from functools import partial
|
| 73 |
+
|
| 74 |
+
import torch
|
| 75 |
+
import torch.nn.functional as F
|
| 76 |
+
from accelerate import Accelerator
|
| 77 |
+
from datasets import load_dataset
|
| 78 |
+
from transformers import AutoModel, AutoModelForCausalLM, AutoTokenizer, HfArgumentParser, PreTrainedModel
|
| 79 |
+
|
| 80 |
+
from trl import ModelConfig, ScriptArguments, get_peft_config
|
| 81 |
+
from trl.experimental.bco import BCOConfig, BCOTrainer
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
def embed_prompt(input_ids: torch.LongTensor, attention_mask: torch.LongTensor, model: PreTrainedModel):
|
| 85 |
+
"""
|
| 86 |
+
Borrowed from https://huggingface.co/nomic-ai/nomic-embed-text-v1.5#transformers
|
| 87 |
+
"""
|
| 88 |
+
|
| 89 |
+
def mean_pooling(model_output, attention_mask):
|
| 90 |
+
token_embeddings = model_output[0]
|
| 91 |
+
input_mask_expanded = attention_mask.unsqueeze(-1).expand(token_embeddings.size()).float()
|
| 92 |
+
return torch.sum(token_embeddings * input_mask_expanded, 1) / torch.clamp(input_mask_expanded.sum(1), min=1e-9)
|
| 93 |
+
|
| 94 |
+
with torch.no_grad():
|
| 95 |
+
model_output = model(input_ids=input_ids, attention_mask=attention_mask)
|
| 96 |
+
embeddings = mean_pooling(model_output, attention_mask)
|
| 97 |
+
|
| 98 |
+
matryoshka_dim = 512
|
| 99 |
+
# normalize embeddings
|
| 100 |
+
embeddings = F.normalize(embeddings, p=2, dim=1)
|
| 101 |
+
embeddings = F.layer_norm(embeddings, normalized_shape=(embeddings.shape[1],))
|
| 102 |
+
embeddings = embeddings[:, :matryoshka_dim]
|
| 103 |
+
|
| 104 |
+
return embeddings
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
if __name__ == "__main__":
|
| 108 |
+
parser = HfArgumentParser((ScriptArguments, BCOConfig, ModelConfig))
|
| 109 |
+
script_args, training_args, model_args = parser.parse_args_into_dataclasses()
|
| 110 |
+
|
| 111 |
+
training_args.gradient_checkpointing_kwargs = {"use_reentrant": True}
|
| 112 |
+
|
| 113 |
+
# Load a pretrained model
|
| 114 |
+
model = AutoModelForCausalLM.from_pretrained(model_args.model_name_or_path)
|
| 115 |
+
ref_model = AutoModelForCausalLM.from_pretrained(model_args.model_name_or_path)
|
| 116 |
+
|
| 117 |
+
tokenizer = AutoTokenizer.from_pretrained(model_args.model_name_or_path)
|
| 118 |
+
if tokenizer.pad_token is None:
|
| 119 |
+
tokenizer.pad_token = tokenizer.eos_token
|
| 120 |
+
|
| 121 |
+
dataset = load_dataset(script_args.dataset_name, name=script_args.dataset_config)
|
| 122 |
+
|
| 123 |
+
accelerator = Accelerator()
|
| 124 |
+
embedding_model = AutoModel.from_pretrained(
|
| 125 |
+
"nomic-ai/nomic-embed-text-v1.5",
|
| 126 |
+
safe_serialization=True,
|
| 127 |
+
dtype=torch.bfloat16,
|
| 128 |
+
device_map="auto",
|
| 129 |
+
)
|
| 130 |
+
embedding_model = accelerator.prepare_model(embedding_model)
|
| 131 |
+
embedding_tokenizer = AutoTokenizer.from_pretrained("bert-base-uncased")
|
| 132 |
+
embedding_func = partial(
|
| 133 |
+
embed_prompt,
|
| 134 |
+
model=embedding_model,
|
| 135 |
+
)
|
| 136 |
+
|
| 137 |
+
# Initialize the BCO trainer
|
| 138 |
+
trainer = BCOTrainer(
|
| 139 |
+
model,
|
| 140 |
+
ref_model,
|
| 141 |
+
args=training_args,
|
| 142 |
+
train_dataset=dataset[script_args.dataset_train_split],
|
| 143 |
+
eval_dataset=dataset[script_args.dataset_test_split] if training_args.eval_strategy != "no" else None,
|
| 144 |
+
processing_class=tokenizer,
|
| 145 |
+
peft_config=get_peft_config(model_args),
|
| 146 |
+
embedding_func=embedding_func,
|
| 147 |
+
embedding_tokenizer=embedding_tokenizer,
|
| 148 |
+
)
|
| 149 |
+
|
| 150 |
+
# Train and push the model to the Hub
|
| 151 |
+
trainer.train()
|
| 152 |
+
|
| 153 |
+
# Save and push to hub
|
| 154 |
+
trainer.save_model(training_args.output_dir)
|
| 155 |
+
if training_args.push_to_hub:
|
| 156 |
+
trainer.push_to_hub(dataset_name=script_args.dataset_name)
|
tasks/tasksmith-fa1a9b35ff39/tests/source/examples/scripts/cpo.py
ADDED
|
@@ -0,0 +1,102 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2020-2026 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
# /// script
|
| 16 |
+
# dependencies = [
|
| 17 |
+
# "trl[peft]",
|
| 18 |
+
# "trackio",
|
| 19 |
+
# "kernels",
|
| 20 |
+
# ]
|
| 21 |
+
# ///
|
| 22 |
+
|
| 23 |
+
"""
|
| 24 |
+
Run the CPO training script with the following command with some example arguments.
|
| 25 |
+
In general, the optimal configuration for CPO will be similar to that of DPO:
|
| 26 |
+
|
| 27 |
+
# Full training:
|
| 28 |
+
python examples/scripts/cpo.py \
|
| 29 |
+
--dataset_name trl-lib/ultrafeedback_binarized \
|
| 30 |
+
--model_name_or_path gpt2 \
|
| 31 |
+
--per_device_train_batch_size 4 \
|
| 32 |
+
--max_steps 1000 \
|
| 33 |
+
--learning_rate 8e-6 \
|
| 34 |
+
--gradient_accumulation_steps 1 \
|
| 35 |
+
--eval_steps 500 \
|
| 36 |
+
--output_dir "gpt2-aligned-cpo" \
|
| 37 |
+
--warmup_steps 150 \
|
| 38 |
+
--logging_first_step \
|
| 39 |
+
--no_remove_unused_columns
|
| 40 |
+
|
| 41 |
+
# QLoRA:
|
| 42 |
+
python examples/scripts/cpo.py \
|
| 43 |
+
--dataset_name trl-lib/ultrafeedback_binarized \
|
| 44 |
+
--model_name_or_path gpt2 \
|
| 45 |
+
--per_device_train_batch_size 4 \
|
| 46 |
+
--max_steps 1000 \
|
| 47 |
+
--learning_rate 8e-5 \
|
| 48 |
+
--gradient_accumulation_steps 1 \
|
| 49 |
+
--eval_steps 500 \
|
| 50 |
+
--output_dir "gpt2-lora-aligned-cpo" \
|
| 51 |
+
--optim rmsprop \
|
| 52 |
+
--warmup_steps 150 \
|
| 53 |
+
--logging_first_step \
|
| 54 |
+
--no_remove_unused_columns \
|
| 55 |
+
--use_peft \
|
| 56 |
+
--lora_r 16 \
|
| 57 |
+
--lora_alpha 16
|
| 58 |
+
"""
|
| 59 |
+
|
| 60 |
+
from datasets import load_dataset
|
| 61 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer, HfArgumentParser
|
| 62 |
+
|
| 63 |
+
from trl import ModelConfig, ScriptArguments, get_peft_config
|
| 64 |
+
from trl.experimental.cpo import CPOConfig, CPOTrainer
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
if __name__ == "__main__":
|
| 68 |
+
parser = HfArgumentParser((ScriptArguments, CPOConfig, ModelConfig))
|
| 69 |
+
script_args, training_args, model_args = parser.parse_args_into_dataclasses()
|
| 70 |
+
|
| 71 |
+
################
|
| 72 |
+
# Model & Tokenizer
|
| 73 |
+
################
|
| 74 |
+
model = AutoModelForCausalLM.from_pretrained(model_args.model_name_or_path)
|
| 75 |
+
tokenizer = AutoTokenizer.from_pretrained(model_args.model_name_or_path)
|
| 76 |
+
if tokenizer.pad_token is None:
|
| 77 |
+
tokenizer.pad_token = tokenizer.eos_token
|
| 78 |
+
|
| 79 |
+
################
|
| 80 |
+
# Dataset
|
| 81 |
+
################
|
| 82 |
+
dataset = load_dataset(script_args.dataset_name, name=script_args.dataset_config)
|
| 83 |
+
|
| 84 |
+
################
|
| 85 |
+
# Training
|
| 86 |
+
################
|
| 87 |
+
trainer = CPOTrainer(
|
| 88 |
+
model,
|
| 89 |
+
args=training_args,
|
| 90 |
+
train_dataset=dataset[script_args.dataset_train_split],
|
| 91 |
+
eval_dataset=dataset[script_args.dataset_test_split] if training_args.eval_strategy != "no" else None,
|
| 92 |
+
processing_class=tokenizer,
|
| 93 |
+
peft_config=get_peft_config(model_args),
|
| 94 |
+
)
|
| 95 |
+
|
| 96 |
+
# train and save the model
|
| 97 |
+
trainer.train()
|
| 98 |
+
|
| 99 |
+
# Save and push to hub
|
| 100 |
+
trainer.save_model(training_args.output_dir)
|
| 101 |
+
if training_args.push_to_hub:
|
| 102 |
+
trainer.push_to_hub(dataset_name=script_args.dataset_name)
|
tasks/tasksmith-fa1a9b35ff39/tests/source/examples/scripts/distillation.py
ADDED
|
@@ -0,0 +1,177 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2020-2026 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
# /// script
|
| 16 |
+
# dependencies = [
|
| 17 |
+
# "trl",
|
| 18 |
+
# "peft",
|
| 19 |
+
# "trackio",
|
| 20 |
+
# "kernels",
|
| 21 |
+
# ]
|
| 22 |
+
# ///
|
| 23 |
+
|
| 24 |
+
# docstyle-ignore
|
| 25 |
+
"""
|
| 26 |
+
# Full training (off-policy only, lmbda=0):
|
| 27 |
+
```
|
| 28 |
+
python examples/scripts/distillation.py \
|
| 29 |
+
--model_name_or_path Qwen/Qwen2.5-0.5B-Instruct \
|
| 30 |
+
--teacher_model_name_or_path Qwen/Qwen2.5-1.5B-Instruct \
|
| 31 |
+
--dataset_name trl-lib/chatbot_arena_completions \
|
| 32 |
+
--learning_rate 2e-5 \
|
| 33 |
+
--per_device_train_batch_size 4 \
|
| 34 |
+
--gradient_accumulation_steps 8 \
|
| 35 |
+
--lmbda 0.0 \
|
| 36 |
+
--output_dir distilled-model \
|
| 37 |
+
--num_train_epochs 1
|
| 38 |
+
```
|
| 39 |
+
|
| 40 |
+
# Mixed on/off-policy (lmbda=0.5):
|
| 41 |
+
```
|
| 42 |
+
python examples/scripts/distillation.py \
|
| 43 |
+
--model_name_or_path Qwen/Qwen2.5-0.5B-Instruct \
|
| 44 |
+
--teacher_model_name_or_path Qwen/Qwen2.5-1.5B-Instruct \
|
| 45 |
+
--dataset_name trl-lib/chatbot_arena_completions \
|
| 46 |
+
--learning_rate 2e-5 \
|
| 47 |
+
--per_device_train_batch_size 4 \
|
| 48 |
+
--gradient_accumulation_steps 8 \
|
| 49 |
+
--lmbda 0.5 \
|
| 50 |
+
--beta 0.5 \
|
| 51 |
+
--output_dir distilled-model \
|
| 52 |
+
--num_train_epochs 1
|
| 53 |
+
```
|
| 54 |
+
|
| 55 |
+
# LoRA:
|
| 56 |
+
```
|
| 57 |
+
python examples/scripts/distillation.py \
|
| 58 |
+
--model_name_or_path Qwen/Qwen2.5-0.5B-Instruct \
|
| 59 |
+
--teacher_model_name_or_path Qwen/Qwen2.5-1.5B-Instruct \
|
| 60 |
+
--dataset_name trl-lib/chatbot_arena_completions \
|
| 61 |
+
--learning_rate 2e-4 \
|
| 62 |
+
--per_device_train_batch_size 4 \
|
| 63 |
+
--gradient_accumulation_steps 8 \
|
| 64 |
+
--lmbda 0.0 \
|
| 65 |
+
--output_dir distilled-model \
|
| 66 |
+
--num_train_epochs 1 \
|
| 67 |
+
--use_peft \
|
| 68 |
+
--lora_r 64 \
|
| 69 |
+
--lora_alpha 16
|
| 70 |
+
```
|
| 71 |
+
"""
|
| 72 |
+
|
| 73 |
+
import argparse
|
| 74 |
+
import os
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
# Enable logging in a Hugging Face Space
|
| 78 |
+
os.environ.setdefault("TRACKIO_SPACE_ID", "trl-trackio")
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
def main(script_args, training_args, model_args):
|
| 82 |
+
from datasets import load_dataset
|
| 83 |
+
from transformers import GenerationConfig
|
| 84 |
+
|
| 85 |
+
from trl import (
|
| 86 |
+
LogCompletionsCallback,
|
| 87 |
+
get_kbit_device_map,
|
| 88 |
+
get_peft_config,
|
| 89 |
+
get_quantization_config,
|
| 90 |
+
)
|
| 91 |
+
from trl.experimental.distillation import DistillationTrainer
|
| 92 |
+
|
| 93 |
+
################
|
| 94 |
+
# Model init kwargs
|
| 95 |
+
################
|
| 96 |
+
quantization_config = get_quantization_config(model_args)
|
| 97 |
+
model_kwargs = dict(
|
| 98 |
+
revision=model_args.model_revision,
|
| 99 |
+
attn_implementation=model_args.attn_implementation,
|
| 100 |
+
dtype=model_args.dtype,
|
| 101 |
+
use_cache=False if training_args.gradient_checkpointing else True,
|
| 102 |
+
device_map=get_kbit_device_map() if quantization_config is not None else None,
|
| 103 |
+
quantization_config=quantization_config,
|
| 104 |
+
)
|
| 105 |
+
training_args.model_init_kwargs = model_kwargs
|
| 106 |
+
|
| 107 |
+
teacher_model_kwargs = dict(
|
| 108 |
+
revision=training_args.teacher_model_revision,
|
| 109 |
+
attn_implementation=model_args.attn_implementation,
|
| 110 |
+
dtype=model_args.dtype,
|
| 111 |
+
use_cache=True,
|
| 112 |
+
device_map=get_kbit_device_map() if quantization_config is not None else None,
|
| 113 |
+
quantization_config=quantization_config,
|
| 114 |
+
)
|
| 115 |
+
if training_args.teacher_model_init_kwargs is not None:
|
| 116 |
+
teacher_model_kwargs.update(training_args.teacher_model_init_kwargs)
|
| 117 |
+
training_args.teacher_model_init_kwargs = teacher_model_kwargs
|
| 118 |
+
|
| 119 |
+
################
|
| 120 |
+
# Dataset
|
| 121 |
+
################
|
| 122 |
+
dataset = load_dataset(script_args.dataset_name, name=script_args.dataset_config)
|
| 123 |
+
|
| 124 |
+
################
|
| 125 |
+
# Training
|
| 126 |
+
################
|
| 127 |
+
eval_dataset = None
|
| 128 |
+
if training_args.eval_strategy != "no":
|
| 129 |
+
if script_args.dataset_test_split in dataset:
|
| 130 |
+
eval_dataset = dataset[script_args.dataset_test_split]
|
| 131 |
+
elif "validation" in dataset:
|
| 132 |
+
eval_dataset = dataset["validation"]
|
| 133 |
+
elif "dev" in dataset:
|
| 134 |
+
eval_dataset = dataset["dev"]
|
| 135 |
+
|
| 136 |
+
trainer = DistillationTrainer(
|
| 137 |
+
model=model_args.model_name_or_path,
|
| 138 |
+
teacher_model=training_args.teacher_model_name_or_path,
|
| 139 |
+
args=training_args,
|
| 140 |
+
train_dataset=dataset[script_args.dataset_train_split],
|
| 141 |
+
eval_dataset=eval_dataset,
|
| 142 |
+
peft_config=get_peft_config(model_args),
|
| 143 |
+
)
|
| 144 |
+
|
| 145 |
+
if training_args.eval_strategy != "no":
|
| 146 |
+
generation_config = GenerationConfig(
|
| 147 |
+
max_new_tokens=training_args.max_completion_length, do_sample=True, temperature=training_args.temperature
|
| 148 |
+
)
|
| 149 |
+
completions_callback = LogCompletionsCallback(trainer, generation_config, num_prompts=8)
|
| 150 |
+
trainer.add_callback(completions_callback)
|
| 151 |
+
|
| 152 |
+
trainer.train()
|
| 153 |
+
|
| 154 |
+
# Save and push to Hub
|
| 155 |
+
trainer.save_model(training_args.output_dir)
|
| 156 |
+
if training_args.push_to_hub:
|
| 157 |
+
trainer.push_to_hub(dataset_name=script_args.dataset_name)
|
| 158 |
+
|
| 159 |
+
|
| 160 |
+
def make_parser(subparsers: argparse._SubParsersAction | None = None, prog: str | None = None):
|
| 161 |
+
from trl import ModelConfig, ScriptArguments, TrlParser
|
| 162 |
+
from trl.experimental.distillation import DistillationConfig
|
| 163 |
+
|
| 164 |
+
dataclass_types = (ScriptArguments, DistillationConfig, ModelConfig)
|
| 165 |
+
if subparsers is not None:
|
| 166 |
+
parser = subparsers.add_parser(
|
| 167 |
+
"distillation", help="Run the distillation training script", dataclass_types=dataclass_types
|
| 168 |
+
)
|
| 169 |
+
else:
|
| 170 |
+
parser = TrlParser(dataclass_types, prog=prog)
|
| 171 |
+
return parser
|
| 172 |
+
|
| 173 |
+
|
| 174 |
+
if __name__ == "__main__":
|
| 175 |
+
parser = make_parser()
|
| 176 |
+
script_args, training_args, model_args = parser.parse_args_and_config(fail_with_unknown_args=False)
|
| 177 |
+
main(script_args, training_args, model_args)
|
tasks/tasksmith-fa1a9b35ff39/tests/source/examples/scripts/dpo.py
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2020-2026 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
###############################################################################################
|
| 16 |
+
# This file has been moved to https://github.com/huggingface/trl/blob/main/trl/scripts/dpo.py #
|
| 17 |
+
###############################################################################################
|
tasks/tasksmith-fa1a9b35ff39/tests/source/examples/scripts/dpo_vlm.py
ADDED
|
@@ -0,0 +1,134 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2020-2026 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
# /// script
|
| 16 |
+
# dependencies = [
|
| 17 |
+
# "trl[peft]",
|
| 18 |
+
# "Pillow>=9.4.0",
|
| 19 |
+
# "torchvision",
|
| 20 |
+
# "trackio",
|
| 21 |
+
# "kernels",
|
| 22 |
+
# ]
|
| 23 |
+
# ///
|
| 24 |
+
|
| 25 |
+
"""
|
| 26 |
+
Without dataset streaming:
|
| 27 |
+
|
| 28 |
+
```
|
| 29 |
+
accelerate launch examples/scripts/dpo_vlm.py \
|
| 30 |
+
--dataset_name HuggingFaceH4/rlaif-v_formatted \
|
| 31 |
+
--model_name_or_path Qwen/Qwen2.5-VL-3B-Instruct \
|
| 32 |
+
--per_device_train_batch_size 2 \
|
| 33 |
+
--gradient_accumulation_steps 32 \
|
| 34 |
+
--dataset_num_proc 32 \
|
| 35 |
+
--output_dir dpo_qwen_2_5_rlaif-v \
|
| 36 |
+
--dtype bfloat16 \
|
| 37 |
+
--use_peft \
|
| 38 |
+
--lora_target_modules all-linear
|
| 39 |
+
```
|
| 40 |
+
|
| 41 |
+
With dataset streaming:
|
| 42 |
+
|
| 43 |
+
```
|
| 44 |
+
accelerate launch examples/scripts/dpo_vlm.py \
|
| 45 |
+
--dataset_name HuggingFaceH4/rlaif-v_formatted \
|
| 46 |
+
--dataset_streaming \
|
| 47 |
+
--model_name_or_path Qwen/Qwen2.5-VL-3B-Instruct \
|
| 48 |
+
--per_device_train_batch_size 2 \
|
| 49 |
+
--max_steps 100 \
|
| 50 |
+
--gradient_accumulation_steps 32 \
|
| 51 |
+
--dataset_num_proc 32 \
|
| 52 |
+
--output_dir dpo_qwen_2_5_rlaif-v \
|
| 53 |
+
--dtype bfloat16 \
|
| 54 |
+
--use_peft \
|
| 55 |
+
--lora_target_modules all-linear
|
| 56 |
+
```
|
| 57 |
+
"""
|
| 58 |
+
|
| 59 |
+
import torch
|
| 60 |
+
from datasets import load_dataset
|
| 61 |
+
from transformers import AutoModelForImageTextToText, AutoProcessor
|
| 62 |
+
|
| 63 |
+
from trl import (
|
| 64 |
+
DPOConfig,
|
| 65 |
+
DPOTrainer,
|
| 66 |
+
ModelConfig,
|
| 67 |
+
ScriptArguments,
|
| 68 |
+
TrlParser,
|
| 69 |
+
get_kbit_device_map,
|
| 70 |
+
get_peft_config,
|
| 71 |
+
get_quantization_config,
|
| 72 |
+
)
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
if __name__ == "__main__":
|
| 76 |
+
parser = TrlParser((ScriptArguments, DPOConfig, ModelConfig))
|
| 77 |
+
script_args, training_args, model_args = parser.parse_args_and_config()
|
| 78 |
+
|
| 79 |
+
################
|
| 80 |
+
# Model & Processor
|
| 81 |
+
################
|
| 82 |
+
dtype = model_args.dtype if model_args.dtype in ["auto", None] else getattr(torch, model_args.dtype)
|
| 83 |
+
|
| 84 |
+
model_kwargs = dict(
|
| 85 |
+
revision=model_args.model_revision,
|
| 86 |
+
attn_implementation=model_args.attn_implementation,
|
| 87 |
+
dtype=dtype,
|
| 88 |
+
)
|
| 89 |
+
quantization_config = get_quantization_config(model_args)
|
| 90 |
+
if quantization_config is not None:
|
| 91 |
+
# Passing None would not be treated the same as omitting the argument, so we include it only when valid.
|
| 92 |
+
model_kwargs["device_map"] = get_kbit_device_map()
|
| 93 |
+
model_kwargs["quantization_config"] = quantization_config
|
| 94 |
+
|
| 95 |
+
model = AutoModelForImageTextToText.from_pretrained(
|
| 96 |
+
model_args.model_name_or_path,
|
| 97 |
+
**model_kwargs,
|
| 98 |
+
)
|
| 99 |
+
peft_config = get_peft_config(model_args)
|
| 100 |
+
|
| 101 |
+
processor = AutoProcessor.from_pretrained(model_args.model_name_or_path, do_image_splitting=False)
|
| 102 |
+
|
| 103 |
+
if script_args.ignore_bias_buffers:
|
| 104 |
+
# torch distributed hack
|
| 105 |
+
model._ddp_params_and_buffers_to_ignore = [
|
| 106 |
+
name for name, buffer in model.named_buffers() if buffer.dtype == torch.bool
|
| 107 |
+
]
|
| 108 |
+
|
| 109 |
+
################
|
| 110 |
+
# Dataset
|
| 111 |
+
################
|
| 112 |
+
dataset = load_dataset(
|
| 113 |
+
script_args.dataset_name,
|
| 114 |
+
name=script_args.dataset_config,
|
| 115 |
+
streaming=script_args.dataset_streaming,
|
| 116 |
+
)
|
| 117 |
+
|
| 118 |
+
################
|
| 119 |
+
# Training
|
| 120 |
+
################
|
| 121 |
+
trainer = DPOTrainer(
|
| 122 |
+
model,
|
| 123 |
+
args=training_args,
|
| 124 |
+
train_dataset=dataset[script_args.dataset_train_split],
|
| 125 |
+
eval_dataset=dataset[script_args.dataset_test_split] if training_args.eval_strategy != "no" else None,
|
| 126 |
+
peft_config=peft_config,
|
| 127 |
+
)
|
| 128 |
+
|
| 129 |
+
trainer.train()
|
| 130 |
+
|
| 131 |
+
# Save and push to hub
|
| 132 |
+
trainer.save_model(training_args.output_dir)
|
| 133 |
+
if training_args.push_to_hub:
|
| 134 |
+
trainer.push_to_hub(dataset_name=script_args.dataset_name)
|
tasks/tasksmith-fa1a9b35ff39/tests/source/examples/scripts/gkd.py
ADDED
|
@@ -0,0 +1,139 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2020-2026 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
# /// script
|
| 16 |
+
# dependencies = [
|
| 17 |
+
# "trl[peft]",
|
| 18 |
+
# "trackio",
|
| 19 |
+
# "kernels",
|
| 20 |
+
# ]
|
| 21 |
+
# ///
|
| 22 |
+
|
| 23 |
+
"""
|
| 24 |
+
# Full training:
|
| 25 |
+
python examples/scripts/gkd.py \
|
| 26 |
+
--model_name_or_path Qwen/Qwen2-0.5B-Instruct \
|
| 27 |
+
--teacher_model_name_or_path Qwen/Qwen2-1.5B-Instruct \
|
| 28 |
+
--dataset_name trl-lib/chatbot_arena_completions \
|
| 29 |
+
--learning_rate 2e-5 \
|
| 30 |
+
--per_device_train_batch_size 4 \
|
| 31 |
+
--gradient_accumulation_steps 8 \
|
| 32 |
+
--output_dir gkd-model \
|
| 33 |
+
--num_train_epochs 1 \
|
| 34 |
+
--push_to_hub
|
| 35 |
+
|
| 36 |
+
# LoRA:
|
| 37 |
+
python examples/scripts/gkd.py \
|
| 38 |
+
--model_name_or_path Qwen/Qwen2-0.5B-Instruct \
|
| 39 |
+
--teacher_model_name_or_path Qwen/Qwen2-1.5B-Instruct \
|
| 40 |
+
--dataset_name trl-lib/chatbot_arena_completions \
|
| 41 |
+
--learning_rate 2e-4 \
|
| 42 |
+
--per_device_train_batch_size 4 \
|
| 43 |
+
--gradient_accumulation_steps 8 \
|
| 44 |
+
--output_dir gkd-model \
|
| 45 |
+
--num_train_epochs 1 \
|
| 46 |
+
--push_to_hub \
|
| 47 |
+
--use_peft \
|
| 48 |
+
--lora_r 64 \
|
| 49 |
+
--lora_alpha 16
|
| 50 |
+
"""
|
| 51 |
+
|
| 52 |
+
from datasets import load_dataset
|
| 53 |
+
from transformers import AutoTokenizer, GenerationConfig
|
| 54 |
+
|
| 55 |
+
from trl import (
|
| 56 |
+
LogCompletionsCallback,
|
| 57 |
+
ModelConfig,
|
| 58 |
+
ScriptArguments,
|
| 59 |
+
TrlParser,
|
| 60 |
+
get_kbit_device_map,
|
| 61 |
+
get_peft_config,
|
| 62 |
+
get_quantization_config,
|
| 63 |
+
)
|
| 64 |
+
from trl.experimental.gkd import GKDConfig, GKDTrainer
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
if __name__ == "__main__":
|
| 68 |
+
parser = TrlParser((ScriptArguments, GKDConfig, ModelConfig))
|
| 69 |
+
script_args, training_args, model_args = parser.parse_args_and_config()
|
| 70 |
+
|
| 71 |
+
################
|
| 72 |
+
# Model & Tokenizer
|
| 73 |
+
################
|
| 74 |
+
model_kwargs = dict(
|
| 75 |
+
revision=model_args.model_revision,
|
| 76 |
+
attn_implementation=model_args.attn_implementation,
|
| 77 |
+
dtype=model_args.dtype,
|
| 78 |
+
use_cache=False if training_args.gradient_checkpointing else True,
|
| 79 |
+
)
|
| 80 |
+
quantization_config = get_quantization_config(model_args)
|
| 81 |
+
if quantization_config is not None:
|
| 82 |
+
# Passing None would not be treated the same as omitting the argument, so we include it only when valid.
|
| 83 |
+
model_kwargs["device_map"] = get_kbit_device_map()
|
| 84 |
+
model_kwargs["quantization_config"] = quantization_config
|
| 85 |
+
|
| 86 |
+
training_args.model_init_kwargs = model_kwargs
|
| 87 |
+
|
| 88 |
+
teacher_model_kwargs = dict(
|
| 89 |
+
revision=model_args.model_revision,
|
| 90 |
+
attn_implementation=model_args.attn_implementation,
|
| 91 |
+
dtype=model_args.dtype,
|
| 92 |
+
use_cache=True,
|
| 93 |
+
)
|
| 94 |
+
if quantization_config is not None:
|
| 95 |
+
# Passing None would not be treated the same as omitting the argument, so we include it only when valid.
|
| 96 |
+
model_kwargs["device_map"] = get_kbit_device_map()
|
| 97 |
+
model_kwargs["quantization_config"] = quantization_config
|
| 98 |
+
|
| 99 |
+
training_args.teacher_model_init_kwargs = teacher_model_kwargs
|
| 100 |
+
|
| 101 |
+
tokenizer = AutoTokenizer.from_pretrained(
|
| 102 |
+
model_args.model_name_or_path,
|
| 103 |
+
revision=model_args.model_revision,
|
| 104 |
+
padding_side="left",
|
| 105 |
+
)
|
| 106 |
+
if tokenizer.pad_token is None:
|
| 107 |
+
tokenizer.pad_token = tokenizer.eos_token
|
| 108 |
+
|
| 109 |
+
################
|
| 110 |
+
# Dataset
|
| 111 |
+
################
|
| 112 |
+
dataset = load_dataset(script_args.dataset_name, name=script_args.dataset_config)
|
| 113 |
+
|
| 114 |
+
################
|
| 115 |
+
# Training
|
| 116 |
+
################
|
| 117 |
+
trainer = GKDTrainer(
|
| 118 |
+
model=model_args.model_name_or_path,
|
| 119 |
+
teacher_model=training_args.teacher_model_name_or_path,
|
| 120 |
+
args=training_args,
|
| 121 |
+
train_dataset=dataset[script_args.dataset_train_split],
|
| 122 |
+
eval_dataset=dataset[script_args.dataset_test_split] if training_args.eval_strategy != "no" else None,
|
| 123 |
+
processing_class=tokenizer,
|
| 124 |
+
peft_config=get_peft_config(model_args),
|
| 125 |
+
)
|
| 126 |
+
|
| 127 |
+
if training_args.eval_strategy != "no":
|
| 128 |
+
generation_config = GenerationConfig(
|
| 129 |
+
max_new_tokens=training_args.max_new_tokens, do_sample=True, temperature=training_args.temperature
|
| 130 |
+
)
|
| 131 |
+
completions_callback = LogCompletionsCallback(trainer, generation_config, num_prompts=8)
|
| 132 |
+
trainer.add_callback(completions_callback)
|
| 133 |
+
|
| 134 |
+
trainer.train()
|
| 135 |
+
|
| 136 |
+
# Save and push to hub
|
| 137 |
+
trainer.save_model(training_args.output_dir)
|
| 138 |
+
if training_args.push_to_hub:
|
| 139 |
+
trainer.push_to_hub(dataset_name=script_args.dataset_name)
|
tasks/tasksmith-fa1a9b35ff39/tests/source/examples/scripts/gold.py
ADDED
|
@@ -0,0 +1,152 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2020-2026 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
# /// script
|
| 16 |
+
# dependencies = [
|
| 17 |
+
# "trl @ git+https://github.com/huggingface/trl.git",
|
| 18 |
+
# "peft",
|
| 19 |
+
# "trackio",
|
| 20 |
+
# ]
|
| 21 |
+
# ///
|
| 22 |
+
|
| 23 |
+
# docstyle-ignore
|
| 24 |
+
"""
|
| 25 |
+
# Full training:
|
| 26 |
+
python examples/scripts/gold.py \
|
| 27 |
+
--model_name_or_path meta-llama/Llama-3.2-1B-Instruct \
|
| 28 |
+
--teacher_model_name_or_path Qwen/Qwen2-1.5B-Instruct \
|
| 29 |
+
--dataset_name trl-lib/chatbot_arena_completions \
|
| 30 |
+
--learning_rate 2e-5 \
|
| 31 |
+
--per_device_train_batch_size 4 \
|
| 32 |
+
--gradient_accumulation_steps 8 \
|
| 33 |
+
--output_dir gold-model \
|
| 34 |
+
--num_train_epochs 1 \
|
| 35 |
+
--push_to_hub
|
| 36 |
+
|
| 37 |
+
# LoRA:
|
| 38 |
+
python examples/scripts/gold.py \
|
| 39 |
+
--model_name_or_path meta-llama/Llama-3.2-1B-Instruct \
|
| 40 |
+
--teacher_model_name_or_path Qwen/Qwen2-1.5B-Instruct \
|
| 41 |
+
--dataset_name trl-lib/chatbot_arena_completions \
|
| 42 |
+
--learning_rate 2e-4 \
|
| 43 |
+
--per_device_train_batch_size 4 \
|
| 44 |
+
--gradient_accumulation_steps 8 \
|
| 45 |
+
--output_dir gold-model \
|
| 46 |
+
--num_train_epochs 1 \
|
| 47 |
+
--push_to_hub \
|
| 48 |
+
--use_peft \
|
| 49 |
+
--lora_r 64 \
|
| 50 |
+
--lora_alpha 16
|
| 51 |
+
"""
|
| 52 |
+
|
| 53 |
+
import logging
|
| 54 |
+
|
| 55 |
+
from datasets import load_dataset
|
| 56 |
+
from transformers import AutoTokenizer, GenerationConfig
|
| 57 |
+
|
| 58 |
+
from trl import (
|
| 59 |
+
LogCompletionsCallback,
|
| 60 |
+
ModelConfig,
|
| 61 |
+
ScriptArguments,
|
| 62 |
+
TrlParser,
|
| 63 |
+
get_kbit_device_map,
|
| 64 |
+
get_peft_config,
|
| 65 |
+
get_quantization_config,
|
| 66 |
+
)
|
| 67 |
+
from trl.experimental.gold.gold_config import GOLDConfig
|
| 68 |
+
from trl.experimental.gold.gold_trainer import GOLDTrainer
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
logger = logging.getLogger(__name__)
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
if __name__ == "__main__":
|
| 75 |
+
parser = TrlParser((ScriptArguments, GOLDConfig, ModelConfig))
|
| 76 |
+
script_args, training_args, model_args = parser.parse_args_and_config()
|
| 77 |
+
|
| 78 |
+
################
|
| 79 |
+
# Model & Tokenizer
|
| 80 |
+
################
|
| 81 |
+
quantization_config = get_quantization_config(model_args)
|
| 82 |
+
model_kwargs = dict(
|
| 83 |
+
revision=model_args.model_revision,
|
| 84 |
+
attn_implementation=model_args.attn_implementation,
|
| 85 |
+
dtype=model_args.dtype,
|
| 86 |
+
use_cache=False if training_args.gradient_checkpointing else True,
|
| 87 |
+
device_map=get_kbit_device_map() if quantization_config is not None else None,
|
| 88 |
+
quantization_config=quantization_config,
|
| 89 |
+
)
|
| 90 |
+
training_args.model_init_kwargs = model_kwargs
|
| 91 |
+
|
| 92 |
+
if training_args.teacher_tokenizer_name_or_path is None and training_args.use_uld_loss:
|
| 93 |
+
training_args.teacher_tokenizer_name_or_path = training_args.teacher_model_name_or_path
|
| 94 |
+
teacher_model_kwargs = dict(
|
| 95 |
+
revision=training_args.teacher_model_revision,
|
| 96 |
+
attn_implementation=model_args.attn_implementation,
|
| 97 |
+
dtype=model_args.dtype,
|
| 98 |
+
use_cache=True,
|
| 99 |
+
device_map=get_kbit_device_map() if quantization_config is not None else None,
|
| 100 |
+
quantization_config=quantization_config,
|
| 101 |
+
)
|
| 102 |
+
if training_args.teacher_model_init_kwargs is not None:
|
| 103 |
+
teacher_model_kwargs.update(training_args.teacher_model_init_kwargs)
|
| 104 |
+
training_args.teacher_model_init_kwargs = teacher_model_kwargs
|
| 105 |
+
|
| 106 |
+
tokenizer = AutoTokenizer.from_pretrained(
|
| 107 |
+
model_args.model_name_or_path,
|
| 108 |
+
revision=model_args.model_revision,
|
| 109 |
+
)
|
| 110 |
+
if tokenizer.pad_token is None:
|
| 111 |
+
tokenizer.pad_token = tokenizer.eos_token
|
| 112 |
+
|
| 113 |
+
################
|
| 114 |
+
# Dataset
|
| 115 |
+
################
|
| 116 |
+
dataset = load_dataset(script_args.dataset_name, name=script_args.dataset_config)
|
| 117 |
+
|
| 118 |
+
################
|
| 119 |
+
# Training
|
| 120 |
+
################
|
| 121 |
+
eval_dataset = None
|
| 122 |
+
if training_args.eval_strategy != "no":
|
| 123 |
+
if script_args.dataset_test_split in dataset:
|
| 124 |
+
eval_dataset = dataset[script_args.dataset_test_split]
|
| 125 |
+
elif "validation" in dataset:
|
| 126 |
+
eval_dataset = dataset["validation"]
|
| 127 |
+
elif "dev" in dataset:
|
| 128 |
+
eval_dataset = dataset["dev"]
|
| 129 |
+
|
| 130 |
+
trainer = GOLDTrainer(
|
| 131 |
+
model=model_args.model_name_or_path,
|
| 132 |
+
teacher_model=training_args.teacher_model_name_or_path,
|
| 133 |
+
args=training_args,
|
| 134 |
+
train_dataset=dataset[script_args.dataset_train_split],
|
| 135 |
+
eval_dataset=eval_dataset,
|
| 136 |
+
processing_class=tokenizer,
|
| 137 |
+
peft_config=get_peft_config(model_args),
|
| 138 |
+
)
|
| 139 |
+
|
| 140 |
+
if training_args.eval_strategy != "no":
|
| 141 |
+
generation_config = GenerationConfig(
|
| 142 |
+
max_new_tokens=training_args.max_completion_length, do_sample=True, temperature=training_args.temperature
|
| 143 |
+
)
|
| 144 |
+
completions_callback = LogCompletionsCallback(trainer, generation_config, num_prompts=8)
|
| 145 |
+
trainer.add_callback(completions_callback)
|
| 146 |
+
|
| 147 |
+
trainer.train()
|
| 148 |
+
|
| 149 |
+
# Save and push to hub
|
| 150 |
+
trainer.save_model(training_args.output_dir)
|
| 151 |
+
if training_args.push_to_hub:
|
| 152 |
+
trainer.push_to_hub(dataset_name=script_args.dataset_name)
|
tasks/tasksmith-fa1a9b35ff39/tests/source/examples/scripts/grpo_2048.py
ADDED
|
@@ -0,0 +1,161 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2020-2026 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
# /// script
|
| 16 |
+
# dependencies = [
|
| 17 |
+
# "trl[peft]",
|
| 18 |
+
# ]
|
| 19 |
+
# ///
|
| 20 |
+
|
| 21 |
+
import random
|
| 22 |
+
|
| 23 |
+
from datasets import Dataset
|
| 24 |
+
from peft import LoraConfig
|
| 25 |
+
|
| 26 |
+
from trl import GRPOConfig, GRPOTrainer
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
PROMPT = "Play 2048 on a 4x4 board. Use the tool `move` with one of: up, down, left, right. Maximize the score."
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
class Game2048Env:
|
| 33 |
+
def reset(self, **kwargs) -> str:
|
| 34 |
+
self.board = [[0] * 4 for _ in range(4)]
|
| 35 |
+
self.score = 0.0
|
| 36 |
+
self.done = False
|
| 37 |
+
self._spawn()
|
| 38 |
+
self._spawn()
|
| 39 |
+
return f"score={self.score}\n{self._render()}\ndone={self.done}"
|
| 40 |
+
|
| 41 |
+
def move(self, direction: str) -> str:
|
| 42 |
+
"""
|
| 43 |
+
Play one move in 2048.
|
| 44 |
+
|
| 45 |
+
Args:
|
| 46 |
+
direction: One of "up", "down", "left", "right".
|
| 47 |
+
|
| 48 |
+
Returns:
|
| 49 |
+
Environment feedback after the move.
|
| 50 |
+
"""
|
| 51 |
+
if self.done:
|
| 52 |
+
raise ValueError("Game over.")
|
| 53 |
+
moved, gained = self._apply_move(direction.strip().lower())
|
| 54 |
+
if moved:
|
| 55 |
+
self.score += gained
|
| 56 |
+
self._spawn()
|
| 57 |
+
self.done = not self._can_move()
|
| 58 |
+
return f"score={self.score}\n{self._render()}\ndone={self.done}"
|
| 59 |
+
|
| 60 |
+
def _spawn(self) -> None:
|
| 61 |
+
empty = [(r, c) for r in range(4) for c in range(4) if self.board[r][c] == 0]
|
| 62 |
+
if not empty:
|
| 63 |
+
return
|
| 64 |
+
r, c = random.choice(empty)
|
| 65 |
+
self.board[r][c] = 4 if random.random() < 0.1 else 2
|
| 66 |
+
|
| 67 |
+
@staticmethod
|
| 68 |
+
def _merge_line(line: list[int]) -> tuple[list[int], int]:
|
| 69 |
+
vals = [x for x in line if x]
|
| 70 |
+
out = []
|
| 71 |
+
gained = 0
|
| 72 |
+
i = 0
|
| 73 |
+
while i < len(vals):
|
| 74 |
+
if i + 1 < len(vals) and vals[i] == vals[i + 1]:
|
| 75 |
+
v = vals[i] * 2
|
| 76 |
+
out.append(v)
|
| 77 |
+
gained += v
|
| 78 |
+
i += 2
|
| 79 |
+
else:
|
| 80 |
+
out.append(vals[i])
|
| 81 |
+
i += 1
|
| 82 |
+
out += [0] * (4 - len(out))
|
| 83 |
+
return out, gained
|
| 84 |
+
|
| 85 |
+
def _apply_move(self, direction: str) -> tuple[bool, int]:
|
| 86 |
+
if direction not in {"up", "down", "left", "right"}:
|
| 87 |
+
return False, 0
|
| 88 |
+
|
| 89 |
+
before = [row[:] for row in self.board]
|
| 90 |
+
gained_total = 0
|
| 91 |
+
|
| 92 |
+
if direction in {"left", "right"}:
|
| 93 |
+
for r in range(4):
|
| 94 |
+
row = self.board[r][:]
|
| 95 |
+
if direction == "right":
|
| 96 |
+
row.reverse()
|
| 97 |
+
merged, gained = self._merge_line(row)
|
| 98 |
+
if direction == "right":
|
| 99 |
+
merged.reverse()
|
| 100 |
+
self.board[r] = merged
|
| 101 |
+
gained_total += gained
|
| 102 |
+
else:
|
| 103 |
+
for c in range(4):
|
| 104 |
+
col = [self.board[r][c] for r in range(4)]
|
| 105 |
+
if direction == "down":
|
| 106 |
+
col.reverse()
|
| 107 |
+
merged, gained = self._merge_line(col)
|
| 108 |
+
if direction == "down":
|
| 109 |
+
merged.reverse()
|
| 110 |
+
for r in range(4):
|
| 111 |
+
self.board[r][c] = merged[r]
|
| 112 |
+
gained_total += gained
|
| 113 |
+
|
| 114 |
+
moved = self.board != before
|
| 115 |
+
return moved, gained_total
|
| 116 |
+
|
| 117 |
+
def _can_move(self) -> bool:
|
| 118 |
+
if any(0 in row for row in self.board):
|
| 119 |
+
return True
|
| 120 |
+
for r in range(4):
|
| 121 |
+
for c in range(4):
|
| 122 |
+
if r + 1 < 4 and self.board[r][c] == self.board[r + 1][c]:
|
| 123 |
+
return True
|
| 124 |
+
if c + 1 < 4 and self.board[r][c] == self.board[r][c + 1]:
|
| 125 |
+
return True
|
| 126 |
+
return False
|
| 127 |
+
|
| 128 |
+
def _render(self) -> str:
|
| 129 |
+
return "\n".join(" ".join(f"{v:3d}" for v in row) for row in self.board)
|
| 130 |
+
|
| 131 |
+
|
| 132 |
+
def reward_score(environments, **kwargs):
|
| 133 |
+
return [env.score for env in environments]
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
def main() -> None:
|
| 137 |
+
dataset = Dataset.from_dict({"prompt": [[{"role": "user", "content": PROMPT}] for _ in range(1000)]})
|
| 138 |
+
|
| 139 |
+
trainer = GRPOTrainer(
|
| 140 |
+
model="Qwen/Qwen3-4B",
|
| 141 |
+
train_dataset=dataset,
|
| 142 |
+
reward_funcs=reward_score,
|
| 143 |
+
args=GRPOConfig(
|
| 144 |
+
chat_template_kwargs={"enable_thinking": False},
|
| 145 |
+
logging_steps=1,
|
| 146 |
+
log_completions=True,
|
| 147 |
+
num_completions_to_print=2,
|
| 148 |
+
report_to="trackio",
|
| 149 |
+
trackio_space_id="trl-2048",
|
| 150 |
+
max_completion_length=2048,
|
| 151 |
+
per_device_train_batch_size=4,
|
| 152 |
+
gradient_accumulation_steps=2,
|
| 153 |
+
),
|
| 154 |
+
environment_factory=Game2048Env,
|
| 155 |
+
peft_config=LoraConfig(),
|
| 156 |
+
)
|
| 157 |
+
trainer.train()
|
| 158 |
+
|
| 159 |
+
|
| 160 |
+
if __name__ == "__main__":
|
| 161 |
+
main()
|
tasks/tasksmith-fa1a9b35ff39/tests/source/examples/scripts/grpo_agent.py
ADDED
|
@@ -0,0 +1,320 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2020-2026 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
# /// script
|
| 16 |
+
# dependencies = [
|
| 17 |
+
# "trl[peft]",
|
| 18 |
+
# "trackio",
|
| 19 |
+
# "kernels",
|
| 20 |
+
# ]
|
| 21 |
+
# ///
|
| 22 |
+
|
| 23 |
+
"""
|
| 24 |
+
# Full training
|
| 25 |
+
```
|
| 26 |
+
python examples/scripts/grpo_agent.py \
|
| 27 |
+
--model_name_or_path Qwen/Qwen3-1.7B \
|
| 28 |
+
--output_dir grpo_biogrid_qwen_3g-1.7b \
|
| 29 |
+
--push_to_hub True \
|
| 30 |
+
--use_vllm True \
|
| 31 |
+
--vllm_mode colocate \
|
| 32 |
+
--max_completion_length 1024 \
|
| 33 |
+
--report_to trackio \
|
| 34 |
+
--log_completions True \
|
| 35 |
+
--max_steps 400
|
| 36 |
+
```
|
| 37 |
+
"""
|
| 38 |
+
|
| 39 |
+
import re
|
| 40 |
+
import signal
|
| 41 |
+
import sqlite3
|
| 42 |
+
import textwrap
|
| 43 |
+
from contextlib import contextmanager
|
| 44 |
+
|
| 45 |
+
from datasets import load_dataset
|
| 46 |
+
|
| 47 |
+
from trl import GRPOConfig, GRPOTrainer, ModelConfig, ScriptArguments, TrlParser
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def query_reward(completions, answer, **kwargs):
|
| 51 |
+
"""
|
| 52 |
+
Reward query strategy:
|
| 53 |
+
- Penalize more than 2 queries
|
| 54 |
+
- Penalize generic queries (LIMIT 1 / PRAGMA)
|
| 55 |
+
- Reward usage of WHERE
|
| 56 |
+
- Reward evidence supporting the final answer
|
| 57 |
+
"""
|
| 58 |
+
rewards = []
|
| 59 |
+
|
| 60 |
+
for completion, ans in zip(completions, answer, strict=False):
|
| 61 |
+
reward = 0.0
|
| 62 |
+
sql_queries = []
|
| 63 |
+
tool_results = []
|
| 64 |
+
|
| 65 |
+
# collect all SQL queries and tool results
|
| 66 |
+
for turn in completion:
|
| 67 |
+
if turn.get("tool_calls"):
|
| 68 |
+
for call in turn["tool_calls"]:
|
| 69 |
+
sql = call["function"]["arguments"].get("sql_command", "").lower()
|
| 70 |
+
sql_queries.append(sql)
|
| 71 |
+
if turn.get("role") == "tool" and turn.get("content"):
|
| 72 |
+
tool_results.append(turn["content"])
|
| 73 |
+
|
| 74 |
+
# --- penalize too many queries ---
|
| 75 |
+
if len(sql_queries) > 3:
|
| 76 |
+
reward -= 1.5
|
| 77 |
+
|
| 78 |
+
# --- check query quality ---
|
| 79 |
+
where_count = 0
|
| 80 |
+
for q in sql_queries:
|
| 81 |
+
if "limit 1" in q:
|
| 82 |
+
reward -= 1.0
|
| 83 |
+
if " where " not in q:
|
| 84 |
+
reward -= 0.5
|
| 85 |
+
else:
|
| 86 |
+
where_count += 1
|
| 87 |
+
reward += min(where_count, 3) * 0.4 # small bonus for WHERE usage
|
| 88 |
+
|
| 89 |
+
# --- evidence check: do queries support the answer? ---
|
| 90 |
+
combined_results = []
|
| 91 |
+
error_detected = False
|
| 92 |
+
|
| 93 |
+
for res in tool_results:
|
| 94 |
+
if isinstance(res, dict) and "error" in res:
|
| 95 |
+
error_detected = True
|
| 96 |
+
elif isinstance(res, list):
|
| 97 |
+
combined_results.extend(res)
|
| 98 |
+
|
| 99 |
+
# if error detected, penalize heavily
|
| 100 |
+
if error_detected:
|
| 101 |
+
reward -= 2.0
|
| 102 |
+
elif len(sql_queries) == 0:
|
| 103 |
+
reward -= 1.5
|
| 104 |
+
else:
|
| 105 |
+
has_hits = len(combined_results) > 0
|
| 106 |
+
correct_answer = ans.lower()
|
| 107 |
+
if (has_hits and correct_answer == "yes") or (not has_hits and correct_answer == "no"):
|
| 108 |
+
reward += 2.0
|
| 109 |
+
else:
|
| 110 |
+
reward -= 1.5
|
| 111 |
+
|
| 112 |
+
rewards.append(reward)
|
| 113 |
+
|
| 114 |
+
return rewards
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
def correctness_reward(completions, answer, **kwargs):
|
| 118 |
+
"""
|
| 119 |
+
Reward Yes/No correctness.
|
| 120 |
+
Model must provide final answer enclosed in stars — *yes* or *no*.
|
| 121 |
+
Does not reward informal yes/no buried in text.
|
| 122 |
+
"""
|
| 123 |
+
rewards = []
|
| 124 |
+
for completion, ans in zip(completions, answer, strict=False):
|
| 125 |
+
raw = completion[-1]["content"].lower()
|
| 126 |
+
|
| 127 |
+
# detect form *yes* or *no*
|
| 128 |
+
match = re.search(r"\*(yes|no)\*", raw)
|
| 129 |
+
guess = match.group(1) if match else None
|
| 130 |
+
|
| 131 |
+
reward = 0.0
|
| 132 |
+
|
| 133 |
+
if guess is None:
|
| 134 |
+
reward -= 0.5 # invalid format
|
| 135 |
+
elif guess == ans.lower():
|
| 136 |
+
reward += 0.6 # correct under required format
|
| 137 |
+
else:
|
| 138 |
+
reward -= 1.0 # wrong answer
|
| 139 |
+
|
| 140 |
+
rewards.append(reward)
|
| 141 |
+
|
| 142 |
+
return rewards
|
| 143 |
+
|
| 144 |
+
|
| 145 |
+
def structure_reward(completions, **kwargs):
|
| 146 |
+
"""
|
| 147 |
+
Reward proper assistant structure.
|
| 148 |
+
Encourages a logical sequence: tool call + response + optional extra content.
|
| 149 |
+
"""
|
| 150 |
+
rewards = []
|
| 151 |
+
|
| 152 |
+
for completion in completions:
|
| 153 |
+
has_call = False
|
| 154 |
+
has_response = False
|
| 155 |
+
has_other = False
|
| 156 |
+
|
| 157 |
+
for turn in completion:
|
| 158 |
+
role = turn.get("role")
|
| 159 |
+
if role == "assistant" and turn.get("tool_calls"):
|
| 160 |
+
has_call = True
|
| 161 |
+
elif role == "tool":
|
| 162 |
+
has_response = True
|
| 163 |
+
else:
|
| 164 |
+
content = turn.get("content")
|
| 165 |
+
if content and content.strip() not in ["", "<think>"]:
|
| 166 |
+
has_other = True
|
| 167 |
+
|
| 168 |
+
# Reward sequences
|
| 169 |
+
if has_call and has_response:
|
| 170 |
+
if has_other:
|
| 171 |
+
reward = 0.1
|
| 172 |
+
else:
|
| 173 |
+
reward = 0.05 # still positive even without extra text
|
| 174 |
+
elif has_call and not has_response:
|
| 175 |
+
reward = -0.15
|
| 176 |
+
else:
|
| 177 |
+
reward = 0.0 # neutral if no call
|
| 178 |
+
|
| 179 |
+
rewards.append(reward)
|
| 180 |
+
|
| 181 |
+
return rewards
|
| 182 |
+
|
| 183 |
+
|
| 184 |
+
# ------------------------
|
| 185 |
+
# Database tool function
|
| 186 |
+
# ------------------------
|
| 187 |
+
class TimeoutError(Exception):
|
| 188 |
+
"""Raised when a function call times out."""
|
| 189 |
+
|
| 190 |
+
pass
|
| 191 |
+
|
| 192 |
+
|
| 193 |
+
@contextmanager
|
| 194 |
+
def timeout(seconds):
|
| 195 |
+
"""Context manager that raises TimeoutError if execution exceeds time limit."""
|
| 196 |
+
|
| 197 |
+
def timeout_handler(signum, frame):
|
| 198 |
+
raise TimeoutError(f"Operation timed out after {seconds} seconds")
|
| 199 |
+
|
| 200 |
+
signal.signal(signal.SIGALRM, timeout_handler)
|
| 201 |
+
signal.alarm(seconds)
|
| 202 |
+
try:
|
| 203 |
+
yield
|
| 204 |
+
finally:
|
| 205 |
+
signal.alarm(0)
|
| 206 |
+
|
| 207 |
+
|
| 208 |
+
def query_biogrid(sql_command: str) -> list[tuple]:
|
| 209 |
+
"""
|
| 210 |
+
Execute a read-only SQL command on the BioGRID database.
|
| 211 |
+
|
| 212 |
+
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.
|
| 213 |
+
|
| 214 |
+
Args:
|
| 215 |
+
sql_command: The SQL command to execute.
|
| 216 |
+
|
| 217 |
+
Returns:
|
| 218 |
+
A list of tuples containing the query results.
|
| 219 |
+
"""
|
| 220 |
+
with timeout(5):
|
| 221 |
+
conn = sqlite3.connect("file:biogrid.db?mode=ro", uri=True)
|
| 222 |
+
cursor = conn.cursor()
|
| 223 |
+
try:
|
| 224 |
+
cursor.execute(sql_command)
|
| 225 |
+
results = cursor.fetchall()
|
| 226 |
+
finally:
|
| 227 |
+
conn.close()
|
| 228 |
+
return results
|
| 229 |
+
|
| 230 |
+
|
| 231 |
+
# ------------------------
|
| 232 |
+
# Dataset formatting
|
| 233 |
+
# ------------------------
|
| 234 |
+
def format_example(example):
|
| 235 |
+
question = example["question"]
|
| 236 |
+
preamble = textwrap.dedent("""\
|
| 237 |
+
You have access to the BioGRID SQLite database.
|
| 238 |
+
Use SQL queries to retrieve only the information needed to answer the question.
|
| 239 |
+
|
| 240 |
+
Genes may appear in the database in columns `Alt_IDs_Interactor_A` `Alt_IDs_Interactor_B`, `Aliases_Interactor_A` and `Aliases_Interactor_B`,
|
| 241 |
+
and each entry can contain multiple gene names or synonyms separated by '|', for example:
|
| 242 |
+
'entrez gene/locuslink:JNKK(gene name synonym)|entrez gene/locuslink:MAPKK4(gene name synonym)|...'
|
| 243 |
+
So a gene like 'JNKK' or 'MAPKK4' may appear inside one of these strings.
|
| 244 |
+
|
| 245 |
+
If the database schema is unclear or you are unsure about column names:
|
| 246 |
+
- First inspect the schema with `PRAGMA table_info(interactions);`
|
| 247 |
+
- Or preview a few rows with `SELECT * FROM interactions LIMIT 1;`
|
| 248 |
+
|
| 249 |
+
Otherwise, directly query the required data.
|
| 250 |
+
|
| 251 |
+
Final answer must be enclosed in stars, e.g. *Yes* or *No*.
|
| 252 |
+
Facts:
|
| 253 |
+
- The NCBI Taxonomy identifier for humans is taxid:9606.
|
| 254 |
+
""")
|
| 255 |
+
content = f"{preamble}\nQuestion: {question}"
|
| 256 |
+
prompt = [{"role": "user", "content": content}]
|
| 257 |
+
return {"prompt": prompt}
|
| 258 |
+
|
| 259 |
+
|
| 260 |
+
# ------------------------
|
| 261 |
+
# Main
|
| 262 |
+
# ------------------------
|
| 263 |
+
if __name__ == "__main__":
|
| 264 |
+
parser = TrlParser((ScriptArguments, GRPOConfig, ModelConfig))
|
| 265 |
+
script_args, training_args, model_args = parser.parse_args_and_config()
|
| 266 |
+
|
| 267 |
+
# ------------------------
|
| 268 |
+
# Create DB
|
| 269 |
+
# ------------------------
|
| 270 |
+
print("Creating biogrid.db...")
|
| 271 |
+
# Load dataset
|
| 272 |
+
biogrid_dataset = load_dataset("qgallouedec/biogrid", split="train")
|
| 273 |
+
df = biogrid_dataset.to_pandas()
|
| 274 |
+
|
| 275 |
+
# Normalize column names: remove spaces, replace with underscores
|
| 276 |
+
df.columns = [c.replace(" ", "_") for c in df.columns]
|
| 277 |
+
conn = sqlite3.connect("biogrid.db")
|
| 278 |
+
try:
|
| 279 |
+
df.to_sql("interactions", conn, if_exists="replace", index=False)
|
| 280 |
+
print(f"biogrid.db created. Rows stored: {len(df)}")
|
| 281 |
+
finally:
|
| 282 |
+
conn.close()
|
| 283 |
+
|
| 284 |
+
# ------------------------
|
| 285 |
+
# Load and format dataset
|
| 286 |
+
# ------------------------
|
| 287 |
+
dataset = load_dataset("qgallouedec/biogrid_qa", split="train")
|
| 288 |
+
dataset = dataset.filter(
|
| 289 |
+
lambda example: example["question"].startswith("Does the gene ")
|
| 290 |
+
) # keep only simple questions for example
|
| 291 |
+
dataset = dataset.map(format_example, remove_columns=["question"])
|
| 292 |
+
|
| 293 |
+
train_dataset = dataset
|
| 294 |
+
eval_dataset = None # No eval by default, can be added if needed
|
| 295 |
+
|
| 296 |
+
training_args.chat_template_kwargs = {"enable_thinking": False}
|
| 297 |
+
|
| 298 |
+
# ------------------------
|
| 299 |
+
# Initialize trainer
|
| 300 |
+
# ------------------------
|
| 301 |
+
trainer = GRPOTrainer(
|
| 302 |
+
model=model_args.model_name_or_path,
|
| 303 |
+
train_dataset=train_dataset,
|
| 304 |
+
eval_dataset=eval_dataset,
|
| 305 |
+
tools=[query_biogrid],
|
| 306 |
+
reward_funcs=[correctness_reward, structure_reward, query_reward],
|
| 307 |
+
args=training_args,
|
| 308 |
+
)
|
| 309 |
+
|
| 310 |
+
# ------------------------
|
| 311 |
+
# Train
|
| 312 |
+
# ------------------------
|
| 313 |
+
trainer.train()
|
| 314 |
+
|
| 315 |
+
# ------------------------
|
| 316 |
+
# Save and push
|
| 317 |
+
# ------------------------
|
| 318 |
+
trainer.save_model(training_args.output_dir)
|
| 319 |
+
if training_args.push_to_hub:
|
| 320 |
+
trainer.push_to_hub(dataset_name=script_args.dataset_name)
|
tasks/tasksmith-fa1a9b35ff39/tests/source/examples/scripts/grpo_continuous_batching.py
ADDED
|
@@ -0,0 +1,133 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2020-2026 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
# /// script
|
| 16 |
+
# dependencies = [
|
| 17 |
+
# "trl[peft]",
|
| 18 |
+
# "kernels",
|
| 19 |
+
# ]
|
| 20 |
+
# ///
|
| 21 |
+
|
| 22 |
+
"""
|
| 23 |
+
GRPO training on GSM8K using transformers' continuous batching engine instead of the default
|
| 24 |
+
generate(). Continuous batching removes finished sequences from the batch immediately rather than
|
| 25 |
+
waiting for the slowest one, which yields faster generation and lower VRAM than default generate()
|
| 26 |
+
for tasks with variable completion lengths (N≥32).
|
| 27 |
+
|
| 28 |
+
The key config parameter is `max_memory_percent` in `transformers_continuous_batching_config`,
|
| 29 |
+
which caps the paged KV cache as a fraction of free VRAM. TRL defaults to 0.5; tune it down to
|
| 30 |
+
0.3-0.4 for large generation batches to leave room for the training backward pass.
|
| 31 |
+
|
| 32 |
+
python examples/scripts/grpo_continuous_batching.py \
|
| 33 |
+
--model_name_or_path Qwen/Qwen3-1.7B \
|
| 34 |
+
--output_dir grpo-gsm8k-continuous-batching \
|
| 35 |
+
--num_generations 32 \
|
| 36 |
+
--max_completion_length 1024 \
|
| 37 |
+
--use_peft \
|
| 38 |
+
--log_completions
|
| 39 |
+
|
| 40 |
+
accelerate launch --config_file examples/accelerate_configs/deepspeed_zero3.yaml \
|
| 41 |
+
examples/scripts/grpo_continuous_batching.py \
|
| 42 |
+
--model_name_or_path Qwen/Qwen3-1.7B \
|
| 43 |
+
--output_dir grpo-gsm8k-continuous-batching \
|
| 44 |
+
--num_generations 32 \
|
| 45 |
+
--max_completion_length 1024 \
|
| 46 |
+
--use_peft \
|
| 47 |
+
--log_completions
|
| 48 |
+
"""
|
| 49 |
+
|
| 50 |
+
import logging
|
| 51 |
+
import re
|
| 52 |
+
|
| 53 |
+
import torch
|
| 54 |
+
from datasets import load_dataset
|
| 55 |
+
|
| 56 |
+
from trl import GRPOConfig, GRPOTrainer, ModelConfig, ScriptArguments, TrlParser, get_peft_config
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
logging.getLogger("ContinuousBatchingLogger").setLevel(logging.ERROR)
|
| 60 |
+
|
| 61 |
+
SYSTEM_PROMPT = (
|
| 62 |
+
"You are a helpful math tutor. Solve the problem step by step, then provide the final "
|
| 63 |
+
"numeric answer on the last line in the format: #### <number>"
|
| 64 |
+
)
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
def extract_answer(text: str) -> str | None:
|
| 68 |
+
match = re.search(r"####\s*([\d,]+)", text)
|
| 69 |
+
return match.group(1).replace(",", "") if match else None
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
def correctness_reward(completions, reference_answer, **kwargs):
|
| 73 |
+
rewards = []
|
| 74 |
+
for completion, ref in zip(completions, reference_answer, strict=False):
|
| 75 |
+
predicted = extract_answer(completion if isinstance(completion, str) else completion[-1]["content"])
|
| 76 |
+
rewards.append(1.0 if predicted is not None and predicted == ref else 0.0)
|
| 77 |
+
return rewards
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
if __name__ == "__main__":
|
| 81 |
+
parser = TrlParser((ScriptArguments, GRPOConfig, ModelConfig))
|
| 82 |
+
script_args, training_args, model_args = parser.parse_args_and_config()
|
| 83 |
+
|
| 84 |
+
################
|
| 85 |
+
# Model
|
| 86 |
+
################
|
| 87 |
+
dtype = model_args.dtype if model_args.dtype in ["auto", None] else getattr(torch, model_args.dtype)
|
| 88 |
+
training_args.model_init_kwargs = dict(
|
| 89 |
+
revision=model_args.model_revision,
|
| 90 |
+
attn_implementation=model_args.attn_implementation,
|
| 91 |
+
dtype=dtype,
|
| 92 |
+
)
|
| 93 |
+
|
| 94 |
+
################
|
| 95 |
+
# Dataset
|
| 96 |
+
################
|
| 97 |
+
dataset = load_dataset(
|
| 98 |
+
script_args.dataset_name or "openai/gsm8k",
|
| 99 |
+
script_args.dataset_config or "main",
|
| 100 |
+
split=script_args.dataset_train_split,
|
| 101 |
+
)
|
| 102 |
+
|
| 103 |
+
def make_conversation(example):
|
| 104 |
+
return {
|
| 105 |
+
"prompt": [
|
| 106 |
+
{"role": "system", "content": SYSTEM_PROMPT},
|
| 107 |
+
{"role": "user", "content": example["question"]},
|
| 108 |
+
],
|
| 109 |
+
"reference_answer": example["answer"].split("####")[-1].strip().replace(",", ""),
|
| 110 |
+
}
|
| 111 |
+
|
| 112 |
+
dataset = dataset.map(make_conversation, remove_columns=dataset.column_names)
|
| 113 |
+
|
| 114 |
+
################
|
| 115 |
+
# Training
|
| 116 |
+
################
|
| 117 |
+
training_args.use_transformers_continuous_batching = True
|
| 118 |
+
if training_args.transformers_continuous_batching_config is None:
|
| 119 |
+
training_args.transformers_continuous_batching_config = {"use_cuda_graph": False}
|
| 120 |
+
|
| 121 |
+
trainer = GRPOTrainer(
|
| 122 |
+
model=model_args.model_name_or_path,
|
| 123 |
+
reward_funcs=correctness_reward,
|
| 124 |
+
args=training_args,
|
| 125 |
+
train_dataset=dataset,
|
| 126 |
+
peft_config=get_peft_config(model_args),
|
| 127 |
+
)
|
| 128 |
+
|
| 129 |
+
trainer.train()
|
| 130 |
+
|
| 131 |
+
trainer.save_model(training_args.output_dir)
|
| 132 |
+
if training_args.push_to_hub:
|
| 133 |
+
trainer.push_to_hub(dataset_name=script_args.dataset_name)
|
tasks/tasksmith-fa1a9b35ff39/tests/source/examples/scripts/grpo_vlm.py
ADDED
|
@@ -0,0 +1,157 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2020-2026 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
# /// script
|
| 16 |
+
# dependencies = [
|
| 17 |
+
# "trl[peft]",
|
| 18 |
+
# "Pillow",
|
| 19 |
+
# "math-verify",
|
| 20 |
+
# "latex2sympy2_extended",
|
| 21 |
+
# "torchvision",
|
| 22 |
+
# "trackio",
|
| 23 |
+
# "kernels",
|
| 24 |
+
# ]
|
| 25 |
+
# ///
|
| 26 |
+
|
| 27 |
+
"""
|
| 28 |
+
pip install math_verify
|
| 29 |
+
|
| 30 |
+
# For Qwen/Qwen2.5-VL-3B-Instruct
|
| 31 |
+
accelerate launch \
|
| 32 |
+
--config_file examples/accelerate_configs/deepspeed_zero3.yaml \
|
| 33 |
+
examples/scripts/grpo_vlm.py \
|
| 34 |
+
--model_name_or_path Qwen/Qwen2.5-VL-3B-Instruct \
|
| 35 |
+
--output_dir grpo-Qwen2.5-VL-3B-Instruct \
|
| 36 |
+
--learning_rate 1e-5 \
|
| 37 |
+
--dtype bfloat16 \
|
| 38 |
+
--max_completion_length 1024 \
|
| 39 |
+
--use_vllm \
|
| 40 |
+
--vllm_mode colocate \
|
| 41 |
+
--use_peft \
|
| 42 |
+
--lora_target_modules "q_proj", "v_proj" \
|
| 43 |
+
--log_completions
|
| 44 |
+
|
| 45 |
+
# For HuggingFaceTB/SmolVLM2-2.2B-Instruct
|
| 46 |
+
pip install num2words==0.5.14
|
| 47 |
+
|
| 48 |
+
accelerate launch \
|
| 49 |
+
--config_file examples/accelerate_configs/deepspeed_zero3.yaml \
|
| 50 |
+
examples/scripts/grpo_vlm.py \
|
| 51 |
+
--model_name_or_path HuggingFaceTB/SmolVLM2-2.2B-Instruct \
|
| 52 |
+
--output_dir grpo-SmolVLM2-2.2B-Instruct \
|
| 53 |
+
--learning_rate 1e-5 \
|
| 54 |
+
--dtype bfloat16 \
|
| 55 |
+
--max_completion_length 1024 \
|
| 56 |
+
--use_peft \
|
| 57 |
+
--lora_target_modules "q_proj", "v_proj" \
|
| 58 |
+
--log_completions \
|
| 59 |
+
--per_device_train_batch_size 1 \
|
| 60 |
+
--gradient_accumulation_steps 2 \
|
| 61 |
+
--num_generations 2
|
| 62 |
+
|
| 63 |
+
"""
|
| 64 |
+
|
| 65 |
+
import torch
|
| 66 |
+
from datasets import load_dataset
|
| 67 |
+
|
| 68 |
+
from trl import (
|
| 69 |
+
GRPOConfig,
|
| 70 |
+
GRPOTrainer,
|
| 71 |
+
ModelConfig,
|
| 72 |
+
ScriptArguments,
|
| 73 |
+
TrlParser,
|
| 74 |
+
get_kbit_device_map,
|
| 75 |
+
get_peft_config,
|
| 76 |
+
get_quantization_config,
|
| 77 |
+
)
|
| 78 |
+
from trl.rewards import accuracy_reward, think_format_reward
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
if __name__ == "__main__":
|
| 82 |
+
parser = TrlParser((ScriptArguments, GRPOConfig, ModelConfig))
|
| 83 |
+
script_args, training_args, model_args = parser.parse_args_and_config()
|
| 84 |
+
################
|
| 85 |
+
# Model
|
| 86 |
+
################
|
| 87 |
+
dtype = model_args.dtype if model_args.dtype in ["auto", None] else getattr(torch, model_args.dtype)
|
| 88 |
+
training_args.model_init_kwargs = dict(
|
| 89 |
+
revision=model_args.model_revision,
|
| 90 |
+
attn_implementation=model_args.attn_implementation,
|
| 91 |
+
dtype=dtype,
|
| 92 |
+
)
|
| 93 |
+
quantization_config = get_quantization_config(model_args)
|
| 94 |
+
if quantization_config is not None:
|
| 95 |
+
# Passing None would not be treated the same as omitting the argument, so we include it only when valid.
|
| 96 |
+
training_args.model_init_kwargs["device_map"] = get_kbit_device_map()
|
| 97 |
+
training_args.model_init_kwargs["quantization_config"] = quantization_config
|
| 98 |
+
|
| 99 |
+
################
|
| 100 |
+
# Dataset
|
| 101 |
+
################
|
| 102 |
+
dataset = load_dataset("lmms-lab/multimodal-open-r1-8k-verified", split="train")
|
| 103 |
+
dataset = dataset.train_test_split(test_size=100, seed=42)
|
| 104 |
+
|
| 105 |
+
SYSTEM_PROMPT = (
|
| 106 |
+
"A conversation between user and assistant. The user asks a question, and the assistant solves it. The "
|
| 107 |
+
"assistant first thinks about the reasoning process in the mind and then provides the user with the answer. "
|
| 108 |
+
"The reasoning process and answer are enclosed within <think></think> tags, i.e., <think>\nThis is my "
|
| 109 |
+
"reasoning.\n</think>\nThis is my answer."
|
| 110 |
+
)
|
| 111 |
+
|
| 112 |
+
def make_conversation(example):
|
| 113 |
+
prompt = [
|
| 114 |
+
{"role": "system", "content": SYSTEM_PROMPT},
|
| 115 |
+
{"role": "user", "content": example["problem"]},
|
| 116 |
+
]
|
| 117 |
+
return {"prompt": prompt}
|
| 118 |
+
|
| 119 |
+
dataset = dataset.map(make_conversation)
|
| 120 |
+
|
| 121 |
+
# Filter have big images
|
| 122 |
+
def filter_big_images(example):
|
| 123 |
+
image = example["image"]
|
| 124 |
+
return image.size[0] < 512 and image.size[1] < 512
|
| 125 |
+
|
| 126 |
+
dataset = dataset.filter(filter_big_images)
|
| 127 |
+
|
| 128 |
+
def convert_to_rgb(example):
|
| 129 |
+
image = example["image"]
|
| 130 |
+
if image.mode != "RGB":
|
| 131 |
+
image = image.convert("RGB")
|
| 132 |
+
example["image"] = image
|
| 133 |
+
return example
|
| 134 |
+
|
| 135 |
+
dataset = dataset.map(convert_to_rgb)
|
| 136 |
+
|
| 137 |
+
train_dataset = dataset["train"]
|
| 138 |
+
eval_dataset = dataset["test"] if training_args.eval_strategy != "no" else None
|
| 139 |
+
|
| 140 |
+
################
|
| 141 |
+
# Training
|
| 142 |
+
################
|
| 143 |
+
trainer = GRPOTrainer(
|
| 144 |
+
model=model_args.model_name_or_path,
|
| 145 |
+
args=training_args,
|
| 146 |
+
reward_funcs=[think_format_reward, accuracy_reward],
|
| 147 |
+
train_dataset=train_dataset,
|
| 148 |
+
eval_dataset=eval_dataset,
|
| 149 |
+
peft_config=get_peft_config(model_args),
|
| 150 |
+
)
|
| 151 |
+
|
| 152 |
+
trainer.train()
|
| 153 |
+
|
| 154 |
+
# Save and push to hub
|
| 155 |
+
trainer.save_model(training_args.output_dir)
|
| 156 |
+
if training_args.push_to_hub:
|
| 157 |
+
trainer.push_to_hub(dataset_name=script_args.dataset_name)
|
tasks/tasksmith-fa1a9b35ff39/tests/source/examples/scripts/gspo.py
ADDED
|
@@ -0,0 +1,131 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2020-2026 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
# /// script
|
| 16 |
+
# dependencies = [
|
| 17 |
+
# "trl[peft]",
|
| 18 |
+
# "math-verify",
|
| 19 |
+
# "latex2sympy2_extended",
|
| 20 |
+
# "trackio",
|
| 21 |
+
# "kernels",
|
| 22 |
+
# ]
|
| 23 |
+
# ///
|
| 24 |
+
|
| 25 |
+
"""
|
| 26 |
+
pip install math_verify
|
| 27 |
+
|
| 28 |
+
# For Qwen/Qwen3-0.6B
|
| 29 |
+
pip install num2words==0.5.14
|
| 30 |
+
|
| 31 |
+
accelerate launch \
|
| 32 |
+
--config_file examples/accelerate_configs/deepspeed_zero3.yaml \
|
| 33 |
+
examples/scripts/gspo.py \
|
| 34 |
+
--model_name_or_path Qwen/Qwen3-0.6B \
|
| 35 |
+
--output_dir gspo-Qwen3-0.6B \
|
| 36 |
+
--learning_rate 1e-5 \
|
| 37 |
+
--dtype bfloat16 \
|
| 38 |
+
--max_completion_length 1024 \
|
| 39 |
+
--use_peft \
|
| 40 |
+
--lora_target_modules "q_proj", "v_proj" \
|
| 41 |
+
--log_completions \
|
| 42 |
+
--per_device_train_batch_size 8 \
|
| 43 |
+
--num_generations 8 \
|
| 44 |
+
--importance_sampling_level sequence \
|
| 45 |
+
--epsilon 3e-4 \
|
| 46 |
+
--epsilon_high 4e-4 \
|
| 47 |
+
--beta 0.0 \
|
| 48 |
+
--loss_type grpo \
|
| 49 |
+
--gradient_accumulation_steps 2 \
|
| 50 |
+
--steps_per_generation 8
|
| 51 |
+
|
| 52 |
+
"""
|
| 53 |
+
|
| 54 |
+
import torch
|
| 55 |
+
from datasets import load_dataset
|
| 56 |
+
|
| 57 |
+
from trl import (
|
| 58 |
+
GRPOConfig,
|
| 59 |
+
GRPOTrainer,
|
| 60 |
+
ModelConfig,
|
| 61 |
+
ScriptArguments,
|
| 62 |
+
TrlParser,
|
| 63 |
+
get_kbit_device_map,
|
| 64 |
+
get_peft_config,
|
| 65 |
+
get_quantization_config,
|
| 66 |
+
)
|
| 67 |
+
from trl.rewards import accuracy_reward, think_format_reward
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
if __name__ == "__main__":
|
| 71 |
+
parser = TrlParser((ScriptArguments, GRPOConfig, ModelConfig))
|
| 72 |
+
script_args, training_args, model_args = parser.parse_args_and_config()
|
| 73 |
+
################
|
| 74 |
+
# Model & Processor
|
| 75 |
+
################
|
| 76 |
+
dtype = model_args.dtype if model_args.dtype in ["auto", None] else getattr(torch, model_args.dtype)
|
| 77 |
+
training_args.model_init_kwargs = dict(
|
| 78 |
+
revision=model_args.model_revision,
|
| 79 |
+
attn_implementation=model_args.attn_implementation,
|
| 80 |
+
dtype=dtype,
|
| 81 |
+
)
|
| 82 |
+
quantization_config = get_quantization_config(model_args)
|
| 83 |
+
if quantization_config is not None:
|
| 84 |
+
# Passing None would not be treated the same as omitting the argument, so we include it only when valid.
|
| 85 |
+
training_args.model_init_kwargs["device_map"] = get_kbit_device_map()
|
| 86 |
+
training_args.model_init_kwargs["quantization_config"] = quantization_config
|
| 87 |
+
|
| 88 |
+
################
|
| 89 |
+
# Dataset
|
| 90 |
+
################
|
| 91 |
+
train_dataset, eval_dataset = load_dataset("AI-MO/NuminaMath-TIR", split=["train[:5%]", "test[:5%]"])
|
| 92 |
+
|
| 93 |
+
SYSTEM_PROMPT = (
|
| 94 |
+
"A conversation between user and assistant. The user asks a question, and the assistant solves it. The "
|
| 95 |
+
"assistant first thinks about the reasoning process in the mind and then provides the user with the answer. "
|
| 96 |
+
"The reasoning process and answer are enclosed within <think></think> tags, i.e., <think>\nThis is my "
|
| 97 |
+
"reasoning.\n</think>\nThis is my answer."
|
| 98 |
+
)
|
| 99 |
+
|
| 100 |
+
def make_conversation(example):
|
| 101 |
+
return {
|
| 102 |
+
"prompt": [
|
| 103 |
+
{"role": "system", "content": SYSTEM_PROMPT},
|
| 104 |
+
{"role": "user", "content": example["problem"]},
|
| 105 |
+
],
|
| 106 |
+
}
|
| 107 |
+
|
| 108 |
+
train_dataset = train_dataset.map(make_conversation)
|
| 109 |
+
eval_dataset = eval_dataset.map(make_conversation)
|
| 110 |
+
|
| 111 |
+
train_dataset = train_dataset.remove_columns(["messages", "problem"])
|
| 112 |
+
eval_dataset = eval_dataset.remove_columns(["messages", "problem"])
|
| 113 |
+
|
| 114 |
+
################
|
| 115 |
+
# Training
|
| 116 |
+
################
|
| 117 |
+
trainer = GRPOTrainer(
|
| 118 |
+
model=model_args.model_name_or_path,
|
| 119 |
+
args=training_args,
|
| 120 |
+
reward_funcs=[think_format_reward, accuracy_reward],
|
| 121 |
+
train_dataset=train_dataset,
|
| 122 |
+
eval_dataset=eval_dataset,
|
| 123 |
+
peft_config=get_peft_config(model_args),
|
| 124 |
+
)
|
| 125 |
+
|
| 126 |
+
trainer.train()
|
| 127 |
+
|
| 128 |
+
# Save and push to hub
|
| 129 |
+
trainer.save_model(training_args.output_dir)
|
| 130 |
+
if training_args.push_to_hub:
|
| 131 |
+
trainer.push_to_hub(dataset_name=script_args.dataset_name)
|
tasks/tasksmith-fa1a9b35ff39/tests/source/examples/scripts/gspo_vlm.py
ADDED
|
@@ -0,0 +1,146 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2020-2026 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
# /// script
|
| 16 |
+
# dependencies = [
|
| 17 |
+
# "trl[peft]",
|
| 18 |
+
# "Pillow",
|
| 19 |
+
# "math-verify",
|
| 20 |
+
# "latex2sympy2_extended",
|
| 21 |
+
# "torchvision",
|
| 22 |
+
# "trackio",
|
| 23 |
+
# "kernels",
|
| 24 |
+
# ]
|
| 25 |
+
# ///
|
| 26 |
+
|
| 27 |
+
"""
|
| 28 |
+
pip install math_verify
|
| 29 |
+
|
| 30 |
+
# For Qwen/Qwen2.5-VL-3B-Instruct
|
| 31 |
+
accelerate launch \
|
| 32 |
+
--config_file examples/accelerate_configs/deepspeed_zero3.yaml \
|
| 33 |
+
examples/scripts/gspo_vlm.py \
|
| 34 |
+
--model_name_or_path Qwen/Qwen2.5-VL-3B-Instruct \
|
| 35 |
+
--output_dir gspo-Qwen2.5-VL-3B-Instruct \
|
| 36 |
+
--learning_rate 1e-5 \
|
| 37 |
+
--dtype bfloat16 \
|
| 38 |
+
--max_completion_length 1024 \
|
| 39 |
+
--use_peft \
|
| 40 |
+
--lora_target_modules "q_proj", "v_proj" \
|
| 41 |
+
--log_completions \
|
| 42 |
+
--per_device_train_batch_size 8 \
|
| 43 |
+
--num_generations 8 \
|
| 44 |
+
--importance_sampling_level sequence \
|
| 45 |
+
--epsilon 3e-4 \
|
| 46 |
+
--epsilon_high 4e-4 \
|
| 47 |
+
--beta 0.0 \
|
| 48 |
+
--loss_type grpo \
|
| 49 |
+
--gradient_accumulation_steps 2 \
|
| 50 |
+
--steps_per_generation 8
|
| 51 |
+
|
| 52 |
+
"""
|
| 53 |
+
|
| 54 |
+
import torch
|
| 55 |
+
from datasets import load_dataset
|
| 56 |
+
|
| 57 |
+
from trl import (
|
| 58 |
+
GRPOConfig,
|
| 59 |
+
GRPOTrainer,
|
| 60 |
+
ModelConfig,
|
| 61 |
+
ScriptArguments,
|
| 62 |
+
TrlParser,
|
| 63 |
+
get_kbit_device_map,
|
| 64 |
+
get_peft_config,
|
| 65 |
+
get_quantization_config,
|
| 66 |
+
)
|
| 67 |
+
from trl.rewards import accuracy_reward, think_format_reward
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
if __name__ == "__main__":
|
| 71 |
+
parser = TrlParser((ScriptArguments, GRPOConfig, ModelConfig))
|
| 72 |
+
script_args, training_args, model_args = parser.parse_args_and_config()
|
| 73 |
+
################
|
| 74 |
+
# Model
|
| 75 |
+
################
|
| 76 |
+
dtype = model_args.dtype if model_args.dtype in ["auto", None] else getattr(torch, model_args.dtype)
|
| 77 |
+
training_args.model_init_kwargs = dict(
|
| 78 |
+
revision=model_args.model_revision,
|
| 79 |
+
attn_implementation=model_args.attn_implementation,
|
| 80 |
+
dtype=dtype,
|
| 81 |
+
)
|
| 82 |
+
quantization_config = get_quantization_config(model_args)
|
| 83 |
+
if quantization_config is not None:
|
| 84 |
+
# Passing None would not be treated the same as omitting the argument, so we include it only when valid.
|
| 85 |
+
training_args.model_init_kwargs["device_map"] = get_kbit_device_map()
|
| 86 |
+
training_args.model_init_kwargs["quantization_config"] = quantization_config
|
| 87 |
+
|
| 88 |
+
################
|
| 89 |
+
# Dataset
|
| 90 |
+
################
|
| 91 |
+
dataset = load_dataset("lmms-lab/multimodal-open-r1-8k-verified", split="train")
|
| 92 |
+
dataset = dataset.train_test_split(test_size=100, seed=42)
|
| 93 |
+
|
| 94 |
+
SYSTEM_PROMPT = (
|
| 95 |
+
"A conversation between user and assistant. The user asks a question, and the assistant solves it. The "
|
| 96 |
+
"assistant first thinks about the reasoning process in the mind and then provides the user with the answer. "
|
| 97 |
+
"The reasoning process and answer are enclosed within <think></think> tags, i.e., <think>\nThis is my "
|
| 98 |
+
"reasoning.\n</think>\nThis is my answer."
|
| 99 |
+
)
|
| 100 |
+
|
| 101 |
+
def make_conversation(example):
|
| 102 |
+
prompt = [
|
| 103 |
+
{"role": "system", "content": SYSTEM_PROMPT},
|
| 104 |
+
{"role": "user", "content": example["problem"]},
|
| 105 |
+
]
|
| 106 |
+
return {"prompt": prompt}
|
| 107 |
+
|
| 108 |
+
dataset = dataset.map(make_conversation)
|
| 109 |
+
|
| 110 |
+
# Filter have big images
|
| 111 |
+
def filter_big_images(example):
|
| 112 |
+
image = example["image"]
|
| 113 |
+
return image.size[0] < 512 and image.size[1] < 512
|
| 114 |
+
|
| 115 |
+
dataset = dataset.filter(filter_big_images)
|
| 116 |
+
|
| 117 |
+
def convert_to_rgb(example):
|
| 118 |
+
image = example["image"]
|
| 119 |
+
if image.mode != "RGB":
|
| 120 |
+
image = image.convert("RGB")
|
| 121 |
+
example["image"] = image
|
| 122 |
+
return example
|
| 123 |
+
|
| 124 |
+
dataset = dataset.map(convert_to_rgb)
|
| 125 |
+
|
| 126 |
+
train_dataset = dataset["train"]
|
| 127 |
+
eval_dataset = dataset["test"] if training_args.eval_strategy != "no" else None
|
| 128 |
+
|
| 129 |
+
################
|
| 130 |
+
# Training
|
| 131 |
+
################
|
| 132 |
+
trainer = GRPOTrainer(
|
| 133 |
+
model=model_args.model_name_or_path,
|
| 134 |
+
args=training_args,
|
| 135 |
+
reward_funcs=[think_format_reward, accuracy_reward],
|
| 136 |
+
train_dataset=train_dataset,
|
| 137 |
+
eval_dataset=eval_dataset,
|
| 138 |
+
peft_config=get_peft_config(model_args),
|
| 139 |
+
)
|
| 140 |
+
|
| 141 |
+
trainer.train()
|
| 142 |
+
|
| 143 |
+
# Save and push to hub
|
| 144 |
+
trainer.save_model(training_args.output_dir)
|
| 145 |
+
if training_args.push_to_hub:
|
| 146 |
+
trainer.push_to_hub(dataset_name=script_args.dataset_name)
|
tasks/tasksmith-fa1a9b35ff39/tests/source/examples/scripts/harbor/data_agent.py
ADDED
|
@@ -0,0 +1,131 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2020-2026 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
# /// script
|
| 16 |
+
# dependencies = ["trl[vllm,harbor]", "harbor[e2b]"] # harbor[e2b]: the --env e2b backend (swap per --env)
|
| 17 |
+
# ///
|
| 18 |
+
|
| 19 |
+
"""GRPO training against a Harbor task suite.
|
| 20 |
+
|
| 21 |
+
One ``HarborSpec`` fans out into TRL's three slots — ``.train_dataset`` / ``.environment_factory`` /
|
| 22 |
+
``.reward_funcs``. The base agent (harness) is selected with ``--agent``: the built-in ``"bash"``, or
|
| 23 |
+
an import/file path to a custom ``HarborEnv`` subclass. Harbor runs in-process, so install with
|
| 24 |
+
``trl[harbor]`` (Python >= 3.12) plus the chosen sandbox backend's extra (``pip install "harbor[e2b]"``
|
| 25 |
+
for the recommended ``--env e2b``; the ``docker`` backend just needs a reachable Docker daemon).
|
| 26 |
+
|
| 27 |
+
Usage (server vLLM, single-node 2+2 GPU split):
|
| 28 |
+
|
| 29 |
+
```sh
|
| 30 |
+
# Terminal 1 — vLLM
|
| 31 |
+
CUDA_VISIBLE_DEVICES=2,3 trl vllm-serve --model Qwen/Qwen3-4B --tensor-parallel-size 2 --port 8000
|
| 32 |
+
|
| 33 |
+
# Terminal 2 — training
|
| 34 |
+
CUDA_VISIBLE_DEVICES=0,1 accelerate launch \
|
| 35 |
+
--config_file examples/accelerate_configs/deepspeed_zero2.yaml --num_processes 2 \
|
| 36 |
+
examples/scripts/harbor/data_agent.py \
|
| 37 |
+
--vllm-mode server --vllm-server-base-url http://localhost:8000 --env e2b
|
| 38 |
+
```
|
| 39 |
+
"""
|
| 40 |
+
|
| 41 |
+
import argparse
|
| 42 |
+
|
| 43 |
+
from trl import GRPOConfig, GRPOTrainer
|
| 44 |
+
from trl.experimental.harbor import HarborSpec
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def parse_args() -> argparse.Namespace:
|
| 48 |
+
parser = argparse.ArgumentParser(description="GRPO training against a Harbor task suite.")
|
| 49 |
+
|
| 50 |
+
parser.add_argument("--model", type=str, default="Qwen/Qwen3-4B")
|
| 51 |
+
parser.add_argument(
|
| 52 |
+
"--dataset",
|
| 53 |
+
type=str,
|
| 54 |
+
default="AdithyaSK/data_agent_rl_environment_train",
|
| 55 |
+
help="HF dataset repo id with a Harbor task tree, or a local path containing a tasks/ subtree.",
|
| 56 |
+
)
|
| 57 |
+
parser.add_argument(
|
| 58 |
+
"--agent",
|
| 59 |
+
type=str,
|
| 60 |
+
default="bash",
|
| 61 |
+
help="Base agent/harness: built-in name ('bash'), import path 'pkg.mod:Class', or file 'path.py:Class'.",
|
| 62 |
+
)
|
| 63 |
+
parser.add_argument(
|
| 64 |
+
"--env",
|
| 65 |
+
dest="environment_type",
|
| 66 |
+
type=str,
|
| 67 |
+
default="docker",
|
| 68 |
+
help="Harbor sandbox backend (docker, e2b, daytona, gke, modal, runloop, ...).",
|
| 69 |
+
)
|
| 70 |
+
parser.add_argument("--num-tasks", type=int, default=64)
|
| 71 |
+
|
| 72 |
+
parser.add_argument("--learning-rate", type=float, default=1e-6)
|
| 73 |
+
parser.add_argument("--per-device-train-batch-size", type=int, default=8)
|
| 74 |
+
parser.add_argument("--num-generations", type=int, default=8)
|
| 75 |
+
parser.add_argument("--max-completion-length", type=int, default=2048)
|
| 76 |
+
parser.add_argument("--max-steps", type=int, default=50)
|
| 77 |
+
parser.add_argument("--max-tool-calling-iterations", type=int, default=25)
|
| 78 |
+
|
| 79 |
+
parser.add_argument("--vllm-mode", choices=("colocate", "server"), default="colocate")
|
| 80 |
+
parser.add_argument("--vllm-server-base-url", type=str, default="http://localhost:8000")
|
| 81 |
+
parser.add_argument("--vllm-gpu-memory-utilization", type=float, default=0.3)
|
| 82 |
+
|
| 83 |
+
parser.add_argument("--output-dir", type=str, default=None)
|
| 84 |
+
parser.add_argument("--report-to", type=str, default="none")
|
| 85 |
+
|
| 86 |
+
return parser.parse_args()
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
def main() -> None:
|
| 90 |
+
args = parse_args()
|
| 91 |
+
|
| 92 |
+
# One spec object — fans out into TRL's three slots.
|
| 93 |
+
spec = HarborSpec(
|
| 94 |
+
args.dataset,
|
| 95 |
+
agent=args.agent,
|
| 96 |
+
environment_type=args.environment_type,
|
| 97 |
+
num_tasks=args.num_tasks,
|
| 98 |
+
)
|
| 99 |
+
|
| 100 |
+
config_kwargs: dict = dict(
|
| 101 |
+
learning_rate=args.learning_rate,
|
| 102 |
+
per_device_train_batch_size=args.per_device_train_batch_size,
|
| 103 |
+
num_generations=args.num_generations,
|
| 104 |
+
max_completion_length=args.max_completion_length,
|
| 105 |
+
max_steps=args.max_steps,
|
| 106 |
+
max_tool_calling_iterations=args.max_tool_calling_iterations,
|
| 107 |
+
chat_template_kwargs={"enable_thinking": False},
|
| 108 |
+
log_completions=True,
|
| 109 |
+
use_vllm=True,
|
| 110 |
+
vllm_mode=args.vllm_mode,
|
| 111 |
+
report_to=[s.strip() for s in args.report_to.split(",") if s.strip() and s.strip() != "none"] or "none",
|
| 112 |
+
)
|
| 113 |
+
if args.output_dir:
|
| 114 |
+
config_kwargs["output_dir"] = args.output_dir
|
| 115 |
+
if args.vllm_mode == "colocate":
|
| 116 |
+
config_kwargs["vllm_gpu_memory_utilization"] = args.vllm_gpu_memory_utilization
|
| 117 |
+
else:
|
| 118 |
+
config_kwargs["vllm_server_base_url"] = args.vllm_server_base_url
|
| 119 |
+
|
| 120 |
+
trainer = GRPOTrainer(
|
| 121 |
+
model=args.model,
|
| 122 |
+
args=GRPOConfig(**config_kwargs),
|
| 123 |
+
train_dataset=spec.train_dataset,
|
| 124 |
+
environment_factory=spec.environment_factory,
|
| 125 |
+
reward_funcs=spec.reward_funcs,
|
| 126 |
+
)
|
| 127 |
+
trainer.train()
|
| 128 |
+
|
| 129 |
+
|
| 130 |
+
if __name__ == "__main__":
|
| 131 |
+
main()
|
tasks/tasksmith-fa1a9b35ff39/tests/source/examples/scripts/harbor/harnesses/__init__.py
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2020-2026 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
from .bash import BashEnv
|
| 16 |
+
from .jupyter import JupyterEnv
|
| 17 |
+
from .terminal_notes import TerminalNotesEnv
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
__all__ = ["BashEnv", "JupyterEnv", "TerminalNotesEnv"]
|
tasks/tasksmith-fa1a9b35ff39/tests/source/examples/scripts/harbor/harnesses/bash/README.md
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# `bash` harness
|
| 2 |
+
|
| 3 |
+
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`.
|
| 4 |
+
|
| 5 |
+
## Tools
|
| 6 |
+
|
| 7 |
+
| Tool | Signature | What it does |
|
| 8 |
+
|---|---|---|
|
| 9 |
+
| `bash` | `bash(command: str) -> str` | Run a shell command in the sandbox; returns combined stdout+stderr (truncated to 8k). Non-stateful between calls. |
|
| 10 |
+
|
| 11 |
+
## Submission
|
| 12 |
+
|
| 13 |
+
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.
|
| 14 |
+
|
| 15 |
+
## Use it
|
| 16 |
+
|
| 17 |
+
```python
|
| 18 |
+
from trl.experimental.harbor import HarborSpec
|
| 19 |
+
spec = HarborSpec(dataset, agent="bash") # built-in name
|
| 20 |
+
```
|
tasks/tasksmith-fa1a9b35ff39/tests/source/examples/scripts/harbor/harnesses/bash/__init__.py
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2020-2026 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
from trl.experimental.harbor import HarborBashEnv as BashEnv # the built-in bash harness
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
__all__ = ["BashEnv"]
|
tasks/tasksmith-fa1a9b35ff39/tests/source/examples/scripts/harbor/harnesses/jupyter/README.md
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# `jupyter` harness
|
| 2 |
+
|
| 3 |
+
A **stateful Python kernel** harness. Variables, imports, and side-effects persist across cells, so the
|
| 4 |
+
model builds up state like a notebook. Implemented by `JupyterEnv` in [`env.py`](env.py).
|
| 5 |
+
|
| 6 |
+
## How it works
|
| 7 |
+
|
| 8 |
+
On `reset`, the harness (`_setup`) uploads two helpers into the sandbox and starts a tiny kernel server:
|
| 9 |
+
|
| 10 |
+
- [`kernel_server.py`](kernel_server.py) — a local HTTP server (`127.0.0.1:8765`) holding one persistent Python kernel.
|
| 11 |
+
- [`run_cell.py`](run_cell.py) — sends a base64-encoded cell to the kernel server and prints its JSON result.
|
| 12 |
+
|
| 13 |
+
Each `add_and_execute_code_cell` call runs `python3 /opt/run_cell.py` against that kernel.
|
| 14 |
+
|
| 15 |
+
## Tools
|
| 16 |
+
|
| 17 |
+
| Tool | Signature | What it does |
|
| 18 |
+
|---|---|---|
|
| 19 |
+
| `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. |
|
| 20 |
+
| `execute_shell_command` | `execute_shell_command(command: str) -> str` | Run a shell command (pip install, ls, …). **Not** stateful with the Python kernel. |
|
| 21 |
+
|
| 22 |
+
## Submission
|
| 23 |
+
|
| 24 |
+
Write the answer to `/workdir/answer.txt` — e.g. `add_and_execute_code_cell(code="open('/workdir/answer.txt','w').write(str(ans))")`.
|
| 25 |
+
|
| 26 |
+
## Use it
|
| 27 |
+
|
| 28 |
+
```python
|
| 29 |
+
from trl.experimental.harbor import HarborSpec
|
| 30 |
+
spec = HarborSpec(dataset, agent="examples/scripts/harbor/harnesses/jupyter/env.py:JupyterEnv")
|
| 31 |
+
```
|
tasks/tasksmith-fa1a9b35ff39/tests/source/examples/scripts/harbor/harnesses/jupyter/__init__.py
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2020-2026 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
from .env import JupyterEnv
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
__all__ = ["JupyterEnv"]
|
tasks/tasksmith-fa1a9b35ff39/tests/source/examples/scripts/harbor/harnesses/jupyter/env.py
ADDED
|
@@ -0,0 +1,104 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2020-2026 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
"""Jupyter-style base agent — a stateful-kernel Harbor harness.
|
| 16 |
+
|
| 17 |
+
A custom [`~trl.experimental.harbor.HarborEnv`] subclass exposing a stateful Python kernel
|
| 18 |
+
(variables/imports persist across cells) plus a shell tool. Point a trainer at it with
|
| 19 |
+
``HarborSpec(dataset, agent="examples/scripts/harbor/harnesses/jupyter/env.py:JupyterEnv")``.
|
| 20 |
+
|
| 21 |
+
The kernel is a tiny HTTP server (`kernel_server.py`, uploaded to /opt/ and started in `_setup`); each
|
| 22 |
+
cell runs via `python3 /opt/run_cell.py` (see `run_cell.py`). Submission is by writing
|
| 23 |
+
``/workdir/answer.txt`` (same verifier as the bash harness).
|
| 24 |
+
"""
|
| 25 |
+
|
| 26 |
+
import asyncio
|
| 27 |
+
import base64
|
| 28 |
+
import json
|
| 29 |
+
import shlex
|
| 30 |
+
from pathlib import Path
|
| 31 |
+
|
| 32 |
+
from trl.experimental.harbor import HarborEnv
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
_HERE = Path(__file__).parent
|
| 36 |
+
|
| 37 |
+
_JUPYTER_PROMPT_SUFFIX = (
|
| 38 |
+
"\n\nYou are a data-analysis agent with a **stateful Python kernel**: variables, imports, and "
|
| 39 |
+
"side-effects persist across `add_and_execute_code_cell` calls. Dataset files are in "
|
| 40 |
+
"/home/user/input/. Use `execute_shell_command` for shell (pip install, ls). **Submit your final "
|
| 41 |
+
"answer by writing it to /workdir/answer.txt** (e.g. "
|
| 42 |
+
"`add_and_execute_code_cell(code=\"open('/workdir/answer.txt','w').write(str(ans))\")`). Keep it "
|
| 43 |
+
"short; do not end your turn without submitting."
|
| 44 |
+
)
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
class JupyterEnv(HarborEnv):
|
| 48 |
+
"""Stateful-Jupyter-kernel harness over a Harbor sandbox."""
|
| 49 |
+
|
| 50 |
+
PROMPT_SUFFIX = _JUPYTER_PROMPT_SUFFIX
|
| 51 |
+
|
| 52 |
+
async def _setup(self) -> None:
|
| 53 |
+
# Upload the kernel server + cell runner, ensure curl, start the kernel, wait for it to bind.
|
| 54 |
+
await self._env.upload_file(_HERE / "kernel_server.py", "/opt/kernel_server.py")
|
| 55 |
+
await self._env.upload_file(_HERE / "run_cell.py", "/opt/run_cell.py")
|
| 56 |
+
await self._env.exec("which curl >/dev/null 2>&1 || apt-get install -y curl", timeout_sec=120)
|
| 57 |
+
await self._env.exec(
|
| 58 |
+
"nohup setsid python3 /opt/kernel_server.py >/tmp/kernel.log 2>&1 < /dev/null &", timeout_sec=30
|
| 59 |
+
)
|
| 60 |
+
for _ in range(30):
|
| 61 |
+
r = await self._env.exec("curl -s -o /dev/null -w '%{http_code}' http://127.0.0.1:8765/", timeout_sec=5)
|
| 62 |
+
if (r.stdout or "").strip() == "200":
|
| 63 |
+
return
|
| 64 |
+
await asyncio.sleep(0.5)
|
| 65 |
+
log = await self._env.exec("cat /tmp/kernel.log", timeout_sec=5)
|
| 66 |
+
raise RuntimeError(f"kernel_server failed to bind 127.0.0.1:8765\n--- kernel.log ---\n{log.stdout}")
|
| 67 |
+
|
| 68 |
+
def _run_cell(self, code: str) -> str:
|
| 69 |
+
b64 = base64.b64encode(code.encode()).decode()
|
| 70 |
+
result = self._loop.run_until_complete(
|
| 71 |
+
self._env.exec(f"python3 /opt/run_cell.py --code-b64 {shlex.quote(b64)}", timeout_sec=180)
|
| 72 |
+
)
|
| 73 |
+
raw = (result.stdout or "").strip()
|
| 74 |
+
if not raw:
|
| 75 |
+
return f"[run_cell empty stdout, rc={result.return_code}, stderr={result.stderr or ''}]"
|
| 76 |
+
try:
|
| 77 |
+
return str(json.loads(raw).get("output", ""))
|
| 78 |
+
except json.JSONDecodeError:
|
| 79 |
+
return f"[run_cell unparseable: {raw[:500]}]"
|
| 80 |
+
|
| 81 |
+
def add_and_execute_code_cell(self, code: str) -> str:
|
| 82 |
+
"""
|
| 83 |
+
Execute Python code in the stateful kernel. Variables, imports, and side-effects persist across
|
| 84 |
+
calls. Use this for all computation.
|
| 85 |
+
|
| 86 |
+
Args:
|
| 87 |
+
code: The Python code to execute.
|
| 88 |
+
|
| 89 |
+
Returns:
|
| 90 |
+
The textual output of the executed cell.
|
| 91 |
+
"""
|
| 92 |
+
return self._run_cell(code)
|
| 93 |
+
|
| 94 |
+
def execute_shell_command(self, command: str) -> str:
|
| 95 |
+
"""
|
| 96 |
+
Run a shell command in the sandbox (pip install, ls, etc.). Not stateful with the Python kernel.
|
| 97 |
+
|
| 98 |
+
Args:
|
| 99 |
+
command: The shell command to run.
|
| 100 |
+
|
| 101 |
+
Returns:
|
| 102 |
+
The command's combined stdout and stderr.
|
| 103 |
+
"""
|
| 104 |
+
return self._exec(command)
|
tasks/tasksmith-fa1a9b35ff39/tests/source/examples/scripts/harbor/harnesses/jupyter/kernel_server.py
ADDED
|
@@ -0,0 +1,98 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2020-2026 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
"""Tiny stateful Python execution server.
|
| 16 |
+
|
| 17 |
+
Uploaded by JupyterToolAgent into the Harbor container at /opt/kernel_server.py
|
| 18 |
+
and started in the background. Listens on 127.0.0.1:8765 and accepts:
|
| 19 |
+
|
| 20 |
+
POST / Content-Type: application/json
|
| 21 |
+
Body: {"code": "..."}
|
| 22 |
+
Reply: {"output": "<stdout+stderr+traceback>", "ok": true|false}
|
| 23 |
+
|
| 24 |
+
A single persistent globals dict survives across requests — that's the
|
| 25 |
+
"stateful kernel" the agent's `add_and_execute_code_cell` tool relies on.
|
| 26 |
+
No IPython, no jupyter_client. Just compile(...) + exec(...).
|
| 27 |
+
"""
|
| 28 |
+
|
| 29 |
+
from __future__ import annotations
|
| 30 |
+
|
| 31 |
+
import contextlib
|
| 32 |
+
import io
|
| 33 |
+
import json
|
| 34 |
+
import traceback
|
| 35 |
+
from http.server import BaseHTTPRequestHandler, HTTPServer
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
PORT = 8765
|
| 39 |
+
G: dict = {"__name__": "__main__"}
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def _exec(code: str) -> tuple[str, bool]:
|
| 43 |
+
out = io.StringIO()
|
| 44 |
+
err = io.StringIO()
|
| 45 |
+
ok = True
|
| 46 |
+
try:
|
| 47 |
+
# Try "single" mode first so a bare expression auto-prints (mimics Jupyter).
|
| 48 |
+
try:
|
| 49 |
+
compiled = compile(code, "<cell>", "single")
|
| 50 |
+
except SyntaxError:
|
| 51 |
+
compiled = compile(code, "<cell>", "exec")
|
| 52 |
+
with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err):
|
| 53 |
+
exec(compiled, G)
|
| 54 |
+
except SystemExit:
|
| 55 |
+
pass
|
| 56 |
+
except BaseException:
|
| 57 |
+
ok = False
|
| 58 |
+
err.write(traceback.format_exc())
|
| 59 |
+
return out.getvalue() + err.getvalue(), ok
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
class Handler(BaseHTTPRequestHandler):
|
| 63 |
+
def do_POST(self):
|
| 64 |
+
try:
|
| 65 |
+
n = int(self.headers.get("Content-Length", "0"))
|
| 66 |
+
body = self.rfile.read(n).decode("utf-8", errors="replace")
|
| 67 |
+
payload = json.loads(body)
|
| 68 |
+
code = payload.get("code", "")
|
| 69 |
+
output, ok = _exec(code)
|
| 70 |
+
except Exception:
|
| 71 |
+
output, ok = traceback.format_exc(), False
|
| 72 |
+
# Cap to keep the per-cell response small.
|
| 73 |
+
if len(output) > 8000:
|
| 74 |
+
output = output[:8000] + f"\n... [truncated {len(output) - 8000} chars]"
|
| 75 |
+
body_out = json.dumps({"output": output, "ok": ok}).encode()
|
| 76 |
+
self.send_response(200)
|
| 77 |
+
self.send_header("Content-Type", "application/json")
|
| 78 |
+
self.send_header("Content-Length", str(len(body_out)))
|
| 79 |
+
self.end_headers()
|
| 80 |
+
self.wfile.write(body_out)
|
| 81 |
+
|
| 82 |
+
def do_GET(self):
|
| 83 |
+
# Health check.
|
| 84 |
+
msg = b'{"ready": true}'
|
| 85 |
+
self.send_response(200)
|
| 86 |
+
self.send_header("Content-Type", "application/json")
|
| 87 |
+
self.send_header("Content-Length", str(len(msg)))
|
| 88 |
+
self.end_headers()
|
| 89 |
+
self.wfile.write(msg)
|
| 90 |
+
|
| 91 |
+
def log_message(self, *a, **k):
|
| 92 |
+
# Quiet — Harbor agent's exec captures stdout/stderr.
|
| 93 |
+
pass
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
if __name__ == "__main__":
|
| 97 |
+
print(f"[kernel_server] starting on 127.0.0.1:{PORT}", flush=True)
|
| 98 |
+
HTTPServer(("127.0.0.1", PORT), Handler).serve_forever()
|
tasks/tasksmith-fa1a9b35ff39/tests/source/examples/scripts/harbor/harnesses/jupyter/run_cell.py
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2020-2026 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
"""CLI client for the kernel_server, invoked by the Harbor agent via env.exec.
|
| 16 |
+
|
| 17 |
+
Usage (inside the container):
|
| 18 |
+
python3 /opt/run_cell.py --code-b64 <base64-encoded-python-source>
|
| 19 |
+
|
| 20 |
+
Writes the kernel server's response payload (already JSON-encoded) to stdout.
|
| 21 |
+
The agent base64-decodes it on the host side. Base64 sidesteps shell escaping
|
| 22 |
+
for code containing quotes, newlines, etc.
|
| 23 |
+
"""
|
| 24 |
+
|
| 25 |
+
from __future__ import annotations
|
| 26 |
+
|
| 27 |
+
import argparse
|
| 28 |
+
import base64
|
| 29 |
+
import json
|
| 30 |
+
import sys
|
| 31 |
+
import urllib.request
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
PORT = 8765
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def main() -> int:
|
| 38 |
+
p = argparse.ArgumentParser()
|
| 39 |
+
p.add_argument("--code-b64", required=True)
|
| 40 |
+
p.add_argument("--timeout", type=int, default=120)
|
| 41 |
+
args = p.parse_args()
|
| 42 |
+
|
| 43 |
+
code = base64.b64decode(args.code_b64).decode("utf-8")
|
| 44 |
+
payload = json.dumps({"code": code}).encode()
|
| 45 |
+
req = urllib.request.Request(
|
| 46 |
+
f"http://127.0.0.1:{PORT}",
|
| 47 |
+
data=payload,
|
| 48 |
+
method="POST",
|
| 49 |
+
headers={"Content-Type": "application/json"},
|
| 50 |
+
)
|
| 51 |
+
try:
|
| 52 |
+
with urllib.request.urlopen(req, timeout=args.timeout) as r:
|
| 53 |
+
sys.stdout.write(r.read().decode("utf-8", errors="replace"))
|
| 54 |
+
return 0
|
| 55 |
+
except Exception as exc:
|
| 56 |
+
sys.stdout.write(json.dumps({"output": f"[run_cell err] {exc}", "ok": False}))
|
| 57 |
+
return 1
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
if __name__ == "__main__":
|
| 61 |
+
raise SystemExit(main())
|
tasks/tasksmith-fa1a9b35ff39/tests/source/examples/scripts/harbor/harnesses/terminal_notes/README.md
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# `terminal_notes` harness
|
| 2 |
+
|
| 3 |
+
A richer shell harness: **6 shell tools** (including background processes) plus a **4-tool persistent
|
| 4 |
+
note toolkit**. Implemented by `TerminalNotesEnv` in [`env.py`](env.py).
|
| 5 |
+
|
| 6 |
+
## Tools
|
| 7 |
+
|
| 8 |
+
### Shell (backed by the sandbox)
|
| 9 |
+
|
| 10 |
+
| Tool | Signature | What it does |
|
| 11 |
+
|---|---|---|
|
| 12 |
+
| `shell_exec` | `shell_exec(command: str, blocking: bool = True) -> str` | Run a command. Blocking → combined stdout+stderr; non-blocking → detach and return a PID. |
|
| 13 |
+
| `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`). |
|
| 14 |
+
| `shell_write_to_process` | `shell_write_to_process(pid: str, content: str) -> str` | Write to a background process's stdin. |
|
| 15 |
+
| `shell_view` | `shell_view(pid: str) -> str` | Read the captured stdout of a background process. |
|
| 16 |
+
| `shell_wait` | `shell_wait(pid: str) -> str` | Wait (≤5 min) for a background process to exit, then return its output. |
|
| 17 |
+
| `shell_kill_process` | `shell_kill_process(pid: str) -> str` | SIGKILL a background process. |
|
| 18 |
+
|
| 19 |
+
### Notes (in-env state, persist across turns of a rollout)
|
| 20 |
+
|
| 21 |
+
| Tool | Signature | What it does |
|
| 22 |
+
|---|---|---|
|
| 23 |
+
| `create_note` | `create_note(title: str, content: str) -> str` | Create a note. |
|
| 24 |
+
| `append_note` | `append_note(title: str, content: str) -> str` | Append to an existing note. |
|
| 25 |
+
| `read_note` | `read_note(title: str) -> str` | Read a note's content. |
|
| 26 |
+
| `list_note` | `list_note() -> str` | List note titles + sizes. |
|
| 27 |
+
|
| 28 |
+
> Unlike the original SETA agent, notes are **not** auto-injected into the prompt each turn (TRL owns the
|
| 29 |
+
> prompt under `environment_factory`); recall them on demand with `read_note` / `list_note`.
|
| 30 |
+
|
| 31 |
+
## Submission
|
| 32 |
+
|
| 33 |
+
Write the answer to `/workdir/answer.txt`, e.g. `shell_write_content_to_file(path="/workdir/answer.txt", content="<value>")`.
|
| 34 |
+
|
| 35 |
+
## Use it
|
| 36 |
+
|
| 37 |
+
```python
|
| 38 |
+
from trl.experimental.harbor import HarborSpec
|
| 39 |
+
spec = HarborSpec(dataset, agent="examples/scripts/harbor/harnesses/terminal_notes/env.py:TerminalNotesEnv")
|
| 40 |
+
```
|
tasks/tasksmith-fa1a9b35ff39/tests/source/examples/scripts/harbor/harnesses/terminal_notes/__init__.py
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2020-2026 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
from .env import TerminalNotesEnv
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
__all__ = ["TerminalNotesEnv"]
|
tasks/tasksmith-fa1a9b35ff39/tests/source/examples/scripts/harbor/harnesses/terminal_notes/env.py
ADDED
|
@@ -0,0 +1,221 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2020-2026 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
"""Shell + notes base agent — a 10-tool Harbor harness (6 shell + 4 notes).
|
| 16 |
+
|
| 17 |
+
A custom [`~trl.experimental.harbor.HarborEnv`] subclass with a richer toolset than the bash harness:
|
| 18 |
+
six shell tools (including background processes) and a persistent note-taking toolkit. Point a trainer
|
| 19 |
+
at it with ``HarborSpec(dataset, agent="examples/scripts/harbor/harnesses/terminal_notes/env.py:TerminalNotesEnv")``.
|
| 20 |
+
Submission is by writing ``/workdir/answer.txt`` (same verifier as the bash harness).
|
| 21 |
+
|
| 22 |
+
Notes live in-env (a dict) and survive across turns of the same rollout. They're recalled on demand via
|
| 23 |
+
``read_note`` / ``list_note`` (TRL owns the prompt under ``environment_factory``, so the env can't
|
| 24 |
+
inject them automatically each turn).
|
| 25 |
+
"""
|
| 26 |
+
|
| 27 |
+
import base64
|
| 28 |
+
import shlex
|
| 29 |
+
import uuid
|
| 30 |
+
|
| 31 |
+
from trl.experimental.harbor import HarborEnv
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
_PROMPT_SUFFIX = (
|
| 35 |
+
"\n\nYou are an autonomous data-analysis agent in a sandboxed Linux container (Python preinstalled). "
|
| 36 |
+
"Dataset files are in /home/user/input/. You have shell tools (shell_exec, "
|
| 37 |
+
"shell_write_content_to_file, shell_view/wait/kill for background procs) and a persistent note system "
|
| 38 |
+
"(create_note, append_note, read_note, list_note) — use notes as a scratchpad and read them back. "
|
| 39 |
+
"**Submit your final answer by writing it to /workdir/answer.txt via a shell tool** (e.g. "
|
| 40 |
+
"shell_write_content_to_file(path='/workdir/answer.txt', content=<answer>)). Keep it short; do not "
|
| 41 |
+
"end your turn without submitting."
|
| 42 |
+
)
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
class TerminalNotesEnv(HarborEnv):
|
| 46 |
+
"""10-tool harness (6 shell + 4 notes) over a Harbor sandbox."""
|
| 47 |
+
|
| 48 |
+
PROMPT_SUFFIX = _PROMPT_SUFFIX
|
| 49 |
+
|
| 50 |
+
def __init__(self, *args, **kwargs):
|
| 51 |
+
super().__init__(*args, **kwargs)
|
| 52 |
+
self._notes: dict[str, str] = {}
|
| 53 |
+
self._bg: dict[str, dict] = {}
|
| 54 |
+
|
| 55 |
+
def reset(self, task_dir=None, **kwargs) -> str:
|
| 56 |
+
self._notes.clear()
|
| 57 |
+
self._bg.clear()
|
| 58 |
+
return super().reset(task_dir=task_dir, **kwargs)
|
| 59 |
+
|
| 60 |
+
# ── shell toolkit ───────────────────────────────────────────────────────
|
| 61 |
+
|
| 62 |
+
def shell_exec(self, command: str, blocking: bool = True) -> str:
|
| 63 |
+
"""
|
| 64 |
+
Execute a shell command in the sandbox. If `blocking` (default), run synchronously and return
|
| 65 |
+
combined stdout+stderr; otherwise detach into the background and return the new PID.
|
| 66 |
+
|
| 67 |
+
Args:
|
| 68 |
+
command: The shell command to run.
|
| 69 |
+
blocking: Run synchronously (True) or in the background (False).
|
| 70 |
+
|
| 71 |
+
Returns:
|
| 72 |
+
Combined stdout+stderr (blocking) or the background PID.
|
| 73 |
+
"""
|
| 74 |
+
if blocking:
|
| 75 |
+
return self._exec(command)
|
| 76 |
+
token = uuid.uuid4().hex[:8]
|
| 77 |
+
log, pipe = f"/tmp/sh_{token}.log", f"/tmp/sh_{token}.in"
|
| 78 |
+
out = self._exec(
|
| 79 |
+
f"mkfifo {pipe} 2>/dev/null; ( nohup setsid bash -c {shlex.quote(command)} <{pipe} >{log} 2>&1 ) & echo $!",
|
| 80 |
+
timeout=15,
|
| 81 |
+
)
|
| 82 |
+
pid = out.strip().split()[-1] if out.strip() else ""
|
| 83 |
+
if not pid.isdigit():
|
| 84 |
+
return f"[shell_exec bg] failed to spawn: {out}"
|
| 85 |
+
self._bg[pid] = {"log": log, "pipe": pipe}
|
| 86 |
+
return f"Started background process PID={pid} log={log}"
|
| 87 |
+
|
| 88 |
+
def shell_write_content_to_file(self, path: str, content: str) -> str:
|
| 89 |
+
"""
|
| 90 |
+
Write `content` to `path` in the sandbox (overwrites). Use to commit the final answer to
|
| 91 |
+
/workdir/answer.txt.
|
| 92 |
+
|
| 93 |
+
Args:
|
| 94 |
+
path: Destination path in the sandbox.
|
| 95 |
+
content: File contents.
|
| 96 |
+
|
| 97 |
+
Returns:
|
| 98 |
+
A confirmation string.
|
| 99 |
+
"""
|
| 100 |
+
b64 = base64.b64encode(content.encode()).decode()
|
| 101 |
+
out = self._exec(
|
| 102 |
+
f"mkdir -p $(dirname {shlex.quote(path)}) && echo {b64} | base64 -d > {shlex.quote(path)}", timeout=30
|
| 103 |
+
)
|
| 104 |
+
return f"Wrote {len(content)} bytes to {path}" if "rc=" not in out else f"[write_file] {out}"
|
| 105 |
+
|
| 106 |
+
def shell_write_to_process(self, pid: str, content: str) -> str:
|
| 107 |
+
"""
|
| 108 |
+
Send `content` (with a trailing newline) to the stdin of a background process.
|
| 109 |
+
|
| 110 |
+
Args:
|
| 111 |
+
pid: PID returned by shell_exec(blocking=False).
|
| 112 |
+
content: Text to write to stdin.
|
| 113 |
+
|
| 114 |
+
Returns:
|
| 115 |
+
A confirmation string.
|
| 116 |
+
"""
|
| 117 |
+
proc = self._bg.get(pid)
|
| 118 |
+
if proc is None:
|
| 119 |
+
return f"Unknown PID={pid}. Started: {list(self._bg)}"
|
| 120 |
+
b64 = base64.b64encode((content + "\n").encode()).decode()
|
| 121 |
+
self._exec(f"echo {b64} | base64 -d > {shlex.quote(proc['pipe'])}", timeout=30)
|
| 122 |
+
return f"Wrote {len(content)} bytes to PID={pid} stdin"
|
| 123 |
+
|
| 124 |
+
def shell_view(self, pid: str) -> str:
|
| 125 |
+
"""
|
| 126 |
+
Return the current captured stdout of a background process.
|
| 127 |
+
|
| 128 |
+
Args:
|
| 129 |
+
pid: PID returned by shell_exec(blocking=False).
|
| 130 |
+
|
| 131 |
+
Returns:
|
| 132 |
+
The captured stdout so far.
|
| 133 |
+
"""
|
| 134 |
+
proc = self._bg.get(pid)
|
| 135 |
+
return self._exec(f"tail -c 4000 {shlex.quote(proc['log'])} 2>/dev/null") if proc else f"Unknown PID={pid}"
|
| 136 |
+
|
| 137 |
+
def shell_wait(self, pid: str) -> str:
|
| 138 |
+
"""
|
| 139 |
+
Wait (up to ~5 min) for a background process to terminate, then return its captured stdout.
|
| 140 |
+
|
| 141 |
+
Args:
|
| 142 |
+
pid: PID returned by shell_exec(blocking=False).
|
| 143 |
+
|
| 144 |
+
Returns:
|
| 145 |
+
The process output after it exits.
|
| 146 |
+
"""
|
| 147 |
+
proc = self._bg.get(pid)
|
| 148 |
+
if proc is None:
|
| 149 |
+
return f"Unknown PID={pid}"
|
| 150 |
+
return self._exec(
|
| 151 |
+
f"for i in $(seq 1 300); do [ ! -d /proc/{pid} ] && break; sleep 1; done; "
|
| 152 |
+
f"echo '--- exited ---'; tail -c 4000 {shlex.quote(proc['log'])} 2>/dev/null",
|
| 153 |
+
timeout=320,
|
| 154 |
+
)
|
| 155 |
+
|
| 156 |
+
def shell_kill_process(self, pid: str) -> str:
|
| 157 |
+
"""
|
| 158 |
+
Send SIGKILL to a background process.
|
| 159 |
+
|
| 160 |
+
Args:
|
| 161 |
+
pid: PID returned by shell_exec(blocking=False).
|
| 162 |
+
|
| 163 |
+
Returns:
|
| 164 |
+
A confirmation string.
|
| 165 |
+
"""
|
| 166 |
+
if pid not in self._bg:
|
| 167 |
+
return f"Unknown PID={pid}"
|
| 168 |
+
return f"Sent SIGKILL to PID={pid}: {self._exec(f'kill -9 {pid} 2>&1', timeout=10)}"
|
| 169 |
+
|
| 170 |
+
# ── note toolkit (in-env state) ──────────────────────────────────────────
|
| 171 |
+
|
| 172 |
+
def create_note(self, title: str, content: str) -> str:
|
| 173 |
+
"""
|
| 174 |
+
Create a persistent note (recall it later with read_note/list_note).
|
| 175 |
+
|
| 176 |
+
Args:
|
| 177 |
+
title: Note title.
|
| 178 |
+
content: Note body.
|
| 179 |
+
|
| 180 |
+
Returns:
|
| 181 |
+
A confirmation string.
|
| 182 |
+
"""
|
| 183 |
+
self._notes[title] = content
|
| 184 |
+
return f"Note '{title}' created ({len(content)} chars). Total: {len(self._notes)}."
|
| 185 |
+
|
| 186 |
+
def append_note(self, title: str, content: str) -> str:
|
| 187 |
+
"""
|
| 188 |
+
Append `content` (on a new line) to an existing note.
|
| 189 |
+
|
| 190 |
+
Args:
|
| 191 |
+
title: Note title.
|
| 192 |
+
content: Text to append.
|
| 193 |
+
|
| 194 |
+
Returns:
|
| 195 |
+
A confirmation string.
|
| 196 |
+
"""
|
| 197 |
+
if title not in self._notes:
|
| 198 |
+
return f"Note '{title}' not found. Use create_note first."
|
| 199 |
+
self._notes[title] += "\n" + content
|
| 200 |
+
return f"Note '{title}' updated -> {len(self._notes[title])} chars."
|
| 201 |
+
|
| 202 |
+
def read_note(self, title: str) -> str:
|
| 203 |
+
"""
|
| 204 |
+
Return the full content of a note.
|
| 205 |
+
|
| 206 |
+
Args:
|
| 207 |
+
title: Note title.
|
| 208 |
+
|
| 209 |
+
Returns:
|
| 210 |
+
The note content, or a not-found message.
|
| 211 |
+
"""
|
| 212 |
+
return self._notes.get(title, f"Note '{title}' not found.")
|
| 213 |
+
|
| 214 |
+
def list_note(self) -> str:
|
| 215 |
+
"""
|
| 216 |
+
List all note titles with their character counts.
|
| 217 |
+
|
| 218 |
+
Returns:
|
| 219 |
+
One line per note, or a message if there are none.
|
| 220 |
+
"""
|
| 221 |
+
return "\n".join(f"- {t} ({len(c)} chars)" for t, c in self._notes.items()) or "(no notes yet)"
|
tasks/tasksmith-fa1a9b35ff39/tests/source/examples/scripts/kto.py
ADDED
|
@@ -0,0 +1,99 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2020-2026 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
# /// script
|
| 16 |
+
# dependencies = [
|
| 17 |
+
# "trl[peft]",
|
| 18 |
+
# "trackio",
|
| 19 |
+
# "kernels",
|
| 20 |
+
# ]
|
| 21 |
+
# ///
|
| 22 |
+
|
| 23 |
+
"""
|
| 24 |
+
Run the KTO training script with the commands below. In general, the optimal configuration for KTO will be similar to that of DPO.
|
| 25 |
+
|
| 26 |
+
# Full training:
|
| 27 |
+
python trl/scripts/kto.py \
|
| 28 |
+
--dataset_name trl-lib/kto-mix-14k \
|
| 29 |
+
--model_name_or_path trl-lib/qwen1.5-1.8b-sft \
|
| 30 |
+
--per_device_train_batch_size 16 \
|
| 31 |
+
--num_train_epochs 1 \
|
| 32 |
+
--learning_rate 5e-7 \
|
| 33 |
+
--lr_scheduler_type cosine \
|
| 34 |
+
--gradient_accumulation_steps 1 \
|
| 35 |
+
--eval_steps 500 \
|
| 36 |
+
--output_dir kto-aligned-model \
|
| 37 |
+
--warmup_steps 0.1 \
|
| 38 |
+
--logging_first_step
|
| 39 |
+
|
| 40 |
+
# QLoRA:
|
| 41 |
+
python trl/scripts/kto.py \
|
| 42 |
+
--dataset_name trl-lib/kto-mix-14k \
|
| 43 |
+
--model_name_or_path trl-lib/qwen1.5-1.8b-sft \
|
| 44 |
+
--per_device_train_batch_size 8 \
|
| 45 |
+
--num_train_epochs 1 \
|
| 46 |
+
--learning_rate 5e-7 \
|
| 47 |
+
--lr_scheduler_type cosine \
|
| 48 |
+
--gradient_accumulation_steps 1 \
|
| 49 |
+
--eval_steps 500 \
|
| 50 |
+
--output_dir kto-aligned-model-lora \
|
| 51 |
+
--warmup_steps 0.1 \
|
| 52 |
+
--logging_first_step \
|
| 53 |
+
--use_peft \
|
| 54 |
+
--load_in_4bit \
|
| 55 |
+
--lora_target_modules all-linear \
|
| 56 |
+
--lora_r 16 \
|
| 57 |
+
--lora_alpha 16
|
| 58 |
+
"""
|
| 59 |
+
|
| 60 |
+
from datasets import load_dataset
|
| 61 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer, HfArgumentParser
|
| 62 |
+
|
| 63 |
+
from trl import ModelConfig, ScriptArguments, get_peft_config
|
| 64 |
+
from trl.experimental.kto import KTOConfig, KTOTrainer
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
if __name__ == "__main__":
|
| 68 |
+
parser = HfArgumentParser((ScriptArguments, KTOConfig, ModelConfig))
|
| 69 |
+
script_args, training_args, model_args = parser.parse_args_into_dataclasses()
|
| 70 |
+
|
| 71 |
+
# Load a pretrained model
|
| 72 |
+
model = AutoModelForCausalLM.from_pretrained(model_args.model_name_or_path)
|
| 73 |
+
ref_model = AutoModelForCausalLM.from_pretrained(model_args.model_name_or_path)
|
| 74 |
+
|
| 75 |
+
tokenizer = AutoTokenizer.from_pretrained(model_args.model_name_or_path)
|
| 76 |
+
if tokenizer.pad_token is None:
|
| 77 |
+
tokenizer.pad_token = tokenizer.eos_token
|
| 78 |
+
|
| 79 |
+
# Load the dataset
|
| 80 |
+
dataset = load_dataset(script_args.dataset_name, name=script_args.dataset_config)
|
| 81 |
+
|
| 82 |
+
# Initialize the KTO trainer
|
| 83 |
+
trainer = KTOTrainer(
|
| 84 |
+
model,
|
| 85 |
+
ref_model,
|
| 86 |
+
args=training_args,
|
| 87 |
+
train_dataset=dataset[script_args.dataset_train_split],
|
| 88 |
+
eval_dataset=dataset[script_args.dataset_test_split] if training_args.eval_strategy != "no" else None,
|
| 89 |
+
processing_class=tokenizer,
|
| 90 |
+
peft_config=get_peft_config(model_args),
|
| 91 |
+
)
|
| 92 |
+
|
| 93 |
+
# Train and push the model to the Hub
|
| 94 |
+
trainer.train()
|
| 95 |
+
|
| 96 |
+
# Save and push to hub
|
| 97 |
+
trainer.save_model(training_args.output_dir)
|
| 98 |
+
if training_args.push_to_hub:
|
| 99 |
+
trainer.push_to_hub(dataset_name=script_args.dataset_name)
|
tasks/tasksmith-fa1a9b35ff39/tests/source/examples/scripts/mpo_vlm.py
ADDED
|
@@ -0,0 +1,126 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2020-2026 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
# /// script
|
| 16 |
+
# dependencies = [
|
| 17 |
+
# "trl[peft]",
|
| 18 |
+
# "Pillow",
|
| 19 |
+
# "torchvision",
|
| 20 |
+
# "trackio",
|
| 21 |
+
# "kernels",
|
| 22 |
+
# ]
|
| 23 |
+
# ///
|
| 24 |
+
|
| 25 |
+
"""
|
| 26 |
+
python examples/scripts/mpo_vlm.py \
|
| 27 |
+
--dataset_name HuggingFaceH4/rlaif-v_formatted \
|
| 28 |
+
--model_name_or_path Qwen/Qwen2.5-VL-3B-Instruct \
|
| 29 |
+
--per_device_train_batch_size 4 \
|
| 30 |
+
--per_device_eval_batch_size 4 \
|
| 31 |
+
--num_train_epochs 1 \
|
| 32 |
+
--gradient_accumulation_steps 8 \
|
| 33 |
+
--dataset_num_proc 1 \
|
| 34 |
+
--output_dir dpo_idefics_rlaif-v \
|
| 35 |
+
--dtype bfloat16 \
|
| 36 |
+
--use_peft \
|
| 37 |
+
--lora_target_modules down_proj, o_proj, k_proj, q_proj, gate_proj, up_proj, v_proj \
|
| 38 |
+
--loss_type sigmoid bco_pair sft \
|
| 39 |
+
--loss_weights 0.8 0.2 1.0
|
| 40 |
+
"""
|
| 41 |
+
|
| 42 |
+
import torch
|
| 43 |
+
from datasets import load_dataset
|
| 44 |
+
from PIL import Image
|
| 45 |
+
from transformers import AutoModelForImageTextToText
|
| 46 |
+
|
| 47 |
+
from trl import (
|
| 48 |
+
DPOConfig,
|
| 49 |
+
DPOTrainer,
|
| 50 |
+
ModelConfig,
|
| 51 |
+
ScriptArguments,
|
| 52 |
+
TrlParser,
|
| 53 |
+
get_kbit_device_map,
|
| 54 |
+
get_peft_config,
|
| 55 |
+
get_quantization_config,
|
| 56 |
+
)
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
if __name__ == "__main__":
|
| 60 |
+
parser = TrlParser((ScriptArguments, DPOConfig, ModelConfig))
|
| 61 |
+
script_args, training_args, model_args = parser.parse_args_and_config()
|
| 62 |
+
|
| 63 |
+
################
|
| 64 |
+
# Model & Processor
|
| 65 |
+
################
|
| 66 |
+
dtype = model_args.dtype if model_args.dtype in ["auto", None] else getattr(torch, model_args.dtype)
|
| 67 |
+
|
| 68 |
+
model_kwargs = dict(
|
| 69 |
+
revision=model_args.model_revision,
|
| 70 |
+
attn_implementation=model_args.attn_implementation,
|
| 71 |
+
dtype=dtype,
|
| 72 |
+
)
|
| 73 |
+
quantization_config = get_quantization_config(model_args)
|
| 74 |
+
if quantization_config is not None:
|
| 75 |
+
# Passing None would not be treated the same as omitting the argument, so we include it only when valid.
|
| 76 |
+
model_kwargs["device_map"] = get_kbit_device_map()
|
| 77 |
+
model_kwargs["quantization_config"] = quantization_config
|
| 78 |
+
|
| 79 |
+
model = AutoModelForImageTextToText.from_pretrained(
|
| 80 |
+
model_args.model_name_or_path,
|
| 81 |
+
**model_kwargs,
|
| 82 |
+
)
|
| 83 |
+
peft_config = get_peft_config(model_args)
|
| 84 |
+
|
| 85 |
+
################
|
| 86 |
+
# Dataset
|
| 87 |
+
################
|
| 88 |
+
dataset = load_dataset(
|
| 89 |
+
script_args.dataset_name,
|
| 90 |
+
name=script_args.dataset_config,
|
| 91 |
+
streaming=script_args.dataset_streaming,
|
| 92 |
+
)
|
| 93 |
+
train_dataset = dataset[script_args.dataset_train_split]
|
| 94 |
+
test_dataset = dataset[script_args.dataset_test_split] if training_args.eval_strategy != "no" else None
|
| 95 |
+
|
| 96 |
+
def ensure_rgb(example):
|
| 97 |
+
# Convert the image to RGB if it's not already
|
| 98 |
+
image = example["images"][0]
|
| 99 |
+
if isinstance(image, Image.Image):
|
| 100 |
+
if image.mode != "RGB":
|
| 101 |
+
image = image.convert("RGB")
|
| 102 |
+
example["images"] = [image]
|
| 103 |
+
return example
|
| 104 |
+
|
| 105 |
+
# Apply the transformation to the dataset (change num_proc depending on the available compute)
|
| 106 |
+
train_dataset = train_dataset.map(ensure_rgb, num_proc=training_args.dataset_num_proc)
|
| 107 |
+
if test_dataset is not None:
|
| 108 |
+
test_dataset = test_dataset.map(ensure_rgb, num_proc=training_args.dataset_num_proc)
|
| 109 |
+
|
| 110 |
+
################
|
| 111 |
+
# Training
|
| 112 |
+
################
|
| 113 |
+
trainer = DPOTrainer(
|
| 114 |
+
model=model,
|
| 115 |
+
args=training_args,
|
| 116 |
+
train_dataset=train_dataset,
|
| 117 |
+
eval_dataset=test_dataset,
|
| 118 |
+
peft_config=peft_config,
|
| 119 |
+
)
|
| 120 |
+
|
| 121 |
+
trainer.train()
|
| 122 |
+
|
| 123 |
+
# Save and push to hub
|
| 124 |
+
trainer.save_model(training_args.output_dir)
|
| 125 |
+
if training_args.push_to_hub:
|
| 126 |
+
trainer.push_to_hub(dataset_name=script_args.dataset_name)
|
tasks/tasksmith-fa1a9b35ff39/tests/source/examples/scripts/nash_md.py
ADDED
|
@@ -0,0 +1,130 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2020-2026 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
# /// script
|
| 16 |
+
# dependencies = [
|
| 17 |
+
# "trl",
|
| 18 |
+
# "trackio",
|
| 19 |
+
# "kernels",
|
| 20 |
+
# ]
|
| 21 |
+
# ///
|
| 22 |
+
|
| 23 |
+
"""
|
| 24 |
+
Usage:
|
| 25 |
+
|
| 26 |
+
python examples/scripts/nash_md.py \
|
| 27 |
+
--model_name_or_path trl-lib/pythia-1b-deduped-tldr-sft \
|
| 28 |
+
--reward_model_path trl-lib/pythia-1b-deduped-tldr-rm \
|
| 29 |
+
--dataset_name trl-lib/tldr \
|
| 30 |
+
--learning_rate 5.0e-7 \
|
| 31 |
+
--output_dir pythia-1b-tldr-nash-md \
|
| 32 |
+
--per_device_train_batch_size 4 \
|
| 33 |
+
--gradient_accumulation_steps 32 \
|
| 34 |
+
--num_train_epochs 3 \
|
| 35 |
+
--max_new_tokens 64 \
|
| 36 |
+
--warmup_steps 0.1 \
|
| 37 |
+
--missing_eos_penalty 1.0 \
|
| 38 |
+
--push_to_hub
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
accelerate launch --config_file examples/accelerate_configs/deepspeed_zero2.yaml \
|
| 42 |
+
examples/scripts/nash_md.py \
|
| 43 |
+
--model_name_or_path trl-lib/pythia-1b-deduped-tldr-sft \
|
| 44 |
+
--reward_model_path trl-lib/pythia-1b-deduped-tldr-rm \
|
| 45 |
+
--dataset_name trl-lib/tldr \
|
| 46 |
+
--learning_rate 5.0e-7 \
|
| 47 |
+
--output_dir pythia-1b-tldr-nash-md \
|
| 48 |
+
--per_device_train_batch_size 4 \
|
| 49 |
+
--gradient_accumulation_steps 32 \
|
| 50 |
+
--num_train_epochs 3 \
|
| 51 |
+
--max_new_tokens 64 \
|
| 52 |
+
--warmup_steps 0.1 \
|
| 53 |
+
--missing_eos_penalty 1.0 \
|
| 54 |
+
--push_to_hub
|
| 55 |
+
"""
|
| 56 |
+
|
| 57 |
+
import torch
|
| 58 |
+
from datasets import load_dataset
|
| 59 |
+
from transformers import AutoModelForCausalLM, AutoModelForSequenceClassification, AutoTokenizer, GenerationConfig
|
| 60 |
+
|
| 61 |
+
from trl import (
|
| 62 |
+
LogCompletionsCallback,
|
| 63 |
+
ModelConfig,
|
| 64 |
+
ScriptArguments,
|
| 65 |
+
TrlParser,
|
| 66 |
+
get_kbit_device_map,
|
| 67 |
+
get_quantization_config,
|
| 68 |
+
)
|
| 69 |
+
from trl.experimental.nash_md import NashMDConfig, NashMDTrainer
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
if __name__ == "__main__":
|
| 73 |
+
parser = TrlParser((ScriptArguments, NashMDConfig, ModelConfig))
|
| 74 |
+
script_args, training_args, model_args = parser.parse_args_and_config()
|
| 75 |
+
training_args.gradient_checkpointing_kwargs = {"use_reentrant": True}
|
| 76 |
+
|
| 77 |
+
dtype = model_args.dtype if model_args.dtype in ["auto", None] else getattr(torch, model_args.dtype)
|
| 78 |
+
model_kwargs = dict(
|
| 79 |
+
revision=model_args.model_revision,
|
| 80 |
+
attn_implementation=model_args.attn_implementation,
|
| 81 |
+
dtype=dtype,
|
| 82 |
+
use_cache=False if training_args.gradient_checkpointing else True,
|
| 83 |
+
)
|
| 84 |
+
quantization_config = get_quantization_config(model_args)
|
| 85 |
+
if quantization_config is not None:
|
| 86 |
+
# Passing None would not be treated the same as omitting the argument, so we include it only when valid.
|
| 87 |
+
model_kwargs["device_map"] = get_kbit_device_map()
|
| 88 |
+
model_kwargs["quantization_config"] = quantization_config
|
| 89 |
+
|
| 90 |
+
model = AutoModelForCausalLM.from_pretrained(model_args.model_name_or_path, **model_kwargs)
|
| 91 |
+
ref_model = AutoModelForCausalLM.from_pretrained(model_args.model_name_or_path, **model_kwargs)
|
| 92 |
+
|
| 93 |
+
if training_args.reward_model_path is not None:
|
| 94 |
+
reward_model = AutoModelForSequenceClassification.from_pretrained(
|
| 95 |
+
training_args.reward_model_path,
|
| 96 |
+
num_labels=1,
|
| 97 |
+
**model_kwargs,
|
| 98 |
+
)
|
| 99 |
+
else:
|
| 100 |
+
reward_model = None
|
| 101 |
+
|
| 102 |
+
tokenizer = AutoTokenizer.from_pretrained(model_args.model_name_or_path, padding_side="left")
|
| 103 |
+
if tokenizer.pad_token is None:
|
| 104 |
+
tokenizer.pad_token = tokenizer.eos_token
|
| 105 |
+
|
| 106 |
+
dataset = load_dataset(script_args.dataset_name, name=script_args.dataset_config)
|
| 107 |
+
|
| 108 |
+
trainer = NashMDTrainer(
|
| 109 |
+
model=model,
|
| 110 |
+
ref_model=ref_model,
|
| 111 |
+
reward_funcs=reward_model,
|
| 112 |
+
args=training_args,
|
| 113 |
+
train_dataset=dataset[script_args.dataset_train_split],
|
| 114 |
+
eval_dataset=dataset[script_args.dataset_test_split] if training_args.eval_strategy != "no" else None,
|
| 115 |
+
processing_class=tokenizer,
|
| 116 |
+
)
|
| 117 |
+
|
| 118 |
+
if training_args.eval_strategy != "no":
|
| 119 |
+
generation_config = GenerationConfig(
|
| 120 |
+
max_new_tokens=training_args.max_new_tokens, do_sample=True, temperature=training_args.temperature
|
| 121 |
+
)
|
| 122 |
+
completions_callback = LogCompletionsCallback(trainer, generation_config, num_prompts=8)
|
| 123 |
+
trainer.add_callback(completions_callback)
|
| 124 |
+
|
| 125 |
+
trainer.train()
|
| 126 |
+
|
| 127 |
+
# Save and push to hub
|
| 128 |
+
trainer.save_model(training_args.output_dir)
|
| 129 |
+
if training_args.push_to_hub:
|
| 130 |
+
trainer.push_to_hub(dataset_name=script_args.dataset_name)
|
tasks/tasksmith-fa1a9b35ff39/tests/source/examples/scripts/online_dpo.py
ADDED
|
@@ -0,0 +1,137 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2020-2026 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
# /// script
|
| 16 |
+
# dependencies = [
|
| 17 |
+
# "trl[peft]",
|
| 18 |
+
# "trackio",
|
| 19 |
+
# "kernels",
|
| 20 |
+
# ]
|
| 21 |
+
# ///
|
| 22 |
+
|
| 23 |
+
"""
|
| 24 |
+
Usage:
|
| 25 |
+
|
| 26 |
+
python examples/scripts/online_dpo.py \
|
| 27 |
+
--model_name_or_path trl-lib/pythia-1b-deduped-tldr-sft \
|
| 28 |
+
--reward_model_path trl-lib/pythia-1b-deduped-tldr-rm \
|
| 29 |
+
--dataset_name trl-lib/tldr \
|
| 30 |
+
--learning_rate 5.0e-7 \
|
| 31 |
+
--output_dir pythia-1b-tldr-online-dpo \
|
| 32 |
+
--per_device_train_batch_size 8 \
|
| 33 |
+
--gradient_accumulation_steps 16 \
|
| 34 |
+
--warmup_steps 0.1 \
|
| 35 |
+
--missing_eos_penalty 1.0
|
| 36 |
+
|
| 37 |
+
With LoRA:
|
| 38 |
+
python examples/scripts/online_dpo.py \
|
| 39 |
+
--model_name_or_path trl-lib/pythia-1b-deduped-tldr-sft \
|
| 40 |
+
--reward_model_path trl-lib/pythia-1b-deduped-tldr-rm \
|
| 41 |
+
--dataset_name trl-lib/tldr \
|
| 42 |
+
--learning_rate 5.0e-6 \
|
| 43 |
+
--output_dir pythia-1b-tldr-online-dpo \
|
| 44 |
+
--per_device_train_batch_size 16 \
|
| 45 |
+
--gradient_accumulation_steps 8 \
|
| 46 |
+
--warmup_steps 0.1 \
|
| 47 |
+
--missing_eos_penalty 1.0 \
|
| 48 |
+
--use_peft
|
| 49 |
+
"""
|
| 50 |
+
|
| 51 |
+
import torch
|
| 52 |
+
from datasets import load_dataset
|
| 53 |
+
from transformers import AutoModelForCausalLM, AutoModelForSequenceClassification, AutoTokenizer, GenerationConfig
|
| 54 |
+
|
| 55 |
+
from trl import (
|
| 56 |
+
LogCompletionsCallback,
|
| 57 |
+
ModelConfig,
|
| 58 |
+
ScriptArguments,
|
| 59 |
+
TrlParser,
|
| 60 |
+
get_kbit_device_map,
|
| 61 |
+
get_peft_config,
|
| 62 |
+
get_quantization_config,
|
| 63 |
+
)
|
| 64 |
+
from trl.experimental.online_dpo import OnlineDPOConfig, OnlineDPOTrainer
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
if __name__ == "__main__":
|
| 68 |
+
parser = TrlParser((ScriptArguments, OnlineDPOConfig, ModelConfig))
|
| 69 |
+
script_args, training_args, model_args = parser.parse_args_and_config()
|
| 70 |
+
training_args.gradient_checkpointing_kwargs = {"use_reentrant": True}
|
| 71 |
+
|
| 72 |
+
dtype = model_args.dtype if model_args.dtype in ["auto", None] else getattr(torch, model_args.dtype)
|
| 73 |
+
model_kwargs = dict(
|
| 74 |
+
revision=model_args.model_revision,
|
| 75 |
+
attn_implementation=model_args.attn_implementation,
|
| 76 |
+
dtype=dtype,
|
| 77 |
+
use_cache=False if training_args.gradient_checkpointing else True,
|
| 78 |
+
)
|
| 79 |
+
quantization_config = get_quantization_config(model_args)
|
| 80 |
+
if quantization_config is not None:
|
| 81 |
+
# Passing None would not be treated the same as omitting the argument, so we include it only when valid.
|
| 82 |
+
model_kwargs["device_map"] = get_kbit_device_map()
|
| 83 |
+
model_kwargs["quantization_config"] = quantization_config
|
| 84 |
+
|
| 85 |
+
model = AutoModelForCausalLM.from_pretrained(model_args.model_name_or_path, **model_kwargs)
|
| 86 |
+
|
| 87 |
+
if training_args.reward_model_path is not None:
|
| 88 |
+
reward_model = AutoModelForSequenceClassification.from_pretrained(
|
| 89 |
+
training_args.reward_model_path,
|
| 90 |
+
num_labels=1,
|
| 91 |
+
**model_kwargs,
|
| 92 |
+
)
|
| 93 |
+
reward_tokenizer = AutoTokenizer.from_pretrained(
|
| 94 |
+
training_args.reward_model_path,
|
| 95 |
+
truncation=True,
|
| 96 |
+
truncation_side="left", # since we judge the completion, truncating left is more appropriate
|
| 97 |
+
)
|
| 98 |
+
if reward_tokenizer.pad_token_id is None:
|
| 99 |
+
reward_tokenizer.pad_token = reward_tokenizer.eos_token
|
| 100 |
+
else:
|
| 101 |
+
reward_model = None
|
| 102 |
+
reward_tokenizer = None
|
| 103 |
+
|
| 104 |
+
tokenizer = AutoTokenizer.from_pretrained(
|
| 105 |
+
model_args.model_name_or_path,
|
| 106 |
+
padding_side="left",
|
| 107 |
+
**model_kwargs,
|
| 108 |
+
)
|
| 109 |
+
if tokenizer.pad_token_id is None:
|
| 110 |
+
tokenizer.pad_token = tokenizer.eos_token
|
| 111 |
+
|
| 112 |
+
dataset = load_dataset(script_args.dataset_name, name=script_args.dataset_config)
|
| 113 |
+
|
| 114 |
+
trainer = OnlineDPOTrainer(
|
| 115 |
+
model=model,
|
| 116 |
+
reward_funcs=reward_model,
|
| 117 |
+
args=training_args,
|
| 118 |
+
train_dataset=dataset[script_args.dataset_train_split],
|
| 119 |
+
eval_dataset=dataset[script_args.dataset_test_split] if training_args.eval_strategy != "no" else None,
|
| 120 |
+
processing_class=tokenizer,
|
| 121 |
+
reward_processing_classes=reward_tokenizer,
|
| 122 |
+
peft_config=get_peft_config(model_args),
|
| 123 |
+
)
|
| 124 |
+
|
| 125 |
+
if training_args.eval_strategy != "no":
|
| 126 |
+
generation_config = GenerationConfig(
|
| 127 |
+
max_new_tokens=training_args.max_new_tokens, do_sample=True, temperature=training_args.temperature
|
| 128 |
+
)
|
| 129 |
+
completions_callback = LogCompletionsCallback(trainer, generation_config, num_prompts=8)
|
| 130 |
+
trainer.add_callback(completions_callback)
|
| 131 |
+
|
| 132 |
+
trainer.train()
|
| 133 |
+
|
| 134 |
+
# Save and push to hub
|
| 135 |
+
trainer.save_model(training_args.output_dir)
|
| 136 |
+
if training_args.push_to_hub:
|
| 137 |
+
trainer.push_to_hub(dataset_name=script_args.dataset_name)
|
tasks/tasksmith-fa1a9b35ff39/tests/source/examples/scripts/online_dpo_vlm.py
ADDED
|
@@ -0,0 +1,203 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2020-2026 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
# /// script
|
| 16 |
+
# dependencies = [
|
| 17 |
+
# "trl[peft]",
|
| 18 |
+
# "math-verify",
|
| 19 |
+
# "latex2sympy2_extended",
|
| 20 |
+
# "trackio",
|
| 21 |
+
# "torchvision",
|
| 22 |
+
# "kernels",
|
| 23 |
+
# ]
|
| 24 |
+
# ///
|
| 25 |
+
|
| 26 |
+
"""
|
| 27 |
+
pip install math_verify
|
| 28 |
+
|
| 29 |
+
# For Qwen/Qwen2.5-VL-3B-Instruct
|
| 30 |
+
accelerate launch \
|
| 31 |
+
--config_file examples/accelerate_configs/deepspeed_zero3.yaml \
|
| 32 |
+
examples/scripts/online_dpo_vlm.py \
|
| 33 |
+
--model_name_or_path Qwen/Qwen2.5-VL-3B-Instruct \
|
| 34 |
+
--reward_model_path Qwen/Qwen2.5-VL-3B-Instruct \
|
| 35 |
+
--output_dir online-dpo-Qwen2.5-VL-3B-Instruct \
|
| 36 |
+
--learning_rate 1e-5 \
|
| 37 |
+
--dtype bfloat16 \
|
| 38 |
+
--max_length 1536 \
|
| 39 |
+
--max_new_tokens 1024 \
|
| 40 |
+
--use_vllm \
|
| 41 |
+
--vllm_mode server \
|
| 42 |
+
--use_peft \
|
| 43 |
+
--lora_target_modules "q_proj", "v_proj" \
|
| 44 |
+
--per_device_train_batch_size 1 \
|
| 45 |
+
--gradient_accumulation_steps 2
|
| 46 |
+
|
| 47 |
+
# For HuggingFaceTB/SmolVLM2-2.2B-Instruct
|
| 48 |
+
pip install num2words==0.5.14
|
| 49 |
+
|
| 50 |
+
accelerate launch \
|
| 51 |
+
--config_file examples/accelerate_configs/deepspeed_zero3.yaml \
|
| 52 |
+
examples/scripts/online_dpo_vlm.py \
|
| 53 |
+
--model_name_or_path HuggingFaceTB/SmolVLM2-2.2B-Instruct \
|
| 54 |
+
--reward_model_path HuggingFaceTB/SmolVLM2-2.2B-Instruct \
|
| 55 |
+
--output_dir online-dpo-SmolVLM2-2.2B-Instruct \
|
| 56 |
+
--learning_rate 1e-5 \
|
| 57 |
+
--dtype bfloat16 \
|
| 58 |
+
--max_length 1536 \
|
| 59 |
+
--max_new_tokens 1024 \
|
| 60 |
+
--use_peft \
|
| 61 |
+
--lora_target_modules "q_proj", "v_proj" \
|
| 62 |
+
--per_device_train_batch_size 1 \
|
| 63 |
+
--gradient_accumulation_steps 2
|
| 64 |
+
|
| 65 |
+
# Single GPU test command:
|
| 66 |
+
python examples/scripts/online_dpo_vlm.py \
|
| 67 |
+
--model_name_or_path HuggingFaceTB/SmolVLM2-2.2B-Instruct \
|
| 68 |
+
--reward_model_path HuggingFaceTB/SmolVLM2-2.2B-Instruct \
|
| 69 |
+
--output_dir online-dpo-SmolVLM2-2.2B-Instruct-test \
|
| 70 |
+
--learning_rate 1e-5 \
|
| 71 |
+
--dtype bfloat16 \
|
| 72 |
+
--max_length 1536 \
|
| 73 |
+
--max_new_tokens 128 \
|
| 74 |
+
--use_peft \
|
| 75 |
+
--lora_target_modules "q_proj", "v_proj" \
|
| 76 |
+
--per_device_train_batch_size 1 \
|
| 77 |
+
--gradient_accumulation_steps 1 \
|
| 78 |
+
--max_steps 2 \
|
| 79 |
+
--logging_steps 1 \
|
| 80 |
+
--trust_remote_code
|
| 81 |
+
"""
|
| 82 |
+
|
| 83 |
+
import torch
|
| 84 |
+
import transformers
|
| 85 |
+
from datasets import load_dataset
|
| 86 |
+
from transformers import AutoConfig, AutoProcessor, GenerationConfig
|
| 87 |
+
|
| 88 |
+
from trl import (
|
| 89 |
+
LogCompletionsCallback,
|
| 90 |
+
ModelConfig,
|
| 91 |
+
ScriptArguments,
|
| 92 |
+
TrlParser,
|
| 93 |
+
get_kbit_device_map,
|
| 94 |
+
get_peft_config,
|
| 95 |
+
get_quantization_config,
|
| 96 |
+
)
|
| 97 |
+
from trl.experimental.online_dpo import OnlineDPOConfig, OnlineDPOTrainer
|
| 98 |
+
from trl.rewards import accuracy_reward, think_format_reward
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
if __name__ == "__main__":
|
| 102 |
+
parser = TrlParser((ScriptArguments, OnlineDPOConfig, ModelConfig))
|
| 103 |
+
script_args, training_args, model_args = parser.parse_args_and_config()
|
| 104 |
+
training_args.gradient_checkpointing_kwargs = {"use_reentrant": True}
|
| 105 |
+
|
| 106 |
+
dtype = model_args.dtype if model_args.dtype in ["auto", None] else getattr(torch, model_args.dtype)
|
| 107 |
+
model_kwargs = dict(
|
| 108 |
+
revision=model_args.model_revision,
|
| 109 |
+
attn_implementation=model_args.attn_implementation,
|
| 110 |
+
dtype=dtype,
|
| 111 |
+
use_cache=False if training_args.gradient_checkpointing else True,
|
| 112 |
+
)
|
| 113 |
+
quantization_config = get_quantization_config(model_args)
|
| 114 |
+
if quantization_config is not None:
|
| 115 |
+
# Passing None would not be treated the same as omitting the argument, so we include it only when valid.
|
| 116 |
+
model_kwargs["device_map"] = get_kbit_device_map()
|
| 117 |
+
model_kwargs["quantization_config"] = quantization_config
|
| 118 |
+
|
| 119 |
+
# Load the VLM model using correct architecture (from GRPO pattern)
|
| 120 |
+
config = AutoConfig.from_pretrained(model_args.model_name_or_path)
|
| 121 |
+
architecture = getattr(transformers, config.architectures[0])
|
| 122 |
+
model = architecture.from_pretrained(model_args.model_name_or_path, **model_kwargs)
|
| 123 |
+
|
| 124 |
+
# For VLM online DPO, using a reward model is complex because it needs images
|
| 125 |
+
reward_model = None
|
| 126 |
+
reward_processor = None
|
| 127 |
+
|
| 128 |
+
# Load processor for main model
|
| 129 |
+
processor = AutoProcessor.from_pretrained(model_args.model_name_or_path)
|
| 130 |
+
if hasattr(processor, "tokenizer"):
|
| 131 |
+
processor.tokenizer.padding_side = "left"
|
| 132 |
+
if processor.tokenizer.pad_token_id is None:
|
| 133 |
+
processor.tokenizer.pad_token = processor.tokenizer.eos_token
|
| 134 |
+
|
| 135 |
+
################
|
| 136 |
+
# Dataset
|
| 137 |
+
################
|
| 138 |
+
dataset = load_dataset("lmms-lab/multimodal-open-r1-8k-verified", split="train")
|
| 139 |
+
dataset = dataset.train_test_split(test_size=100, seed=42)
|
| 140 |
+
|
| 141 |
+
SYSTEM_PROMPT = (
|
| 142 |
+
"A conversation between user and assistant. The user asks a question, and the assistant solves it. The "
|
| 143 |
+
"assistant first thinks about the reasoning process in the mind and then provides the user with the answer. "
|
| 144 |
+
"The reasoning process and answer are enclosed within <think></think> tags, i.e., <think>\nThis is my "
|
| 145 |
+
"reasoning.\n</think>\nThis is my answer."
|
| 146 |
+
)
|
| 147 |
+
|
| 148 |
+
def make_conversation(example):
|
| 149 |
+
# Create conversational format that OnlineDPOTrainer expects
|
| 150 |
+
prompt = [
|
| 151 |
+
{"role": "system", "content": SYSTEM_PROMPT},
|
| 152 |
+
{"role": "user", "content": example["problem"]},
|
| 153 |
+
]
|
| 154 |
+
return {"prompt": prompt, "image": example["image"]}
|
| 155 |
+
|
| 156 |
+
dataset = dataset.map(make_conversation)
|
| 157 |
+
|
| 158 |
+
# Filter big images (from GRPO pattern)
|
| 159 |
+
def filter_big_images(example):
|
| 160 |
+
image = example["image"]
|
| 161 |
+
return image.size[0] < 512 and image.size[1] < 512
|
| 162 |
+
|
| 163 |
+
dataset = dataset.filter(filter_big_images)
|
| 164 |
+
|
| 165 |
+
def convert_to_rgb(example):
|
| 166 |
+
image = example["image"]
|
| 167 |
+
if image.mode != "RGB":
|
| 168 |
+
image = image.convert("RGB")
|
| 169 |
+
example["image"] = image
|
| 170 |
+
return example
|
| 171 |
+
|
| 172 |
+
dataset = dataset.map(convert_to_rgb)
|
| 173 |
+
|
| 174 |
+
train_dataset = dataset["train"]
|
| 175 |
+
eval_dataset = dataset["test"] if training_args.eval_strategy != "no" else None
|
| 176 |
+
|
| 177 |
+
################
|
| 178 |
+
# Training
|
| 179 |
+
################
|
| 180 |
+
trainer = OnlineDPOTrainer(
|
| 181 |
+
model=model,
|
| 182 |
+
reward_funcs=[think_format_reward, accuracy_reward], # Use same reward functions as GRPO VLM
|
| 183 |
+
args=training_args,
|
| 184 |
+
train_dataset=train_dataset,
|
| 185 |
+
eval_dataset=eval_dataset,
|
| 186 |
+
processing_class=processor,
|
| 187 |
+
peft_config=get_peft_config(model_args),
|
| 188 |
+
)
|
| 189 |
+
|
| 190 |
+
# Add completion logging callback (from online DPO pattern)
|
| 191 |
+
if training_args.eval_strategy != "no":
|
| 192 |
+
generation_config = GenerationConfig(
|
| 193 |
+
max_new_tokens=training_args.max_new_tokens, do_sample=True, temperature=training_args.temperature
|
| 194 |
+
)
|
| 195 |
+
completions_callback = LogCompletionsCallback(trainer, generation_config, num_prompts=8)
|
| 196 |
+
trainer.add_callback(completions_callback)
|
| 197 |
+
|
| 198 |
+
trainer.train()
|
| 199 |
+
|
| 200 |
+
# Save and push to hub
|
| 201 |
+
trainer.save_model(training_args.output_dir)
|
| 202 |
+
if training_args.push_to_hub:
|
| 203 |
+
trainer.push_to_hub(dataset_name="lmms-lab/multimodal-open-r1-8k-verified")
|
tasks/tasksmith-fa1a9b35ff39/tests/source/examples/scripts/openenv/browsergym.py
ADDED
|
@@ -0,0 +1,291 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2020-2026 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
# /// script
|
| 16 |
+
# dependencies = [
|
| 17 |
+
# "trl[vllm,peft]",
|
| 18 |
+
# "trackio",
|
| 19 |
+
# "kernels",
|
| 20 |
+
# "openenv-browsergym-env @ git+https://huggingface.co/spaces/openenv/browsergym_env",
|
| 21 |
+
# ]
|
| 22 |
+
# ///
|
| 23 |
+
|
| 24 |
+
"""
|
| 25 |
+
GRPO training with OpenEnv's BrowserGym environment for VLMs (Vision Language Models).
|
| 26 |
+
|
| 27 |
+
This script uses `environment_factory` with multimodal tool responses: each tool action
|
| 28 |
+
returns a screenshot (PIL Image) alongside the accessibility tree text, allowing the VLM
|
| 29 |
+
to see the page visually after each action.
|
| 30 |
+
|
| 31 |
+
Setup:
|
| 32 |
+
```sh
|
| 33 |
+
pip install "openenv-browsergym-env @ git+https://huggingface.co/spaces/openenv/browsergym_env"
|
| 34 |
+
```
|
| 35 |
+
|
| 36 |
+
Usage:
|
| 37 |
+
```sh
|
| 38 |
+
# Without vLLM (default, 1 GPU)
|
| 39 |
+
python examples/scripts/openenv/browsergym.py
|
| 40 |
+
|
| 41 |
+
# With vLLM colocate (1 GPU, requires vLLM support for the model)
|
| 42 |
+
python examples/scripts/openenv/browsergym.py --use-vllm
|
| 43 |
+
|
| 44 |
+
# With vLLM server (2 GPUs)
|
| 45 |
+
CUDA_VISIBLE_DEVICES=0 trl vllm-serve --model Qwen/Qwen3.5-2B --host 0.0.0.0 --port 8000
|
| 46 |
+
CUDA_VISIBLE_DEVICES=1 python examples/scripts/openenv/browsergym.py --use-vllm --vllm-mode server
|
| 47 |
+
```
|
| 48 |
+
"""
|
| 49 |
+
|
| 50 |
+
from __future__ import annotations
|
| 51 |
+
|
| 52 |
+
import argparse
|
| 53 |
+
from datetime import datetime
|
| 54 |
+
from pathlib import Path
|
| 55 |
+
|
| 56 |
+
import numpy as np
|
| 57 |
+
from browsergym_env import BrowserGymAction, BrowserGymEnv
|
| 58 |
+
from datasets import Dataset
|
| 59 |
+
from PIL import Image
|
| 60 |
+
|
| 61 |
+
from trl import GRPOConfig, GRPOTrainer
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def parse_args() -> argparse.Namespace:
|
| 65 |
+
parser = argparse.ArgumentParser(description="GRPO training with BrowserGym VLM environment.")
|
| 66 |
+
parser.add_argument("--model-id", default="Qwen/Qwen3.5-2B")
|
| 67 |
+
parser.add_argument("--space-url", default="https://openenv-browsergym-env.hf.space")
|
| 68 |
+
parser.add_argument("--task-name", default="click-test", help="BrowserGym task name to pass to reset().")
|
| 69 |
+
parser.add_argument("--dataset-prompt", default="Complete the web task successfully.")
|
| 70 |
+
parser.add_argument("--dataset-size", type=int, default=1000)
|
| 71 |
+
parser.add_argument("--max-steps", type=int, default=10)
|
| 72 |
+
parser.add_argument("--max-completion-length", type=int, default=1024)
|
| 73 |
+
parser.add_argument("--image-size", type=int, default=512, help="Resize screenshots to this size. 0 to disable.")
|
| 74 |
+
parser.add_argument("--num-generations", type=int, default=4)
|
| 75 |
+
parser.add_argument("--gradient-accumulation-steps", type=int, default=32)
|
| 76 |
+
parser.add_argument("--learning-rate", type=float, default=5e-6)
|
| 77 |
+
parser.add_argument("--num-epochs", type=int, default=1)
|
| 78 |
+
parser.add_argument("--logging-steps", type=int, default=1)
|
| 79 |
+
parser.add_argument("--output-dir", default=None)
|
| 80 |
+
parser.add_argument("--use-vllm", action="store_true", default=False, help="Enable vLLM for generation.")
|
| 81 |
+
parser.add_argument("--vllm-mode", choices=("colocate", "server"), default="colocate")
|
| 82 |
+
parser.add_argument("--vllm-server-url", default="http://localhost:8000")
|
| 83 |
+
return parser.parse_args()
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
def sanitize_name(name: str) -> str:
|
| 87 |
+
return name.replace("/", "-")
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
SYSTEM_PROMPT = """You control a web browser to complete tasks.
|
| 91 |
+
|
| 92 |
+
The page structure shows elements as: [bid] element_type 'element_text'
|
| 93 |
+
For example: [13] button 'Click Me!' means the element has bid='13'.
|
| 94 |
+
|
| 95 |
+
You will see a screenshot of the page after each action. Use the visual information
|
| 96 |
+
along with the page structure to decide your next action.
|
| 97 |
+
|
| 98 |
+
Use the available tools to interact with the page:
|
| 99 |
+
- click: Click an element by its bid
|
| 100 |
+
- fill: Fill an input field with text
|
| 101 |
+
- send_keys: Send keyboard input
|
| 102 |
+
- scroll: Scroll the page
|
| 103 |
+
- noop: Do nothing
|
| 104 |
+
|
| 105 |
+
Complete the given task as efficiently as possible."""
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
def reward_completion(completions, environments, **kwargs) -> list[float]:
|
| 109 |
+
return [env.reward for env in environments]
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
def main() -> None:
|
| 113 |
+
args = parse_args()
|
| 114 |
+
|
| 115 |
+
space_url = args.space_url
|
| 116 |
+
max_steps = args.max_steps
|
| 117 |
+
image_size = args.image_size
|
| 118 |
+
|
| 119 |
+
dataset = Dataset.from_dict(
|
| 120 |
+
{
|
| 121 |
+
"prompt": [
|
| 122 |
+
[
|
| 123 |
+
{"role": "system", "content": SYSTEM_PROMPT},
|
| 124 |
+
{"role": "user", "content": args.dataset_prompt},
|
| 125 |
+
]
|
| 126 |
+
]
|
| 127 |
+
* args.dataset_size
|
| 128 |
+
}
|
| 129 |
+
)
|
| 130 |
+
|
| 131 |
+
class BrowserGymVLMEnv:
|
| 132 |
+
def __init__(self):
|
| 133 |
+
self.client = BrowserGymEnv(base_url=space_url)
|
| 134 |
+
self.reward = 0.0
|
| 135 |
+
self.done = False
|
| 136 |
+
self._step_count = 0
|
| 137 |
+
|
| 138 |
+
def reset(self, **kwargs) -> str | None:
|
| 139 |
+
self.reward = 0.0
|
| 140 |
+
self.done = False
|
| 141 |
+
self._step_count = 0
|
| 142 |
+
result = self.client.reset(task_name=args.task_name)
|
| 143 |
+
self.done = result.done
|
| 144 |
+
return self._format_observation(result.observation)
|
| 145 |
+
|
| 146 |
+
def click(self, bid: str) -> list:
|
| 147 |
+
"""Click an element on the page.
|
| 148 |
+
|
| 149 |
+
Args:
|
| 150 |
+
bid: The BrowserGym ID of the element to click.
|
| 151 |
+
|
| 152 |
+
Returns:
|
| 153 |
+
The updated page observation with screenshot.
|
| 154 |
+
"""
|
| 155 |
+
return self._do_action(f"click('{bid}')")
|
| 156 |
+
|
| 157 |
+
def fill(self, bid: str, text: str) -> list:
|
| 158 |
+
"""Fill an input field with text.
|
| 159 |
+
|
| 160 |
+
Args:
|
| 161 |
+
bid: The BrowserGym ID of the input field.
|
| 162 |
+
text: The text to type into the field.
|
| 163 |
+
|
| 164 |
+
Returns:
|
| 165 |
+
The updated page observation with screenshot.
|
| 166 |
+
"""
|
| 167 |
+
return self._do_action(f"fill('{bid}', '{text}')")
|
| 168 |
+
|
| 169 |
+
def send_keys(self, text: str) -> list:
|
| 170 |
+
"""Send keyboard input to the page.
|
| 171 |
+
|
| 172 |
+
Args:
|
| 173 |
+
text: The keyboard input to send.
|
| 174 |
+
|
| 175 |
+
Returns:
|
| 176 |
+
The updated page observation with screenshot.
|
| 177 |
+
"""
|
| 178 |
+
return self._do_action(f"send_keys('{text}')")
|
| 179 |
+
|
| 180 |
+
def scroll(self, direction: str) -> list:
|
| 181 |
+
"""Scroll the page.
|
| 182 |
+
|
| 183 |
+
Args:
|
| 184 |
+
direction: Direction to scroll, either 'up' or 'down'.
|
| 185 |
+
|
| 186 |
+
Returns:
|
| 187 |
+
The updated page observation with screenshot.
|
| 188 |
+
"""
|
| 189 |
+
return self._do_action(f"scroll('{direction}')")
|
| 190 |
+
|
| 191 |
+
def noop(self) -> list:
|
| 192 |
+
"""Do nothing and observe the current page state.
|
| 193 |
+
|
| 194 |
+
Returns:
|
| 195 |
+
The current page observation with screenshot.
|
| 196 |
+
"""
|
| 197 |
+
return self._do_action("noop()")
|
| 198 |
+
|
| 199 |
+
def _do_action(self, action_str: str) -> list:
|
| 200 |
+
if self.done:
|
| 201 |
+
raise ValueError("Episode is done.")
|
| 202 |
+
|
| 203 |
+
self._step_count += 1
|
| 204 |
+
result = self.client.step(BrowserGymAction(action_str=action_str))
|
| 205 |
+
observation = result.observation
|
| 206 |
+
step_reward = float(result.reward or 0.0)
|
| 207 |
+
self.done = result.done
|
| 208 |
+
|
| 209 |
+
if self.done and step_reward > 0:
|
| 210 |
+
self.reward = 1.0
|
| 211 |
+
elif self.done:
|
| 212 |
+
self.reward = 0.0
|
| 213 |
+
else:
|
| 214 |
+
self.reward = step_reward
|
| 215 |
+
|
| 216 |
+
if self._step_count >= max_steps:
|
| 217 |
+
self.done = True
|
| 218 |
+
|
| 219 |
+
return self._format_observation_multimodal(observation)
|
| 220 |
+
|
| 221 |
+
def _format_observation(self, observation) -> str:
|
| 222 |
+
"""Format initial observation as text (for reset, appended to prompt)."""
|
| 223 |
+
parts = []
|
| 224 |
+
if observation.goal:
|
| 225 |
+
parts.append(f"Goal: {observation.goal}")
|
| 226 |
+
if observation.axtree_txt:
|
| 227 |
+
axtree = observation.axtree_txt
|
| 228 |
+
if len(axtree) > 2000:
|
| 229 |
+
axtree = axtree[:2000] + "..."
|
| 230 |
+
parts.append(f"Page structure:\n{axtree}")
|
| 231 |
+
return "\n\n".join(parts) if parts else "No observation available."
|
| 232 |
+
|
| 233 |
+
def _format_observation_multimodal(self, observation) -> list:
|
| 234 |
+
"""Format observation as multimodal content blocks (screenshot + text)."""
|
| 235 |
+
content = []
|
| 236 |
+
|
| 237 |
+
# Add screenshot if available
|
| 238 |
+
if observation.screenshot is not None:
|
| 239 |
+
screenshot_array = np.array(observation.screenshot, dtype=np.uint8)
|
| 240 |
+
screenshot_image = Image.fromarray(screenshot_array)
|
| 241 |
+
if image_size > 0:
|
| 242 |
+
screenshot_image.thumbnail((image_size, image_size), Image.LANCZOS)
|
| 243 |
+
content.append({"type": "image", "image": screenshot_image})
|
| 244 |
+
|
| 245 |
+
# Add text observation
|
| 246 |
+
parts = []
|
| 247 |
+
if observation.goal:
|
| 248 |
+
parts.append(f"Goal: {observation.goal}")
|
| 249 |
+
if observation.last_action_error and observation.error:
|
| 250 |
+
parts.append(f"Error: {observation.error}")
|
| 251 |
+
if observation.axtree_txt:
|
| 252 |
+
axtree = observation.axtree_txt
|
| 253 |
+
if len(axtree) > 2000:
|
| 254 |
+
axtree = axtree[:2000] + "..."
|
| 255 |
+
parts.append(f"Page structure:\n{axtree}")
|
| 256 |
+
text = "\n\n".join(parts) if parts else "No observation available."
|
| 257 |
+
content.append({"type": "text", "text": text})
|
| 258 |
+
|
| 259 |
+
return content
|
| 260 |
+
|
| 261 |
+
timestamp = datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
|
| 262 |
+
default_output_dir = Path("outputs") / f"browsergym-vlm-grpo-{sanitize_name(args.model_id)}-{timestamp}"
|
| 263 |
+
output_dir = Path(args.output_dir or default_output_dir)
|
| 264 |
+
|
| 265 |
+
trainer = GRPOTrainer(
|
| 266 |
+
model=args.model_id,
|
| 267 |
+
reward_funcs=reward_completion,
|
| 268 |
+
train_dataset=dataset,
|
| 269 |
+
args=GRPOConfig(
|
| 270 |
+
use_vllm=args.use_vllm,
|
| 271 |
+
vllm_mode=args.vllm_mode if args.use_vllm else "colocate",
|
| 272 |
+
vllm_server_base_url=args.vllm_server_url if args.use_vllm and args.vllm_mode == "server" else None,
|
| 273 |
+
output_dir=str(output_dir),
|
| 274 |
+
num_train_epochs=args.num_epochs,
|
| 275 |
+
learning_rate=args.learning_rate,
|
| 276 |
+
gradient_accumulation_steps=args.gradient_accumulation_steps,
|
| 277 |
+
num_generations=args.num_generations,
|
| 278 |
+
max_completion_length=args.max_completion_length,
|
| 279 |
+
logging_steps=args.logging_steps,
|
| 280 |
+
log_completions=True,
|
| 281 |
+
report_to="trackio",
|
| 282 |
+
trackio_space_id=f"browsergym-vlm-grpo-{sanitize_name(args.model_id)}",
|
| 283 |
+
chat_template_kwargs={"enable_thinking": False},
|
| 284 |
+
),
|
| 285 |
+
environment_factory=BrowserGymVLMEnv,
|
| 286 |
+
)
|
| 287 |
+
trainer.train()
|
| 288 |
+
|
| 289 |
+
|
| 290 |
+
if __name__ == "__main__":
|
| 291 |
+
main()
|
tasks/tasksmith-fa1a9b35ff39/tests/source/examples/scripts/openenv/browsergym_llm.py
ADDED
|
@@ -0,0 +1,463 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2020-2026 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
# /// script
|
| 16 |
+
# dependencies = [
|
| 17 |
+
# "trl[vllm,peft]",
|
| 18 |
+
# "trackio",
|
| 19 |
+
# "kernels",
|
| 20 |
+
# "openenv-browsergym-env @ git+https://huggingface.co/spaces/openenv/browsergym_env",
|
| 21 |
+
# ]
|
| 22 |
+
# ///
|
| 23 |
+
|
| 24 |
+
"""
|
| 25 |
+
Simple script to run GRPO training with OpenEnv's BrowserGym environment and vLLM for LLMs.
|
| 26 |
+
|
| 27 |
+
This script is optimized for text-only Language Models (LLMs). It uses the accessibility
|
| 28 |
+
tree text from BrowserGym, making it memory-efficient.
|
| 29 |
+
|
| 30 |
+
The environment runs on a Hugging Face Space by default.
|
| 31 |
+
|
| 32 |
+
Setup (Option A - Install from HF Space, recommended):
|
| 33 |
+
|
| 34 |
+
```sh
|
| 35 |
+
uv pip install git+https://huggingface.co/spaces/openenv/browsergym_env
|
| 36 |
+
```
|
| 37 |
+
|
| 38 |
+
Setup (Option B - Clone OpenEnv repo, for development):
|
| 39 |
+
|
| 40 |
+
```sh
|
| 41 |
+
git clone https://github.com/huggingface/OpenEnv.git
|
| 42 |
+
cd OpenEnv/envs/browsergym_env
|
| 43 |
+
uv pip install -e .
|
| 44 |
+
```
|
| 45 |
+
|
| 46 |
+
# Option 1: HF Spaces + Colocated vLLM (1 GPU required)
|
| 47 |
+
```sh
|
| 48 |
+
python examples/scripts/openenv/browsergym_llm.py --vllm-mode colocate
|
| 49 |
+
```
|
| 50 |
+
|
| 51 |
+
# Option 2: HF Spaces + Separate vLLM server (2 GPUs required)
|
| 52 |
+
|
| 53 |
+
# Spin up vLLM server (Terminal 1)
|
| 54 |
+
```sh
|
| 55 |
+
CUDA_VISIBLE_DEVICES=0 trl vllm-serve --model Qwen/Qwen3-0.6B --host 0.0.0.0 --port 8001
|
| 56 |
+
```
|
| 57 |
+
|
| 58 |
+
# Run training (Terminal 2)
|
| 59 |
+
```sh
|
| 60 |
+
CUDA_VISIBLE_DEVICES=1 python examples/scripts/openenv/browsergym_llm.py --vllm-mode server --vllm-server-url http://localhost:8001
|
| 61 |
+
```
|
| 62 |
+
"""
|
| 63 |
+
|
| 64 |
+
from __future__ import annotations
|
| 65 |
+
|
| 66 |
+
import argparse
|
| 67 |
+
from datetime import datetime
|
| 68 |
+
from pathlib import Path
|
| 69 |
+
|
| 70 |
+
from browsergym_env import BrowserGymAction, BrowserGymEnv
|
| 71 |
+
from datasets import Dataset
|
| 72 |
+
|
| 73 |
+
from trl import GRPOConfig, GRPOTrainer
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
def parse_args() -> argparse.Namespace:
|
| 77 |
+
parser = argparse.ArgumentParser(description="Run GRPO training for BrowserGym MiniWoB using OpenEnv environment.")
|
| 78 |
+
parser.add_argument(
|
| 79 |
+
"--model-id",
|
| 80 |
+
default="Qwen/Qwen3-0.6B",
|
| 81 |
+
help="Model identifier passed to GRPOTrainer for fine-tuning.",
|
| 82 |
+
)
|
| 83 |
+
parser.add_argument(
|
| 84 |
+
"--space-url",
|
| 85 |
+
type=str,
|
| 86 |
+
default="https://openenv-browsergym-env.hf.space",
|
| 87 |
+
help="URL for the Hugging Face Space running the BrowserGym environment.",
|
| 88 |
+
)
|
| 89 |
+
parser.add_argument(
|
| 90 |
+
"--benchmark",
|
| 91 |
+
default="miniwob",
|
| 92 |
+
help="BrowserGym benchmark to use (miniwob, webarena, etc.).",
|
| 93 |
+
)
|
| 94 |
+
parser.add_argument(
|
| 95 |
+
"--task-name",
|
| 96 |
+
default="click-test",
|
| 97 |
+
help="Specific task within the benchmark (e.g., click-test, click-button).",
|
| 98 |
+
)
|
| 99 |
+
parser.add_argument(
|
| 100 |
+
"--dataset-prompt",
|
| 101 |
+
default="Complete the web task successfully.",
|
| 102 |
+
help="Prompt text used to seed the training dataset.",
|
| 103 |
+
)
|
| 104 |
+
parser.add_argument(
|
| 105 |
+
"--dataset-size",
|
| 106 |
+
type=int,
|
| 107 |
+
default=1000,
|
| 108 |
+
help="Number of entries to include in the synthetic training dataset.",
|
| 109 |
+
)
|
| 110 |
+
parser.add_argument(
|
| 111 |
+
"--max-steps",
|
| 112 |
+
type=int,
|
| 113 |
+
default=10,
|
| 114 |
+
help="Maximum number of steps per episode.",
|
| 115 |
+
)
|
| 116 |
+
parser.add_argument(
|
| 117 |
+
"--max-completion-length",
|
| 118 |
+
type=int,
|
| 119 |
+
default=1024,
|
| 120 |
+
help="Maximum completion length in tokens for tool-calling generation.",
|
| 121 |
+
)
|
| 122 |
+
parser.add_argument(
|
| 123 |
+
"--temperature",
|
| 124 |
+
type=float,
|
| 125 |
+
default=0.7,
|
| 126 |
+
help="Sampling temperature used during rollout generation.",
|
| 127 |
+
)
|
| 128 |
+
parser.add_argument(
|
| 129 |
+
"--top-k",
|
| 130 |
+
type=int,
|
| 131 |
+
default=50,
|
| 132 |
+
help="Top-k sampling parameter forwarded to vLLM.",
|
| 133 |
+
)
|
| 134 |
+
parser.add_argument(
|
| 135 |
+
"--top-p",
|
| 136 |
+
type=float,
|
| 137 |
+
default=None,
|
| 138 |
+
help="Optional top-p sampling parameter forwarded to vLLM.",
|
| 139 |
+
)
|
| 140 |
+
parser.add_argument(
|
| 141 |
+
"--learning-rate",
|
| 142 |
+
type=float,
|
| 143 |
+
default=5e-6,
|
| 144 |
+
help="Learning rate for GRPO training.",
|
| 145 |
+
)
|
| 146 |
+
parser.add_argument(
|
| 147 |
+
"--weight-decay",
|
| 148 |
+
type=float,
|
| 149 |
+
default=0.0,
|
| 150 |
+
help="Weight decay applied during optimization.",
|
| 151 |
+
)
|
| 152 |
+
parser.add_argument(
|
| 153 |
+
"--gradient-accumulation-steps",
|
| 154 |
+
type=int,
|
| 155 |
+
default=32,
|
| 156 |
+
help="Gradient accumulation steps for GRPO training.",
|
| 157 |
+
)
|
| 158 |
+
parser.add_argument(
|
| 159 |
+
"--warmup-steps",
|
| 160 |
+
type=int,
|
| 161 |
+
default=10,
|
| 162 |
+
help="Warmup steps for the scheduler.",
|
| 163 |
+
)
|
| 164 |
+
parser.add_argument(
|
| 165 |
+
"--per-device-batch-size",
|
| 166 |
+
type=int,
|
| 167 |
+
default=1,
|
| 168 |
+
help="Per-device train batch size.",
|
| 169 |
+
)
|
| 170 |
+
parser.add_argument(
|
| 171 |
+
"--num-generations",
|
| 172 |
+
type=int,
|
| 173 |
+
default=4,
|
| 174 |
+
help="Number of rollout generations per dataset prompt.",
|
| 175 |
+
)
|
| 176 |
+
parser.add_argument(
|
| 177 |
+
"--num-epochs",
|
| 178 |
+
type=int,
|
| 179 |
+
default=1,
|
| 180 |
+
help="Number of training epochs.",
|
| 181 |
+
)
|
| 182 |
+
parser.add_argument(
|
| 183 |
+
"--save-interval",
|
| 184 |
+
type=int,
|
| 185 |
+
default=50,
|
| 186 |
+
help="Interval (in steps) between checkpoint saves.",
|
| 187 |
+
)
|
| 188 |
+
parser.add_argument(
|
| 189 |
+
"--save-total-limit",
|
| 190 |
+
type=int,
|
| 191 |
+
default=None,
|
| 192 |
+
help="Maximum number of checkpoints to keep.",
|
| 193 |
+
)
|
| 194 |
+
parser.add_argument(
|
| 195 |
+
"--output-dir",
|
| 196 |
+
default=None,
|
| 197 |
+
help="Directory where training outputs and checkpoints are stored.",
|
| 198 |
+
)
|
| 199 |
+
parser.add_argument(
|
| 200 |
+
"--run-name",
|
| 201 |
+
default=None,
|
| 202 |
+
help="Optional run name for logging systems.",
|
| 203 |
+
)
|
| 204 |
+
parser.add_argument(
|
| 205 |
+
"--project",
|
| 206 |
+
default=None,
|
| 207 |
+
help="Optional project identifier for logging systems.",
|
| 208 |
+
)
|
| 209 |
+
parser.add_argument(
|
| 210 |
+
"--vllm-mode",
|
| 211 |
+
choices=("colocate", "server"),
|
| 212 |
+
default="colocate",
|
| 213 |
+
help="vLLM execution mode: 'colocate' or 'server'.",
|
| 214 |
+
)
|
| 215 |
+
parser.add_argument(
|
| 216 |
+
"--vllm-server-url",
|
| 217 |
+
type=str,
|
| 218 |
+
default="http://localhost:8001",
|
| 219 |
+
help="URL for the vLLM server (only used when --vllm-mode=server).",
|
| 220 |
+
)
|
| 221 |
+
parser.add_argument(
|
| 222 |
+
"--logging-steps",
|
| 223 |
+
type=int,
|
| 224 |
+
default=1,
|
| 225 |
+
help="Frequency of logging steps for GRPO training.",
|
| 226 |
+
)
|
| 227 |
+
return parser.parse_args()
|
| 228 |
+
|
| 229 |
+
|
| 230 |
+
def sanitize_name(name: str) -> str:
|
| 231 |
+
return name.replace("/", "-")
|
| 232 |
+
|
| 233 |
+
|
| 234 |
+
# ---------------------------------------------------------------------------
|
| 235 |
+
# System Prompt
|
| 236 |
+
# ---------------------------------------------------------------------------
|
| 237 |
+
|
| 238 |
+
SYSTEM_PROMPT = """You control a web browser to complete tasks.
|
| 239 |
+
|
| 240 |
+
The page structure shows elements as: [bid] element_type 'element_text'
|
| 241 |
+
For example: [13] button 'Click Me!' means the element has bid='13'.
|
| 242 |
+
|
| 243 |
+
Use the available tools to interact with the page:
|
| 244 |
+
- click: Click an element by its bid
|
| 245 |
+
- fill: Fill an input field with text
|
| 246 |
+
- send_keys: Send keyboard input
|
| 247 |
+
- scroll: Scroll the page
|
| 248 |
+
- noop: Do nothing
|
| 249 |
+
|
| 250 |
+
Complete the given task as efficiently as possible."""
|
| 251 |
+
|
| 252 |
+
|
| 253 |
+
# ---------------------------------------------------------------------------
|
| 254 |
+
# Reward
|
| 255 |
+
# ---------------------------------------------------------------------------
|
| 256 |
+
|
| 257 |
+
|
| 258 |
+
def reward_completion(environments, **kwargs) -> list[float]:
|
| 259 |
+
"""Reward for task completion."""
|
| 260 |
+
return [env.reward for env in environments]
|
| 261 |
+
|
| 262 |
+
|
| 263 |
+
# ---------------------------------------------------------------------------
|
| 264 |
+
# Main entrypoint
|
| 265 |
+
# ---------------------------------------------------------------------------
|
| 266 |
+
|
| 267 |
+
|
| 268 |
+
def main() -> None:
|
| 269 |
+
args = parse_args()
|
| 270 |
+
|
| 271 |
+
space_url = args.space_url
|
| 272 |
+
max_steps = args.max_steps
|
| 273 |
+
|
| 274 |
+
dataset = Dataset.from_dict(
|
| 275 |
+
{
|
| 276 |
+
"prompt": [
|
| 277 |
+
[
|
| 278 |
+
{"role": "system", "content": SYSTEM_PROMPT},
|
| 279 |
+
{"role": "user", "content": args.dataset_prompt},
|
| 280 |
+
]
|
| 281 |
+
]
|
| 282 |
+
* args.dataset_size
|
| 283 |
+
}
|
| 284 |
+
)
|
| 285 |
+
|
| 286 |
+
class BrowserGymLLMEnv:
|
| 287 |
+
def __init__(self):
|
| 288 |
+
self.client = BrowserGymEnv(base_url=space_url)
|
| 289 |
+
self.reward = 0.0
|
| 290 |
+
self._done = False
|
| 291 |
+
self._step_count = 0
|
| 292 |
+
|
| 293 |
+
def _ensure_large_max_size(self):
|
| 294 |
+
"""Raise WebSocket max message size for large observations (e.g. accessibility trees).
|
| 295 |
+
|
| 296 |
+
openenv-core<=0.2.1 does not pass max_size to ws_connect, so the websockets library
|
| 297 |
+
defaults to 1MB. We force a connection and patch it to 100MB before any messages are sent.
|
| 298 |
+
"""
|
| 299 |
+
self.client.connect()
|
| 300 |
+
ws = self.client._ws
|
| 301 |
+
if ws is not None and hasattr(ws, "protocol"):
|
| 302 |
+
proto = ws.protocol
|
| 303 |
+
# websockets <16: max_size; websockets >=16: max_message_size
|
| 304 |
+
attr = "max_size" if hasattr(proto, "max_size") else "max_message_size"
|
| 305 |
+
if getattr(proto, attr) == 2**20:
|
| 306 |
+
setattr(proto, attr, 100 * 1024 * 1024)
|
| 307 |
+
|
| 308 |
+
def reset(self, **kwargs) -> str:
|
| 309 |
+
self.reward = 0.0
|
| 310 |
+
self._done = False
|
| 311 |
+
self._step_count = 0
|
| 312 |
+
self._ensure_large_max_size()
|
| 313 |
+
result = self.client.reset(task_name=args.task_name)
|
| 314 |
+
self._done = result.done
|
| 315 |
+
return self._format_observation(result.observation)
|
| 316 |
+
|
| 317 |
+
def click(self, bid: str) -> str:
|
| 318 |
+
"""Click an element on the page.
|
| 319 |
+
|
| 320 |
+
Args:
|
| 321 |
+
bid: The BrowserGym ID of the element to click.
|
| 322 |
+
|
| 323 |
+
Returns:
|
| 324 |
+
The updated page observation.
|
| 325 |
+
"""
|
| 326 |
+
return self._do_action(f"click({bid!r})")
|
| 327 |
+
|
| 328 |
+
def fill(self, bid: str, text: str) -> str:
|
| 329 |
+
"""Fill an input field with text.
|
| 330 |
+
|
| 331 |
+
Args:
|
| 332 |
+
bid: The BrowserGym ID of the input field.
|
| 333 |
+
text: The text to type into the field.
|
| 334 |
+
|
| 335 |
+
Returns:
|
| 336 |
+
The updated page observation.
|
| 337 |
+
"""
|
| 338 |
+
return self._do_action(f"fill({bid!r}, {text!r})")
|
| 339 |
+
|
| 340 |
+
def send_keys(self, text: str) -> str:
|
| 341 |
+
"""Send keyboard input to the page.
|
| 342 |
+
|
| 343 |
+
Args:
|
| 344 |
+
text: The keyboard input to send.
|
| 345 |
+
|
| 346 |
+
Returns:
|
| 347 |
+
The updated page observation.
|
| 348 |
+
"""
|
| 349 |
+
return self._do_action(f"send_keys({text!r})")
|
| 350 |
+
|
| 351 |
+
def scroll(self, direction: str) -> str:
|
| 352 |
+
"""Scroll the page.
|
| 353 |
+
|
| 354 |
+
Args:
|
| 355 |
+
direction: Direction to scroll, either 'up' or 'down'.
|
| 356 |
+
|
| 357 |
+
Returns:
|
| 358 |
+
The updated page observation.
|
| 359 |
+
"""
|
| 360 |
+
return self._do_action(f"scroll({direction!r})")
|
| 361 |
+
|
| 362 |
+
def noop(self) -> str:
|
| 363 |
+
"""Do nothing and observe the current page state.
|
| 364 |
+
|
| 365 |
+
Returns:
|
| 366 |
+
The current page observation.
|
| 367 |
+
"""
|
| 368 |
+
return self._do_action("noop()")
|
| 369 |
+
|
| 370 |
+
def _do_action(self, action_str: str) -> str:
|
| 371 |
+
if self._done:
|
| 372 |
+
raise ValueError("Episode is done.")
|
| 373 |
+
|
| 374 |
+
self._step_count += 1
|
| 375 |
+
result = self.client.step(BrowserGymAction(action_str=action_str))
|
| 376 |
+
observation = result.observation
|
| 377 |
+
step_reward = float(result.reward or 0.0)
|
| 378 |
+
self._done = result.done
|
| 379 |
+
|
| 380 |
+
# Reward shaping: binary success/failure on completion
|
| 381 |
+
if self._done and step_reward > 0:
|
| 382 |
+
self.reward = 1.0
|
| 383 |
+
elif self._done:
|
| 384 |
+
self.reward = 0.0
|
| 385 |
+
else:
|
| 386 |
+
self.reward = step_reward
|
| 387 |
+
|
| 388 |
+
# Enforce max steps
|
| 389 |
+
if self._step_count >= max_steps:
|
| 390 |
+
self._done = True
|
| 391 |
+
|
| 392 |
+
return self._format_observation(observation)
|
| 393 |
+
|
| 394 |
+
def _format_observation(self, observation) -> str:
|
| 395 |
+
parts = []
|
| 396 |
+
if observation.goal:
|
| 397 |
+
parts.append(f"Goal: {observation.goal}")
|
| 398 |
+
if observation.last_action_error and observation.error:
|
| 399 |
+
parts.append(f"Error: {observation.error}")
|
| 400 |
+
if observation.axtree_txt:
|
| 401 |
+
axtree = observation.axtree_txt
|
| 402 |
+
if len(axtree) > 2000:
|
| 403 |
+
axtree = axtree[:2000] + "..."
|
| 404 |
+
parts.append(f"Page structure:\n{axtree}")
|
| 405 |
+
return "\n\n".join(parts) if parts else "No observation available."
|
| 406 |
+
|
| 407 |
+
timestamp = datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
|
| 408 |
+
default_output_dir = Path("outputs") / f"browsergym-grpo-{sanitize_name(args.model_id)}-{timestamp}"
|
| 409 |
+
output_dir = Path(args.output_dir or default_output_dir)
|
| 410 |
+
|
| 411 |
+
grpo_config = GRPOConfig(
|
| 412 |
+
use_vllm=True,
|
| 413 |
+
vllm_mode=args.vllm_mode,
|
| 414 |
+
vllm_server_base_url=args.vllm_server_url if args.vllm_mode == "server" else None,
|
| 415 |
+
vllm_gpu_memory_utilization=0.4,
|
| 416 |
+
output_dir=str(output_dir),
|
| 417 |
+
num_train_epochs=args.num_epochs,
|
| 418 |
+
learning_rate=args.learning_rate,
|
| 419 |
+
weight_decay=args.weight_decay,
|
| 420 |
+
gradient_accumulation_steps=args.gradient_accumulation_steps,
|
| 421 |
+
per_device_train_batch_size=args.per_device_batch_size,
|
| 422 |
+
warmup_steps=args.warmup_steps,
|
| 423 |
+
num_generations=args.num_generations,
|
| 424 |
+
generation_batch_size=args.num_generations,
|
| 425 |
+
max_completion_length=args.max_completion_length,
|
| 426 |
+
logging_steps=args.logging_steps,
|
| 427 |
+
report_to="trackio",
|
| 428 |
+
trackio_space_id=f"browsergym-grpo-{sanitize_name(args.model_id)}-{timestamp}",
|
| 429 |
+
save_strategy="steps",
|
| 430 |
+
save_steps=args.save_interval,
|
| 431 |
+
save_total_limit=args.save_total_limit,
|
| 432 |
+
temperature=args.temperature,
|
| 433 |
+
top_k=args.top_k,
|
| 434 |
+
top_p=args.top_p,
|
| 435 |
+
chat_template_kwargs={"enable_thinking": False},
|
| 436 |
+
)
|
| 437 |
+
|
| 438 |
+
grpo_config.run_name = args.run_name or f"run-{timestamp}"
|
| 439 |
+
grpo_config.project = args.project or f"group-{sanitize_name(args.model_id)}"
|
| 440 |
+
|
| 441 |
+
trainer = GRPOTrainer(
|
| 442 |
+
model=args.model_id,
|
| 443 |
+
reward_funcs=[reward_completion],
|
| 444 |
+
train_dataset=dataset,
|
| 445 |
+
args=grpo_config,
|
| 446 |
+
environment_factory=BrowserGymLLMEnv,
|
| 447 |
+
)
|
| 448 |
+
|
| 449 |
+
print("=" * 80)
|
| 450 |
+
print("Starting GRPO training with BrowserGym environment (LLM mode)")
|
| 451 |
+
print(f"Benchmark: {args.benchmark}")
|
| 452 |
+
print(f"Task: {args.task_name}")
|
| 453 |
+
print(f"Model: {args.model_id}")
|
| 454 |
+
print("Mode: LLM (text-only, using accessibility tree)")
|
| 455 |
+
print(f"Using {args.num_generations} rollouts per dataset prompt")
|
| 456 |
+
print(f"Output directory: {output_dir}")
|
| 457 |
+
print("=" * 80)
|
| 458 |
+
|
| 459 |
+
trainer.train()
|
| 460 |
+
|
| 461 |
+
|
| 462 |
+
if __name__ == "__main__":
|
| 463 |
+
main()
|
tasks/tasksmith-fa1a9b35ff39/tests/source/examples/scripts/openenv/carla.py
ADDED
|
@@ -0,0 +1,219 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2020-2026 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
# /// script
|
| 16 |
+
# dependencies = [
|
| 17 |
+
# "trl",
|
| 18 |
+
# "openenv-carla-env @ git+https://huggingface.co/spaces/sergiopaniego/carla_env",
|
| 19 |
+
# ]
|
| 20 |
+
# ///
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
"""
|
| 24 |
+
Simple script to run GRPO training with OpenEnv's CARLA environment. The environment simulates an emergency
|
| 25 |
+
driving scenario where pedestrians are ahead and the model must learn to observe the scene and take the
|
| 26 |
+
correct action (e.g., swerve to an empty lane) to minimize casualties.
|
| 27 |
+
|
| 28 |
+
Setup (Option A - Install from HF Space, recommended):
|
| 29 |
+
|
| 30 |
+
```sh
|
| 31 |
+
uv pip install git+https://huggingface.co/spaces/sergiopaniego/carla_env
|
| 32 |
+
```
|
| 33 |
+
|
| 34 |
+
Setup (Option B - Clone OpenEnv repo, for development):
|
| 35 |
+
|
| 36 |
+
```sh
|
| 37 |
+
git clone https://github.com/huggingface/OpenEnv.git
|
| 38 |
+
cd OpenEnv/envs/carla_env
|
| 39 |
+
uv pip install -e .
|
| 40 |
+
```
|
| 41 |
+
|
| 42 |
+
Usage:
|
| 43 |
+
|
| 44 |
+
```sh
|
| 45 |
+
python examples/scripts/openenv/carla.py
|
| 46 |
+
python examples/scripts/openenv/carla.py --model Qwen/Qwen3-1.7B --env-urls https://server1.hf.space https://server2.hf.space
|
| 47 |
+
```
|
| 48 |
+
"""
|
| 49 |
+
|
| 50 |
+
import argparse
|
| 51 |
+
|
| 52 |
+
from carla_env import CarlaAction, CarlaEnv
|
| 53 |
+
from datasets import Dataset
|
| 54 |
+
|
| 55 |
+
from trl import GRPOConfig, GRPOTrainer
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
def parse_args():
|
| 59 |
+
parser = argparse.ArgumentParser(description="Run GRPO training with CARLA environment.")
|
| 60 |
+
parser.add_argument(
|
| 61 |
+
"--model",
|
| 62 |
+
type=str,
|
| 63 |
+
default="Qwen/Qwen3-0.6B",
|
| 64 |
+
help="Model to use for training.",
|
| 65 |
+
)
|
| 66 |
+
parser.add_argument(
|
| 67 |
+
"--env-urls",
|
| 68 |
+
type=str,
|
| 69 |
+
nargs="+",
|
| 70 |
+
default=["https://sergiopaniego-carla-env.hf.space"],
|
| 71 |
+
help="URLs for the CARLA environment servers (one per environment instance).",
|
| 72 |
+
)
|
| 73 |
+
parser.add_argument(
|
| 74 |
+
"--trackio-space-id",
|
| 75 |
+
type=str,
|
| 76 |
+
default="carla-grpo-trolley",
|
| 77 |
+
help="Trackio space identifier.",
|
| 78 |
+
)
|
| 79 |
+
parser.add_argument(
|
| 80 |
+
"--hub-model-id",
|
| 81 |
+
type=str,
|
| 82 |
+
default=None,
|
| 83 |
+
help="Hub model ID to push the trained model to (e.g., sergiopaniego/Qwen3-0.6B-carla-trolley-escape).",
|
| 84 |
+
)
|
| 85 |
+
parser.add_argument(
|
| 86 |
+
"--run-name",
|
| 87 |
+
type=str,
|
| 88 |
+
default=None,
|
| 89 |
+
help="Run name for tracking.",
|
| 90 |
+
)
|
| 91 |
+
return parser.parse_args()
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
PROMPT = """You control an autonomous vehicle in an emergency. There are pedestrians ahead and you must \
|
| 95 |
+
decide what to do immediately.
|
| 96 |
+
|
| 97 |
+
You have the following tools available:
|
| 98 |
+
- `observe`: Advance time and get a new observation of the scene.
|
| 99 |
+
- `emergency_stop`: Apply maximum braking to stop the vehicle.
|
| 100 |
+
- `lane_change(direction)`: Change lane to the left or right. Direction must be "left" or "right".
|
| 101 |
+
|
| 102 |
+
Observe the scene first, then decide the best course of action to minimize harm."""
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
SIM_TICKS = 10 # Number of simulation steps to advance after each action
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
class CarlaGRPOEnv:
|
| 109 |
+
_env_url_iter = None
|
| 110 |
+
|
| 111 |
+
def __init__(self):
|
| 112 |
+
url = next(CarlaGRPOEnv._env_url_iter)
|
| 113 |
+
self.client = CarlaEnv(base_url=url, connect_timeout_s=30, message_timeout_s=120)
|
| 114 |
+
|
| 115 |
+
@staticmethod
|
| 116 |
+
def _describe(obs) -> str:
|
| 117 |
+
"""Build a text description from the observation fields."""
|
| 118 |
+
parts = []
|
| 119 |
+
parts.append(f"Speed: {obs.speed_kmh:.1f} km/h.")
|
| 120 |
+
if obs.nearby_actors:
|
| 121 |
+
for actor in obs.nearby_actors:
|
| 122 |
+
parts.append(f"- {actor.get('type', 'actor')} at {actor.get('distance', '?')}m")
|
| 123 |
+
else:
|
| 124 |
+
parts.append("No nearby actors detected.")
|
| 125 |
+
if obs.collision_detected:
|
| 126 |
+
parts.append(f"COLLISION detected with {obs.collided_with or 'unknown'}!")
|
| 127 |
+
return "\n".join(parts)
|
| 128 |
+
|
| 129 |
+
def _advance(self, ticks: int = SIM_TICKS):
|
| 130 |
+
"""Advance the simulation by calling observe repeatedly, return the last result."""
|
| 131 |
+
result = None
|
| 132 |
+
for _ in range(ticks):
|
| 133 |
+
result = self.client.step(CarlaAction(action_type="observe"))
|
| 134 |
+
if result.done:
|
| 135 |
+
break
|
| 136 |
+
return result
|
| 137 |
+
|
| 138 |
+
def reset(self, **kwargs) -> str | None:
|
| 139 |
+
result = self.client.reset(scenario_name="trolley_micro_escape_exists")
|
| 140 |
+
self.reward = 0.0
|
| 141 |
+
return self._describe(result.observation)
|
| 142 |
+
|
| 143 |
+
def observe(self) -> str:
|
| 144 |
+
"""
|
| 145 |
+
Get the current scene description without taking any action.
|
| 146 |
+
|
| 147 |
+
Returns:
|
| 148 |
+
The scene description with vehicle state and nearby actors.
|
| 149 |
+
"""
|
| 150 |
+
result = self._advance()
|
| 151 |
+
self.reward = result.observation.rubric_reward or 0.0
|
| 152 |
+
return self._describe(result.observation)
|
| 153 |
+
|
| 154 |
+
def emergency_stop(self) -> str:
|
| 155 |
+
"""
|
| 156 |
+
Apply maximum braking to stop the vehicle.
|
| 157 |
+
|
| 158 |
+
Returns:
|
| 159 |
+
The scene description after braking.
|
| 160 |
+
"""
|
| 161 |
+
self.client.step(CarlaAction(action_type="emergency_stop"))
|
| 162 |
+
result = self._advance()
|
| 163 |
+
self.reward = result.observation.rubric_reward or 0.0
|
| 164 |
+
return self._describe(result.observation)
|
| 165 |
+
|
| 166 |
+
def lane_change(self, direction: str) -> str:
|
| 167 |
+
"""
|
| 168 |
+
Change lane to avoid obstacles.
|
| 169 |
+
|
| 170 |
+
Args:
|
| 171 |
+
direction: Direction to change lane, either "left" or "right".
|
| 172 |
+
|
| 173 |
+
Returns:
|
| 174 |
+
The scene description after changing lane.
|
| 175 |
+
"""
|
| 176 |
+
self.client.step(CarlaAction(action_type="lane_change", lane_direction=direction))
|
| 177 |
+
result = self._advance()
|
| 178 |
+
self.reward = result.observation.rubric_reward or 0.0
|
| 179 |
+
return self._describe(result.observation)
|
| 180 |
+
|
| 181 |
+
|
| 182 |
+
def reward_func(environments, **kwargs):
|
| 183 |
+
return [environment.reward for environment in environments]
|
| 184 |
+
|
| 185 |
+
|
| 186 |
+
def main():
|
| 187 |
+
args = parse_args()
|
| 188 |
+
CarlaGRPOEnv._env_url_iter = iter(args.env_urls)
|
| 189 |
+
|
| 190 |
+
dataset = Dataset.from_dict({"prompt": [[{"role": "user", "content": PROMPT}] for _ in range(1000)]})
|
| 191 |
+
|
| 192 |
+
trainer = GRPOTrainer(
|
| 193 |
+
model=args.model,
|
| 194 |
+
train_dataset=dataset,
|
| 195 |
+
reward_funcs=reward_func,
|
| 196 |
+
args=GRPOConfig(
|
| 197 |
+
chat_template_kwargs={"enable_thinking": False},
|
| 198 |
+
log_completions=True,
|
| 199 |
+
logging_steps=2,
|
| 200 |
+
num_completions_to_print=1,
|
| 201 |
+
max_completion_length=1024,
|
| 202 |
+
per_device_train_batch_size=len(args.env_urls),
|
| 203 |
+
steps_per_generation=1,
|
| 204 |
+
num_generations=len(args.env_urls),
|
| 205 |
+
gradient_accumulation_steps=16,
|
| 206 |
+
max_steps=50,
|
| 207 |
+
push_to_hub=args.hub_model_id is not None,
|
| 208 |
+
hub_model_id=args.hub_model_id,
|
| 209 |
+
run_name=args.run_name,
|
| 210 |
+
report_to="trackio",
|
| 211 |
+
trackio_space_id=args.trackio_space_id,
|
| 212 |
+
),
|
| 213 |
+
environment_factory=CarlaGRPOEnv,
|
| 214 |
+
)
|
| 215 |
+
trainer.train()
|
| 216 |
+
|
| 217 |
+
|
| 218 |
+
if __name__ == "__main__":
|
| 219 |
+
main()
|
tasks/tasksmith-fa1a9b35ff39/tests/source/examples/scripts/openenv/carla_vlm.py
ADDED
|
@@ -0,0 +1,262 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2020-2026 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
# /// script
|
| 16 |
+
# dependencies = [
|
| 17 |
+
# "trl",
|
| 18 |
+
# "openenv-carla-env @ git+https://huggingface.co/spaces/sergiopaniego/carla_env",
|
| 19 |
+
# ]
|
| 20 |
+
# ///
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
"""
|
| 24 |
+
GRPO training with OpenEnv's CARLA environment for VLMs (Vision Language Models).
|
| 25 |
+
|
| 26 |
+
VLM adaptation of `carla.py`: each tool call returns a camera image alongside the text
|
| 27 |
+
scene description, so the model sees the driving scene after each action.
|
| 28 |
+
|
| 29 |
+
Setup:
|
| 30 |
+
|
| 31 |
+
```sh
|
| 32 |
+
uv pip install git+https://huggingface.co/spaces/sergiopaniego/carla_env
|
| 33 |
+
```
|
| 34 |
+
|
| 35 |
+
Usage (requires at least 2 CARLA Spaces, each supports only 1 concurrent connection):
|
| 36 |
+
|
| 37 |
+
```sh
|
| 38 |
+
python examples/scripts/openenv/carla_vlm.py \
|
| 39 |
+
--model Qwen/Qwen3.5-0.8B \
|
| 40 |
+
--env-urls https://server1.hf.space https://server2.hf.space
|
| 41 |
+
```
|
| 42 |
+
"""
|
| 43 |
+
|
| 44 |
+
import argparse
|
| 45 |
+
import base64
|
| 46 |
+
from io import BytesIO
|
| 47 |
+
|
| 48 |
+
from carla_env import CarlaAction, CarlaEnv
|
| 49 |
+
from datasets import Dataset
|
| 50 |
+
from PIL import Image
|
| 51 |
+
|
| 52 |
+
from trl import GRPOConfig, GRPOTrainer
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def parse_args():
|
| 56 |
+
parser = argparse.ArgumentParser(description="Run GRPO VLM training with CARLA environment.")
|
| 57 |
+
parser.add_argument(
|
| 58 |
+
"--model",
|
| 59 |
+
type=str,
|
| 60 |
+
default="Qwen/Qwen3.5-0.8B",
|
| 61 |
+
help="Model to use for training.",
|
| 62 |
+
)
|
| 63 |
+
parser.add_argument(
|
| 64 |
+
"--env-urls",
|
| 65 |
+
type=str,
|
| 66 |
+
nargs="+",
|
| 67 |
+
default=["https://sergiopaniego-carla-env.hf.space"],
|
| 68 |
+
help="URLs for the CARLA environment servers (one per environment instance).",
|
| 69 |
+
)
|
| 70 |
+
parser.add_argument(
|
| 71 |
+
"--image-size",
|
| 72 |
+
type=int,
|
| 73 |
+
default=256,
|
| 74 |
+
help="Resize camera images to this size. 0 to disable.",
|
| 75 |
+
)
|
| 76 |
+
parser.add_argument(
|
| 77 |
+
"--max-completion-length",
|
| 78 |
+
type=int,
|
| 79 |
+
default=1024,
|
| 80 |
+
help="Maximum number of tokens in the generated completion.",
|
| 81 |
+
)
|
| 82 |
+
parser.add_argument(
|
| 83 |
+
"--gradient-accumulation-steps",
|
| 84 |
+
type=int,
|
| 85 |
+
default=16,
|
| 86 |
+
help="Number of steps to accumulate gradients over before updating.",
|
| 87 |
+
)
|
| 88 |
+
parser.add_argument(
|
| 89 |
+
"--max-steps",
|
| 90 |
+
type=int,
|
| 91 |
+
default=50,
|
| 92 |
+
help="Number of training steps to run.",
|
| 93 |
+
)
|
| 94 |
+
parser.add_argument(
|
| 95 |
+
"--trackio-space-id",
|
| 96 |
+
type=str,
|
| 97 |
+
default="carla-grpo-trolley-vlm",
|
| 98 |
+
help="Trackio space identifier.",
|
| 99 |
+
)
|
| 100 |
+
parser.add_argument(
|
| 101 |
+
"--hub-model-id",
|
| 102 |
+
type=str,
|
| 103 |
+
default=None,
|
| 104 |
+
help="Hub model ID to push the trained model to.",
|
| 105 |
+
)
|
| 106 |
+
parser.add_argument(
|
| 107 |
+
"--run-name",
|
| 108 |
+
type=str,
|
| 109 |
+
default=None,
|
| 110 |
+
help="Run name for tracking.",
|
| 111 |
+
)
|
| 112 |
+
return parser.parse_args()
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
PROMPT = """You control an autonomous vehicle in an emergency. There are pedestrians ahead and you must \
|
| 116 |
+
decide what to do immediately.
|
| 117 |
+
|
| 118 |
+
You will see a camera image from the vehicle after each action. Use the visual information
|
| 119 |
+
along with the scene description to decide your next action.
|
| 120 |
+
|
| 121 |
+
You have the following tools available:
|
| 122 |
+
- `observe`: Advance time and get a new observation of the scene with a camera image.
|
| 123 |
+
- `emergency_stop`: Apply maximum braking to stop the vehicle.
|
| 124 |
+
- `lane_change(direction)`: Change lane to the left or right. Direction must be "left" or "right".
|
| 125 |
+
|
| 126 |
+
Observe the scene first, then decide the best course of action to minimize harm."""
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
SIM_TICKS = 10 # Number of simulation steps to advance after each action
|
| 130 |
+
|
| 131 |
+
|
| 132 |
+
class CarlaGRPOEnv:
|
| 133 |
+
_env_url_iter = None
|
| 134 |
+
_image_size = 256
|
| 135 |
+
|
| 136 |
+
def __init__(self):
|
| 137 |
+
url = next(CarlaGRPOEnv._env_url_iter)
|
| 138 |
+
self.client = CarlaEnv(base_url=url, connect_timeout_s=30, message_timeout_s=120)
|
| 139 |
+
|
| 140 |
+
@staticmethod
|
| 141 |
+
def _describe(obs) -> str:
|
| 142 |
+
"""Build a text description from the observation fields."""
|
| 143 |
+
parts = [f"Speed: {obs.speed_kmh:.1f} km/h."]
|
| 144 |
+
if obs.nearby_actors:
|
| 145 |
+
for actor in obs.nearby_actors:
|
| 146 |
+
parts.append(f"- {actor.get('type', 'actor')} at {actor.get('distance', '?')}m")
|
| 147 |
+
else:
|
| 148 |
+
parts.append("No nearby actors detected.")
|
| 149 |
+
if obs.collision_detected:
|
| 150 |
+
parts.append(f"COLLISION detected with {obs.collided_with or 'unknown'}!")
|
| 151 |
+
return "\n".join(parts)
|
| 152 |
+
|
| 153 |
+
@staticmethod
|
| 154 |
+
def _decode_image(camera_image_b64, target_size):
|
| 155 |
+
"""Decode base64 JPEG image and optionally resize."""
|
| 156 |
+
img = Image.open(BytesIO(base64.b64decode(camera_image_b64)))
|
| 157 |
+
if target_size > 0:
|
| 158 |
+
img.thumbnail((target_size, target_size), Image.LANCZOS)
|
| 159 |
+
return img
|
| 160 |
+
|
| 161 |
+
def _format_multimodal(self, obs) -> list:
|
| 162 |
+
"""Format observation as multimodal content blocks (camera image + text)."""
|
| 163 |
+
content = []
|
| 164 |
+
if obs.camera_image is not None:
|
| 165 |
+
content.append({"type": "image", "image": self._decode_image(obs.camera_image, CarlaGRPOEnv._image_size)})
|
| 166 |
+
content.append({"type": "text", "text": self._describe(obs)})
|
| 167 |
+
return content
|
| 168 |
+
|
| 169 |
+
def _advance_and_capture(self, ticks: int = SIM_TICKS):
|
| 170 |
+
"""Advance the simulation, then capture an image of the current state."""
|
| 171 |
+
result = None
|
| 172 |
+
for _ in range(ticks):
|
| 173 |
+
result = self.client.step(CarlaAction(action_type="observe"))
|
| 174 |
+
if result.done:
|
| 175 |
+
break
|
| 176 |
+
capture_result = self.client.step(CarlaAction(action_type="capture_image"))
|
| 177 |
+
result.observation.camera_image = capture_result.observation.camera_image
|
| 178 |
+
return result
|
| 179 |
+
|
| 180 |
+
def reset(self, **kwargs) -> str | None:
|
| 181 |
+
result = self.client.reset(scenario_name="trolley_micro_escape_exists")
|
| 182 |
+
self.reward = 0.0
|
| 183 |
+
return self._describe(result.observation)
|
| 184 |
+
|
| 185 |
+
def observe(self) -> list:
|
| 186 |
+
"""
|
| 187 |
+
Get the current scene with a camera image and description.
|
| 188 |
+
|
| 189 |
+
Returns:
|
| 190 |
+
The camera image and scene description with vehicle state and nearby actors.
|
| 191 |
+
"""
|
| 192 |
+
result = self._advance_and_capture()
|
| 193 |
+
self.reward = result.observation.rubric_reward or 0.0
|
| 194 |
+
return self._format_multimodal(result.observation)
|
| 195 |
+
|
| 196 |
+
def emergency_stop(self) -> list:
|
| 197 |
+
"""
|
| 198 |
+
Apply maximum braking to stop the vehicle.
|
| 199 |
+
|
| 200 |
+
Returns:
|
| 201 |
+
The camera image and scene description after braking.
|
| 202 |
+
"""
|
| 203 |
+
self.client.step(CarlaAction(action_type="emergency_stop"))
|
| 204 |
+
result = self._advance_and_capture()
|
| 205 |
+
self.reward = result.observation.rubric_reward or 0.0
|
| 206 |
+
return self._format_multimodal(result.observation)
|
| 207 |
+
|
| 208 |
+
def lane_change(self, direction: str) -> list:
|
| 209 |
+
"""
|
| 210 |
+
Change lane to avoid obstacles.
|
| 211 |
+
|
| 212 |
+
Args:
|
| 213 |
+
direction: Direction to change lane, either "left" or "right".
|
| 214 |
+
|
| 215 |
+
Returns:
|
| 216 |
+
The camera image and scene description after changing lane.
|
| 217 |
+
"""
|
| 218 |
+
self.client.step(CarlaAction(action_type="lane_change", lane_direction=direction))
|
| 219 |
+
result = self._advance_and_capture()
|
| 220 |
+
self.reward = result.observation.rubric_reward or 0.0
|
| 221 |
+
return self._format_multimodal(result.observation)
|
| 222 |
+
|
| 223 |
+
|
| 224 |
+
def reward_func(environments, **kwargs):
|
| 225 |
+
return [environment.reward for environment in environments]
|
| 226 |
+
|
| 227 |
+
|
| 228 |
+
def main():
|
| 229 |
+
args = parse_args()
|
| 230 |
+
CarlaGRPOEnv._env_url_iter = iter(args.env_urls)
|
| 231 |
+
CarlaGRPOEnv._image_size = args.image_size
|
| 232 |
+
|
| 233 |
+
dataset = Dataset.from_dict({"prompt": [[{"role": "user", "content": PROMPT}] for _ in range(1000)]})
|
| 234 |
+
|
| 235 |
+
trainer = GRPOTrainer(
|
| 236 |
+
model=args.model,
|
| 237 |
+
train_dataset=dataset,
|
| 238 |
+
reward_funcs=reward_func,
|
| 239 |
+
args=GRPOConfig(
|
| 240 |
+
chat_template_kwargs={"enable_thinking": False},
|
| 241 |
+
log_completions=True,
|
| 242 |
+
logging_steps=2,
|
| 243 |
+
num_completions_to_print=1,
|
| 244 |
+
max_completion_length=args.max_completion_length,
|
| 245 |
+
per_device_train_batch_size=len(args.env_urls),
|
| 246 |
+
steps_per_generation=1,
|
| 247 |
+
num_generations=len(args.env_urls),
|
| 248 |
+
gradient_accumulation_steps=args.gradient_accumulation_steps,
|
| 249 |
+
max_steps=args.max_steps,
|
| 250 |
+
push_to_hub=args.hub_model_id is not None,
|
| 251 |
+
hub_model_id=args.hub_model_id,
|
| 252 |
+
run_name=args.run_name,
|
| 253 |
+
report_to="trackio",
|
| 254 |
+
trackio_space_id=args.trackio_space_id,
|
| 255 |
+
),
|
| 256 |
+
environment_factory=CarlaGRPOEnv,
|
| 257 |
+
)
|
| 258 |
+
trainer.train()
|
| 259 |
+
|
| 260 |
+
|
| 261 |
+
if __name__ == "__main__":
|
| 262 |
+
main()
|
tasks/tasksmith-fa1a9b35ff39/tests/source/examples/scripts/openenv/carla_vlm_gemma.py
ADDED
|
@@ -0,0 +1,278 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2020-2026 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
# /// script
|
| 16 |
+
# dependencies = [
|
| 17 |
+
# "trl",
|
| 18 |
+
# "openenv-carla-env @ git+https://huggingface.co/spaces/sergiopaniego/carla_env",
|
| 19 |
+
# ]
|
| 20 |
+
# ///
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
"""
|
| 24 |
+
GRPO training with OpenEnv's CARLA environment for Gemma VLMs.
|
| 25 |
+
|
| 26 |
+
Gemma-specific variant of `carla_vlm.py` with LoRA support (memory-efficient training
|
| 27 |
+
by excluding the vision encoder from adapter targets) and a tuned learning rate.
|
| 28 |
+
|
| 29 |
+
Setup:
|
| 30 |
+
|
| 31 |
+
```sh
|
| 32 |
+
uv pip install git+https://huggingface.co/spaces/sergiopaniego/carla_env
|
| 33 |
+
```
|
| 34 |
+
|
| 35 |
+
Usage (requires at least 2 CARLA Spaces, each supports only 1 concurrent connection):
|
| 36 |
+
|
| 37 |
+
```sh
|
| 38 |
+
python examples/scripts/openenv/carla_vlm_gemma.py \
|
| 39 |
+
--env-urls https://server1.hf.space https://server2.hf.space \
|
| 40 |
+
--use-lora
|
| 41 |
+
```
|
| 42 |
+
"""
|
| 43 |
+
|
| 44 |
+
import argparse
|
| 45 |
+
import base64
|
| 46 |
+
from io import BytesIO
|
| 47 |
+
|
| 48 |
+
from carla_env import CarlaAction, CarlaEnv
|
| 49 |
+
from datasets import Dataset
|
| 50 |
+
from PIL import Image
|
| 51 |
+
|
| 52 |
+
from trl import GRPOConfig, GRPOTrainer
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def parse_args():
|
| 56 |
+
parser = argparse.ArgumentParser(description="Run GRPO VLM training with CARLA environment.")
|
| 57 |
+
parser.add_argument("--model", type=str, default="google/gemma-4-E2B-it")
|
| 58 |
+
parser.add_argument(
|
| 59 |
+
"--env-urls",
|
| 60 |
+
type=str,
|
| 61 |
+
nargs="+",
|
| 62 |
+
required=True,
|
| 63 |
+
help="URLs for CARLA environment servers. At least 2 required (1 Space = 1 connection).",
|
| 64 |
+
)
|
| 65 |
+
parser.add_argument("--dataset-size", type=int, default=1000)
|
| 66 |
+
parser.add_argument("--max-completion-length", type=int, default=3072)
|
| 67 |
+
parser.add_argument("--per-device-train-batch-size", type=int, default=None, help="Defaults to len(env-urls).")
|
| 68 |
+
parser.add_argument("--gradient-accumulation-steps", type=int, default=16)
|
| 69 |
+
parser.add_argument("--max-steps", type=int, default=100)
|
| 70 |
+
parser.add_argument("--image-size", type=int, default=256, help="Resize camera images to this size. 0 to disable.")
|
| 71 |
+
parser.add_argument("--trackio-space-id", type=str, default=None, help="Trackio Space ID for logging.")
|
| 72 |
+
parser.add_argument("--use-lora", action="store_true", help="Use LoRA for memory-efficient training.")
|
| 73 |
+
parser.add_argument("--lora-r", type=int, default=128, help="LoRA rank.")
|
| 74 |
+
parser.add_argument("--lora-alpha", type=int, default=256, help="LoRA alpha.")
|
| 75 |
+
parser.add_argument(
|
| 76 |
+
"--lora-target-modules",
|
| 77 |
+
type=str,
|
| 78 |
+
default="llm-only",
|
| 79 |
+
help="LoRA target modules. Use 'llm-only' to skip vision encoder, 'all-linear' for all.",
|
| 80 |
+
)
|
| 81 |
+
parser.add_argument(
|
| 82 |
+
"--learning-rate", type=float, default=5e-6, help="Learning rate. Default 5e-6 (good for LoRA r=128)."
|
| 83 |
+
)
|
| 84 |
+
parser.add_argument("--hub-model-id", type=str, default=None)
|
| 85 |
+
parser.add_argument("--run-name", type=str, default=None)
|
| 86 |
+
parser.add_argument("--report-to", type=str, default="trackio", help="Logging backend: wandb, trackio, none.")
|
| 87 |
+
return parser.parse_args()
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
PROMPT = """\
|
| 91 |
+
You control an autonomous vehicle in an emergency. There are pedestrians ahead and you must \
|
| 92 |
+
decide what to do immediately.
|
| 93 |
+
|
| 94 |
+
You will see a camera image from the vehicle after each action. Use the visual information
|
| 95 |
+
along with the scene description to decide your next action.
|
| 96 |
+
|
| 97 |
+
You have the following tools available:
|
| 98 |
+
- `observe`: Advance time and get a new observation of the scene with a camera image.
|
| 99 |
+
- `emergency_stop`: Apply maximum braking to stop the vehicle.
|
| 100 |
+
- `lane_change(direction)`: Change lane to the left or right. Direction must be "left" or "right".
|
| 101 |
+
|
| 102 |
+
Make one tool call at a time, wait for the result, then decide your next action.
|
| 103 |
+
Observe the scene first, then decide the best course of action to minimize harm.
|
| 104 |
+
Consider all available actions - sometimes avoiding the obstacle by changing lanes \
|
| 105 |
+
is safer than stopping in its path."""
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
SIM_TICKS = 10 # Number of simulation steps to advance after each action
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
class CarlaVLMEnv:
|
| 112 |
+
_env_url_iter = None
|
| 113 |
+
_image_size = 256
|
| 114 |
+
|
| 115 |
+
def __init__(self):
|
| 116 |
+
self.url = next(CarlaVLMEnv._env_url_iter)
|
| 117 |
+
self.client = CarlaEnv(base_url=self.url, connect_timeout_s=30, message_timeout_s=120)
|
| 118 |
+
self.reward = 0.0
|
| 119 |
+
|
| 120 |
+
@staticmethod
|
| 121 |
+
def _describe(obs) -> str:
|
| 122 |
+
parts = [f"Speed: {obs.speed_kmh:.1f} km/h."]
|
| 123 |
+
if obs.nearby_actors:
|
| 124 |
+
for actor in obs.nearby_actors:
|
| 125 |
+
parts.append(f"- {actor.get('type', 'actor')} at {actor.get('distance', '?')}m")
|
| 126 |
+
else:
|
| 127 |
+
parts.append("No nearby actors detected.")
|
| 128 |
+
if obs.collision_detected:
|
| 129 |
+
parts.append(f"COLLISION detected with {obs.collided_with or 'unknown'}!")
|
| 130 |
+
return "\n".join(parts)
|
| 131 |
+
|
| 132 |
+
@staticmethod
|
| 133 |
+
def _decode_image(camera_image_b64, target_size):
|
| 134 |
+
"""Decode base64 JPEG image and optionally resize."""
|
| 135 |
+
img = Image.open(BytesIO(base64.b64decode(camera_image_b64)))
|
| 136 |
+
if target_size > 0:
|
| 137 |
+
img.thumbnail((target_size, target_size), Image.LANCZOS)
|
| 138 |
+
return img
|
| 139 |
+
|
| 140 |
+
def _format_multimodal(self, obs) -> list:
|
| 141 |
+
"""Format observation as multimodal content blocks (camera image + text)."""
|
| 142 |
+
content = []
|
| 143 |
+
if obs.camera_image is not None:
|
| 144 |
+
content.append({"type": "image", "image": self._decode_image(obs.camera_image, CarlaVLMEnv._image_size)})
|
| 145 |
+
content.append({"type": "text", "text": self._describe(obs)})
|
| 146 |
+
return content
|
| 147 |
+
|
| 148 |
+
def _advance_and_capture(self, ticks: int = SIM_TICKS):
|
| 149 |
+
"""Advance the simulation, then capture an image of the current state."""
|
| 150 |
+
result = None
|
| 151 |
+
for _ in range(ticks):
|
| 152 |
+
result = self.client.step(CarlaAction(action_type="observe"))
|
| 153 |
+
if result.done:
|
| 154 |
+
break
|
| 155 |
+
capture_result = self.client.step(CarlaAction(action_type="capture_image"))
|
| 156 |
+
result.observation.camera_image = capture_result.observation.camera_image
|
| 157 |
+
return result
|
| 158 |
+
|
| 159 |
+
def reset(self, **kwargs) -> str | None:
|
| 160 |
+
for attempt in range(3):
|
| 161 |
+
try:
|
| 162 |
+
result = self.client.reset(scenario_name="trolley_micro_escape_exists")
|
| 163 |
+
self.reward = 0.0
|
| 164 |
+
return self._describe(result.observation)
|
| 165 |
+
except Exception as e:
|
| 166 |
+
if attempt == 2:
|
| 167 |
+
raise
|
| 168 |
+
print(f"[WARN] reset failed (attempt {attempt + 1}/3): {e}. Reconnecting...")
|
| 169 |
+
self.client = CarlaEnv(base_url=self.url, connect_timeout_s=30, message_timeout_s=120)
|
| 170 |
+
|
| 171 |
+
def observe(self) -> list:
|
| 172 |
+
"""
|
| 173 |
+
Get the current scene with a camera image and description.
|
| 174 |
+
|
| 175 |
+
Returns:
|
| 176 |
+
The camera image and scene description with vehicle state and nearby actors.
|
| 177 |
+
"""
|
| 178 |
+
result = self._advance_and_capture()
|
| 179 |
+
self.reward = result.observation.rubric_reward or 0.0
|
| 180 |
+
return self._format_multimodal(result.observation)
|
| 181 |
+
|
| 182 |
+
def emergency_stop(self) -> list:
|
| 183 |
+
"""
|
| 184 |
+
Apply maximum braking to stop the vehicle.
|
| 185 |
+
|
| 186 |
+
Returns:
|
| 187 |
+
The camera image and scene description after braking.
|
| 188 |
+
"""
|
| 189 |
+
self.client.step(CarlaAction(action_type="emergency_stop"))
|
| 190 |
+
result = self._advance_and_capture()
|
| 191 |
+
self.reward = result.observation.rubric_reward or 0.0
|
| 192 |
+
print(f"[DEBUG env] emergency_stop: done={result.done}, reward={self.reward}")
|
| 193 |
+
return self._format_multimodal(result.observation)
|
| 194 |
+
|
| 195 |
+
def lane_change(self, direction: str) -> list:
|
| 196 |
+
"""
|
| 197 |
+
Change lane to avoid obstacles.
|
| 198 |
+
|
| 199 |
+
Args:
|
| 200 |
+
direction: Direction to change lane, either "left" or "right".
|
| 201 |
+
|
| 202 |
+
Returns:
|
| 203 |
+
The camera image and scene description after changing lane.
|
| 204 |
+
"""
|
| 205 |
+
self.client.step(CarlaAction(action_type="lane_change", lane_direction=direction))
|
| 206 |
+
result = self._advance_and_capture()
|
| 207 |
+
self.reward = result.observation.rubric_reward or 0.0
|
| 208 |
+
print(f"[DEBUG env] lane_change({direction}): done={result.done}, reward={self.reward}")
|
| 209 |
+
return self._format_multimodal(result.observation)
|
| 210 |
+
|
| 211 |
+
|
| 212 |
+
def reward_func(completions, environments, **kwargs):
|
| 213 |
+
rewards = [env.reward for env in environments]
|
| 214 |
+
for i, (comp, env) in enumerate(zip(completions, environments, strict=False)):
|
| 215 |
+
tools = [
|
| 216 |
+
msg["tool_calls"][0]["function"]["name"] for msg in comp if isinstance(msg, dict) and msg.get("tool_calls")
|
| 217 |
+
]
|
| 218 |
+
print(f"[DEBUG reward] gen={i} tools={tools} env_reward={env.reward}")
|
| 219 |
+
return rewards
|
| 220 |
+
|
| 221 |
+
|
| 222 |
+
def main():
|
| 223 |
+
args = parse_args()
|
| 224 |
+
CarlaVLMEnv._env_url_iter = iter(args.env_urls)
|
| 225 |
+
CarlaVLMEnv._image_size = args.image_size
|
| 226 |
+
|
| 227 |
+
dataset = Dataset.from_dict({"prompt": [[{"role": "user", "content": PROMPT}] for _ in range(args.dataset_size)]})
|
| 228 |
+
|
| 229 |
+
peft_config = None
|
| 230 |
+
if args.use_lora:
|
| 231 |
+
from peft import LoraConfig
|
| 232 |
+
|
| 233 |
+
if args.lora_target_modules == "llm-only":
|
| 234 |
+
target_modules = "all-linear"
|
| 235 |
+
exclude_modules = ["vision_tower", "multi_modal_projector"]
|
| 236 |
+
else:
|
| 237 |
+
target_modules = args.lora_target_modules
|
| 238 |
+
exclude_modules = None
|
| 239 |
+
|
| 240 |
+
peft_config = LoraConfig(
|
| 241 |
+
r=args.lora_r,
|
| 242 |
+
lora_alpha=args.lora_alpha,
|
| 243 |
+
target_modules=target_modules,
|
| 244 |
+
exclude_modules=exclude_modules,
|
| 245 |
+
task_type="CAUSAL_LM",
|
| 246 |
+
)
|
| 247 |
+
|
| 248 |
+
trainer = GRPOTrainer(
|
| 249 |
+
model=args.model,
|
| 250 |
+
train_dataset=dataset,
|
| 251 |
+
reward_funcs=reward_func,
|
| 252 |
+
peft_config=peft_config,
|
| 253 |
+
args=GRPOConfig(
|
| 254 |
+
chat_template_kwargs={"enable_thinking": False},
|
| 255 |
+
log_completions=True,
|
| 256 |
+
logging_steps=2,
|
| 257 |
+
num_completions_to_print=1,
|
| 258 |
+
max_completion_length=args.max_completion_length,
|
| 259 |
+
per_device_train_batch_size=args.per_device_train_batch_size or len(args.env_urls),
|
| 260 |
+
steps_per_generation=1,
|
| 261 |
+
num_generations=len(args.env_urls),
|
| 262 |
+
max_tool_calling_iterations=10,
|
| 263 |
+
learning_rate=args.learning_rate,
|
| 264 |
+
gradient_accumulation_steps=args.gradient_accumulation_steps,
|
| 265 |
+
max_steps=args.max_steps,
|
| 266 |
+
push_to_hub=args.hub_model_id is not None,
|
| 267 |
+
hub_model_id=args.hub_model_id,
|
| 268 |
+
run_name=args.run_name,
|
| 269 |
+
report_to=args.report_to,
|
| 270 |
+
trackio_space_id=args.trackio_space_id,
|
| 271 |
+
),
|
| 272 |
+
environment_factory=CarlaVLMEnv,
|
| 273 |
+
)
|
| 274 |
+
trainer.train()
|
| 275 |
+
|
| 276 |
+
|
| 277 |
+
if __name__ == "__main__":
|
| 278 |
+
main()
|
tasks/tasksmith-fa1a9b35ff39/tests/source/examples/scripts/openenv/catch.py
ADDED
|
@@ -0,0 +1,347 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2020-2026 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
# /// script
|
| 16 |
+
# dependencies = [
|
| 17 |
+
# "trl[vllm,peft]",
|
| 18 |
+
# "trackio",
|
| 19 |
+
# "kernels",
|
| 20 |
+
# "openenv-openspiel-env @ git+https://huggingface.co/spaces/openenv/openspiel_env",
|
| 21 |
+
# ]
|
| 22 |
+
# ///
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
"""
|
| 26 |
+
Simple script to run GRPO training with OpenEnv's Catch environment (OpenSpiel) and vLLM. The reward function
|
| 27 |
+
is based on the catch game where the agent tries to catch falling balls.
|
| 28 |
+
|
| 29 |
+
Setup (Option A - Install from HF Space, recommended):
|
| 30 |
+
|
| 31 |
+
```sh
|
| 32 |
+
uv pip install git+https://huggingface.co/spaces/openenv/openspiel_env
|
| 33 |
+
```
|
| 34 |
+
|
| 35 |
+
Setup (Option B - Clone OpenEnv repo, for development):
|
| 36 |
+
|
| 37 |
+
```sh
|
| 38 |
+
git clone https://github.com/huggingface/OpenEnv.git
|
| 39 |
+
cd OpenEnv/envs/openspiel_env
|
| 40 |
+
uv pip install -e .
|
| 41 |
+
```
|
| 42 |
+
|
| 43 |
+
# Option 1: HF Spaces + Colocated vLLM (1 GPU required)
|
| 44 |
+
```sh
|
| 45 |
+
python examples/scripts/openenv/catch.py --env-mode space --env-host https://openenv-openspiel-env.hf.space --vllm-mode colocate
|
| 46 |
+
```
|
| 47 |
+
|
| 48 |
+
# Option 2: HF Spaces + Separate vLLM server (2 GPUs required)
|
| 49 |
+
|
| 50 |
+
# Spin up vLLM server (Terminal 1)
|
| 51 |
+
```sh
|
| 52 |
+
CUDA_VISIBLE_DEVICES=0 trl vllm-serve --model Qwen/Qwen2.5-0.5B-Instruct --host 0.0.0.0 --port 8000
|
| 53 |
+
```
|
| 54 |
+
|
| 55 |
+
# Run training (Terminal 2)
|
| 56 |
+
```sh
|
| 57 |
+
CUDA_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
|
| 58 |
+
```
|
| 59 |
+
|
| 60 |
+
# Option 3: Local + Colocated vLLM (1 GPU required)
|
| 61 |
+
|
| 62 |
+
# Start the environment only if using --env-mode docker-local
|
| 63 |
+
```sh
|
| 64 |
+
docker run -d -p 8001:8001 registry.hf.space/openenv-openspiel-env:latest
|
| 65 |
+
```
|
| 66 |
+
|
| 67 |
+
```sh
|
| 68 |
+
python examples/scripts/openenv/catch.py --env-mode docker-local --vllm-mode colocate
|
| 69 |
+
```
|
| 70 |
+
"""
|
| 71 |
+
|
| 72 |
+
# ruff: noqa: T201
|
| 73 |
+
import argparse
|
| 74 |
+
import os
|
| 75 |
+
import subprocess
|
| 76 |
+
import sys
|
| 77 |
+
import time
|
| 78 |
+
from pathlib import Path
|
| 79 |
+
|
| 80 |
+
import requests
|
| 81 |
+
from datasets import Dataset
|
| 82 |
+
from openspiel_env import OpenSpielEnv
|
| 83 |
+
from openspiel_env.models import OpenSpielAction
|
| 84 |
+
|
| 85 |
+
from trl import GRPOConfig, GRPOTrainer, RichProgressCallback
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
def parse_args():
|
| 89 |
+
parser = argparse.ArgumentParser(description="Run GRPO training with OpenSpiel Catch environment and vLLM.")
|
| 90 |
+
|
| 91 |
+
# --- Environment settings ---
|
| 92 |
+
parser.add_argument("--env-host", type=str, default="0.0.0.0", help="Host for the environment server.")
|
| 93 |
+
parser.add_argument("--env-port", type=int, default=8001, help="Port for the environment server.")
|
| 94 |
+
parser.add_argument(
|
| 95 |
+
"--env-mode",
|
| 96 |
+
choices=["local", "docker-local", "docker-image", "docker-hub", "space"],
|
| 97 |
+
default="docker-image",
|
| 98 |
+
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.",
|
| 99 |
+
)
|
| 100 |
+
# --- Generation and model config ---
|
| 101 |
+
parser.add_argument(
|
| 102 |
+
"--model",
|
| 103 |
+
type=str,
|
| 104 |
+
default="Qwen/Qwen2.5-0.5B-Instruct",
|
| 105 |
+
help="Model name or path.",
|
| 106 |
+
)
|
| 107 |
+
parser.add_argument(
|
| 108 |
+
"--dataset-size",
|
| 109 |
+
type=int,
|
| 110 |
+
default=1000,
|
| 111 |
+
help="Number of prompts to use for training dataset.",
|
| 112 |
+
)
|
| 113 |
+
parser.add_argument(
|
| 114 |
+
"--env-image", type=str, default="openspiel-env:latest", help="Docker image for the OpenSpiel environment."
|
| 115 |
+
)
|
| 116 |
+
parser.add_argument(
|
| 117 |
+
"--vllm-mode",
|
| 118 |
+
choices=["colocate", "server"],
|
| 119 |
+
default="colocate",
|
| 120 |
+
help="vLLM execution mode: 'colocate' or 'server'.",
|
| 121 |
+
)
|
| 122 |
+
parser.add_argument(
|
| 123 |
+
"--vllm-server-url",
|
| 124 |
+
type=str,
|
| 125 |
+
default="http://localhost:8000",
|
| 126 |
+
help="URL for the vLLM server (only used when --vllm-mode=server).",
|
| 127 |
+
)
|
| 128 |
+
|
| 129 |
+
return parser.parse_args()
|
| 130 |
+
|
| 131 |
+
|
| 132 |
+
def start_env_server(env_host: str, env_port: int):
|
| 133 |
+
"""Launch the OpenSpiel Catch environment locally via uvicorn."""
|
| 134 |
+
env_url = f"http://{env_host}:{env_port}"
|
| 135 |
+
print(f"⚡ Starting FastAPI server for OpenSpiel Catch Environment on {env_url}...")
|
| 136 |
+
|
| 137 |
+
work_dir = str(Path.cwd().parent.absolute())
|
| 138 |
+
process = subprocess.Popen(
|
| 139 |
+
[
|
| 140 |
+
sys.executable,
|
| 141 |
+
"-m",
|
| 142 |
+
"uvicorn",
|
| 143 |
+
"envs.openspiel_env.server.app:app",
|
| 144 |
+
"--host",
|
| 145 |
+
env_host,
|
| 146 |
+
"--port",
|
| 147 |
+
str(env_port),
|
| 148 |
+
],
|
| 149 |
+
env={**os.environ, "PYTHONPATH": f"{work_dir}/src"},
|
| 150 |
+
stdout=subprocess.PIPE,
|
| 151 |
+
stderr=subprocess.PIPE,
|
| 152 |
+
text=True,
|
| 153 |
+
cwd=work_dir,
|
| 154 |
+
)
|
| 155 |
+
|
| 156 |
+
print("⏳ Waiting for server to start...")
|
| 157 |
+
time.sleep(5)
|
| 158 |
+
|
| 159 |
+
try:
|
| 160 |
+
requests.get(f"{env_url}/health", timeout=2)
|
| 161 |
+
print("\n✅ OpenSpiel Catch Environment server is running!")
|
| 162 |
+
except Exception as e:
|
| 163 |
+
print(f"\n❌ Server failed to start: {e}")
|
| 164 |
+
if process.stderr:
|
| 165 |
+
print(process.stderr.read())
|
| 166 |
+
raise
|
| 167 |
+
|
| 168 |
+
return process
|
| 169 |
+
|
| 170 |
+
|
| 171 |
+
BASE_PROMPT = """You are an AI agent playing the game **Catch**.
|
| 172 |
+
|
| 173 |
+
### Game Description
|
| 174 |
+
- The game is played on a **10×5 grid**.
|
| 175 |
+
- There is one **falling ball** and one **paddle** that you control at the bottom.
|
| 176 |
+
- The objective is to **move the paddle left or right to catch the ball** as it falls.
|
| 177 |
+
- The episode ends when the ball reaches the bottom row:
|
| 178 |
+
- You get **+1 reward** if you catch it.
|
| 179 |
+
- You get **–1 reward** if you miss it.
|
| 180 |
+
|
| 181 |
+
### Observation Format
|
| 182 |
+
Each observation is a flattened 10x5 grid (list of 50 floats).
|
| 183 |
+
- 1.0 → occupied (ball or paddle)
|
| 184 |
+
- 0.0 → empty cell
|
| 185 |
+
|
| 186 |
+
You have the following tools available:
|
| 187 |
+
- `move(direction)`: Move the paddle left or right. Direction must be "left" or "right".
|
| 188 |
+
- `stay`: Do nothing and let the ball fall one step.
|
| 189 |
+
|
| 190 |
+
Observe the grid, determine where the ball is relative to the paddle, then move accordingly.
|
| 191 |
+
"""
|
| 192 |
+
|
| 193 |
+
|
| 194 |
+
def reward_from_env(environments, **kwargs):
|
| 195 |
+
rewards = []
|
| 196 |
+
for env in environments:
|
| 197 |
+
if env.done:
|
| 198 |
+
# Catch gives +1 for catching, -1 for missing. Clamp to [0, 1] for GRPO advantage estimation.
|
| 199 |
+
rewards.append(max(env.reward, 0.0))
|
| 200 |
+
else:
|
| 201 |
+
rewards.append(0.0) # Incomplete episode
|
| 202 |
+
return rewards
|
| 203 |
+
|
| 204 |
+
|
| 205 |
+
def main():
|
| 206 |
+
args = parse_args()
|
| 207 |
+
|
| 208 |
+
# Select environment mode — all modes resolve to env_url
|
| 209 |
+
if args.env_mode == "local":
|
| 210 |
+
env_url = f"http://{args.env_host}:{args.env_port}"
|
| 211 |
+
server_process = start_env_server(args.env_host, args.env_port)
|
| 212 |
+
elif args.env_mode == "docker-local":
|
| 213 |
+
env_url = f"http://{args.env_host}:{args.env_port}"
|
| 214 |
+
server_process = None
|
| 215 |
+
print(f"🌍 Using existing OpenSpiel Environment (Docker) at: {env_url}")
|
| 216 |
+
elif args.env_mode == "docker-image":
|
| 217 |
+
_bootstrap = OpenSpielEnv.from_docker_image(args.env_image)
|
| 218 |
+
env_url = _bootstrap.base_url
|
| 219 |
+
server_process = None
|
| 220 |
+
print("🌍 Using OpenSpiel Environment (Docker) from local Image")
|
| 221 |
+
elif args.env_mode == "docker-hub":
|
| 222 |
+
_bootstrap = OpenSpielEnv.from_hub(args.env_image)
|
| 223 |
+
env_url = _bootstrap.base_url
|
| 224 |
+
server_process = None
|
| 225 |
+
print("🌍 Using existing OpenSpiel Environment (Docker) from Hub Image")
|
| 226 |
+
elif args.env_mode == "space":
|
| 227 |
+
env_url = args.env_host
|
| 228 |
+
server_process = None
|
| 229 |
+
print(f"🌍 Using Hugging Face Space environment at: {env_url}")
|
| 230 |
+
else:
|
| 231 |
+
raise ValueError(f"Unknown environment mode: {args.env_mode}")
|
| 232 |
+
|
| 233 |
+
dataset = Dataset.from_dict({"prompt": [[{"role": "user", "content": BASE_PROMPT}]] * args.dataset_size})
|
| 234 |
+
|
| 235 |
+
class CatchEnv:
|
| 236 |
+
ROWS = 10
|
| 237 |
+
COLS = 5
|
| 238 |
+
|
| 239 |
+
def __init__(self):
|
| 240 |
+
self.client = OpenSpielEnv(base_url=env_url)
|
| 241 |
+
self.reward = 0.0
|
| 242 |
+
self.done = False
|
| 243 |
+
|
| 244 |
+
@staticmethod
|
| 245 |
+
def _format_obs(info_state: list[float]) -> str:
|
| 246 |
+
"""Convert the flat 50-float observation into a readable text description."""
|
| 247 |
+
rows, cols = CatchEnv.ROWS, CatchEnv.COLS
|
| 248 |
+
ball_row = ball_col = paddle_col = None
|
| 249 |
+
for idx, val in enumerate(info_state):
|
| 250 |
+
if val == 1.0:
|
| 251 |
+
r, c = divmod(idx, cols)
|
| 252 |
+
if r < rows - 1:
|
| 253 |
+
ball_row, ball_col = r + 1, c + 1
|
| 254 |
+
else:
|
| 255 |
+
paddle_col = c + 1
|
| 256 |
+
parts = []
|
| 257 |
+
if ball_row is not None and ball_col is not None:
|
| 258 |
+
parts.append(f"Ball: row {ball_row}/{rows}, column {ball_col}/{cols}")
|
| 259 |
+
if paddle_col is not None:
|
| 260 |
+
parts.append(f"Paddle: column {paddle_col}/{cols}")
|
| 261 |
+
if ball_col is not None and paddle_col is not None:
|
| 262 |
+
diff = ball_col - paddle_col
|
| 263 |
+
if diff < 0:
|
| 264 |
+
parts.append(f"The ball is {abs(diff)} column(s) to the LEFT of the paddle.")
|
| 265 |
+
elif diff > 0:
|
| 266 |
+
parts.append(f"The ball is {diff} column(s) to the RIGHT of the paddle.")
|
| 267 |
+
else:
|
| 268 |
+
parts.append("The ball is directly above the paddle.")
|
| 269 |
+
return "\n".join(parts)
|
| 270 |
+
|
| 271 |
+
def reset(self, **kwargs) -> str:
|
| 272 |
+
env_result = self.client.reset()
|
| 273 |
+
self.reward = 0.0
|
| 274 |
+
self.done = env_result.observation.done
|
| 275 |
+
return self._format_obs(env_result.observation.info_state)
|
| 276 |
+
|
| 277 |
+
def _do_action(self, action_id: int) -> str:
|
| 278 |
+
if self.done:
|
| 279 |
+
raise ValueError("Episode is done.")
|
| 280 |
+
env_result = self.client.step(OpenSpielAction(action_id=action_id, game_name="catch"))
|
| 281 |
+
self.reward = env_result.reward or 0.0
|
| 282 |
+
self.done = env_result.observation.done
|
| 283 |
+
return self._format_obs(env_result.observation.info_state)
|
| 284 |
+
|
| 285 |
+
def move(self, direction: str) -> str:
|
| 286 |
+
"""Move the paddle left or right.
|
| 287 |
+
|
| 288 |
+
Args:
|
| 289 |
+
direction: Direction to move, either "left" or "right".
|
| 290 |
+
|
| 291 |
+
Returns:
|
| 292 |
+
The observation after moving.
|
| 293 |
+
"""
|
| 294 |
+
if direction == "left":
|
| 295 |
+
action_id = 0
|
| 296 |
+
elif direction == "right":
|
| 297 |
+
action_id = 2
|
| 298 |
+
else:
|
| 299 |
+
raise ValueError(f"Invalid direction {direction!r}: must be 'left' or 'right'.")
|
| 300 |
+
return self._do_action(action_id)
|
| 301 |
+
|
| 302 |
+
def stay(self) -> str:
|
| 303 |
+
"""Do nothing and let the ball fall one step.
|
| 304 |
+
|
| 305 |
+
Returns:
|
| 306 |
+
The observation after staying.
|
| 307 |
+
"""
|
| 308 |
+
return self._do_action(1)
|
| 309 |
+
|
| 310 |
+
training_args = GRPOConfig(
|
| 311 |
+
output_dir=f"{args.model.split('/')[-1]}-GRPO-Catch",
|
| 312 |
+
use_vllm=True,
|
| 313 |
+
vllm_mode=args.vllm_mode,
|
| 314 |
+
vllm_server_base_url=args.vllm_server_url if args.vllm_mode == "server" else None,
|
| 315 |
+
vllm_gpu_memory_utilization=0.2,
|
| 316 |
+
logging_steps=1,
|
| 317 |
+
log_completions=True,
|
| 318 |
+
report_to="trackio",
|
| 319 |
+
trackio_space_id=f"{args.model.split('/')[-1]}-GRPO-Catch",
|
| 320 |
+
num_train_epochs=1,
|
| 321 |
+
per_device_train_batch_size=2,
|
| 322 |
+
num_generations=8,
|
| 323 |
+
max_completion_length=4096,
|
| 324 |
+
gradient_accumulation_steps=16,
|
| 325 |
+
chat_template_kwargs={"enable_thinking": False},
|
| 326 |
+
)
|
| 327 |
+
|
| 328 |
+
trainer = GRPOTrainer(
|
| 329 |
+
model=args.model,
|
| 330 |
+
reward_funcs=reward_from_env,
|
| 331 |
+
args=training_args,
|
| 332 |
+
train_dataset=dataset,
|
| 333 |
+
environment_factory=CatchEnv,
|
| 334 |
+
callbacks=[RichProgressCallback()],
|
| 335 |
+
)
|
| 336 |
+
|
| 337 |
+
try:
|
| 338 |
+
trainer.train()
|
| 339 |
+
finally:
|
| 340 |
+
if server_process:
|
| 341 |
+
print("🛑 Terminating environment server...")
|
| 342 |
+
server_process.terminate()
|
| 343 |
+
server_process.wait()
|
| 344 |
+
|
| 345 |
+
|
| 346 |
+
if __name__ == "__main__":
|
| 347 |
+
main()
|
tasks/tasksmith-fa1a9b35ff39/tests/source/examples/scripts/openenv/echo.py
ADDED
|
@@ -0,0 +1,133 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2020-2026 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
# /// script
|
| 16 |
+
# dependencies = [
|
| 17 |
+
# "trl",
|
| 18 |
+
# "openenv-echo-env @ git+https://huggingface.co/spaces/qgallouedec/echo_env",
|
| 19 |
+
# ]
|
| 20 |
+
# ///
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
"""
|
| 24 |
+
Simple script to run GRPO training with OpenEnv's Echo environment. The environment echoes back the message
|
| 25 |
+
sent to it and rewards longer completions.
|
| 26 |
+
|
| 27 |
+
Setup (Option A - Install from HF Space, recommended):
|
| 28 |
+
|
| 29 |
+
```sh
|
| 30 |
+
uv pip install git+https://huggingface.co/spaces/qgallouedec/echo_env
|
| 31 |
+
```
|
| 32 |
+
|
| 33 |
+
Setup (Option B - Clone OpenEnv repo, for development):
|
| 34 |
+
|
| 35 |
+
```sh
|
| 36 |
+
git clone https://github.com/huggingface/OpenEnv.git
|
| 37 |
+
cd OpenEnv/envs/echo_env
|
| 38 |
+
uv pip install -e .
|
| 39 |
+
```
|
| 40 |
+
|
| 41 |
+
Usage:
|
| 42 |
+
|
| 43 |
+
```sh
|
| 44 |
+
python examples/scripts/openenv/echo.py
|
| 45 |
+
python examples/scripts/openenv/echo.py --model Qwen/Qwen2.5-0.5B-Instruct --env-host https://qgallouedec-echo-env.hf.space
|
| 46 |
+
```
|
| 47 |
+
"""
|
| 48 |
+
|
| 49 |
+
import argparse
|
| 50 |
+
|
| 51 |
+
from datasets import Dataset
|
| 52 |
+
from echo_env import EchoEnv
|
| 53 |
+
from echo_env.models import EchoAction
|
| 54 |
+
|
| 55 |
+
from trl import GRPOConfig, GRPOTrainer
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
def parse_args():
|
| 59 |
+
parser = argparse.ArgumentParser(description="Run GRPO training with Echo environment.")
|
| 60 |
+
parser.add_argument(
|
| 61 |
+
"--model",
|
| 62 |
+
type=str,
|
| 63 |
+
default="Qwen/Qwen3-0.6B",
|
| 64 |
+
help="Model to use for training.",
|
| 65 |
+
)
|
| 66 |
+
parser.add_argument(
|
| 67 |
+
"--env-host",
|
| 68 |
+
type=str,
|
| 69 |
+
default="https://qgallouedec-echo-env.hf.space",
|
| 70 |
+
help="URL for the Echo environment HF Space.",
|
| 71 |
+
)
|
| 72 |
+
return parser.parse_args()
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
def reward_func(environments, **kwargs):
|
| 76 |
+
return [env.reward for env in environments]
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
def main():
|
| 80 |
+
args = parse_args()
|
| 81 |
+
|
| 82 |
+
dataset = Dataset.from_dict(
|
| 83 |
+
{
|
| 84 |
+
"prompt": [
|
| 85 |
+
[{"role": "user", "content": "Try to echo 'Hello World!' in the environment."}],
|
| 86 |
+
[{"role": "user", "content": "Make the environment echo 'Goodbye World!'"}],
|
| 87 |
+
[{"role": "user", "content": "Can you ask the environment to echo 'TRL is great!'?"}],
|
| 88 |
+
[{"role": "user", "content": "What happens if you ask the environment to echo 'I love RLHF!'?"}],
|
| 89 |
+
[{"role": "user", "content": "Try to make the environment echo 'OpenEnv is awesome!'"}],
|
| 90 |
+
],
|
| 91 |
+
}
|
| 92 |
+
)
|
| 93 |
+
|
| 94 |
+
class EchoToolEnv:
|
| 95 |
+
def __init__(self):
|
| 96 |
+
self.env = EchoEnv(base_url=args.env_host)
|
| 97 |
+
self.reward = 0.0
|
| 98 |
+
|
| 99 |
+
def reset(self, **kwargs) -> None | str:
|
| 100 |
+
self.reward = 0.0
|
| 101 |
+
return None
|
| 102 |
+
|
| 103 |
+
def echo(self, message: str) -> str:
|
| 104 |
+
"""
|
| 105 |
+
Echo the message back from the environment.
|
| 106 |
+
|
| 107 |
+
Args:
|
| 108 |
+
message: The message to echo
|
| 109 |
+
|
| 110 |
+
Returns:
|
| 111 |
+
The echoed message.
|
| 112 |
+
"""
|
| 113 |
+
observation = self.env.step(EchoAction(message=message))
|
| 114 |
+
self.reward = observation.observation.reward
|
| 115 |
+
return observation.observation.echoed_message
|
| 116 |
+
|
| 117 |
+
trainer = GRPOTrainer(
|
| 118 |
+
model=args.model,
|
| 119 |
+
train_dataset=dataset,
|
| 120 |
+
reward_funcs=reward_func,
|
| 121 |
+
args=GRPOConfig(
|
| 122 |
+
chat_template_kwargs={"enable_thinking": False},
|
| 123 |
+
log_completions=True,
|
| 124 |
+
logging_steps=2,
|
| 125 |
+
num_completions_to_print=1,
|
| 126 |
+
),
|
| 127 |
+
environment_factory=EchoToolEnv,
|
| 128 |
+
)
|
| 129 |
+
trainer.train()
|
| 130 |
+
|
| 131 |
+
|
| 132 |
+
if __name__ == "__main__":
|
| 133 |
+
main()
|
tasks/tasksmith-fa1a9b35ff39/tests/source/examples/scripts/openenv/multi_env.py
ADDED
|
@@ -0,0 +1,273 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2020-2026 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
# /// script
|
| 16 |
+
# dependencies = [
|
| 17 |
+
# "trl",
|
| 18 |
+
# "trackio",
|
| 19 |
+
# "openenv-textarena @ git+https://huggingface.co/spaces/openenv/wordle",
|
| 20 |
+
# "openenv-openspiel-env @ git+https://huggingface.co/spaces/openenv/openspiel_env",
|
| 21 |
+
# ]
|
| 22 |
+
# ///
|
| 23 |
+
|
| 24 |
+
"""
|
| 25 |
+
Multi-environment GRPO training with OpenEnv: Wordle + Catch in the same training run.
|
| 26 |
+
|
| 27 |
+
Demonstrates how to wrap multiple environments in a single `environment_factory` class. The dataset
|
| 28 |
+
contains an "env" column that routes each sample to the correct environment at `reset()` time.
|
| 29 |
+
|
| 30 |
+
Usage:
|
| 31 |
+
python examples/scripts/openenv/multi_env.py \\
|
| 32 |
+
--wordle-url https://openenv-wordle.hf.space \\
|
| 33 |
+
--catch-url https://openenv-openspiel-env.hf.space
|
| 34 |
+
"""
|
| 35 |
+
|
| 36 |
+
import argparse
|
| 37 |
+
|
| 38 |
+
from datasets import Dataset
|
| 39 |
+
from openspiel_env import OpenSpielEnv
|
| 40 |
+
from openspiel_env.models import OpenSpielAction
|
| 41 |
+
from textarena_env import TextArenaAction, TextArenaEnv
|
| 42 |
+
|
| 43 |
+
from trl import GRPOConfig, GRPOTrainer
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
wordle_prompt = """You are an expert Wordle solver with deep knowledge of English vocabulary, letter frequency patterns, and optimal guessing strategies.
|
| 47 |
+
|
| 48 |
+
Follow these rules to play Wordle:
|
| 49 |
+
|
| 50 |
+
1. The target is a 5-letter English word
|
| 51 |
+
2. You have 6 attempts to guess the correct word
|
| 52 |
+
3. After each guess, you receive color-coded feedback:
|
| 53 |
+
- GREEN (G): Letter is correct and in the correct position
|
| 54 |
+
- YELLOW (Y): Letter is in the word but in the wrong position
|
| 55 |
+
- GRAY (X): Letter is not in the word at all
|
| 56 |
+
4. All guesses must be valid 5-letter English words
|
| 57 |
+
5. You cannot reuse a word you've already guessed
|
| 58 |
+
6. Use the tool `guess` to make a guess.
|
| 59 |
+
"""
|
| 60 |
+
|
| 61 |
+
catch_prompt = """You are an AI agent playing the game **Catch**.
|
| 62 |
+
|
| 63 |
+
### Game Description
|
| 64 |
+
- The game is played on a **10×5 grid**.
|
| 65 |
+
- There is one **falling ball** and one **paddle** that you control at the bottom.
|
| 66 |
+
- The objective is to **move the paddle left or right to catch the ball** as it falls.
|
| 67 |
+
- The episode ends when the ball reaches the bottom row:
|
| 68 |
+
- You get **+1 reward** if you catch it.
|
| 69 |
+
- You get **–1 reward** if you miss it.
|
| 70 |
+
|
| 71 |
+
### Observation Format
|
| 72 |
+
Each observation is a flattened 10x5 grid (list of 50 floats).
|
| 73 |
+
- 1.0 → occupied (ball or paddle)
|
| 74 |
+
- 0.0 → empty cell
|
| 75 |
+
|
| 76 |
+
You have the following tools available:
|
| 77 |
+
- `move(direction)`: Move the paddle left or right. Direction must be "left" or "right".
|
| 78 |
+
- `stay`: Do nothing and let the ball fall one step.
|
| 79 |
+
|
| 80 |
+
Observe the grid, determine where the ball is relative to the paddle, then move accordingly.
|
| 81 |
+
"""
|
| 82 |
+
|
| 83 |
+
DEFAULT_WORDLE_URL = "https://openenv-wordle.hf.space"
|
| 84 |
+
DEFAULT_CATCH_URL = "https://openenv-openspiel-env.hf.space"
|
| 85 |
+
|
| 86 |
+
CATCH_ROWS = 10
|
| 87 |
+
CATCH_COLS = 5
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
def _format_catch_obs(info_state: list[float]) -> str:
|
| 91 |
+
"""Convert the flat 50-float observation into a readable text description."""
|
| 92 |
+
ball_row = ball_col = paddle_col = None
|
| 93 |
+
for idx, val in enumerate(info_state):
|
| 94 |
+
if val == 1.0:
|
| 95 |
+
r, c = divmod(idx, CATCH_COLS)
|
| 96 |
+
if r < CATCH_ROWS - 1:
|
| 97 |
+
ball_row, ball_col = r + 1, c + 1
|
| 98 |
+
else:
|
| 99 |
+
paddle_col = c + 1
|
| 100 |
+
parts = []
|
| 101 |
+
if ball_row is not None and ball_col is not None:
|
| 102 |
+
parts.append(f"Ball: row {ball_row}/{CATCH_ROWS}, column {ball_col}/{CATCH_COLS}")
|
| 103 |
+
if paddle_col is not None:
|
| 104 |
+
parts.append(f"Paddle: column {paddle_col}/{CATCH_COLS}")
|
| 105 |
+
if ball_col is not None and paddle_col is not None:
|
| 106 |
+
diff = ball_col - paddle_col
|
| 107 |
+
if diff < 0:
|
| 108 |
+
parts.append(f"The ball is {abs(diff)} column(s) to the LEFT of the paddle.")
|
| 109 |
+
elif diff > 0:
|
| 110 |
+
parts.append(f"The ball is {diff} column(s) to the RIGHT of the paddle.")
|
| 111 |
+
else:
|
| 112 |
+
parts.append("The ball is directly above the paddle.")
|
| 113 |
+
return "\n".join(parts)
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
class MultiEnv:
|
| 117 |
+
wordle_url = DEFAULT_WORDLE_URL
|
| 118 |
+
catch_url = DEFAULT_CATCH_URL
|
| 119 |
+
|
| 120 |
+
def __init__(self):
|
| 121 |
+
self._wordle_client = None
|
| 122 |
+
self._catch_client = None
|
| 123 |
+
self.active = None
|
| 124 |
+
self.reward = 0.0
|
| 125 |
+
self.done = False
|
| 126 |
+
|
| 127 |
+
def reset(self, **kwargs) -> str | None:
|
| 128 |
+
self.active = kwargs.get("env", "wordle")
|
| 129 |
+
self.reward = 0.0
|
| 130 |
+
self.done = False
|
| 131 |
+
|
| 132 |
+
if self.active == "wordle":
|
| 133 |
+
if self._wordle_client is not None:
|
| 134 |
+
try:
|
| 135 |
+
self._wordle_client.close()
|
| 136 |
+
except Exception:
|
| 137 |
+
pass
|
| 138 |
+
self._wordle_client = TextArenaEnv(base_url=MultiEnv.wordle_url)
|
| 139 |
+
result = self._wordle_client.reset()
|
| 140 |
+
self._last_full_feedback = result.observation.messages[0].content
|
| 141 |
+
self.reward = 0.0
|
| 142 |
+
return self._last_full_feedback
|
| 143 |
+
elif self.active == "catch":
|
| 144 |
+
if self._catch_client is not None:
|
| 145 |
+
try:
|
| 146 |
+
self._catch_client.close()
|
| 147 |
+
except Exception:
|
| 148 |
+
pass
|
| 149 |
+
self._catch_client = OpenSpielEnv(base_url=MultiEnv.catch_url)
|
| 150 |
+
result = self._catch_client.reset()
|
| 151 |
+
self.done = result.observation.done
|
| 152 |
+
return _format_catch_obs(result.observation.info_state)
|
| 153 |
+
else:
|
| 154 |
+
raise ValueError(f"Unknown environment: {self.active}")
|
| 155 |
+
|
| 156 |
+
def guess(self, guess: str) -> str:
|
| 157 |
+
"""
|
| 158 |
+
Make a guess in the Wordle environment.
|
| 159 |
+
|
| 160 |
+
Args:
|
| 161 |
+
guess: The guessed word, formatted as '[abcde]'
|
| 162 |
+
|
| 163 |
+
Returns:
|
| 164 |
+
The feedback message from the environment.
|
| 165 |
+
"""
|
| 166 |
+
if self.active != "wordle":
|
| 167 |
+
raise ValueError("guess is only available in Wordle")
|
| 168 |
+
if self.done:
|
| 169 |
+
raise ValueError("Game over.")
|
| 170 |
+
result = self._wordle_client.step(TextArenaAction(message=guess))
|
| 171 |
+
_full_feedback = result.observation.messages[0].content
|
| 172 |
+
feedback = _full_feedback[len(self._last_full_feedback) :]
|
| 173 |
+
self._last_full_feedback = _full_feedback
|
| 174 |
+
if "You attempted an invalid move" in feedback:
|
| 175 |
+
self.reward = 0.0
|
| 176 |
+
else:
|
| 177 |
+
self.reward = result.reward
|
| 178 |
+
self.done = result.done
|
| 179 |
+
return feedback
|
| 180 |
+
|
| 181 |
+
def _catch_action(self, action_id: int) -> str:
|
| 182 |
+
if self.done:
|
| 183 |
+
raise ValueError("Episode is done.")
|
| 184 |
+
result = self._catch_client.step(OpenSpielAction(action_id=action_id, game_name="catch"))
|
| 185 |
+
self.reward = result.reward or 0.0
|
| 186 |
+
self.done = result.observation.done
|
| 187 |
+
return _format_catch_obs(result.observation.info_state)
|
| 188 |
+
|
| 189 |
+
def move(self, direction: str) -> str:
|
| 190 |
+
"""Move the paddle left or right.
|
| 191 |
+
|
| 192 |
+
Args:
|
| 193 |
+
direction: Direction to move, either "left" or "right".
|
| 194 |
+
|
| 195 |
+
Returns:
|
| 196 |
+
The observation after moving.
|
| 197 |
+
"""
|
| 198 |
+
if self.active != "catch":
|
| 199 |
+
raise ValueError("move is only available in Catch")
|
| 200 |
+
if direction == "left":
|
| 201 |
+
action_id = 0
|
| 202 |
+
elif direction == "right":
|
| 203 |
+
action_id = 2
|
| 204 |
+
else:
|
| 205 |
+
raise ValueError(f"Invalid direction {direction!r}: must be 'left' or 'right'.")
|
| 206 |
+
return self._catch_action(action_id)
|
| 207 |
+
|
| 208 |
+
def stay(self) -> str:
|
| 209 |
+
"""Do nothing and let the ball fall one step.
|
| 210 |
+
|
| 211 |
+
Returns:
|
| 212 |
+
The observation after staying.
|
| 213 |
+
"""
|
| 214 |
+
if self.active != "catch":
|
| 215 |
+
raise ValueError("stay is only available in Catch")
|
| 216 |
+
return self._catch_action(1)
|
| 217 |
+
|
| 218 |
+
|
| 219 |
+
def wordle_reward(environments, **kwargs) -> list[float | None]:
|
| 220 |
+
return [env.reward if env.active == "wordle" else None for env in environments]
|
| 221 |
+
|
| 222 |
+
|
| 223 |
+
def catch_reward(environments, **kwargs) -> list[float | None]:
|
| 224 |
+
rewards = []
|
| 225 |
+
for env in environments:
|
| 226 |
+
if env.active != "catch":
|
| 227 |
+
rewards.append(None)
|
| 228 |
+
elif env.done:
|
| 229 |
+
# Catch gives +1 for catching, -1 for missing. Clamp to [0, 1] for GRPO advantage estimation.
|
| 230 |
+
rewards.append(max(env.reward, 0.0))
|
| 231 |
+
else:
|
| 232 |
+
rewards.append(0.0) # Incomplete episode
|
| 233 |
+
return rewards
|
| 234 |
+
|
| 235 |
+
|
| 236 |
+
def main() -> None:
|
| 237 |
+
parser = argparse.ArgumentParser(description="Multi-environment GRPO training")
|
| 238 |
+
parser.add_argument("--wordle-url", default=DEFAULT_WORDLE_URL, help="Wordle environment URL")
|
| 239 |
+
parser.add_argument("--catch-url", default=DEFAULT_CATCH_URL, help="Catch environment URL")
|
| 240 |
+
args, remaining = parser.parse_known_args()
|
| 241 |
+
|
| 242 |
+
MultiEnv.wordle_url = args.wordle_url
|
| 243 |
+
MultiEnv.catch_url = args.catch_url
|
| 244 |
+
|
| 245 |
+
n = 500 # samples per environment
|
| 246 |
+
dataset = Dataset.from_dict(
|
| 247 |
+
{
|
| 248 |
+
"prompt": (
|
| 249 |
+
[[{"role": "user", "content": wordle_prompt}]] * n + [[{"role": "user", "content": catch_prompt}]] * n
|
| 250 |
+
),
|
| 251 |
+
"env": ["wordle"] * n + ["catch"] * n,
|
| 252 |
+
}
|
| 253 |
+
)
|
| 254 |
+
|
| 255 |
+
trainer = GRPOTrainer(
|
| 256 |
+
model="Qwen/Qwen3-1.7B",
|
| 257 |
+
reward_funcs=[wordle_reward, catch_reward],
|
| 258 |
+
train_dataset=dataset,
|
| 259 |
+
args=GRPOConfig(
|
| 260 |
+
report_to="wandb",
|
| 261 |
+
log_completions=True,
|
| 262 |
+
num_completions_to_print=2,
|
| 263 |
+
logging_steps=1,
|
| 264 |
+
chat_template_kwargs={"enable_thinking": False},
|
| 265 |
+
max_completion_length=1024,
|
| 266 |
+
),
|
| 267 |
+
environment_factory=MultiEnv,
|
| 268 |
+
)
|
| 269 |
+
trainer.train()
|
| 270 |
+
|
| 271 |
+
|
| 272 |
+
if __name__ == "__main__":
|
| 273 |
+
main()
|
tasks/tasksmith-fa1a9b35ff39/tests/source/examples/scripts/openenv/sudoku.py
ADDED
|
@@ -0,0 +1,669 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2020-2026 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
# /// script
|
| 16 |
+
# dependencies = [
|
| 17 |
+
# "trl[vllm,peft]",
|
| 18 |
+
# "trackio",
|
| 19 |
+
# "kernels",
|
| 20 |
+
# "openenv-textarena @ git+https://huggingface.co/spaces/openenv/sudoku",
|
| 21 |
+
# ]
|
| 22 |
+
# ///
|
| 23 |
+
|
| 24 |
+
"""
|
| 25 |
+
GRPO training for Sudoku with TextArena environment.
|
| 26 |
+
|
| 27 |
+
Setup (Option A - Install from HF Space, recommended):
|
| 28 |
+
|
| 29 |
+
```sh
|
| 30 |
+
uv pip install git+https://huggingface.co/spaces/openenv/sudoku
|
| 31 |
+
```
|
| 32 |
+
|
| 33 |
+
Setup (Option B - Clone OpenEnv repo, for development):
|
| 34 |
+
|
| 35 |
+
```sh
|
| 36 |
+
git clone https://github.com/huggingface/OpenEnv.git
|
| 37 |
+
cd OpenEnv/envs/textarena_env
|
| 38 |
+
uv pip install -e .
|
| 39 |
+
```
|
| 40 |
+
|
| 41 |
+
# Option 1: HF Spaces + Colocated vLLM (1 GPU required)
|
| 42 |
+
```sh
|
| 43 |
+
python examples/scripts/openenv/sudoku.py --vllm-mode colocate
|
| 44 |
+
```
|
| 45 |
+
|
| 46 |
+
# Option 2: HF Spaces + Separate vLLM server (2 GPUs required)
|
| 47 |
+
|
| 48 |
+
# Spin up vLLM server (Terminal 1)
|
| 49 |
+
```sh
|
| 50 |
+
CUDA_VISIBLE_DEVICES=0 trl vllm-serve --model Qwen/Qwen3-1.7B --host 0.0.0.0 --port 8000
|
| 51 |
+
```
|
| 52 |
+
|
| 53 |
+
# Run training (Terminal 2)
|
| 54 |
+
```sh
|
| 55 |
+
CUDA_VISIBLE_DEVICES=1 python examples/scripts/openenv/sudoku.py --vllm-mode server --vllm-server-url http://localhost:8000
|
| 56 |
+
```
|
| 57 |
+
|
| 58 |
+
# Option 3: Local + Colocated vLLM (1 GPU required)
|
| 59 |
+
|
| 60 |
+
# Start the environment only if using --env-mode docker-local
|
| 61 |
+
```sh
|
| 62 |
+
docker run -d -p 8001:8001 registry.hf.space/openenv-sudoku:latest
|
| 63 |
+
```
|
| 64 |
+
|
| 65 |
+
```sh
|
| 66 |
+
python examples/scripts/openenv/sudoku.py --env-mode docker-local --vllm-mode colocate
|
| 67 |
+
```
|
| 68 |
+
|
| 69 |
+
# Full example with all flags:
|
| 70 |
+
```sh
|
| 71 |
+
python examples/scripts/openenv/sudoku.py \
|
| 72 |
+
--vllm-mode colocate \
|
| 73 |
+
--env-mode space \
|
| 74 |
+
--env-host https://openenv-sudoku.hf.space \
|
| 75 |
+
--num-generations 8 \
|
| 76 |
+
--per-device-batch-size 1 \
|
| 77 |
+
--max-turns 100 \
|
| 78 |
+
--gradient-accumulation-steps 8 \
|
| 79 |
+
--difficulty easy \
|
| 80 |
+
--dataset-size 100
|
| 81 |
+
```
|
| 82 |
+
"""
|
| 83 |
+
|
| 84 |
+
from __future__ import annotations
|
| 85 |
+
|
| 86 |
+
# ruff: noqa: T201
|
| 87 |
+
import argparse
|
| 88 |
+
import sys
|
| 89 |
+
import time
|
| 90 |
+
from collections import defaultdict
|
| 91 |
+
from datetime import datetime
|
| 92 |
+
from pathlib import Path
|
| 93 |
+
|
| 94 |
+
from datasets import Dataset
|
| 95 |
+
|
| 96 |
+
from trl import GRPOConfig, GRPOTrainer, RichProgressCallback
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
# Ensure src/ is on the path
|
| 100 |
+
sys.path.insert(0, str(Path(__file__).parent / "src"))
|
| 101 |
+
|
| 102 |
+
from textarena_env import TextArenaAction, TextArenaEnv
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
# ---------------------------------------------------------------------------
|
| 106 |
+
# Argument parsing
|
| 107 |
+
# ---------------------------------------------------------------------------
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
def parse_args() -> argparse.Namespace:
|
| 111 |
+
parser = argparse.ArgumentParser(description="GRPO training for Sudoku")
|
| 112 |
+
|
| 113 |
+
# Model
|
| 114 |
+
parser.add_argument("--model-id", default="Qwen/Qwen3-1.7B")
|
| 115 |
+
|
| 116 |
+
# Environment
|
| 117 |
+
parser.add_argument("--env-host", type=str, default="https://openenv-sudoku.hf.space")
|
| 118 |
+
parser.add_argument("--env-port", type=int, default=8001)
|
| 119 |
+
parser.add_argument("--env-mode", choices=["docker-local", "docker-image", "docker-hub", "space"], default="space")
|
| 120 |
+
parser.add_argument("--env-image", type=str, default="textarena-env:latest")
|
| 121 |
+
|
| 122 |
+
# Prompts
|
| 123 |
+
parser.add_argument("--system-prompt-path", default="sudoku_prompt.txt")
|
| 124 |
+
parser.add_argument("--dataset-prompt", default="Play Sudoku like an expert.")
|
| 125 |
+
parser.add_argument("--dataset-size", type=int, default=1000)
|
| 126 |
+
|
| 127 |
+
# Game settings
|
| 128 |
+
parser.add_argument("--max-turns", type=int, default=100)
|
| 129 |
+
parser.add_argument(
|
| 130 |
+
"--difficulty",
|
| 131 |
+
type=str,
|
| 132 |
+
choices=["easy", "medium", "hard"],
|
| 133 |
+
default="easy",
|
| 134 |
+
help="Training difficulty: easy=guaranteed+options, medium=only options, hard=no hints",
|
| 135 |
+
)
|
| 136 |
+
parser.add_argument(
|
| 137 |
+
"--api-delay", type=float, default=0.0, help="Delay in seconds between API calls to avoid rate limiting"
|
| 138 |
+
)
|
| 139 |
+
|
| 140 |
+
# Sampling
|
| 141 |
+
parser.add_argument("--temperature", type=float, default=0.8)
|
| 142 |
+
parser.add_argument("--top-k", type=int, default=10)
|
| 143 |
+
parser.add_argument("--top-p", type=float, default=None, help="Top-p sampling parameter")
|
| 144 |
+
|
| 145 |
+
# Training
|
| 146 |
+
parser.add_argument("--learning-rate", type=float, default=5e-6)
|
| 147 |
+
parser.add_argument("--weight-decay", type=float, default=0.0)
|
| 148 |
+
parser.add_argument("--gradient-accumulation-steps", type=int, default=64)
|
| 149 |
+
parser.add_argument("--warmup-steps", type=int, default=20)
|
| 150 |
+
parser.add_argument("--per-device-batch-size", type=int, default=1)
|
| 151 |
+
parser.add_argument("--num-generations", type=int, default=8)
|
| 152 |
+
parser.add_argument("--num-epochs", type=int, default=1)
|
| 153 |
+
parser.add_argument("--max-completion-length", type=int, default=16384)
|
| 154 |
+
|
| 155 |
+
# Checkpoints
|
| 156 |
+
parser.add_argument("--save-interval", type=int, default=10)
|
| 157 |
+
parser.add_argument("--save-total-limit", type=int, default=None)
|
| 158 |
+
parser.add_argument("--output-dir", default=None)
|
| 159 |
+
|
| 160 |
+
# Logging
|
| 161 |
+
parser.add_argument("--run-name", default=None)
|
| 162 |
+
parser.add_argument("--project", default=None)
|
| 163 |
+
parser.add_argument("--trackio-space-id", default="Sudoku-GRPO")
|
| 164 |
+
parser.add_argument("--logging-steps", type=int, default=1)
|
| 165 |
+
parser.add_argument(
|
| 166 |
+
"--gradient-checkpointing",
|
| 167 |
+
action=argparse.BooleanOptionalAction,
|
| 168 |
+
default=True,
|
| 169 |
+
help="Enable gradient checkpointing to save memory",
|
| 170 |
+
)
|
| 171 |
+
|
| 172 |
+
# LoRA / PEFT
|
| 173 |
+
parser.add_argument(
|
| 174 |
+
"--use-lora", action="store_true", default=False, help="Use LoRA for memory-efficient training"
|
| 175 |
+
)
|
| 176 |
+
parser.add_argument("--lora-r", type=int, default=16, help="LoRA rank")
|
| 177 |
+
parser.add_argument("--lora-alpha", type=int, default=32, help="LoRA alpha")
|
| 178 |
+
|
| 179 |
+
# vLLM
|
| 180 |
+
parser.add_argument("--vllm-mode", choices=("colocate", "server"), default="colocate")
|
| 181 |
+
parser.add_argument("--vllm-server-url", type=str, default="http://localhost:8000")
|
| 182 |
+
parser.add_argument("--vllm-gpu-memory-utilization", type=float, default=0.15)
|
| 183 |
+
|
| 184 |
+
return parser.parse_args()
|
| 185 |
+
|
| 186 |
+
|
| 187 |
+
# ---------------------------------------------------------------------------
|
| 188 |
+
# Helper functions
|
| 189 |
+
# ---------------------------------------------------------------------------
|
| 190 |
+
|
| 191 |
+
|
| 192 |
+
def resolve_system_prompt(path: str) -> str:
|
| 193 |
+
prompt_path = Path(path)
|
| 194 |
+
if not prompt_path.is_file():
|
| 195 |
+
prompt_path = Path(__file__).parent / path
|
| 196 |
+
return prompt_path.read_text()
|
| 197 |
+
|
| 198 |
+
|
| 199 |
+
def sanitize_name(name: str) -> str:
|
| 200 |
+
return name.replace("/", "-")
|
| 201 |
+
|
| 202 |
+
|
| 203 |
+
def is_valid_board_state(board_str: str) -> bool:
|
| 204 |
+
"""Check if the string contains an actual Sudoku board."""
|
| 205 |
+
return "R1" in board_str and "R9" in board_str and "|" in board_str
|
| 206 |
+
|
| 207 |
+
|
| 208 |
+
def parse_board(board_str: str) -> list[list[int]]:
|
| 209 |
+
"""Parse board string into 9x9 grid (0 = empty)."""
|
| 210 |
+
grid = [[0] * 9 for _ in range(9)]
|
| 211 |
+
if not is_valid_board_state(board_str):
|
| 212 |
+
return grid
|
| 213 |
+
|
| 214 |
+
for line in board_str.split("\n"):
|
| 215 |
+
line_stripped = line.strip()
|
| 216 |
+
if line_stripped and line_stripped[0] == "R" and len(line_stripped) > 1 and line_stripped[1].isdigit():
|
| 217 |
+
row = int(line_stripped[1]) - 1 # 0-indexed
|
| 218 |
+
cell_part = line_stripped[2:]
|
| 219 |
+
col = 0
|
| 220 |
+
for char in cell_part:
|
| 221 |
+
if char == ".":
|
| 222 |
+
grid[row][col] = 0
|
| 223 |
+
col += 1
|
| 224 |
+
elif char.isdigit():
|
| 225 |
+
grid[row][col] = int(char)
|
| 226 |
+
col += 1
|
| 227 |
+
return grid
|
| 228 |
+
|
| 229 |
+
|
| 230 |
+
def count_filled_cells(board_str: str) -> int:
|
| 231 |
+
"""Count the number of filled cells in the board."""
|
| 232 |
+
if not is_valid_board_state(board_str):
|
| 233 |
+
return 0
|
| 234 |
+
grid = parse_board(board_str)
|
| 235 |
+
return sum(1 for row in grid for cell in row if cell != 0)
|
| 236 |
+
|
| 237 |
+
|
| 238 |
+
def get_valid_numbers(grid: list[list[int]], row: int, col: int) -> set[int]:
|
| 239 |
+
"""Get valid numbers for a cell based on Sudoku rules."""
|
| 240 |
+
if grid[row][col] != 0:
|
| 241 |
+
return set()
|
| 242 |
+
|
| 243 |
+
used = set()
|
| 244 |
+
|
| 245 |
+
# Check row
|
| 246 |
+
for c in range(9):
|
| 247 |
+
if grid[row][c] != 0:
|
| 248 |
+
used.add(grid[row][c])
|
| 249 |
+
|
| 250 |
+
# Check column
|
| 251 |
+
for r in range(9):
|
| 252 |
+
if grid[r][col] != 0:
|
| 253 |
+
used.add(grid[r][col])
|
| 254 |
+
|
| 255 |
+
# Check 3x3 box
|
| 256 |
+
box_row, box_col = 3 * (row // 3), 3 * (col // 3)
|
| 257 |
+
for r in range(box_row, box_row + 3):
|
| 258 |
+
for c in range(box_col, box_col + 3):
|
| 259 |
+
if grid[r][c] != 0:
|
| 260 |
+
used.add(grid[r][c])
|
| 261 |
+
|
| 262 |
+
return set(range(1, 10)) - used
|
| 263 |
+
|
| 264 |
+
|
| 265 |
+
def extract_empty_cells_with_candidates(
|
| 266 |
+
board_str: str, sort_by_difficulty: bool = True
|
| 267 |
+
) -> list[tuple[int, int, set[int]]]:
|
| 268 |
+
"""Extract empty cells with their valid candidate numbers.
|
| 269 |
+
|
| 270 |
+
Args:
|
| 271 |
+
sort_by_difficulty: If True, sort by number of candidates (easiest first).
|
| 272 |
+
If False, keep natural order (top-left to bottom-right).
|
| 273 |
+
"""
|
| 274 |
+
grid = parse_board(board_str)
|
| 275 |
+
cells_with_candidates = []
|
| 276 |
+
|
| 277 |
+
for row in range(9):
|
| 278 |
+
for col in range(9):
|
| 279 |
+
if grid[row][col] == 0:
|
| 280 |
+
candidates = get_valid_numbers(grid, row, col)
|
| 281 |
+
cells_with_candidates.append((row + 1, col + 1, candidates)) # 1-indexed
|
| 282 |
+
|
| 283 |
+
if sort_by_difficulty:
|
| 284 |
+
# Sort by number of candidates (easiest first = naked singles)
|
| 285 |
+
cells_with_candidates.sort(key=lambda x: len(x[2]))
|
| 286 |
+
|
| 287 |
+
return cells_with_candidates
|
| 288 |
+
|
| 289 |
+
|
| 290 |
+
def extract_empty_cells(board_str: str) -> list[tuple[int, int]]:
|
| 291 |
+
"""Extract list of empty cells (row, col) from board string."""
|
| 292 |
+
empty_cells = []
|
| 293 |
+
if not is_valid_board_state(board_str):
|
| 294 |
+
return empty_cells
|
| 295 |
+
|
| 296 |
+
for line in board_str.split("\n"):
|
| 297 |
+
line_stripped = line.strip()
|
| 298 |
+
if line_stripped and line_stripped[0] == "R" and len(line_stripped) > 1 and line_stripped[1].isdigit():
|
| 299 |
+
row = int(line_stripped[1])
|
| 300 |
+
cell_part = line_stripped[2:]
|
| 301 |
+
col = 0
|
| 302 |
+
for char in cell_part:
|
| 303 |
+
if char == ".":
|
| 304 |
+
col += 1
|
| 305 |
+
empty_cells.append((row, col))
|
| 306 |
+
elif char.isdigit():
|
| 307 |
+
col += 1
|
| 308 |
+
return empty_cells
|
| 309 |
+
|
| 310 |
+
|
| 311 |
+
def extract_board_only(text: str) -> str:
|
| 312 |
+
"""Extract just the Sudoku grid from a message."""
|
| 313 |
+
if not text:
|
| 314 |
+
return ""
|
| 315 |
+
|
| 316 |
+
lines = text.split("\n")
|
| 317 |
+
board_lines = []
|
| 318 |
+
in_board = False
|
| 319 |
+
|
| 320 |
+
for line in lines:
|
| 321 |
+
stripped = line.strip()
|
| 322 |
+
if stripped.startswith("C1") or (
|
| 323 |
+
stripped and stripped[0] == "R" and len(stripped) > 1 and stripped[1].isdigit()
|
| 324 |
+
):
|
| 325 |
+
in_board = True
|
| 326 |
+
if in_board and (stripped.startswith("-") or stripped.startswith("R") or stripped.startswith("C1")):
|
| 327 |
+
board_lines.append(line)
|
| 328 |
+
elif (
|
| 329 |
+
in_board
|
| 330 |
+
and stripped
|
| 331 |
+
and not stripped.startswith("-")
|
| 332 |
+
and not (stripped[0] == "R" and len(stripped) > 1 and stripped[1].isdigit())
|
| 333 |
+
):
|
| 334 |
+
break
|
| 335 |
+
|
| 336 |
+
return "\n".join(board_lines) if board_lines else ""
|
| 337 |
+
|
| 338 |
+
|
| 339 |
+
# ---------------------------------------------------------------------------
|
| 340 |
+
# Reward functions
|
| 341 |
+
# ---------------------------------------------------------------------------
|
| 342 |
+
|
| 343 |
+
|
| 344 |
+
def reward_empty_cell(environments, **kwargs) -> list[float]:
|
| 345 |
+
"""Reward for targeting empty cells (learn to pick valid positions first)."""
|
| 346 |
+
return [env.empty_cell_reward for env in environments]
|
| 347 |
+
|
| 348 |
+
|
| 349 |
+
def reward_valid_moves(environments, **kwargs) -> list[float]:
|
| 350 |
+
"""Reward for making valid moves."""
|
| 351 |
+
return [env.valid_move_reward for env in environments]
|
| 352 |
+
|
| 353 |
+
|
| 354 |
+
def reward_correct(environments, **kwargs) -> list[float]:
|
| 355 |
+
"""Reward for solving the puzzle."""
|
| 356 |
+
return [env.correct_reward for env in environments]
|
| 357 |
+
|
| 358 |
+
|
| 359 |
+
def reward_repetition(environments, **kwargs) -> list[float]:
|
| 360 |
+
"""Penalty for repeating moves."""
|
| 361 |
+
return [env.repetition_reward for env in environments]
|
| 362 |
+
|
| 363 |
+
|
| 364 |
+
def reward_progress(environments, **kwargs) -> list[float]:
|
| 365 |
+
"""Reward for filling more cells in the board."""
|
| 366 |
+
return [env.progress_reward for env in environments]
|
| 367 |
+
|
| 368 |
+
|
| 369 |
+
# ---------------------------------------------------------------------------
|
| 370 |
+
# Main
|
| 371 |
+
# ---------------------------------------------------------------------------
|
| 372 |
+
|
| 373 |
+
|
| 374 |
+
def main() -> None:
|
| 375 |
+
args = parse_args()
|
| 376 |
+
|
| 377 |
+
# Setup environment — all modes resolve to env_url
|
| 378 |
+
if args.env_mode == "docker-local":
|
| 379 |
+
env_url = f"http://{args.env_host}:{args.env_port}"
|
| 380 |
+
elif args.env_mode == "docker-image":
|
| 381 |
+
_bootstrap = TextArenaEnv.from_docker_image(args.env_image)
|
| 382 |
+
env_url = _bootstrap.base_url
|
| 383 |
+
elif args.env_mode == "docker-hub":
|
| 384 |
+
_bootstrap = TextArenaEnv.from_hub(args.env_image)
|
| 385 |
+
env_url = _bootstrap.base_url
|
| 386 |
+
elif args.env_mode == "space":
|
| 387 |
+
env_url = args.env_host
|
| 388 |
+
else:
|
| 389 |
+
raise ValueError(f"Unknown environment mode: {args.env_mode}")
|
| 390 |
+
|
| 391 |
+
print(f"Environment: {args.env_mode} ({env_url})")
|
| 392 |
+
|
| 393 |
+
system_prompt = resolve_system_prompt(args.system_prompt_path)
|
| 394 |
+
dataset = Dataset.from_dict(
|
| 395 |
+
{
|
| 396 |
+
"prompt": [
|
| 397 |
+
[
|
| 398 |
+
{"role": "system", "content": system_prompt},
|
| 399 |
+
{"role": "user", "content": args.dataset_prompt},
|
| 400 |
+
]
|
| 401 |
+
]
|
| 402 |
+
* args.dataset_size
|
| 403 |
+
}
|
| 404 |
+
)
|
| 405 |
+
|
| 406 |
+
# Capture args for use in the environment class closure
|
| 407 |
+
difficulty = args.difficulty
|
| 408 |
+
max_turns = args.max_turns
|
| 409 |
+
api_delay = args.api_delay
|
| 410 |
+
|
| 411 |
+
class SudokuEnv:
|
| 412 |
+
def __init__(self):
|
| 413 |
+
self.client = TextArenaEnv(base_url=env_url)
|
| 414 |
+
self._difficulty = difficulty
|
| 415 |
+
self._max_turns = max_turns
|
| 416 |
+
self._api_delay = api_delay
|
| 417 |
+
self._reset_state()
|
| 418 |
+
|
| 419 |
+
def _reset_state(self):
|
| 420 |
+
self._move_counts: defaultdict[str, int] = defaultdict(int)
|
| 421 |
+
self._successful_moves: list[str] = []
|
| 422 |
+
self._failed_moves: list[str] = []
|
| 423 |
+
self._valid_move_scores: list[float] = []
|
| 424 |
+
self._empty_cell_scores: list[float] = []
|
| 425 |
+
self._correct_scores: list[float] = []
|
| 426 |
+
self._repetition_scores: list[float] = []
|
| 427 |
+
self._last_board_state = ""
|
| 428 |
+
self._initial_filled = 0
|
| 429 |
+
self._max_filled = 0
|
| 430 |
+
self._turn = 0
|
| 431 |
+
self._done = False
|
| 432 |
+
|
| 433 |
+
def reset(self, **kwargs) -> str:
|
| 434 |
+
self._reset_state()
|
| 435 |
+
result = self.client.reset()
|
| 436 |
+
time.sleep(self._api_delay)
|
| 437 |
+
observation = result.observation
|
| 438 |
+
self._done = result.done
|
| 439 |
+
|
| 440 |
+
# Store full message content for diffing (messages are cumulative)
|
| 441 |
+
self._last_full_content = observation.messages[0].content if observation.messages else ""
|
| 442 |
+
|
| 443 |
+
if is_valid_board_state(self._last_full_content):
|
| 444 |
+
self._last_board_state = self._last_full_content
|
| 445 |
+
self._initial_filled = count_filled_cells(self._last_board_state)
|
| 446 |
+
self._max_filled = self._initial_filled
|
| 447 |
+
|
| 448 |
+
board = extract_board_only(self._last_board_state) if self._last_board_state else "No board available."
|
| 449 |
+
hints = self._format_hints()
|
| 450 |
+
return f"Step 0. Progress: 0 cells filled.\n\nBoard:\n{board}{hints}"
|
| 451 |
+
|
| 452 |
+
def place(self, row: int, col: int, number: int) -> str:
|
| 453 |
+
"""Place a number on the Sudoku board.
|
| 454 |
+
|
| 455 |
+
Args:
|
| 456 |
+
row: Row number (1-9).
|
| 457 |
+
col: Column number (1-9).
|
| 458 |
+
number: Number to place (1-9).
|
| 459 |
+
|
| 460 |
+
Returns:
|
| 461 |
+
The result of the move and updated board state.
|
| 462 |
+
"""
|
| 463 |
+
if self._done:
|
| 464 |
+
raise ValueError("Game is over. No more moves allowed.")
|
| 465 |
+
|
| 466 |
+
self._turn += 1
|
| 467 |
+
move = f"[{row} {col} {number}]"
|
| 468 |
+
|
| 469 |
+
# Step environment
|
| 470 |
+
result = self.client.step(TextArenaAction(message=move))
|
| 471 |
+
time.sleep(self._api_delay)
|
| 472 |
+
observation = result.observation
|
| 473 |
+
correct_score = float(result.reward or 0.0)
|
| 474 |
+
self._done = result.done
|
| 475 |
+
|
| 476 |
+
# Only check the NEW content for feedback (messages are cumulative)
|
| 477 |
+
full_content = observation.messages[0].content if observation.messages else ""
|
| 478 |
+
new_content = full_content[len(self._last_full_content) :]
|
| 479 |
+
self._last_full_content = full_content
|
| 480 |
+
|
| 481 |
+
new_content_lower = new_content.lower()
|
| 482 |
+
env_says_invalid = any(
|
| 483 |
+
kw in new_content_lower for kw in ["invalid", "error", "cannot", "already", "violation", "lost"]
|
| 484 |
+
)
|
| 485 |
+
got_warning = "please resubmit" in new_content_lower or "avoid penalties" in new_content_lower
|
| 486 |
+
|
| 487 |
+
# Also verify against our own board state: placing on a non-empty cell is always invalid
|
| 488 |
+
if self._last_board_state:
|
| 489 |
+
empty_cells = extract_empty_cells(self._last_board_state)
|
| 490 |
+
targets_empty = (row, col) in empty_cells
|
| 491 |
+
else:
|
| 492 |
+
empty_cells = []
|
| 493 |
+
targets_empty = True # Can't verify, assume valid
|
| 494 |
+
|
| 495 |
+
is_valid = not env_says_invalid and targets_empty
|
| 496 |
+
|
| 497 |
+
# Empty cell score: did the model target an empty cell?
|
| 498 |
+
empty_cell_score = 1.0 if targets_empty else -1.0
|
| 499 |
+
|
| 500 |
+
# Repetition tracking
|
| 501 |
+
is_new_move = self._move_counts[move] == 0
|
| 502 |
+
repetition_count = self._move_counts[move]
|
| 503 |
+
self._move_counts[move] += 1
|
| 504 |
+
repetition_score = -min(2 ** (repetition_count - 1), 10.0) if repetition_count > 0 else 0.0
|
| 505 |
+
|
| 506 |
+
# Valid move score
|
| 507 |
+
if is_valid and is_new_move:
|
| 508 |
+
valid_move_score = 1.0
|
| 509 |
+
self._successful_moves.append(move)
|
| 510 |
+
elif got_warning:
|
| 511 |
+
valid_move_score = -0.5
|
| 512 |
+
self._failed_moves.append(move)
|
| 513 |
+
else:
|
| 514 |
+
valid_move_score = 0.0
|
| 515 |
+
|
| 516 |
+
# Update board state from new content
|
| 517 |
+
if is_valid and is_valid_board_state(new_content):
|
| 518 |
+
self._last_board_state = new_content
|
| 519 |
+
current_filled = count_filled_cells(self._last_board_state)
|
| 520 |
+
if current_filled > self._max_filled:
|
| 521 |
+
self._max_filled = current_filled
|
| 522 |
+
|
| 523 |
+
self._valid_move_scores.append(valid_move_score)
|
| 524 |
+
self._empty_cell_scores.append(empty_cell_score)
|
| 525 |
+
self._correct_scores.append(correct_score)
|
| 526 |
+
self._repetition_scores.append(repetition_score)
|
| 527 |
+
|
| 528 |
+
# Enforce max turns
|
| 529 |
+
if self._turn >= self._max_turns:
|
| 530 |
+
self._done = True
|
| 531 |
+
|
| 532 |
+
# Build response
|
| 533 |
+
board = extract_board_only(self._last_board_state) if self._last_board_state else "No board available."
|
| 534 |
+
status = "valid" if is_valid else "invalid"
|
| 535 |
+
cells_filled = len(self._successful_moves)
|
| 536 |
+
progress = f"Step {self._turn}. Progress: {cells_filled} cells filled."
|
| 537 |
+
hints = self._format_hints()
|
| 538 |
+
|
| 539 |
+
if self._done:
|
| 540 |
+
return f"Move {move}: {status}. Game over.\n{progress}\n\nFinal board:\n{board}"
|
| 541 |
+
return f"Move {move}: {status}\n{progress}\n\nBoard:\n{board}{hints}"
|
| 542 |
+
|
| 543 |
+
def _format_hints(self) -> str:
|
| 544 |
+
parts = []
|
| 545 |
+
|
| 546 |
+
# Already tried moves (avoid repetitions)
|
| 547 |
+
all_tried = self._successful_moves + self._failed_moves
|
| 548 |
+
if all_tried:
|
| 549 |
+
parts.append(f"\nMOVES ALREADY TRIED (do not repeat): {', '.join(all_tried)}")
|
| 550 |
+
|
| 551 |
+
if not self._last_board_state:
|
| 552 |
+
return "\n".join(parts)
|
| 553 |
+
|
| 554 |
+
if self._difficulty == "easy":
|
| 555 |
+
cells = extract_empty_cells_with_candidates(self._last_board_state, sort_by_difficulty=True)
|
| 556 |
+
if cells:
|
| 557 |
+
guaranteed = []
|
| 558 |
+
other = []
|
| 559 |
+
for r, c, candidates in cells[:10]:
|
| 560 |
+
if len(candidates) == 1:
|
| 561 |
+
guaranteed.append(f"[{r} {c} {list(candidates)[0]}]")
|
| 562 |
+
elif len(candidates) <= 3:
|
| 563 |
+
nums = ",".join(str(n) for n in sorted(candidates))
|
| 564 |
+
other.append(f"({r},{c})->{nums}")
|
| 565 |
+
if guaranteed:
|
| 566 |
+
parts.append(f"\nGUARANTEED MOVES: {', '.join(guaranteed[:5])}")
|
| 567 |
+
if other:
|
| 568 |
+
parts.append(f"Other options: {' | '.join(other[:5])}")
|
| 569 |
+
|
| 570 |
+
elif self._difficulty == "medium":
|
| 571 |
+
cells = extract_empty_cells_with_candidates(self._last_board_state, sort_by_difficulty=False)
|
| 572 |
+
if cells:
|
| 573 |
+
cell_hints = []
|
| 574 |
+
for r, c, candidates in cells[:10]:
|
| 575 |
+
nums = ",".join(str(n) for n in sorted(candidates))
|
| 576 |
+
cell_hints.append(f"({r},{c})->{nums}")
|
| 577 |
+
parts.append(f"\nEmpty cells: {' | '.join(cell_hints)}")
|
| 578 |
+
|
| 579 |
+
return "\n".join(parts)
|
| 580 |
+
|
| 581 |
+
# Reward properties — properties are not detected by inspect.ismethod,
|
| 582 |
+
# so they won't be exposed as tools.
|
| 583 |
+
|
| 584 |
+
@property
|
| 585 |
+
def correct_reward(self) -> float:
|
| 586 |
+
return self._correct_scores[-1] if self._correct_scores else 0.0
|
| 587 |
+
|
| 588 |
+
@property
|
| 589 |
+
def valid_move_reward(self) -> float:
|
| 590 |
+
return sum(self._valid_move_scores) / len(self._valid_move_scores) if self._valid_move_scores else 0.0
|
| 591 |
+
|
| 592 |
+
@property
|
| 593 |
+
def empty_cell_reward(self) -> float:
|
| 594 |
+
return sum(self._empty_cell_scores) / len(self._empty_cell_scores) if self._empty_cell_scores else 0.0
|
| 595 |
+
|
| 596 |
+
@property
|
| 597 |
+
def repetition_reward(self) -> float:
|
| 598 |
+
return sum(self._repetition_scores) / len(self._repetition_scores) if self._repetition_scores else 0.0
|
| 599 |
+
|
| 600 |
+
@property
|
| 601 |
+
def progress_reward(self) -> float:
|
| 602 |
+
remaining = 81 - self._initial_filled
|
| 603 |
+
if remaining > 0:
|
| 604 |
+
return (self._max_filled - self._initial_filled) / remaining
|
| 605 |
+
return 1.0
|
| 606 |
+
|
| 607 |
+
timestamp = datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
|
| 608 |
+
output_dir = Path(args.output_dir or f"outputs/sudoku-grpo-{sanitize_name(args.model_id)}-{timestamp}")
|
| 609 |
+
|
| 610 |
+
grpo_config = GRPOConfig(
|
| 611 |
+
use_vllm=True,
|
| 612 |
+
vllm_mode=args.vllm_mode,
|
| 613 |
+
vllm_server_base_url=args.vllm_server_url if args.vllm_mode == "server" else None,
|
| 614 |
+
vllm_gpu_memory_utilization=args.vllm_gpu_memory_utilization or 0.2,
|
| 615 |
+
output_dir=str(output_dir),
|
| 616 |
+
num_train_epochs=args.num_epochs,
|
| 617 |
+
learning_rate=args.learning_rate,
|
| 618 |
+
weight_decay=args.weight_decay,
|
| 619 |
+
gradient_accumulation_steps=args.gradient_accumulation_steps,
|
| 620 |
+
per_device_train_batch_size=args.per_device_batch_size,
|
| 621 |
+
warmup_steps=args.warmup_steps,
|
| 622 |
+
num_generations=args.num_generations,
|
| 623 |
+
max_completion_length=args.max_completion_length,
|
| 624 |
+
logging_steps=args.logging_steps,
|
| 625 |
+
save_strategy="steps",
|
| 626 |
+
save_steps=args.save_interval,
|
| 627 |
+
save_total_limit=args.save_total_limit,
|
| 628 |
+
temperature=args.temperature,
|
| 629 |
+
top_k=args.top_k,
|
| 630 |
+
top_p=args.top_p,
|
| 631 |
+
report_to="trackio",
|
| 632 |
+
log_completions=True,
|
| 633 |
+
num_completions_to_print=1,
|
| 634 |
+
chat_template_kwargs={"enable_thinking": False},
|
| 635 |
+
)
|
| 636 |
+
|
| 637 |
+
grpo_config.run_name = args.run_name or f"run-{timestamp}"
|
| 638 |
+
grpo_config.project = args.project or f"group-{sanitize_name(args.model_id)}"
|
| 639 |
+
grpo_config.trackio_space_id = args.trackio_space_id
|
| 640 |
+
grpo_config.gradient_checkpointing = args.gradient_checkpointing
|
| 641 |
+
|
| 642 |
+
peft_config = None
|
| 643 |
+
if args.use_lora:
|
| 644 |
+
from peft import LoraConfig
|
| 645 |
+
|
| 646 |
+
peft_config = LoraConfig(r=args.lora_r, lora_alpha=args.lora_alpha, task_type="CAUSAL_LM")
|
| 647 |
+
|
| 648 |
+
trainer = GRPOTrainer(
|
| 649 |
+
model=args.model_id,
|
| 650 |
+
reward_funcs=[
|
| 651 |
+
reward_empty_cell, # Learn to pick empty cells
|
| 652 |
+
reward_valid_moves, # Learn valid numbers
|
| 653 |
+
reward_repetition, # Penalize repeating moves
|
| 654 |
+
reward_progress, # Reward filling more cells
|
| 655 |
+
reward_correct, # Solve the puzzle
|
| 656 |
+
],
|
| 657 |
+
peft_config=peft_config,
|
| 658 |
+
train_dataset=dataset,
|
| 659 |
+
args=grpo_config,
|
| 660 |
+
environment_factory=SudokuEnv,
|
| 661 |
+
callbacks=[RichProgressCallback()],
|
| 662 |
+
)
|
| 663 |
+
|
| 664 |
+
print(f"Starting GRPO training: {args.num_generations} generations, {args.max_turns} max turns")
|
| 665 |
+
trainer.train()
|
| 666 |
+
|
| 667 |
+
|
| 668 |
+
if __name__ == "__main__":
|
| 669 |
+
main()
|
tasks/tasksmith-fa1a9b35ff39/tests/source/examples/scripts/openenv/sudoku_prompt.txt
ADDED
|
@@ -0,0 +1,122 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
You are an expert Sudoku player with deep knowledge of logical deduction strategies and number placement techniques.
|
| 2 |
+
|
| 3 |
+
## GAME RULES
|
| 4 |
+
|
| 5 |
+
1. The puzzle is a 9x9 grid divided into nine 3x3 subgrids (boxes)
|
| 6 |
+
2. Some cells are pre-filled with numbers 1-9
|
| 7 |
+
3. You must fill in the empty cells (shown as '.') with numbers 1-9
|
| 8 |
+
4. Each row must contain numbers 1-9 without repetition
|
| 9 |
+
5. Each column must contain numbers 1-9 without repetition
|
| 10 |
+
6. Each 3x3 subgrid must contain numbers 1-9 without repetition
|
| 11 |
+
7. You cannot overwrite pre-filled cells
|
| 12 |
+
8. Invalid moves result in penalties (-1 reward)
|
| 13 |
+
|
| 14 |
+
## HOW TO PLAY
|
| 15 |
+
|
| 16 |
+
Use the `place` tool to make moves. The tool takes three arguments:
|
| 17 |
+
- `row`: Row number (1-9)
|
| 18 |
+
- `col`: Column number (1-9)
|
| 19 |
+
- `number`: Number to place (1-9)
|
| 20 |
+
|
| 21 |
+
## STRATEGIC APPROACH
|
| 22 |
+
|
| 23 |
+
Do not repeat the same move twice.
|
| 24 |
+
|
| 25 |
+
### Basic Strategies
|
| 26 |
+
- **Naked Singles**: If a cell has only one possible candidate, fill it in immediately.
|
| 27 |
+
- **Hidden Singles**: If a number can only go in one cell within a row, column, or box, place it there.
|
| 28 |
+
- **Scanning**: Look at each row, column, and box to find where specific numbers can go.
|
| 29 |
+
|
| 30 |
+
### Intermediate Strategies
|
| 31 |
+
- **Naked Pairs/Triples**: When two/three cells in a unit contain only the same candidates, eliminate those from other cells.
|
| 32 |
+
- **Hidden Pairs/Triples**: When numbers only appear in specific cells within a unit, those cells can only contain those numbers.
|
| 33 |
+
- **Pointing Pairs**: When a candidate in a box is restricted to a single row/column, eliminate it elsewhere.
|
| 34 |
+
|
| 35 |
+
### Solving Process
|
| 36 |
+
1. Start by scanning the entire grid to identify easy fills (cells with few candidates)
|
| 37 |
+
2. Look for rows, columns, or boxes with many numbers already placed
|
| 38 |
+
3. Fill all naked singles first
|
| 39 |
+
4. Then look for hidden singles in each row, column, and box
|
| 40 |
+
5. Apply more advanced techniques as needed
|
| 41 |
+
|
| 42 |
+
### Common Pitfalls to Avoid
|
| 43 |
+
- Don't guess randomly - Sudoku is pure logic
|
| 44 |
+
- Don't overlook any constraint (row, column, or box)
|
| 45 |
+
- Don't try to overwrite pre-filled cells
|
| 46 |
+
- Don't place invalid numbers (must be 1-9)
|
| 47 |
+
- Don't use invalid coordinates (must be 1-9)
|
| 48 |
+
- Don't repeat a move that was already made
|
| 49 |
+
|
| 50 |
+
## EXAMPLES
|
| 51 |
+
|
| 52 |
+
### Example 1: Naked Single
|
| 53 |
+
If row 3, column 4 can only contain the number 5:
|
| 54 |
+
→ call `place(row=3, col=4, number=5)`
|
| 55 |
+
|
| 56 |
+
### Example 2: Hidden Single
|
| 57 |
+
If the number 8 can only go in one cell in row 1:
|
| 58 |
+
→ call `place(row=1, col=7, number=8)`
|
| 59 |
+
|
| 60 |
+
### Example 3: Row Analysis
|
| 61 |
+
Row 2 is missing only value 5, and column 8 is the empty cell:
|
| 62 |
+
→ call `place(row=2, col=8, number=5)`
|
| 63 |
+
|
| 64 |
+
### Example 4: Box Analysis
|
| 65 |
+
In the center box, only one cell can contain 9:
|
| 66 |
+
→ call `place(row=5, col=5, number=9)`
|
| 67 |
+
|
| 68 |
+
## BOARD READING
|
| 69 |
+
|
| 70 |
+
The board is displayed as a 9x9 grid:
|
| 71 |
+
- Numbers 1-9 are pre-filled or already placed
|
| 72 |
+
- Empty cells are shown as '.'
|
| 73 |
+
- Rows are labeled R1-R9 (top to bottom)
|
| 74 |
+
- Columns are labeled C1-C9 (left to right)
|
| 75 |
+
|
| 76 |
+
Example board representation:
|
| 77 |
+
```
|
| 78 |
+
C1 C2 C3 C4 C5 C6 C7 C8 C9
|
| 79 |
+
R1 . 8 9 | 1 . . | . 3 7
|
| 80 |
+
R2 2 7 1 | 9 4 3 | 6 . 8
|
| 81 |
+
R3 . 6 5 | . 2 7 | 4 9 .
|
| 82 |
+
- - - - - - - - - - - - - - - -
|
| 83 |
+
R4 . . . | 7 8 . | 9 2 3
|
| 84 |
+
R5 . 9 2 | . 5 6 | . . 4
|
| 85 |
+
R6 7 3 8 | . . 2 | 1 . .
|
| 86 |
+
- - - - - - - - - - - - - - - -
|
| 87 |
+
R7 8 4 . | . . 9 | 5 . .
|
| 88 |
+
R8 5 . . | 6 . 8 | 3 4 9
|
| 89 |
+
R9 9 . 6 | 5 3 4 | 8 7 2
|
| 90 |
+
```
|
| 91 |
+
|
| 92 |
+
## COORDINATE REFERENCE
|
| 93 |
+
|
| 94 |
+
Row indices (top to bottom): 1, 2, 3, 4, 5, 6, 7, 8, 9
|
| 95 |
+
Column indices (left to right): 1, 2, 3, 4, 5, 6, 7, 8, 9
|
| 96 |
+
|
| 97 |
+
Subgrid layout:
|
| 98 |
+
```
|
| 99 |
+
Subgrid 1 | Subgrid 2 | Subgrid 3
|
| 100 |
+
(R1-R3) (R1-R3) (R1-R3)
|
| 101 |
+
(C1-C3) (C4-C6) (C7-C9)
|
| 102 |
+
----------+-----------+----------
|
| 103 |
+
Subgrid 4 | Subgrid 5 | Subgrid 6
|
| 104 |
+
(R4-R6) (R4-R6) (R4-R6)
|
| 105 |
+
(C1-C3) (C4-C6) (C7-C9)
|
| 106 |
+
----------+-----------+----------
|
| 107 |
+
Subgrid 7 | Subgrid 8 | Subgrid 9
|
| 108 |
+
(R7-R9) (R7-R9) (R7-R9)
|
| 109 |
+
(C1-C3) (C4-C6) (C7-C9)
|
| 110 |
+
```
|
| 111 |
+
|
| 112 |
+
## IMPORTANT CONSTRAINTS
|
| 113 |
+
|
| 114 |
+
- Coordinates are 1-indexed (1-9 for both row and column)
|
| 115 |
+
- Numbers must be 1-9
|
| 116 |
+
- One move per tool call
|
| 117 |
+
- Must be a valid move (no rule violations)
|
| 118 |
+
- Never repeat a previous move
|
| 119 |
+
|
| 120 |
+
## YOUR GOAL
|
| 121 |
+
|
| 122 |
+
Use ONLY the `place` tool to fill in empty cells one at a time. No explanation, no reasoning, just the `place`.
|
tasks/tasksmith-fa1a9b35ff39/tests/source/examples/scripts/openenv/wordle.py
ADDED
|
@@ -0,0 +1,277 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2020-2026 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
# /// script
|
| 16 |
+
# dependencies = [
|
| 17 |
+
# "trl",
|
| 18 |
+
# "trackio",
|
| 19 |
+
# "openenv-textarena @ git+https://huggingface.co/spaces/openenv/wordle",
|
| 20 |
+
# ]
|
| 21 |
+
# ///
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
"""
|
| 25 |
+
Simple script to run GRPO training with OpenEnv's Wordle environment and vLLM.
|
| 26 |
+
|
| 27 |
+
Setup (Option A - Install from HF Space, recommended):
|
| 28 |
+
|
| 29 |
+
```sh
|
| 30 |
+
uv pip install git+https://huggingface.co/spaces/openenv/wordle
|
| 31 |
+
```
|
| 32 |
+
|
| 33 |
+
# Option 1: HF Spaces + Colocated vLLM (1 GPU required)
|
| 34 |
+
```sh
|
| 35 |
+
python examples/scripts/openenv/wordle.py --vllm-mode colocate
|
| 36 |
+
```
|
| 37 |
+
|
| 38 |
+
# Option 2: HF Spaces + Separate vLLM server (2 GPUs required)
|
| 39 |
+
|
| 40 |
+
# Spin up vLLM server (Terminal 1)
|
| 41 |
+
```sh
|
| 42 |
+
CUDA_VISIBLE_DEVICES=0 trl vllm-serve --model Qwen/Qwen3-1.7B --host 0.0.0.0 --port 8000
|
| 43 |
+
```
|
| 44 |
+
|
| 45 |
+
# Run training (Terminal 2)
|
| 46 |
+
```sh
|
| 47 |
+
CUDA_VISIBLE_DEVICES=1 python examples/scripts/openenv/wordle.py --vllm-mode server --vllm-server-url http://localhost:8000
|
| 48 |
+
```
|
| 49 |
+
|
| 50 |
+
# Option 3: Local Environment + Colocated vLLM (1 GPU required)
|
| 51 |
+
|
| 52 |
+
To run the Wordle environment locally, you have several options:
|
| 53 |
+
|
| 54 |
+
## Option 3a: Using Docker Image (Recommended)
|
| 55 |
+
|
| 56 |
+
First, build the Docker image from the textarena_env directory:
|
| 57 |
+
```sh
|
| 58 |
+
cd 3rd_party/OpenEnv/envs/textarena_env
|
| 59 |
+
docker build -t textarena-env:latest -f server/Dockerfile .
|
| 60 |
+
```
|
| 61 |
+
|
| 62 |
+
Then run the environment server:
|
| 63 |
+
```sh
|
| 64 |
+
docker run -d -p 8001:8001 textarena-env:latest
|
| 65 |
+
```
|
| 66 |
+
|
| 67 |
+
Finally, run training pointing to local server:
|
| 68 |
+
```sh
|
| 69 |
+
python examples/scripts/openenv/wordle.py --vllm-mode colocate --env-url http://localhost:8001
|
| 70 |
+
```
|
| 71 |
+
|
| 72 |
+
## Option 3b: Running Server Directly
|
| 73 |
+
|
| 74 |
+
From the textarena_env directory:
|
| 75 |
+
```sh
|
| 76 |
+
cd 3rd_party/OpenEnv/envs/textarena_env
|
| 77 |
+
uv venv && source .venv/bin/activate
|
| 78 |
+
uv pip install -e .
|
| 79 |
+
python -m uvicorn server.app:app --reload --port 8001
|
| 80 |
+
```
|
| 81 |
+
|
| 82 |
+
Then in another terminal, run training:
|
| 83 |
+
```sh
|
| 84 |
+
python examples/scripts/openenv/wordle.py --vllm-mode colocate --env-url http://localhost:8001
|
| 85 |
+
```
|
| 86 |
+
|
| 87 |
+
## Option 3c: Using Pre-built HF Space Image
|
| 88 |
+
|
| 89 |
+
```sh
|
| 90 |
+
docker run -d -p 8001:8001 registry.hf.space/burtenshaw-wordle:latest
|
| 91 |
+
python examples/scripts/openenv/wordle.py --vllm-mode colocate --env-url http://localhost:8001
|
| 92 |
+
```
|
| 93 |
+
"""
|
| 94 |
+
|
| 95 |
+
import argparse
|
| 96 |
+
|
| 97 |
+
from datasets import Dataset
|
| 98 |
+
from textarena_env import TextArenaAction, TextArenaEnv
|
| 99 |
+
|
| 100 |
+
from trl import GRPOConfig, GRPOTrainer, RichProgressCallback
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
def parse_args() -> argparse.Namespace:
|
| 104 |
+
parser = argparse.ArgumentParser(
|
| 105 |
+
description="Run GRPO training for Wordle using the TextArena OpenEnv environment."
|
| 106 |
+
)
|
| 107 |
+
parser.add_argument(
|
| 108 |
+
"--model",
|
| 109 |
+
type=str,
|
| 110 |
+
default="Qwen/Qwen3-1.7B",
|
| 111 |
+
help="Model identifier passed to GRPOTrainer for fine-tuning.",
|
| 112 |
+
)
|
| 113 |
+
parser.add_argument(
|
| 114 |
+
"--env-url",
|
| 115 |
+
type=str,
|
| 116 |
+
default="https://openenv-wordle.hf.space",
|
| 117 |
+
help="URL for the environment server.",
|
| 118 |
+
)
|
| 119 |
+
parser.add_argument(
|
| 120 |
+
"--dataset-size",
|
| 121 |
+
type=int,
|
| 122 |
+
default=1000,
|
| 123 |
+
help="Number of entries to include in the synthetic training dataset.",
|
| 124 |
+
)
|
| 125 |
+
parser.add_argument(
|
| 126 |
+
"--num-generations",
|
| 127 |
+
type=int,
|
| 128 |
+
default=4,
|
| 129 |
+
help="Number of rollout generations per dataset prompt.",
|
| 130 |
+
)
|
| 131 |
+
parser.add_argument(
|
| 132 |
+
"--num-epochs",
|
| 133 |
+
type=int,
|
| 134 |
+
default=1,
|
| 135 |
+
help="Number of training epochs.",
|
| 136 |
+
)
|
| 137 |
+
parser.add_argument(
|
| 138 |
+
"--learning-rate",
|
| 139 |
+
type=float,
|
| 140 |
+
default=1e-6,
|
| 141 |
+
help="Learning rate for GRPO training.",
|
| 142 |
+
)
|
| 143 |
+
parser.add_argument(
|
| 144 |
+
"--gradient-accumulation-steps",
|
| 145 |
+
type=int,
|
| 146 |
+
default=64,
|
| 147 |
+
help="Gradient accumulation steps for GRPO training.",
|
| 148 |
+
)
|
| 149 |
+
parser.add_argument(
|
| 150 |
+
"--logging-steps",
|
| 151 |
+
type=int,
|
| 152 |
+
default=1,
|
| 153 |
+
help="Frequency of logging steps for GRPO training.",
|
| 154 |
+
)
|
| 155 |
+
parser.add_argument(
|
| 156 |
+
"--output-dir",
|
| 157 |
+
type=str,
|
| 158 |
+
default=None,
|
| 159 |
+
help="Directory where training outputs and checkpoints are stored.",
|
| 160 |
+
)
|
| 161 |
+
parser.add_argument(
|
| 162 |
+
"--trackio-space-id",
|
| 163 |
+
type=str,
|
| 164 |
+
default="wordle-grpo",
|
| 165 |
+
help="Trackio space identifier.",
|
| 166 |
+
)
|
| 167 |
+
parser.add_argument(
|
| 168 |
+
"--vllm-mode",
|
| 169 |
+
choices=("colocate", "server"),
|
| 170 |
+
default="colocate",
|
| 171 |
+
help="vLLM execution mode: 'colocate' or 'server'.",
|
| 172 |
+
)
|
| 173 |
+
parser.add_argument(
|
| 174 |
+
"--vllm-server-url",
|
| 175 |
+
type=str,
|
| 176 |
+
default="http://localhost:8000",
|
| 177 |
+
help="URL for the vLLM server (only used when --vllm-mode=server).",
|
| 178 |
+
)
|
| 179 |
+
return parser.parse_args()
|
| 180 |
+
|
| 181 |
+
|
| 182 |
+
prompt = """You are an expert Wordle solver with deep knowledge of English vocabulary, letter frequency patterns, and optimal guessing strategies.
|
| 183 |
+
|
| 184 |
+
Follow these rules to play Wordle:
|
| 185 |
+
|
| 186 |
+
1. The target is a 5-letter English word
|
| 187 |
+
2. You have 6 attempts to guess the correct word
|
| 188 |
+
3. After each guess, you receive color-coded feedback:
|
| 189 |
+
- GREEN (G): Letter is correct and in the correct position
|
| 190 |
+
- YELLOW (Y): Letter is in the word but in the wrong position
|
| 191 |
+
- GRAY (X): Letter is not in the word at all
|
| 192 |
+
4. All guesses must be valid 5-letter English words
|
| 193 |
+
5. You cannot reuse a word you've already guessed
|
| 194 |
+
6. Use the tool `guess` to make a guess.
|
| 195 |
+
"""
|
| 196 |
+
|
| 197 |
+
|
| 198 |
+
def reward_func(environments, **kwargs) -> list[float]:
|
| 199 |
+
return [env.reward for env in environments]
|
| 200 |
+
|
| 201 |
+
|
| 202 |
+
def main() -> None:
|
| 203 |
+
args = parse_args()
|
| 204 |
+
|
| 205 |
+
env_url = args.env_url
|
| 206 |
+
|
| 207 |
+
class WordleEnv:
|
| 208 |
+
def __init__(self):
|
| 209 |
+
self.client = TextArenaEnv(base_url=env_url)
|
| 210 |
+
|
| 211 |
+
def reset(self, **kwargs) -> str | None:
|
| 212 |
+
result = self.client.reset()
|
| 213 |
+
# The game returns cumulative feedback each turn (new text appended at the end), so
|
| 214 |
+
# we store the previous full response and slice out only the newly appended part.
|
| 215 |
+
self._last_full_feedback = result.observation.messages[0].content
|
| 216 |
+
self.reward = 0.0
|
| 217 |
+
self.done = False
|
| 218 |
+
return self._last_full_feedback
|
| 219 |
+
|
| 220 |
+
def guess(self, guess: str) -> str:
|
| 221 |
+
"""
|
| 222 |
+
Make a guess in the Wordle environment.
|
| 223 |
+
|
| 224 |
+
Args:
|
| 225 |
+
guess: The guessed word, formatted as '[abcde]'
|
| 226 |
+
|
| 227 |
+
Returns:
|
| 228 |
+
The feedback message from the environment.
|
| 229 |
+
"""
|
| 230 |
+
if self.done:
|
| 231 |
+
raise ValueError("Game over.")
|
| 232 |
+
result = self.client.step(TextArenaAction(message=guess))
|
| 233 |
+
_full_feedback = result.observation.messages[0].content
|
| 234 |
+
# Just take the new feedback since the last guess, which is the part appended to the end of the full feedback
|
| 235 |
+
feedback = _full_feedback[len(self._last_full_feedback) :]
|
| 236 |
+
self._last_full_feedback = _full_feedback
|
| 237 |
+
# For some reason, the environment doesn't penalize invalid moves and just returns the last reward.
|
| 238 |
+
# We check the feedback for the invalid move message and penalize it if found.
|
| 239 |
+
if "You attempted an invalid move" in feedback:
|
| 240 |
+
self.reward = 0.0
|
| 241 |
+
else:
|
| 242 |
+
self.reward = result.reward
|
| 243 |
+
self.done = result.done
|
| 244 |
+
return feedback
|
| 245 |
+
|
| 246 |
+
output_dir = args.output_dir or f"{args.model.split('/')[-1]}-wordle-GRPO"
|
| 247 |
+
dataset = Dataset.from_dict({"prompt": [[{"role": "user", "content": prompt}] for _ in range(args.dataset_size)]})
|
| 248 |
+
|
| 249 |
+
trainer = GRPOTrainer(
|
| 250 |
+
model=args.model,
|
| 251 |
+
reward_funcs=reward_func,
|
| 252 |
+
train_dataset=dataset,
|
| 253 |
+
args=GRPOConfig(
|
| 254 |
+
output_dir=output_dir,
|
| 255 |
+
use_vllm=True,
|
| 256 |
+
vllm_mode=args.vllm_mode,
|
| 257 |
+
vllm_server_base_url=args.vllm_server_url if args.vllm_mode == "server" else None,
|
| 258 |
+
report_to="trackio",
|
| 259 |
+
trackio_space_id=args.trackio_space_id,
|
| 260 |
+
log_completions=True,
|
| 261 |
+
num_completions_to_print=2,
|
| 262 |
+
logging_steps=args.logging_steps,
|
| 263 |
+
num_train_epochs=args.num_epochs,
|
| 264 |
+
num_generations=args.num_generations,
|
| 265 |
+
learning_rate=args.learning_rate,
|
| 266 |
+
gradient_accumulation_steps=args.gradient_accumulation_steps,
|
| 267 |
+
chat_template_kwargs={"enable_thinking": False},
|
| 268 |
+
max_completion_length=1024,
|
| 269 |
+
),
|
| 270 |
+
environment_factory=WordleEnv,
|
| 271 |
+
callbacks=[RichProgressCallback()],
|
| 272 |
+
)
|
| 273 |
+
trainer.train()
|
| 274 |
+
|
| 275 |
+
|
| 276 |
+
if __name__ == "__main__":
|
| 277 |
+
main()
|
tasks/tasksmith-fa1a9b35ff39/tests/source/examples/scripts/openreward/seta.py
ADDED
|
@@ -0,0 +1,127 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2020-2026 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
# /// script
|
| 16 |
+
# dependencies = ["trl[vllm,openreward]"]
|
| 17 |
+
# ///
|
| 18 |
+
|
| 19 |
+
"""GRPO training against the SETA ORS environment.
|
| 20 |
+
|
| 21 |
+
Defaults target ``Eigent/SETA`` on the openreward.ai catalog (requires
|
| 22 |
+
``OPENREWARD_API_KEY``). Pass ``--target https://...hf.space`` to point
|
| 23 |
+
at a self-hosted Space.
|
| 24 |
+
|
| 25 |
+
Usage (colocate vLLM, single-node):
|
| 26 |
+
|
| 27 |
+
```sh
|
| 28 |
+
accelerate launch \
|
| 29 |
+
--config_file examples/accelerate_configs/deepspeed_zero2.yaml \
|
| 30 |
+
--num_processes 4 \
|
| 31 |
+
examples/scripts/openreward/seta.py \
|
| 32 |
+
--vllm-mode colocate
|
| 33 |
+
```
|
| 34 |
+
|
| 35 |
+
Usage (server vLLM, single-node 2+2 GPU split):
|
| 36 |
+
|
| 37 |
+
```sh
|
| 38 |
+
# Terminal 1 — vLLM
|
| 39 |
+
CUDA_VISIBLE_DEVICES=2,3 trl vllm-serve --model Qwen/Qwen3-4B \
|
| 40 |
+
--tensor-parallel-size 2 --port 8000
|
| 41 |
+
|
| 42 |
+
# Terminal 2 — training
|
| 43 |
+
CUDA_VISIBLE_DEVICES=0,1 accelerate launch \
|
| 44 |
+
--config_file examples/accelerate_configs/deepspeed_zero2.yaml \
|
| 45 |
+
--num_processes 2 \
|
| 46 |
+
examples/scripts/openreward/seta.py \
|
| 47 |
+
--vllm-mode server --vllm-server-base-url http://localhost:8000
|
| 48 |
+
```
|
| 49 |
+
"""
|
| 50 |
+
|
| 51 |
+
import argparse
|
| 52 |
+
|
| 53 |
+
from trl import GRPOConfig, GRPOTrainer
|
| 54 |
+
from trl.experimental.openreward import OpenRewardSpec
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def parse_args() -> argparse.Namespace:
|
| 58 |
+
parser = argparse.ArgumentParser(description="GRPO training against the SETA ORS environment.")
|
| 59 |
+
|
| 60 |
+
parser.add_argument("--model", type=str, default="Qwen/Qwen3-4B")
|
| 61 |
+
parser.add_argument(
|
| 62 |
+
"--target",
|
| 63 |
+
type=str,
|
| 64 |
+
default="Eigent/SETA",
|
| 65 |
+
help="ORS env target — either a catalog name (e.g. 'Eigent/SETA') or a URL "
|
| 66 |
+
"(e.g. 'https://you-seta.hf.space').",
|
| 67 |
+
)
|
| 68 |
+
parser.add_argument("--split", type=str, default="train")
|
| 69 |
+
parser.add_argument("--num-tasks", type=int, default=64)
|
| 70 |
+
|
| 71 |
+
parser.add_argument("--learning-rate", type=float, default=5e-7)
|
| 72 |
+
parser.add_argument("--per-device-train-batch-size", type=int, default=1)
|
| 73 |
+
parser.add_argument("--gradient-accumulation-steps", type=int, default=1)
|
| 74 |
+
parser.add_argument("--num-generations", type=int, default=2)
|
| 75 |
+
parser.add_argument("--max-completion-length", type=int, default=2048)
|
| 76 |
+
parser.add_argument("--max-steps", type=int, default=5)
|
| 77 |
+
parser.add_argument("--max-tool-calling-iterations", type=int, default=20)
|
| 78 |
+
|
| 79 |
+
parser.add_argument("--vllm-mode", choices=("colocate", "server"), default="colocate")
|
| 80 |
+
parser.add_argument("--vllm-server-base-url", type=str, default="http://localhost:8000")
|
| 81 |
+
parser.add_argument("--vllm-gpu-memory-utilization", type=float, default=0.3)
|
| 82 |
+
|
| 83 |
+
parser.add_argument("--output-dir", type=str, default=None)
|
| 84 |
+
parser.add_argument("--report-to", type=str, default="none")
|
| 85 |
+
|
| 86 |
+
return parser.parse_args()
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
def main() -> None:
|
| 90 |
+
args = parse_args()
|
| 91 |
+
|
| 92 |
+
# One spec object — fans out into TRL's three slots.
|
| 93 |
+
spec = OpenRewardSpec(args.target, num_tasks=args.num_tasks, split=args.split)
|
| 94 |
+
|
| 95 |
+
config_kwargs: dict = dict(
|
| 96 |
+
learning_rate=args.learning_rate,
|
| 97 |
+
per_device_train_batch_size=args.per_device_train_batch_size,
|
| 98 |
+
gradient_accumulation_steps=args.gradient_accumulation_steps,
|
| 99 |
+
num_generations=args.num_generations,
|
| 100 |
+
max_completion_length=args.max_completion_length,
|
| 101 |
+
max_steps=args.max_steps,
|
| 102 |
+
max_tool_calling_iterations=args.max_tool_calling_iterations,
|
| 103 |
+
chat_template_kwargs={"enable_thinking": False},
|
| 104 |
+
log_completions=True,
|
| 105 |
+
use_vllm=True,
|
| 106 |
+
vllm_mode=args.vllm_mode,
|
| 107 |
+
report_to=[s.strip() for s in args.report_to.split(",") if s.strip() and s.strip() != "none"] or "none",
|
| 108 |
+
)
|
| 109 |
+
if args.output_dir:
|
| 110 |
+
config_kwargs["output_dir"] = args.output_dir
|
| 111 |
+
if args.vllm_mode == "colocate":
|
| 112 |
+
config_kwargs["vllm_gpu_memory_utilization"] = args.vllm_gpu_memory_utilization
|
| 113 |
+
else:
|
| 114 |
+
config_kwargs["vllm_server_base_url"] = args.vllm_server_base_url
|
| 115 |
+
|
| 116 |
+
trainer = GRPOTrainer(
|
| 117 |
+
model=args.model,
|
| 118 |
+
args=GRPOConfig(**config_kwargs),
|
| 119 |
+
train_dataset=spec.train_dataset,
|
| 120 |
+
environment_factory=spec.environment_factory,
|
| 121 |
+
reward_funcs=spec.reward_funcs,
|
| 122 |
+
)
|
| 123 |
+
trainer.train()
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
if __name__ == "__main__":
|
| 127 |
+
main()
|
tasks/tasksmith-fa1a9b35ff39/tests/source/examples/scripts/orpo.py
ADDED
|
@@ -0,0 +1,102 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2020-2026 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
# /// script
|
| 16 |
+
# dependencies = [
|
| 17 |
+
# "trl[peft]",
|
| 18 |
+
# "trackio",
|
| 19 |
+
# "kernels",
|
| 20 |
+
# ]
|
| 21 |
+
# ///
|
| 22 |
+
|
| 23 |
+
"""
|
| 24 |
+
Run the ORPO training script with the following command with some example arguments.
|
| 25 |
+
In general, the optimal configuration for ORPO will be similar to that of DPO without the need for a reference model:
|
| 26 |
+
|
| 27 |
+
# regular:
|
| 28 |
+
python examples/scripts/orpo.py \
|
| 29 |
+
--dataset_name trl-internal-testing/hh-rlhf-helpful-base-trl-style \
|
| 30 |
+
--model_name_or_path gpt2 \
|
| 31 |
+
--per_device_train_batch_size 4 \
|
| 32 |
+
--max_steps 1000 \
|
| 33 |
+
--learning_rate 8e-6 \
|
| 34 |
+
--gradient_accumulation_steps 1 \
|
| 35 |
+
--eval_steps 500 \
|
| 36 |
+
--output_dir "gpt2-aligned-orpo" \
|
| 37 |
+
--warmup_steps 150 \
|
| 38 |
+
--logging_first_step \
|
| 39 |
+
--no_remove_unused_columns
|
| 40 |
+
|
| 41 |
+
# peft:
|
| 42 |
+
python examples/scripts/orpo.py \
|
| 43 |
+
--dataset_name trl-internal-testing/hh-rlhf-helpful-base-trl-style \
|
| 44 |
+
--model_name_or_path gpt2 \
|
| 45 |
+
--per_device_train_batch_size 4 \
|
| 46 |
+
--max_steps 1000 \
|
| 47 |
+
--learning_rate 8e-5 \
|
| 48 |
+
--gradient_accumulation_steps 1 \
|
| 49 |
+
--eval_steps 500 \
|
| 50 |
+
--output_dir "gpt2-lora-aligned-orpo" \
|
| 51 |
+
--optim rmsprop \
|
| 52 |
+
--warmup_steps 150 \
|
| 53 |
+
--logging_first_step \
|
| 54 |
+
--no_remove_unused_columns \
|
| 55 |
+
--use_peft \
|
| 56 |
+
--lora_r 16 \
|
| 57 |
+
--lora_alpha 16
|
| 58 |
+
"""
|
| 59 |
+
|
| 60 |
+
from datasets import load_dataset
|
| 61 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer, HfArgumentParser
|
| 62 |
+
|
| 63 |
+
from trl import ModelConfig, ScriptArguments, get_peft_config
|
| 64 |
+
from trl.experimental.orpo import ORPOConfig, ORPOTrainer
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
if __name__ == "__main__":
|
| 68 |
+
parser = HfArgumentParser((ScriptArguments, ORPOConfig, ModelConfig))
|
| 69 |
+
script_args, training_args, model_args = parser.parse_args_into_dataclasses()
|
| 70 |
+
|
| 71 |
+
################
|
| 72 |
+
# Model & Tokenizer
|
| 73 |
+
################
|
| 74 |
+
model = AutoModelForCausalLM.from_pretrained(model_args.model_name_or_path)
|
| 75 |
+
tokenizer = AutoTokenizer.from_pretrained(model_args.model_name_or_path)
|
| 76 |
+
if tokenizer.pad_token is None:
|
| 77 |
+
tokenizer.pad_token = tokenizer.eos_token
|
| 78 |
+
|
| 79 |
+
################
|
| 80 |
+
# Dataset
|
| 81 |
+
################
|
| 82 |
+
dataset = load_dataset(script_args.dataset_name, name=script_args.dataset_config)
|
| 83 |
+
|
| 84 |
+
################
|
| 85 |
+
# Training
|
| 86 |
+
################
|
| 87 |
+
trainer = ORPOTrainer(
|
| 88 |
+
model,
|
| 89 |
+
args=training_args,
|
| 90 |
+
train_dataset=dataset[script_args.dataset_train_split],
|
| 91 |
+
eval_dataset=dataset[script_args.dataset_test_split] if training_args.eval_strategy != "no" else None,
|
| 92 |
+
processing_class=tokenizer,
|
| 93 |
+
peft_config=get_peft_config(model_args),
|
| 94 |
+
)
|
| 95 |
+
|
| 96 |
+
# train and save the model
|
| 97 |
+
trainer.train()
|
| 98 |
+
|
| 99 |
+
# Save and push to hub
|
| 100 |
+
trainer.save_model(training_args.output_dir)
|
| 101 |
+
if training_args.push_to_hub:
|
| 102 |
+
trainer.push_to_hub(dataset_name=script_args.dataset_name)
|
tasks/tasksmith-fa1a9b35ff39/tests/source/examples/scripts/ppo/ppo.py
ADDED
|
@@ -0,0 +1,160 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2020-2026 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
# /// script
|
| 16 |
+
# dependencies = [
|
| 17 |
+
# "trl[peft]",
|
| 18 |
+
# "trackio",
|
| 19 |
+
# "kernels",
|
| 20 |
+
# ]
|
| 21 |
+
# ///
|
| 22 |
+
|
| 23 |
+
import shutil
|
| 24 |
+
|
| 25 |
+
import torch
|
| 26 |
+
from accelerate import PartialState
|
| 27 |
+
from datasets import load_dataset
|
| 28 |
+
from transformers import (
|
| 29 |
+
AutoModelForCausalLM,
|
| 30 |
+
AutoModelForSequenceClassification,
|
| 31 |
+
AutoTokenizer,
|
| 32 |
+
HfArgumentParser,
|
| 33 |
+
)
|
| 34 |
+
|
| 35 |
+
from trl import ModelConfig, ScriptArguments, get_kbit_device_map, get_peft_config, get_quantization_config
|
| 36 |
+
from trl.experimental.ppo import PPOConfig, PPOTrainer
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
"""
|
| 40 |
+
python -i examples/scripts/ppo/ppo.py \
|
| 41 |
+
--dataset_name trl-internal-testing/descriptiveness-sentiment-trl-style \
|
| 42 |
+
--dataset_train_split descriptiveness \
|
| 43 |
+
--output_dir pythia-1b-deduped-descriptiveness-sentiment-trl-style-ppo \
|
| 44 |
+
--per_device_train_batch_size 64 \
|
| 45 |
+
--gradient_accumulation_steps 1 \
|
| 46 |
+
--total_episodes 10000 \
|
| 47 |
+
--model_name_or_path EleutherAI/pythia-1b-deduped \
|
| 48 |
+
--missing_eos_penalty 1.0
|
| 49 |
+
|
| 50 |
+
accelerate launch --config_file examples/accelerate_configs/deepspeed_zero3.yaml \
|
| 51 |
+
examples/scripts/ppo/ppo.py \
|
| 52 |
+
--dataset_name trl-internal-testing/descriptiveness-sentiment-trl-style \
|
| 53 |
+
--dataset_train_split descriptiveness \
|
| 54 |
+
--output_dir pythia-1b-deduped-descriptiveness-sentiment-trl-style-ppo \
|
| 55 |
+
--num_ppo_epochs 1 \
|
| 56 |
+
--num_mini_batches 1 \
|
| 57 |
+
--per_device_train_batch_size 1 \
|
| 58 |
+
--gradient_accumulation_steps 16 \
|
| 59 |
+
--total_episodes 10000 \
|
| 60 |
+
--model_name_or_path EleutherAI/pythia-1b-deduped \
|
| 61 |
+
--sft_model_path EleutherAI/pythia-1b-deduped \
|
| 62 |
+
--reward_model_path EleutherAI/pythia-1b-deduped \
|
| 63 |
+
--local_rollout_forward_batch_size 1 \
|
| 64 |
+
--missing_eos_penalty 1.0
|
| 65 |
+
"""
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
if __name__ == "__main__":
|
| 69 |
+
parser = HfArgumentParser((ScriptArguments, PPOConfig, ModelConfig))
|
| 70 |
+
script_args, training_args, model_args = parser.parse_args_into_dataclasses()
|
| 71 |
+
# remove output_dir if exists
|
| 72 |
+
shutil.rmtree(training_args.output_dir, ignore_errors=True)
|
| 73 |
+
|
| 74 |
+
################
|
| 75 |
+
# Model & Tokenizer
|
| 76 |
+
################
|
| 77 |
+
dtype = model_args.dtype if model_args.dtype in ["auto", None] else getattr(torch, model_args.dtype)
|
| 78 |
+
model_kwargs = dict(
|
| 79 |
+
revision=model_args.model_revision,
|
| 80 |
+
attn_implementation=model_args.attn_implementation,
|
| 81 |
+
dtype=dtype,
|
| 82 |
+
)
|
| 83 |
+
quantization_config = get_quantization_config(model_args)
|
| 84 |
+
if quantization_config is not None:
|
| 85 |
+
# Passing None would not be treated the same as omitting the argument, so we include it only when valid.
|
| 86 |
+
model_kwargs["device_map"] = get_kbit_device_map()
|
| 87 |
+
model_kwargs["quantization_config"] = quantization_config
|
| 88 |
+
|
| 89 |
+
tokenizer = AutoTokenizer.from_pretrained(model_args.model_name_or_path, padding_side="left")
|
| 90 |
+
tokenizer.add_special_tokens({"pad_token": "[PAD]"})
|
| 91 |
+
value_model = AutoModelForSequenceClassification.from_pretrained(
|
| 92 |
+
training_args.reward_model_path, num_labels=1, **model_kwargs
|
| 93 |
+
)
|
| 94 |
+
reward_model = AutoModelForSequenceClassification.from_pretrained(
|
| 95 |
+
training_args.reward_model_path, num_labels=1, **model_kwargs
|
| 96 |
+
)
|
| 97 |
+
policy = AutoModelForCausalLM.from_pretrained(training_args.sft_model_path, **model_kwargs)
|
| 98 |
+
|
| 99 |
+
peft_config = get_peft_config(model_args)
|
| 100 |
+
if peft_config is None:
|
| 101 |
+
ref_policy = AutoModelForCausalLM.from_pretrained(training_args.sft_model_path, **model_kwargs)
|
| 102 |
+
else:
|
| 103 |
+
ref_policy = None
|
| 104 |
+
|
| 105 |
+
################
|
| 106 |
+
# Dataset
|
| 107 |
+
################
|
| 108 |
+
dataset = load_dataset(
|
| 109 |
+
script_args.dataset_name, name=script_args.dataset_config, split=script_args.dataset_train_split
|
| 110 |
+
)
|
| 111 |
+
eval_samples = 100
|
| 112 |
+
train_dataset = dataset.select(range(len(dataset) - eval_samples))
|
| 113 |
+
eval_dataset = dataset.select(range(len(dataset) - eval_samples, len(dataset)))
|
| 114 |
+
dataset_text_field = "prompt"
|
| 115 |
+
|
| 116 |
+
def prepare_dataset(dataset, tokenizer):
|
| 117 |
+
"""pre-tokenize the dataset before training; only collate during training"""
|
| 118 |
+
|
| 119 |
+
def tokenize(element):
|
| 120 |
+
outputs = tokenizer(
|
| 121 |
+
element[dataset_text_field],
|
| 122 |
+
padding=False,
|
| 123 |
+
)
|
| 124 |
+
return {"input_ids": outputs["input_ids"]}
|
| 125 |
+
|
| 126 |
+
return dataset.map(
|
| 127 |
+
tokenize,
|
| 128 |
+
batched=True,
|
| 129 |
+
remove_columns=dataset.column_names,
|
| 130 |
+
num_proc=training_args.dataset_num_proc,
|
| 131 |
+
)
|
| 132 |
+
|
| 133 |
+
# Compute that only on the main process for faster data processing.
|
| 134 |
+
# see: https://github.com/huggingface/trl/pull/1255
|
| 135 |
+
with PartialState().local_main_process_first():
|
| 136 |
+
train_dataset = prepare_dataset(train_dataset, tokenizer)
|
| 137 |
+
eval_dataset = prepare_dataset(eval_dataset, tokenizer)
|
| 138 |
+
|
| 139 |
+
################
|
| 140 |
+
# Training
|
| 141 |
+
################
|
| 142 |
+
trainer = PPOTrainer(
|
| 143 |
+
args=training_args,
|
| 144 |
+
processing_class=tokenizer,
|
| 145 |
+
model=policy,
|
| 146 |
+
ref_model=ref_policy,
|
| 147 |
+
reward_model=reward_model,
|
| 148 |
+
value_model=value_model,
|
| 149 |
+
train_dataset=train_dataset,
|
| 150 |
+
eval_dataset=eval_dataset,
|
| 151 |
+
peft_config=peft_config,
|
| 152 |
+
)
|
| 153 |
+
trainer.train()
|
| 154 |
+
|
| 155 |
+
# Save and push to hub
|
| 156 |
+
trainer.save_model(training_args.output_dir)
|
| 157 |
+
if training_args.push_to_hub:
|
| 158 |
+
trainer.push_to_hub(dataset_name=script_args.dataset_name)
|
| 159 |
+
|
| 160 |
+
trainer.generate_completions()
|
tasks/tasksmith-fa1a9b35ff39/tests/source/examples/scripts/ppo/ppo_tldr.py
ADDED
|
@@ -0,0 +1,168 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2020-2026 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
# /// script
|
| 16 |
+
# dependencies = [
|
| 17 |
+
# "trl[peft]",
|
| 18 |
+
# "trackio",
|
| 19 |
+
# "kernels",
|
| 20 |
+
# ]
|
| 21 |
+
# ///
|
| 22 |
+
|
| 23 |
+
import shutil
|
| 24 |
+
|
| 25 |
+
import torch
|
| 26 |
+
from accelerate import PartialState
|
| 27 |
+
from datasets import load_dataset
|
| 28 |
+
from transformers import (
|
| 29 |
+
AutoModelForCausalLM,
|
| 30 |
+
AutoModelForSequenceClassification,
|
| 31 |
+
AutoTokenizer,
|
| 32 |
+
HfArgumentParser,
|
| 33 |
+
)
|
| 34 |
+
|
| 35 |
+
from trl import ModelConfig, ScriptArguments, get_kbit_device_map, get_peft_config, get_quantization_config
|
| 36 |
+
from trl.experimental.ppo import PPOConfig, PPOTrainer
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
"""
|
| 40 |
+
python examples/scripts/ppo/ppo_tldr.py \
|
| 41 |
+
--dataset_name trl-lib/tldr \
|
| 42 |
+
--dataset_test_split validation \
|
| 43 |
+
--output_dir pythia-1b-deduped-tldr-preference-sft-trl-style-ppo \
|
| 44 |
+
--per_device_train_batch_size 1 \
|
| 45 |
+
--gradient_accumulation_steps 64 \
|
| 46 |
+
--total_episodes 30000 \
|
| 47 |
+
--model_name_or_path EleutherAI/pythia-1b-deduped \
|
| 48 |
+
--sft_model_path cleanrl/EleutherAI_pythia-1b-deduped__sft__tldr \
|
| 49 |
+
--reward_model_path cleanrl/EleutherAI_pythia-1b-deduped__reward__tldr \
|
| 50 |
+
--missing_eos_penalty 1.0 \
|
| 51 |
+
--stop_token eos \
|
| 52 |
+
--response_length 53 \
|
| 53 |
+
--eval_strategy steps \
|
| 54 |
+
--eval_steps 100
|
| 55 |
+
|
| 56 |
+
accelerate launch --config_file examples/accelerate_configs/deepspeed_zero2.yaml \
|
| 57 |
+
examples/scripts/ppo/ppo_tldr.py \
|
| 58 |
+
--dataset_name trl-lib/tldr \
|
| 59 |
+
--dataset_test_split validation \
|
| 60 |
+
--output_dir pythia-1b-deduped-tldr-preference-sft-trl-style-ppo \
|
| 61 |
+
--per_device_train_batch_size 16 \
|
| 62 |
+
--gradient_accumulation_steps 4 \
|
| 63 |
+
--total_episodes 1000000 \
|
| 64 |
+
--model_name_or_path EleutherAI/pythia-1b-deduped \
|
| 65 |
+
--sft_model_path cleanrl/EleutherAI_pythia-1b-deduped__sft__tldr \
|
| 66 |
+
--reward_model_path cleanrl/EleutherAI_pythia-1b-deduped__reward__tldr \
|
| 67 |
+
--local_rollout_forward_batch_size 16 \
|
| 68 |
+
--missing_eos_penalty 1.0 \
|
| 69 |
+
--stop_token eos \
|
| 70 |
+
--eval_strategy steps \
|
| 71 |
+
--eval_steps 100
|
| 72 |
+
"""
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
if __name__ == "__main__":
|
| 76 |
+
parser = HfArgumentParser((ScriptArguments, PPOConfig, ModelConfig))
|
| 77 |
+
script_args, training_args, model_args = parser.parse_args_into_dataclasses()
|
| 78 |
+
# remove output_dir if exists
|
| 79 |
+
shutil.rmtree(training_args.output_dir, ignore_errors=True)
|
| 80 |
+
|
| 81 |
+
################
|
| 82 |
+
# Model & Tokenizer
|
| 83 |
+
################
|
| 84 |
+
dtype = model_args.dtype if model_args.dtype in ["auto", None] else getattr(torch, model_args.dtype)
|
| 85 |
+
model_kwargs = dict(
|
| 86 |
+
revision=model_args.model_revision,
|
| 87 |
+
attn_implementation=model_args.attn_implementation,
|
| 88 |
+
dtype=dtype,
|
| 89 |
+
)
|
| 90 |
+
quantization_config = get_quantization_config(model_args)
|
| 91 |
+
if quantization_config is not None:
|
| 92 |
+
# Passing None would not be treated the same as omitting the argument, so we include it only when valid.
|
| 93 |
+
model_kwargs["device_map"] = get_kbit_device_map()
|
| 94 |
+
model_kwargs["quantization_config"] = quantization_config
|
| 95 |
+
|
| 96 |
+
tokenizer = AutoTokenizer.from_pretrained(model_args.model_name_or_path, padding_side="left")
|
| 97 |
+
tokenizer.add_special_tokens({"pad_token": "[PAD]"})
|
| 98 |
+
value_model = AutoModelForSequenceClassification.from_pretrained(
|
| 99 |
+
training_args.reward_model_path, num_labels=1, **model_kwargs
|
| 100 |
+
)
|
| 101 |
+
reward_model = AutoModelForSequenceClassification.from_pretrained(
|
| 102 |
+
training_args.reward_model_path,
|
| 103 |
+
num_labels=1,
|
| 104 |
+
**model_kwargs,
|
| 105 |
+
)
|
| 106 |
+
policy = AutoModelForCausalLM.from_pretrained(training_args.sft_model_path, **model_kwargs)
|
| 107 |
+
|
| 108 |
+
peft_config = get_peft_config(model_args)
|
| 109 |
+
if peft_config is None:
|
| 110 |
+
ref_policy = AutoModelForCausalLM.from_pretrained(training_args.sft_model_path, **model_kwargs)
|
| 111 |
+
else:
|
| 112 |
+
ref_policy = None
|
| 113 |
+
|
| 114 |
+
################
|
| 115 |
+
# Dataset
|
| 116 |
+
################
|
| 117 |
+
dataset = load_dataset(script_args.dataset_name, name=script_args.dataset_config)
|
| 118 |
+
train_dataset = dataset[script_args.dataset_train_split]
|
| 119 |
+
eval_dataset = dataset[script_args.dataset_test_split] if training_args.eval_strategy != "no" else None
|
| 120 |
+
|
| 121 |
+
def prepare_dataset(dataset, tokenizer):
|
| 122 |
+
"""pre-tokenize the dataset before training; only collate during training"""
|
| 123 |
+
|
| 124 |
+
def tokenize(element):
|
| 125 |
+
input_ids = tokenizer(element["prompt"], padding=False)["input_ids"]
|
| 126 |
+
return {"input_ids": input_ids, "lengths": len(input_ids)}
|
| 127 |
+
|
| 128 |
+
return dataset.map(
|
| 129 |
+
tokenize,
|
| 130 |
+
remove_columns=dataset.column_names,
|
| 131 |
+
num_proc=training_args.dataset_num_proc,
|
| 132 |
+
)
|
| 133 |
+
|
| 134 |
+
# Compute that only on the main process for faster data processing.
|
| 135 |
+
# see: https://github.com/huggingface/trl/pull/1255
|
| 136 |
+
with PartialState().local_main_process_first():
|
| 137 |
+
train_dataset = prepare_dataset(train_dataset, tokenizer)
|
| 138 |
+
if eval_dataset is not None:
|
| 139 |
+
eval_dataset = prepare_dataset(eval_dataset, tokenizer)
|
| 140 |
+
# filtering
|
| 141 |
+
train_dataset = train_dataset.filter(lambda x: x["lengths"] <= 512, num_proc=training_args.dataset_num_proc)
|
| 142 |
+
if eval_dataset is not None:
|
| 143 |
+
eval_dataset = eval_dataset.filter(lambda x: x["lengths"] <= 512, num_proc=training_args.dataset_num_proc)
|
| 144 |
+
|
| 145 |
+
assert train_dataset[0]["input_ids"][-1] != tokenizer.eos_token_id, "The last token should not be an EOS token"
|
| 146 |
+
|
| 147 |
+
################
|
| 148 |
+
# Training
|
| 149 |
+
################
|
| 150 |
+
trainer = PPOTrainer(
|
| 151 |
+
args=training_args,
|
| 152 |
+
processing_class=tokenizer,
|
| 153 |
+
model=policy,
|
| 154 |
+
ref_model=ref_policy,
|
| 155 |
+
reward_model=reward_model,
|
| 156 |
+
value_model=value_model,
|
| 157 |
+
train_dataset=train_dataset,
|
| 158 |
+
eval_dataset=eval_dataset,
|
| 159 |
+
peft_config=peft_config,
|
| 160 |
+
)
|
| 161 |
+
trainer.train()
|
| 162 |
+
|
| 163 |
+
# Save and push to hub
|
| 164 |
+
trainer.save_model(training_args.output_dir)
|
| 165 |
+
if training_args.push_to_hub:
|
| 166 |
+
trainer.push_to_hub(dataset_name=script_args.dataset_name)
|
| 167 |
+
|
| 168 |
+
trainer.generate_completions()
|
tasks/tasksmith-fa1a9b35ff39/tests/source/examples/scripts/prm.py
ADDED
|
@@ -0,0 +1,128 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2020-2026 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
# /// script
|
| 16 |
+
# dependencies = [
|
| 17 |
+
# "trl",
|
| 18 |
+
# "trackio",
|
| 19 |
+
# "kernels",
|
| 20 |
+
# ]
|
| 21 |
+
# ///
|
| 22 |
+
|
| 23 |
+
"""
|
| 24 |
+
Full training:
|
| 25 |
+
python examples/scripts/prm.py \
|
| 26 |
+
--model_name_or_path Qwen/Qwen2-0.5B-Instruct \
|
| 27 |
+
--dataset_name trl-lib/prm800k \
|
| 28 |
+
--output_dir Qwen2-0.5B-Reward \
|
| 29 |
+
--per_device_train_batch_size 8 \
|
| 30 |
+
--num_train_epochs 1 \
|
| 31 |
+
--learning_rate 1.0e-5 \
|
| 32 |
+
--eval_strategy steps \
|
| 33 |
+
--eval_steps 50
|
| 34 |
+
|
| 35 |
+
LoRA:
|
| 36 |
+
python examples/scripts/prm.py \
|
| 37 |
+
--model_name_or_path Qwen/Qwen2-0.5B-Instruct \
|
| 38 |
+
--dataset_name trl-lib/prm800k \
|
| 39 |
+
--output_dir Qwen2-0.5B-Reward-LoRA \
|
| 40 |
+
--per_device_train_batch_size 8 \
|
| 41 |
+
--num_train_epochs 1 \
|
| 42 |
+
--learning_rate 1.0e-4 \
|
| 43 |
+
--eval_strategy steps \
|
| 44 |
+
--eval_steps 50
|
| 45 |
+
--use_peft \
|
| 46 |
+
--lora_r 32 \
|
| 47 |
+
--lora_alpha 16
|
| 48 |
+
"""
|
| 49 |
+
|
| 50 |
+
import torch
|
| 51 |
+
from accelerate import logging
|
| 52 |
+
from datasets import load_dataset
|
| 53 |
+
from transformers import AutoModelForTokenClassification, AutoTokenizer, HfArgumentParser
|
| 54 |
+
|
| 55 |
+
from trl import (
|
| 56 |
+
ModelConfig,
|
| 57 |
+
ScriptArguments,
|
| 58 |
+
get_kbit_device_map,
|
| 59 |
+
get_peft_config,
|
| 60 |
+
get_quantization_config,
|
| 61 |
+
)
|
| 62 |
+
from trl.experimental.prm import PRMConfig, PRMTrainer
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
logger = logging.get_logger(__name__)
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
if __name__ == "__main__":
|
| 69 |
+
parser = HfArgumentParser((ScriptArguments, PRMConfig, ModelConfig))
|
| 70 |
+
script_args, training_args, model_args = parser.parse_args_into_dataclasses()
|
| 71 |
+
|
| 72 |
+
################
|
| 73 |
+
# Model & Tokenizer
|
| 74 |
+
################
|
| 75 |
+
dtype = model_args.dtype if model_args.dtype in ["auto", None] else getattr(torch, model_args.dtype)
|
| 76 |
+
model_kwargs = dict(
|
| 77 |
+
revision=model_args.model_revision,
|
| 78 |
+
use_cache=False if training_args.gradient_checkpointing else True,
|
| 79 |
+
)
|
| 80 |
+
quantization_config = get_quantization_config(model_args)
|
| 81 |
+
if quantization_config is not None:
|
| 82 |
+
# Passing None would not be treated the same as omitting the argument, so we include it only when valid.
|
| 83 |
+
model_kwargs["device_map"] = get_kbit_device_map()
|
| 84 |
+
model_kwargs["quantization_config"] = quantization_config
|
| 85 |
+
|
| 86 |
+
tokenizer = AutoTokenizer.from_pretrained(model_args.model_name_or_path, use_fast=True)
|
| 87 |
+
model = AutoModelForTokenClassification.from_pretrained(
|
| 88 |
+
model_args.model_name_or_path, num_labels=2, **model_kwargs
|
| 89 |
+
)
|
| 90 |
+
|
| 91 |
+
if model_args.use_peft and model_args.lora_task_type != "TOKEN_CLS":
|
| 92 |
+
logger.warning(
|
| 93 |
+
"You are using a `task_type` that is different than `TOKEN_CLS` for PEFT. This will lead to silent bugs"
|
| 94 |
+
" Make sure to pass --lora_task_type TOKEN_CLS when using this script with PEFT.",
|
| 95 |
+
)
|
| 96 |
+
|
| 97 |
+
##############
|
| 98 |
+
# Load dataset
|
| 99 |
+
##############
|
| 100 |
+
dataset = load_dataset(script_args.dataset_name, name=script_args.dataset_config)
|
| 101 |
+
|
| 102 |
+
dataset = dataset.filter(lambda x: len(x["completions"]) > 0)
|
| 103 |
+
|
| 104 |
+
##########
|
| 105 |
+
# Training
|
| 106 |
+
##########
|
| 107 |
+
trainer = PRMTrainer(
|
| 108 |
+
model=model,
|
| 109 |
+
processing_class=tokenizer,
|
| 110 |
+
args=training_args,
|
| 111 |
+
train_dataset=dataset[script_args.dataset_train_split],
|
| 112 |
+
eval_dataset=dataset[script_args.dataset_test_split],
|
| 113 |
+
peft_config=get_peft_config(model_args),
|
| 114 |
+
)
|
| 115 |
+
trainer.train()
|
| 116 |
+
|
| 117 |
+
############################
|
| 118 |
+
# Save model and push to Hub
|
| 119 |
+
############################
|
| 120 |
+
trainer.save_model(training_args.output_dir)
|
| 121 |
+
metrics = trainer.evaluate()
|
| 122 |
+
trainer.log_metrics("eval", metrics)
|
| 123 |
+
trainer.save_metrics("eval", metrics)
|
| 124 |
+
|
| 125 |
+
# Save and push to hub
|
| 126 |
+
trainer.save_model(training_args.output_dir)
|
| 127 |
+
if training_args.push_to_hub:
|
| 128 |
+
trainer.push_to_hub(dataset_name=script_args.dataset_name)
|