File size: 12,402 Bytes
1fa3c6c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
# Copyright 2020-2026 The HuggingFace Team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

# /// script
# dependencies = [
#     "trl[vllm,peft]",
#     "trackio",
#     "kernels",
#     "openenv-openspiel-env @ git+https://huggingface.co/spaces/openenv/openspiel_env",
# ]
# ///


"""

Simple script to run GRPO training with OpenEnv's Catch environment (OpenSpiel) and vLLM. The reward function

is based on the catch game where the agent tries to catch falling balls.



Setup (Option A - Install from HF Space, recommended):



```sh

uv pip install git+https://huggingface.co/spaces/openenv/openspiel_env

```



Setup (Option B - Clone OpenEnv repo, for development):



```sh

git clone https://github.com/meta-pytorch/OpenEnv.git

cd OpenEnv/envs/openspiel_env

uv pip install -e .

```



# Option 1: HF Spaces + Colocated vLLM (1 GPU required)

```sh

python examples/scripts/openenv/catch.py --env-mode space --env-host https://openenv-openspiel-env.hf.space --vllm-mode colocate

```



# Option 2: HF Spaces + Separate vLLM server (2 GPUs required)



# Spin up vLLM server (Terminal 1)

```sh

CUDA_VISIBLE_DEVICES=0 trl vllm-serve --model Qwen/Qwen2.5-0.5B-Instruct --host 0.0.0.0 --port 8000

```



# Run training (Terminal 2)

```sh

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

```



# Option 3: Local + Colocated vLLM (1 GPU required)



# Start the environment only if using --env-mode docker-local

```sh

docker run -d -p 8001:8001 registry.hf.space/openenv-openspiel-env:latest

```



```sh

python examples/scripts/openenv/catch.py --env-mode docker-local --vllm-mode colocate

```

"""

# ruff: noqa: T201
import argparse
import os
import subprocess
import sys
import time
from pathlib import Path

import requests
from datasets import Dataset
from openspiel_env import OpenSpielEnv
from openspiel_env.models import OpenSpielAction

from trl import GRPOConfig, GRPOTrainer, RichProgressCallback


def parse_args():
    parser = argparse.ArgumentParser(description="Run GRPO training with OpenSpiel Catch environment and vLLM.")

    # --- Environment settings ---
    parser.add_argument("--env-host", type=str, default="0.0.0.0", help="Host for the environment server.")
    parser.add_argument("--env-port", type=int, default=8001, help="Port for the environment server.")
    parser.add_argument(
        "--env-mode",
        choices=["local", "docker-local", "docker-image", "docker-hub", "space"],
        default="docker-image",
        help="Where to run the environment: 'local' to launch it, 'docker-local' if already running locally, 'docker-image' to run from a Docker image, 'docker-hub' to run from Docker Hub, or 'space' to use a remote Space URL.",
    )
    # --- Generation and model config ---
    parser.add_argument(
        "--model",
        type=str,
        default="Qwen/Qwen2.5-0.5B-Instruct",
        help="Model name or path.",
    )
    parser.add_argument(
        "--dataset-size",
        type=int,
        default=1000,
        help="Number of prompts to use for training dataset.",
    )
    parser.add_argument(
        "--env-image", type=str, default="openspiel-env:latest", help="Docker image for the OpenSpiel environment."
    )
    parser.add_argument(
        "--vllm-mode",
        choices=["colocate", "server"],
        default="colocate",
        help="vLLM execution mode: 'colocate' or 'server'.",
    )
    parser.add_argument(
        "--vllm-server-url",
        type=str,
        default="http://localhost:8000",
        help="URL for the vLLM server (only used when --vllm-mode=server).",
    )

    return parser.parse_args()


def start_env_server(env_host: str, env_port: int):
    """Launch the OpenSpiel Catch environment locally via uvicorn."""
    env_url = f"http://{env_host}:{env_port}"
    print(f"⚑ Starting FastAPI server for OpenSpiel Catch Environment on {env_url}...")

    work_dir = str(Path.cwd().parent.absolute())
    process = subprocess.Popen(
        [
            sys.executable,
            "-m",
            "uvicorn",
            "envs.openspiel_env.server.app:app",
            "--host",
            env_host,
            "--port",
            str(env_port),
        ],
        env={**os.environ, "PYTHONPATH": f"{work_dir}/src"},
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE,
        text=True,
        cwd=work_dir,
    )

    print("⏳ Waiting for server to start...")
    time.sleep(5)

    try:
        requests.get(f"{env_url}/health", timeout=2)
        print("\nβœ… OpenSpiel Catch Environment server is running!")
    except Exception as e:
        print(f"\n❌ Server failed to start: {e}")
        if process.stderr:
            print(process.stderr.read())
        raise

    return process


BASE_PROMPT = """You are an AI agent playing the game **Catch**.



### Game Description

- The game is played on a **10Γ—5 grid**.

- There is one **falling ball** and one **paddle** that you control at the bottom.

- The objective is to **move the paddle left or right to catch the ball** as it falls.

- The episode ends when the ball reaches the bottom row:

  - You get **+1 reward** if you catch it.

  - You get **–1 reward** if you miss it.



### Observation Format

Each observation is a flattened 10x5 grid (list of 50 floats).

- 1.0 β†’ occupied (ball or paddle)

- 0.0 β†’ empty cell



You have the following tools available:

- `move(direction)`: Move the paddle left or right. Direction must be "left" or "right".

- `stay`: Do nothing and let the ball fall one step.



Observe the grid, determine where the ball is relative to the paddle, then move accordingly.

"""


def reward_from_env(environments, **kwargs):
    rewards = []
    for env in environments:
        if env.done:
            # Catch gives +1 for catching, -1 for missing. Clamp to [0, 1] for GRPO advantage estimation.
            rewards.append(max(env.reward, 0.0))
        else:
            rewards.append(0.0)  # Incomplete episode
    return rewards


def main():
    args = parse_args()

    # Select environment mode β€” all modes resolve to env_url
    if args.env_mode == "local":
        env_url = f"http://{args.env_host}:{args.env_port}"
        server_process = start_env_server(args.env_host, args.env_port)
    elif args.env_mode == "docker-local":
        env_url = f"http://{args.env_host}:{args.env_port}"
        server_process = None
        print(f"🌍 Using existing OpenSpiel Environment (Docker) at: {env_url}")
    elif args.env_mode == "docker-image":
        _bootstrap = OpenSpielEnv.from_docker_image(args.env_image)
        env_url = _bootstrap.base_url
        server_process = None
        print("🌍 Using OpenSpiel Environment (Docker) from local Image")
    elif args.env_mode == "docker-hub":
        _bootstrap = OpenSpielEnv.from_hub(args.env_image)
        env_url = _bootstrap.base_url
        server_process = None
        print("🌍 Using existing OpenSpiel Environment (Docker) from Hub Image")
    elif args.env_mode == "space":
        env_url = args.env_host
        server_process = None
        print(f"🌍 Using Hugging Face Space environment at: {env_url}")
    else:
        raise ValueError(f"Unknown environment mode: {args.env_mode}")

    dataset = Dataset.from_dict({"prompt": [[{"role": "user", "content": BASE_PROMPT}]] * args.dataset_size})

    class CatchEnv:
        ROWS = 10
        COLS = 5

        def __init__(self):
            self.client = OpenSpielEnv(base_url=env_url)
            self.reward = 0.0
            self.done = False

        @staticmethod
        def _format_obs(info_state: list[float]) -> str:
            """Convert the flat 50-float observation into a readable text description."""
            rows, cols = CatchEnv.ROWS, CatchEnv.COLS
            ball_row = ball_col = paddle_col = None
            for idx, val in enumerate(info_state):
                if val == 1.0:
                    r, c = divmod(idx, cols)
                    if r < rows - 1:
                        ball_row, ball_col = r + 1, c + 1
                    else:
                        paddle_col = c + 1
            parts = []
            if ball_row is not None and ball_col is not None:
                parts.append(f"Ball: row {ball_row}/{rows}, column {ball_col}/{cols}")
            if paddle_col is not None:
                parts.append(f"Paddle: column {paddle_col}/{cols}")
            if ball_col is not None and paddle_col is not None:
                diff = ball_col - paddle_col
                if diff < 0:
                    parts.append(f"The ball is {abs(diff)} column(s) to the LEFT of the paddle.")
                elif diff > 0:
                    parts.append(f"The ball is {diff} column(s) to the RIGHT of the paddle.")
                else:
                    parts.append("The ball is directly above the paddle.")
            return "\n".join(parts)

        def reset(self, **kwargs) -> str:
            env_result = self.client.reset()
            self.reward = 0.0
            self.done = env_result.observation.done
            return self._format_obs(env_result.observation.info_state)

        def _do_action(self, action_id: int) -> str:
            if self.done:
                raise ValueError("Episode is done.")
            env_result = self.client.step(OpenSpielAction(action_id=action_id, game_name="catch"))
            self.reward = env_result.reward or 0.0
            self.done = env_result.observation.done
            return self._format_obs(env_result.observation.info_state)

        def move(self, direction: str) -> str:
            """Move the paddle left or right.



            Args:

                direction: Direction to move, either "left" or "right".



            Returns:

                The observation after moving.

            """
            if direction == "left":
                action_id = 0
            elif direction == "right":
                action_id = 2
            else:
                raise ValueError(f"Invalid direction {direction!r}: must be 'left' or 'right'.")
            return self._do_action(action_id)

        def stay(self) -> str:
            """Do nothing and let the ball fall one step.



            Returns:

                The observation after staying.

            """
            return self._do_action(1)

    training_args = GRPOConfig(
        output_dir=f"{args.model.split('/')[-1]}-GRPO-Catch",
        use_vllm=True,
        vllm_mode=args.vllm_mode,
        vllm_server_base_url=args.vllm_server_url if args.vllm_mode == "server" else None,
        vllm_gpu_memory_utilization=0.2,
        logging_steps=1,
        log_completions=True,
        report_to="trackio",
        trackio_space_id=f"{args.model.split('/')[-1]}-GRPO-Catch",
        num_train_epochs=1,
        per_device_train_batch_size=2,
        num_generations=8,
        max_completion_length=4096,
        gradient_accumulation_steps=16,
        chat_template_kwargs={"enable_thinking": False},
    )

    trainer = GRPOTrainer(
        model=args.model,
        reward_funcs=reward_from_env,
        args=training_args,
        train_dataset=dataset,
        environment_factory=CatchEnv,
        callbacks=[RichProgressCallback()],
    )

    try:
        trainer.train()
    finally:
        if server_process:
            print("πŸ›‘ Terminating environment server...")
            server_process.terminate()
            server_process.wait()


if __name__ == "__main__":
    main()