hard007ik commited on
Commit
caea08d
·
1 Parent(s): d11ffe8

Add GRPO training scaffolding (Module 5 rollout_func pattern) + plot artifacts

Browse files
.hfignore CHANGED
@@ -6,6 +6,13 @@
6
  rollout_baseline.py
7
  test_env_smoke.py
8
 
 
 
 
 
 
 
 
9
  # Course material / docs we don't want to ship inside the Space.
10
  *.pdf
11
  *.odt
 
6
  rollout_baseline.py
7
  test_env_smoke.py
8
 
9
+ # Training scaffolding lives only on the GPU host that trains a model against
10
+ # the deployed Space. The Space itself just serves the env, never trains.
11
+ train_jewelry_grpo.py
12
+ training/
13
+ shopmanager-grpo-out/
14
+ *.trackio
15
+
16
  # Course material / docs we don't want to ship inside the Space.
17
  *.pdf
18
  *.odt
pyproject.toml CHANGED
@@ -29,6 +29,22 @@ dev = [
29
  "pytest-cov>=4.0.0",
30
  ]
31
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
32
  [project.scripts]
33
  # Server entry point - enables running via: uv run --project . server
34
  # or: python -m ShopManagerEng.server.app
@@ -36,5 +52,5 @@ server = "ShopManagerEng.server.app:main"
36
 
37
  [tool.setuptools]
38
  include-package-data = true
39
- packages = ["ShopManagerEng", "ShopManagerEng.server"]
40
- package-dir = { "ShopManagerEng" = ".", "ShopManagerEng.server" = "server" }
 
29
  "pytest-cov>=4.0.0",
30
  ]
31
 
32
+ # GRPO training stack. Install only on a GPU host (vLLM is GPU-only).
33
+ # pip install -e '.[train]'
34
+ # Mirrors openenv-course Module 5 versions. trl>=0.17 is the cutoff that
35
+ # introduced trl.experimental.openenv.generate_rollout_completions.
36
+ train = [
37
+ "trl>=0.17.0",
38
+ "transformers>=4.46.0",
39
+ "datasets>=2.20.0",
40
+ "accelerate>=1.0.0",
41
+ "vllm>=0.6.3",
42
+ "trackio",
43
+ "torch>=2.4.0",
44
+ # Local plotting of loss + reward curves (hackathon submission evidence).
45
+ "matplotlib>=3.7",
46
+ ]
47
+
48
  [project.scripts]
49
  # Server entry point - enables running via: uv run --project . server
50
  # or: python -m ShopManagerEng.server.app
 
52
 
53
  [tool.setuptools]
54
  include-package-data = true
55
+ packages = ["ShopManagerEng", "ShopManagerEng.server", "ShopManagerEng.training"]
56
+ package-dir = { "ShopManagerEng" = ".", "ShopManagerEng.server" = "server", "ShopManagerEng.training" = "training" }
train_jewelry_grpo.py ADDED
@@ -0,0 +1,335 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """GRPO training entry point for the JewelryShop OpenEnv (Module 5 style).
2
+
3
+ Canonical TRL >= 0.17 + OpenEnv pattern:
4
+
5
+ 1. Persistent sync env client (one WebSocket reused across rollouts)
6
+ 2. rollout_func(prompts, trainer) (returns prompt_ids/completion_ids/logprobs + rewards)
7
+ 3. Pure reward_funcs(completions, ...) (read kwargs the rollout puts there)
8
+ 4. GRPOTrainer(..., rollout_func=...) (NO `environment_factory`)
9
+
10
+ Design notes:
11
+ - Reward shaping: ONE primary reward (`reward_total = obs.cumulative_reward`)
12
+ drives gradients; per-phase rewards (market/warehouse/showroom) are exposed
13
+ for monitoring with weight 0 in the GRPO advantage.
14
+ - Tasks: dataset rows embed [TASK=<task_id>] which the rollout extracts so each
15
+ episode trains against a specific per-phase weight profile from openenv.yaml.
16
+ - Smoke: --smoke imports everything, builds the rollout func, opens the env
17
+ and does a single reset() round-trip — no GPU and no model weights needed.
18
+ Use this to validate wiring before paying for a GPU.
19
+
20
+ Quick local smoke (no GPU, no model load):
21
+ python train_jewelry_grpo.py --smoke
22
+
23
+ Full local quick check (CPU; slow, but verifies trainer.train() starts):
24
+ TRAIN_MODEL=Qwen/Qwen3-0.6B python train_jewelry_grpo.py --quick
25
+
26
+ Cloud (HF Jobs) — see README/TRAINING for the exact `hf jobs run` command.
27
+ """
28
+ from __future__ import annotations
29
+
30
+ import argparse
31
+ import os
32
+ import sys
33
+ from pathlib import Path
34
+
35
+ # Make `from ShopManagerEng...` imports work whether you launch this from inside
36
+ # the package directory or one level up.
37
+ ROOT = Path(__file__).resolve().parent
38
+ PARENT = ROOT.parent
39
+ if str(PARENT) not in sys.path:
40
+ sys.path.insert(0, str(PARENT))
41
+
42
+ try:
43
+ from ShopManagerEng.client import JewelryShopEnv
44
+ from ShopManagerEng.training.plotting import (
45
+ build_metrics_callback,
46
+ save_training_artifacts,
47
+ )
48
+ from ShopManagerEng.training.prompts import SYSTEM_PROMPT
49
+ from ShopManagerEng.training.rewards import (
50
+ ALL_REWARDS,
51
+ REWARD_WEIGHTS_MONITOR_ONLY,
52
+ )
53
+ from ShopManagerEng.training.rollout import VALID_TASKS, build_rollout_func
54
+ except ImportError: # script-style invocation from inside the folder
55
+ from client import JewelryShopEnv # type: ignore
56
+ from training.plotting import ( # type: ignore
57
+ build_metrics_callback,
58
+ save_training_artifacts,
59
+ )
60
+ from training.prompts import SYSTEM_PROMPT # type: ignore
61
+ from training.rewards import ( # type: ignore
62
+ ALL_REWARDS,
63
+ REWARD_WEIGHTS_MONITOR_ONLY,
64
+ )
65
+ from training.rollout import VALID_TASKS, build_rollout_func # type: ignore
66
+
67
+
68
+ def _build_dataset(dataset_size: int):
69
+ """Cycle through the 3 graded tasks; embed task id in prompt for the rollout."""
70
+ from datasets import Dataset
71
+
72
+ rows = []
73
+ for i in range(dataset_size):
74
+ task_id = VALID_TASKS[i % len(VALID_TASKS)]
75
+ rows.append(
76
+ {
77
+ "prompt": (
78
+ f"[TASK={task_id}] Manage a jewelry shop episode end-to-end. "
79
+ f"Maximize the {task_id} task reward."
80
+ ),
81
+ "task_id": task_id,
82
+ }
83
+ )
84
+ return Dataset.from_list(rows)
85
+
86
+
87
+ def _resolve_precision():
88
+ """CPU/GPU autodetect; mirror the well-tested defaults."""
89
+ try:
90
+ import torch
91
+ has_cuda = bool(torch.cuda.is_available())
92
+ except Exception:
93
+ has_cuda = False
94
+ if has_cuda:
95
+ return {"bf16": True}
96
+ return {"use_cpu": True, "bf16": False, "fp16": False}
97
+
98
+
99
+ def main() -> None:
100
+ ap = argparse.ArgumentParser()
101
+ ap.add_argument(
102
+ "--model",
103
+ default=os.environ.get("TRAIN_MODEL", "Qwen/Qwen3-1.7B"),
104
+ help="HF model id (default: Qwen/Qwen3-1.7B; matches openenv-course Module 5).",
105
+ )
106
+ ap.add_argument(
107
+ "--env-url",
108
+ default=os.environ.get(
109
+ "ENV_URL", "https://hard007ik-shopmanagereng.hf.space"
110
+ ),
111
+ help="Base URL of the running OpenEnv server (Space or http://127.0.0.1:8000).",
112
+ )
113
+ ap.add_argument(
114
+ "--output-dir",
115
+ default=os.environ.get("TRAIN_OUTPUT_DIR", "shopmanager-grpo-out"),
116
+ )
117
+ ap.add_argument("--dataset-size", type=int, default=300)
118
+ ap.add_argument("--num-generations", type=int, default=2)
119
+ ap.add_argument("--per-device-batch", type=int, default=1)
120
+ ap.add_argument("--grad-accum", type=int, default=32)
121
+ ap.add_argument("--max-completion-length", type=int, default=64)
122
+ ap.add_argument("--max-prompt-length", type=int, default=2048)
123
+ ap.add_argument("--max-turns", type=int, default=15)
124
+ ap.add_argument("--lr", type=float, default=5e-6)
125
+ ap.add_argument("--warmup-steps", type=int, default=10)
126
+ ap.add_argument("--max-steps", type=int, default=-1, help="-1 = epoch-bounded.")
127
+ ap.add_argument("--epochs", type=int, default=1)
128
+ ap.add_argument(
129
+ "--vllm-gpu-mem",
130
+ type=float,
131
+ default=0.3,
132
+ help="Fraction of GPU mem reserved for vLLM. Lower if OOM.",
133
+ )
134
+ ap.add_argument("--push-to-hub", action="store_true")
135
+ ap.add_argument(
136
+ "--report-to",
137
+ default=os.environ.get("TRAIN_REPORT_TO", "trackio"),
138
+ help="trackio | wandb | none",
139
+ )
140
+ ap.add_argument(
141
+ "--smoke",
142
+ action="store_true",
143
+ help="No training. Imports, env connect, one reset() — validates wiring.",
144
+ )
145
+ ap.add_argument(
146
+ "--quick",
147
+ action="store_true",
148
+ help="CPU-friendly tiny run (1 step, num_generations=2, max_completion=32).",
149
+ )
150
+ args = ap.parse_args()
151
+
152
+ if args.smoke:
153
+ # No transformers / vllm load: just import + connect + reset, then
154
+ # also exercise the plotting pipeline on a fake log_history so the
155
+ # submission-artifact path is proven before we burn a GPU on it.
156
+ env = JewelryShopEnv(base_url=args.env_url)
157
+ sync_env = env.sync()
158
+ sync_env.connect()
159
+ try:
160
+ r = sync_env.reset(task_id=VALID_TASKS[0])
161
+ print(f"[SMOKE] connected to {args.env_url}")
162
+ print(
163
+ f"[SMOKE] reset OK: phase={r.observation.phase}, "
164
+ f"done={r.done}, cumulative_reward="
165
+ f"{getattr(r.observation, 'cumulative_reward', 0)}"
166
+ )
167
+ print(f"[SMOKE] system prompt loaded ({len(SYSTEM_PROMPT)} chars)")
168
+ print("[SMOKE] reward funcs:", [f.__name__ for f in ALL_REWARDS])
169
+ print("[SMOKE] reward weights:", REWARD_WEIGHTS_MONITOR_ONLY)
170
+ finally:
171
+ try:
172
+ sync_env.close()
173
+ except Exception:
174
+ pass
175
+
176
+ # Prove the plotting pipeline works (writes PNG + CSV + JSON to
177
+ # output_dir using a synthetic, monotonic log). This is what the
178
+ # real run will produce — same code path.
179
+ fake_history = []
180
+ for step in range(1, 21):
181
+ fake_history.append(
182
+ {
183
+ "step": step,
184
+ "loss": 1.0 / step,
185
+ "reward": 0.05 * step,
186
+ "rewards/reward_total": min(0.05 * step, 1.0),
187
+ "rewards/reward_market": min(0.02 * step, 0.6),
188
+ "rewards/reward_warehouse": min(0.015 * step, 0.6),
189
+ "rewards/reward_showroom": min(0.018 * step, 0.6),
190
+ }
191
+ )
192
+ summary = save_training_artifacts(
193
+ fake_history,
194
+ args.output_dir,
195
+ run_config={"smoke": True, "model": args.model, "env_url": args.env_url},
196
+ )
197
+ print(
198
+ f"[SMOKE] plot pipeline OK -> {args.output_dir}/loss_curve.png, "
199
+ f"{args.output_dir}/reward_curve.png, "
200
+ f"{args.output_dir}/reward_total_curve.png"
201
+ )
202
+ print(
203
+ f"[SMOKE] summary peak_reward_total={summary['reward_total']['max']:.3f} "
204
+ f"final_loss={summary['loss']['final']:.4f}"
205
+ )
206
+ print("[SMOKE] OK — wiring is sane.")
207
+ return
208
+
209
+ # ── Heavy imports only past the smoke gate ──
210
+ from transformers import AutoTokenizer
211
+ from trl import GRPOConfig, GRPOTrainer
212
+
213
+ tokenizer = AutoTokenizer.from_pretrained(args.model)
214
+ if tokenizer.pad_token is None:
215
+ tokenizer.pad_token = tokenizer.eos_token
216
+
217
+ env = JewelryShopEnv(base_url=args.env_url)
218
+ sync_env = env.sync()
219
+ sync_env.connect()
220
+ print(f"[TRAIN] env: {args.env_url}")
221
+ print(f"[TRAIN] model: {args.model}")
222
+
223
+ rollout_func = build_rollout_func(
224
+ sync_env=sync_env,
225
+ tokenizer=tokenizer,
226
+ system_prompt=SYSTEM_PROMPT,
227
+ max_turns=args.max_turns,
228
+ model_name=args.model,
229
+ )
230
+
231
+ if args.quick:
232
+ # Override to tiny CPU-friendly numbers.
233
+ args.dataset_size = 4
234
+ args.num_generations = 2
235
+ args.per_device_batch = 2
236
+ args.grad_accum = 1
237
+ args.max_completion_length = 32
238
+ args.max_steps = 1
239
+ args.warmup_steps = 0
240
+
241
+ dataset = _build_dataset(args.dataset_size)
242
+ precision = _resolve_precision()
243
+ use_cpu = precision.get("use_cpu", False)
244
+
245
+ grpo_config = GRPOConfig(
246
+ output_dir=args.output_dir,
247
+ num_train_epochs=args.epochs,
248
+ learning_rate=args.lr,
249
+ gradient_accumulation_steps=args.grad_accum,
250
+ per_device_train_batch_size=args.per_device_batch,
251
+ warmup_steps=args.warmup_steps,
252
+ num_generations=args.num_generations,
253
+ max_completion_length=args.max_completion_length,
254
+ max_prompt_length=args.max_prompt_length,
255
+ # vLLM is the canonical generation backend on GPU; turn off on CPU smoke.
256
+ use_vllm=not use_cpu,
257
+ vllm_mode="colocate" if not use_cpu else None,
258
+ vllm_gpu_memory_utilization=args.vllm_gpu_mem if not use_cpu else None,
259
+ gradient_checkpointing=True,
260
+ gradient_checkpointing_kwargs={"use_reentrant": False},
261
+ reward_weights=REWARD_WEIGHTS_MONITOR_ONLY,
262
+ report_to=args.report_to if args.report_to != "none" else "none",
263
+ logging_steps=1,
264
+ save_steps=20,
265
+ push_to_hub=args.push_to_hub,
266
+ max_steps=args.max_steps if args.max_steps > 0 else -1,
267
+ **precision,
268
+ )
269
+
270
+ print(f"[TRAIN] device={'cpu' if use_cpu else 'gpu'} precision={precision}")
271
+ print(f"[TRAIN] dataset_size={args.dataset_size} num_generations={args.num_generations}")
272
+
273
+ trainer = GRPOTrainer(
274
+ model=args.model,
275
+ processing_class=tokenizer,
276
+ reward_funcs=list(ALL_REWARDS),
277
+ train_dataset=dataset,
278
+ args=grpo_config,
279
+ rollout_func=rollout_func,
280
+ )
281
+
282
+ # Persist loss + reward plots into output_dir every N steps + at the end.
283
+ # This is the hackathon "evidence you actually trained" artifact set.
284
+ trainer.add_callback(build_metrics_callback(args.output_dir, snapshot_every=5))
285
+
286
+ run_config = {
287
+ "model": args.model,
288
+ "env_url": args.env_url,
289
+ "dataset_size": args.dataset_size,
290
+ "num_generations": args.num_generations,
291
+ "per_device_batch": args.per_device_batch,
292
+ "grad_accum": args.grad_accum,
293
+ "max_completion_length": args.max_completion_length,
294
+ "max_prompt_length": args.max_prompt_length,
295
+ "max_turns": args.max_turns,
296
+ "lr": args.lr,
297
+ "warmup_steps": args.warmup_steps,
298
+ "max_steps": args.max_steps,
299
+ "epochs": args.epochs,
300
+ "vllm_gpu_mem": args.vllm_gpu_mem,
301
+ "reward_weights": REWARD_WEIGHTS_MONITOR_ONLY,
302
+ "precision": precision,
303
+ }
304
+
305
+ try:
306
+ trainer.train()
307
+ finally:
308
+ try:
309
+ sync_env.close()
310
+ except Exception:
311
+ pass
312
+ # Always persist whatever metrics we have, even on a crash mid-run.
313
+ try:
314
+ summary = save_training_artifacts(
315
+ list(trainer.state.log_history or []),
316
+ args.output_dir,
317
+ run_config=run_config,
318
+ )
319
+ print(
320
+ f"[ARTIFACTS] wrote loss/reward plots + metrics to {args.output_dir}\n"
321
+ f"[ARTIFACTS] final loss={summary['loss']['final']:.4f} "
322
+ f"max_reward_total={summary['reward_total']['max']:.4f} "
323
+ f"final_reward_total={summary['reward_total']['final']:.4f}"
324
+ )
325
+ except Exception as exc:
326
+ print(f"[ARTIFACTS] failed to save metrics: {exc}")
327
+
328
+ trainer.save_model(args.output_dir)
329
+ if args.push_to_hub:
330
+ trainer.push_to_hub()
331
+ print(f"[DONE] saved to {args.output_dir}")
332
+
333
+
334
+ if __name__ == "__main__":
335
+ main()
training/__init__.py ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ """ShopManagerEng training package.
2
+
3
+ Course-style (Module 5) GRPO training scaffolding for the JewelryShop env.
4
+ Uses TRL's `rollout_func=...` entry point with vLLM colocate generation.
5
+ """
training/parse_action.py ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Parse free-form model text into a typed JewelryAction.
2
+
3
+ Mirrors inference.py:get_action_from_text so the action surface during
4
+ training matches what was used during evaluation.
5
+ """
6
+ from __future__ import annotations
7
+
8
+ from typing import Tuple
9
+
10
+ try:
11
+ from ..models import JewelryAction
12
+ except ImportError:
13
+ from models import JewelryAction
14
+
15
+
16
+ def parse_model_text_to_action(phase: str, text: str) -> Tuple[JewelryAction, str]:
17
+ """Return (action, normalised_text) for the current phase.
18
+
19
+ Robust against typical LLM output noise: backticks, quotes, leading/trailing
20
+ whitespace. Falls back to safe defaults so a single bad token never breaks
21
+ the rollout.
22
+ """
23
+ text = (text or "").strip().replace("`", "").strip(" \t\n\r\"'")
24
+
25
+ if phase == "market":
26
+ lower = text.lower()
27
+ if lower.startswith("buy"):
28
+ qty_str = lower.replace("buy", "").strip()
29
+ try:
30
+ qty = float(qty_str)
31
+ except ValueError:
32
+ qty = 1.0
33
+ return JewelryAction(market_action="buy", gold_qty=qty), f"buy {qty}"
34
+ if "wait" in lower:
35
+ return JewelryAction(market_action="wait"), "wait"
36
+ try:
37
+ qty = float(text)
38
+ return JewelryAction(market_action="buy", gold_qty=qty), f"buy {qty}"
39
+ except ValueError:
40
+ return JewelryAction(market_action="wait"), "wait"
41
+
42
+ if phase == "warehouse":
43
+ lower = text.lower()
44
+ for product in ("necklace", "bracelet", "ring"):
45
+ if product in lower:
46
+ return JewelryAction(product_choice=product), product
47
+ return JewelryAction(product_choice="ring"), "ring"
48
+
49
+ if phase == "showroom":
50
+ return JewelryAction(message=text), text
51
+
52
+ return JewelryAction(), text
training/plotting.py ADDED
@@ -0,0 +1,280 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Persist training metrics + loss/reward plots to disk.
2
+
3
+ Why this exists: the hackathon submission asks for "evidence you actually
4
+ trained — at minimum loss and reward plots from a real run." Since we run as
5
+ a script (not a notebook), nothing renders automatically. This module:
6
+
7
+ * Snapshots ``trainer.state.log_history`` every N steps via a TrainerCallback
8
+ (so a crashed run still leaves partial evidence behind), and
9
+ * Dumps a final set of artifacts (CSV, JSON, PNGs) after ``trainer.train()``.
10
+
11
+ All artifacts land in the trainer's ``output_dir`` so they ride back to the
12
+ Hugging Face Hub when ``push_to_hub=True``.
13
+ """
14
+ from __future__ import annotations
15
+
16
+ import csv
17
+ import json
18
+ import logging
19
+ from pathlib import Path
20
+ from typing import Any, Dict, Iterable, List, Optional
21
+
22
+ logger = logging.getLogger(__name__)
23
+
24
+
25
+ # Reward keys we track. TRL logs reward functions under "rewards/<func_name>"
26
+ # (and a single-scalar "reward" = sum of weighted rewards).
27
+ PRIMARY_REWARD_KEY = "rewards/reward_total"
28
+ PHASE_REWARD_KEYS = (
29
+ "rewards/reward_market",
30
+ "rewards/reward_warehouse",
31
+ "rewards/reward_showroom",
32
+ )
33
+ LOSS_KEY = "loss"
34
+ STEP_KEY = "step"
35
+
36
+
37
+ def _flatten_log_history(log_history: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
38
+ """Make sure every row carries a `step` field even when TRL omits it on epoch logs."""
39
+ cleaned: List[Dict[str, Any]] = []
40
+ last_step = 0
41
+ for row in log_history:
42
+ step = row.get("step", row.get("global_step", last_step))
43
+ last_step = step or last_step
44
+ merged = {"step": last_step, **{k: v for k, v in row.items() if k != "step"}}
45
+ cleaned.append(merged)
46
+ return cleaned
47
+
48
+
49
+ def _series(rows: List[Dict[str, Any]], key: str) -> List[tuple]:
50
+ """Return ``[(step, value), ...]`` for the given metric key."""
51
+ out: List[tuple] = []
52
+ for r in rows:
53
+ if key in r and r[key] is not None:
54
+ try:
55
+ out.append((int(r["step"]), float(r[key])))
56
+ except (TypeError, ValueError):
57
+ continue
58
+ return out
59
+
60
+
61
+ def _save_csv(rows: List[Dict[str, Any]], path: Path) -> None:
62
+ if not rows:
63
+ return
64
+ columns: List[str] = []
65
+ seen = set()
66
+ for r in rows:
67
+ for k in r.keys():
68
+ if k not in seen:
69
+ seen.add(k)
70
+ columns.append(k)
71
+ with path.open("w", newline="") as f:
72
+ writer = csv.DictWriter(f, fieldnames=columns)
73
+ writer.writeheader()
74
+ writer.writerows(rows)
75
+
76
+
77
+ def _save_json(rows: List[Dict[str, Any]], path: Path) -> None:
78
+ with path.open("w") as f:
79
+ json.dump(rows, f, indent=2, default=str)
80
+
81
+
82
+ def _try_plot(
83
+ series: Iterable[tuple],
84
+ title: str,
85
+ ylabel: str,
86
+ out_path: Path,
87
+ *,
88
+ label: Optional[str] = None,
89
+ ) -> bool:
90
+ """Draw a single-series line plot. Silently no-ops if matplotlib is missing."""
91
+ try:
92
+ import matplotlib
93
+
94
+ matplotlib.use("Agg")
95
+ import matplotlib.pyplot as plt
96
+ except Exception as exc:
97
+ logger.warning("matplotlib unavailable, skipping %s (%s)", out_path.name, exc)
98
+ return False
99
+
100
+ pts = list(series)
101
+ if not pts:
102
+ logger.warning("no data for %s, skipping plot", out_path.name)
103
+ return False
104
+ xs, ys = zip(*pts)
105
+ fig, ax = plt.subplots(figsize=(8, 4.5))
106
+ ax.plot(xs, ys, marker="o", linewidth=1.5, label=label or ylabel)
107
+ ax.set_xlabel("training step")
108
+ ax.set_ylabel(ylabel)
109
+ ax.set_title(title)
110
+ ax.grid(True, alpha=0.3)
111
+ if label:
112
+ ax.legend(loc="best")
113
+ fig.tight_layout()
114
+ fig.savefig(out_path, dpi=120)
115
+ plt.close(fig)
116
+ return True
117
+
118
+
119
+ def _try_plot_multi(
120
+ name_to_series: Dict[str, Iterable[tuple]],
121
+ title: str,
122
+ ylabel: str,
123
+ out_path: Path,
124
+ ) -> bool:
125
+ """Draw a multi-series line plot."""
126
+ try:
127
+ import matplotlib
128
+
129
+ matplotlib.use("Agg")
130
+ import matplotlib.pyplot as plt
131
+ except Exception as exc:
132
+ logger.warning("matplotlib unavailable, skipping %s (%s)", out_path.name, exc)
133
+ return False
134
+
135
+ fig, ax = plt.subplots(figsize=(8.5, 5))
136
+ drew_any = False
137
+ for label, pts in name_to_series.items():
138
+ pts = list(pts)
139
+ if not pts:
140
+ continue
141
+ xs, ys = zip(*pts)
142
+ ax.plot(xs, ys, marker="o", linewidth=1.3, label=label)
143
+ drew_any = True
144
+ if not drew_any:
145
+ plt.close(fig)
146
+ logger.warning("no data for %s, skipping plot", out_path.name)
147
+ return False
148
+ ax.set_xlabel("training step")
149
+ ax.set_ylabel(ylabel)
150
+ ax.set_title(title)
151
+ ax.grid(True, alpha=0.3)
152
+ ax.legend(loc="best")
153
+ fig.tight_layout()
154
+ fig.savefig(out_path, dpi=120)
155
+ plt.close(fig)
156
+ return True
157
+
158
+
159
+ def _summary_stats(series: List[tuple]) -> Dict[str, float]:
160
+ if not series:
161
+ return {"final": 0.0, "max": 0.0, "min": 0.0, "mean": 0.0, "n": 0}
162
+ ys = [v for _, v in series]
163
+ return {
164
+ "final": float(ys[-1]),
165
+ "max": float(max(ys)),
166
+ "min": float(min(ys)),
167
+ "mean": float(sum(ys) / len(ys)),
168
+ "n": len(ys),
169
+ }
170
+
171
+
172
+ def save_training_artifacts(
173
+ log_history: List[Dict[str, Any]],
174
+ output_dir: str | Path,
175
+ *,
176
+ run_config: Optional[Dict[str, Any]] = None,
177
+ ) -> Dict[str, Any]:
178
+ """Write metrics + loss/reward plots into ``output_dir``.
179
+
180
+ Returns the summary dict that was also written to ``training_summary.json``.
181
+ """
182
+ out = Path(output_dir)
183
+ out.mkdir(parents=True, exist_ok=True)
184
+
185
+ rows = _flatten_log_history(log_history)
186
+ _save_csv(rows, out / "metrics.csv")
187
+ _save_json(rows, out / "metrics.json")
188
+
189
+ loss_series = _series(rows, LOSS_KEY)
190
+ total_reward_series = _series(rows, PRIMARY_REWARD_KEY)
191
+ # Some TRL versions log a flat "reward" scalar in addition. Prefer the
192
+ # named primary; fall back to "reward" if the named one is empty.
193
+ if not total_reward_series:
194
+ total_reward_series = _series(rows, "reward")
195
+
196
+ phase_series = {
197
+ "market": _series(rows, "rewards/reward_market"),
198
+ "warehouse": _series(rows, "rewards/reward_warehouse"),
199
+ "showroom": _series(rows, "rewards/reward_showroom"),
200
+ }
201
+
202
+ _try_plot(
203
+ loss_series,
204
+ title="Training loss (GRPO)",
205
+ ylabel="loss",
206
+ out_path=out / "loss_curve.png",
207
+ label="loss",
208
+ )
209
+ _try_plot(
210
+ total_reward_series,
211
+ title="Reward (total) — env cumulative_reward in [0, 1]",
212
+ ylabel="reward",
213
+ out_path=out / "reward_total_curve.png",
214
+ label="reward_total",
215
+ )
216
+ _try_plot_multi(
217
+ {
218
+ "reward_total": total_reward_series,
219
+ **{f"reward_{k}": v for k, v in phase_series.items()},
220
+ },
221
+ title="Rewards over training",
222
+ ylabel="reward",
223
+ out_path=out / "reward_curve.png",
224
+ )
225
+
226
+ summary: Dict[str, Any] = {
227
+ "loss": _summary_stats(loss_series),
228
+ "reward_total": _summary_stats(total_reward_series),
229
+ "reward_market": _summary_stats(phase_series["market"]),
230
+ "reward_warehouse": _summary_stats(phase_series["warehouse"]),
231
+ "reward_showroom": _summary_stats(phase_series["showroom"]),
232
+ "n_log_rows": len(rows),
233
+ "output_dir": str(out.resolve()),
234
+ }
235
+ if run_config is not None:
236
+ summary["run_config"] = run_config
237
+
238
+ with (out / "training_summary.json").open("w") as f:
239
+ json.dump(summary, f, indent=2, default=str)
240
+
241
+ logger.info("Wrote training artifacts to %s", out.resolve())
242
+ return summary
243
+
244
+
245
+ def build_metrics_callback(output_dir: str | Path, snapshot_every: int = 5):
246
+ """Return a TrainerCallback that snapshots metrics every N steps + on end.
247
+
248
+ Imported lazily so this module can be inspected on a machine without
249
+ transformers installed (e.g. for the local --smoke run).
250
+ """
251
+ from transformers.trainer_callback import TrainerCallback
252
+
253
+ out = Path(output_dir)
254
+
255
+ class MetricsSaverCallback(TrainerCallback):
256
+ """Persist metrics CSV/JSON + plots periodically and at the end."""
257
+
258
+ def __init__(self) -> None:
259
+ self._last_snapshot_step = -1
260
+
261
+ def _snapshot(self, state) -> None:
262
+ try:
263
+ save_training_artifacts(list(state.log_history or []), out)
264
+ except Exception as exc: # never let plotting kill training
265
+ logger.warning("metrics snapshot failed: %s", exc)
266
+
267
+ def on_log(self, args, state, control, **kwargs):
268
+ step = int(getattr(state, "global_step", 0) or 0)
269
+ if step <= 0:
270
+ return control
271
+ if (step - self._last_snapshot_step) >= max(snapshot_every, 1):
272
+ self._snapshot(state)
273
+ self._last_snapshot_step = step
274
+ return control
275
+
276
+ def on_train_end(self, args, state, control, **kwargs):
277
+ self._snapshot(state)
278
+ return control
279
+
280
+ return MetricsSaverCallback()
training/prompts.py ADDED
@@ -0,0 +1,169 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """System prompt + per-turn user-prompt builder for the JewelryShop env.
2
+
3
+ Logic mirrors `inference.py`'s `build_user_prompt` so that whatever the model
4
+ saw during inference evaluation it also sees during training. Kept as a plain
5
+ sync function (no asyncio) so it composes cleanly with TRL's rollout_func.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ import math
10
+ import textwrap
11
+ from typing import List
12
+
13
+
14
+ SYSTEM_PROMPT = textwrap.dedent(
15
+ """
16
+ You are an expert agent running a jewelry shop. The episode runs in 3 phases
17
+ and may loop back to MARKET if the warehouse runs out of gold. The episode
18
+ reward is the SUM of per-step partial rewards across the whole episode and
19
+ is bounded in [0, 1]. Each task weights the phases differently:
20
+ - market_timing -> phase 1 = 0.6, phase 2 = 0.2, phase 3 = 0.2
21
+ - demand_crafter -> phase 1 = 0.2, phase 2 = 0.6, phase 3 = 0.2
22
+ - profit_negotiator -> phase 1 = 0.2, phase 2 = 0.2, phase 3 = 0.6
23
+
24
+ ## Phase 1: MARKET (buy / wait)
25
+ Two modes:
26
+ - synthetic mode: gold price moves randomly each WAIT step within a round cap.
27
+ - real mode: gold price comes from a live source (yfinance: GC=F),
28
+ no round cap; WAIT just refreshes the live quote.
29
+ Coordination from the warehouse:
30
+ - inventory_urgent=True / cannot_wait=True means you MUST buy now;
31
+ WAIT will be blocked. Submit "buy X.XX" with an affordable troy-oz qty.
32
+ Behavior:
33
+ - If you can wait, observe the price trend in gold_price_history before buying.
34
+ - Reserve cash for labor (ring=$200, necklace=$300, bracelet=$100).
35
+ - Respond: "buy X.XX" (troy oz of gold) or "wait".
36
+
37
+ ## Phase 2: WAREHOUSE (choose product)
38
+ You see two demand fields:
39
+ - demand : the TRUE per-product demand for THIS episode (ground truth).
40
+ - demand_forecast : a NOISY signal you can also lean on for planning.
41
+ Products: ring (1oz + $200), necklace (2oz + $300), bracelet (0.5oz + $100).
42
+ If you don't have enough gold to craft your choice, the env may BOUNCE you back
43
+ to MARKET to buy more (up to max_market_reentries times). After max bounces or
44
+ when truly broke, the customer leaves and the episode ends.
45
+ Respond: "ring", "necklace", or "bracelet".
46
+
47
+ ## Phase 3: SHOWROOM (negotiate)
48
+ The customer makes an offer; if you counter, they raise it ~5% per round,
49
+ up to 5 rounds. After 5 rounds with no acceptance, the customer leaves
50
+ (no phase-3 reward). Reject also gives 0 phase-3 reward.
51
+ Respond: "I accept" or a counter like "How about $X?". NEVER explicitly reject.
52
+
53
+ CRITICAL: Respond with ONLY the action value. No explanations.
54
+ """
55
+ ).strip()
56
+
57
+
58
+ def build_user_prompt(step: int, obs, last_reward: float, history: List[str]) -> str:
59
+ """Format a single observation into a user prompt the LLM sees this turn.
60
+
61
+ Mirrors inference.py:build_user_prompt so the model sees the same input shape
62
+ during training and at evaluation time.
63
+ """
64
+ history_block = "\n".join(history[-4:]) if history else "None"
65
+
66
+ if obs.phase == "market":
67
+ prices = getattr(obs, "gold_price_history", []) or []
68
+ trend = ""
69
+ if len(prices) >= 2:
70
+ if prices[-1] < prices[-2]:
71
+ trend = "FALLING (might keep dropping, consider waiting)"
72
+ else:
73
+ trend = "RISING (buy now before it gets more expensive)"
74
+
75
+ if getattr(obs, "cannot_wait", False):
76
+ trend = (
77
+ "URGENT: inventory needs gold now — you cannot wait; buy at the current "
78
+ "live quote with an affordable gold_qty (troy oz)."
79
+ )
80
+
81
+ max_rounds = getattr(obs, "max_market_rounds", None)
82
+ rounds_left = (max_rounds - getattr(obs, "market_round", 0)) if max_rounds else None
83
+
84
+ reserve = 300.0
85
+ gold_price = getattr(obs, "gold_price", 0) or 0
86
+ cash = getattr(obs, "cash", 0) or 0
87
+ if gold_price > 0:
88
+ raw_qty = (cash - reserve) / gold_price
89
+ suggested_qty = max(math.floor(raw_qty * 100) / 100, 0.01)
90
+ else:
91
+ suggested_qty = 1.0
92
+
93
+ rl = "unlimited" if rounds_left is None else str(rounds_left)
94
+ phase_hint = (
95
+ f"Price: ${gold_price}/oz ({getattr(obs, 'gold_price_source', '') or 'n/a'}). "
96
+ f"Price history: {prices}. Trend: {trend}. "
97
+ f"Rounds / waits so far: {getattr(obs, 'market_round', 0)}; cap: {rl}. "
98
+ f"Gold on hand: {getattr(obs, 'gold_oz', 0)} troy oz "
99
+ f"(~{getattr(obs, 'gold_grams', 0):.2f} g). "
100
+ f"If buying, suggested qty: {suggested_qty} oz (reserves $300 for labor). "
101
+ f"Respond: 'buy {suggested_qty}' or 'wait'"
102
+ )
103
+
104
+ elif obs.phase == "warehouse":
105
+ demand = getattr(obs, "demand", {}) or {}
106
+ forecast = getattr(obs, "demand_forecast", {}) or {}
107
+ best_product = max(demand, key=demand.get) if demand else "ring"
108
+ phase_hint = (
109
+ f"Demand (episode): ring={demand.get('ring', 0):.0%}, "
110
+ f"necklace={demand.get('necklace', 0):.0%}, "
111
+ f"bracelet={demand.get('bracelet', 0):.0%}. "
112
+ f"Forecast (noisy): ring={forecast.get('ring', 0):.0%}, "
113
+ f"necklace={forecast.get('necklace', 0):.0%}, "
114
+ f"bracelet={forecast.get('bracelet', 0):.0%}. "
115
+ f"Highest demand: {best_product}. "
116
+ f"You have {getattr(obs, 'gold_oz', 0)}oz gold and "
117
+ f"${getattr(obs, 'cash', 0)} cash. "
118
+ f"Respond with EXACTLY: {best_product}"
119
+ )
120
+
121
+ elif obs.phase == "showroom":
122
+ cost_basis = getattr(obs, "cost_basis", 0) or 0
123
+ current_offer = getattr(obs, "current_offer", 0) or 0
124
+ negotiation_round = getattr(obs, "negotiation_round", 0) or 0
125
+
126
+ margin = ""
127
+ if current_offer and cost_basis > 0:
128
+ margin_pct = ((current_offer - cost_basis) / cost_basis) * 100
129
+ margin = f"Margin: {margin_pct:+.1f}%. "
130
+
131
+ should_accept = negotiation_round >= 4 or (
132
+ current_offer and cost_basis > 0 and current_offer > cost_basis * 1.3
133
+ )
134
+
135
+ if should_accept:
136
+ phase_hint = (
137
+ f"Cost: ${cost_basis}. Offer: ${current_offer}. {margin}"
138
+ f"Round {negotiation_round}/5. "
139
+ f"Respond with EXACTLY: I accept"
140
+ )
141
+ else:
142
+ counter_msgs = [
143
+ "I need a better price for this quality piece",
144
+ "That's too low, this craftsmanship deserves more",
145
+ f"How about ${round(cost_basis * 1.4, 2)}?",
146
+ f"I can't go below ${round(cost_basis * 1.3, 2)}",
147
+ ]
148
+ msg = counter_msgs[min(negotiation_round, len(counter_msgs) - 1)]
149
+ phase_hint = (
150
+ f"Cost: ${cost_basis}. Offer: ${current_offer}. {margin}"
151
+ f"Round {negotiation_round}/5. "
152
+ f"DO NOT ACCEPT. Counter-offer. "
153
+ f"Respond with EXACTLY: {msg}"
154
+ )
155
+ else:
156
+ phase_hint = ""
157
+
158
+ return textwrap.dedent(
159
+ f"""
160
+ Step: {step} | Phase: {obs.phase} | Last reward: {last_reward:.2f}
161
+ Cash: ${getattr(obs, 'cash', 0)} | Gold: {getattr(obs, 'gold_oz', 0)}oz | Rings: {getattr(obs, 'inventory', {})}
162
+ Gold Price: ${getattr(obs, 'gold_price', 0)}/oz
163
+ Env Message: {getattr(obs, 'message', '')}
164
+
165
+ {phase_hint}
166
+
167
+ History: {history_block}
168
+ """
169
+ ).strip()
training/rewards.py ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Reward functions consumed by GRPOTrainer.
2
+
3
+ Design choice: ONE primary reward (``reward_total``) drives advantages, while
4
+ the three per-phase rewards are exposed for *monitoring only* via TRL's logged
5
+ reward metrics. Their config weight should be set to 0.0 to avoid double
6
+ counting the cumulative phase sum.
7
+
8
+ If you actually want phase-level shaping in the gradient, change the
9
+ GRPOConfig ``reward_weights`` to e.g. [1.0, 0.2, 0.2, 0.2].
10
+ """
11
+ from __future__ import annotations
12
+
13
+ from typing import Any, List
14
+
15
+
16
+ def _pull(kwargs: dict, key: str, n: int) -> List[float]:
17
+ vals = kwargs.get(key)
18
+ if not vals:
19
+ return [0.0] * n
20
+ return [float(v) for v in vals]
21
+
22
+
23
+ def reward_total(completions: List[Any], **kwargs) -> List[float]:
24
+ """Authoritative trajectory return: env's cumulative_reward in [0, 1]."""
25
+ return _pull(kwargs, "total_reward", len(completions))
26
+
27
+
28
+ def reward_market(completions: List[Any], **kwargs) -> List[float]:
29
+ """Sum of per-step partials emitted while phase == 'market'. Monitoring."""
30
+ return _pull(kwargs, "market_reward", len(completions))
31
+
32
+
33
+ def reward_warehouse(completions: List[Any], **kwargs) -> List[float]:
34
+ """Sum of per-step partials emitted while phase == 'warehouse'. Monitoring."""
35
+ return _pull(kwargs, "warehouse_reward", len(completions))
36
+
37
+
38
+ def reward_showroom(completions: List[Any], **kwargs) -> List[float]:
39
+ """Sum of per-step partials emitted while phase == 'showroom'. Monitoring."""
40
+ return _pull(kwargs, "showroom_reward", len(completions))
41
+
42
+
43
+ # Convenience tuple for single-import use
44
+ ALL_REWARDS = (reward_total, reward_market, reward_warehouse, reward_showroom)
45
+
46
+ # Matching weights so only `reward_total` contributes to the GRPO advantage.
47
+ # Plug this straight into GRPOConfig(reward_weights=REWARD_WEIGHTS_MONITOR_ONLY).
48
+ REWARD_WEIGHTS_MONITOR_ONLY = [1.0, 0.0, 0.0, 0.0]
training/rollout.py ADDED
@@ -0,0 +1,190 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Module 5 (TRL OpenEnv Wordle) style rollout for ShopManagerEng.
2
+
3
+ Two public symbols:
4
+
5
+ * ``rollout_once(...)`` — plays a single multi-turn jewelry-shop episode
6
+ against an already-connected sync env client and returns the per-episode
7
+ signals TRL/GRPO needs.
8
+ * ``build_rollout_func(...)`` — closure factory that returns the
9
+ ``rollout_func(prompts, trainer=None)`` callable handed to ``GRPOTrainer``.
10
+
11
+ The pattern (canonical for OpenEnv + TRL >= 0.17):
12
+
13
+ sync_env = env.sync(); sync_env.connect() # one persistent WS
14
+ trainer = GRPOTrainer(..., rollout_func=rollout_func)
15
+ trainer.train()
16
+ """
17
+ from __future__ import annotations
18
+
19
+ import re
20
+ from typing import Any, Callable, Dict, List, Optional
21
+
22
+ try:
23
+ from .parse_action import parse_model_text_to_action
24
+ from .prompts import build_user_prompt
25
+ except ImportError:
26
+ from training.parse_action import parse_model_text_to_action
27
+ from training.prompts import build_user_prompt
28
+
29
+
30
+ # Set of valid task ids supported by openenv.yaml; first one is the default.
31
+ VALID_TASKS = ("market_timing", "demand_crafter", "profit_negotiator")
32
+ _TASK_RE = re.compile(r"\[TASK=(\w+)\]")
33
+
34
+
35
+ def extract_task_id(prompt_text: str, default: str = VALID_TASKS[0]) -> str:
36
+ """Pull the [TASK=...] tag the dataset embeds, or fall back to the default."""
37
+ m = _TASK_RE.search(prompt_text or "")
38
+ if not m:
39
+ return default
40
+ candidate = m.group(1)
41
+ return candidate if candidate in VALID_TASKS else default
42
+
43
+
44
+ def _apply_chat_template(tokenizer, messages, model_name: str = "") -> str:
45
+ """Apply chat template, opting out of Qwen3 'thinking' mode when applicable."""
46
+ template_kwargs: Dict[str, Any] = {
47
+ "add_generation_prompt": True,
48
+ "tokenize": False,
49
+ }
50
+ # Qwen3 family supports the `enable_thinking` switch — disable it for short
51
+ # action outputs. Other models silently ignore unknown kwargs in newer
52
+ # transformers; older ones may raise, hence the lower() guard.
53
+ if "qwen3" in (model_name or "").lower():
54
+ template_kwargs["enable_thinking"] = False
55
+ return tokenizer.apply_chat_template(messages, **template_kwargs)
56
+
57
+
58
+ def rollout_once(
59
+ *,
60
+ trainer,
61
+ sync_env,
62
+ tokenizer,
63
+ dataset_prompt: str,
64
+ system_prompt: str,
65
+ max_turns: int,
66
+ model_name: str = "",
67
+ ) -> Dict[str, Any]:
68
+ """Play one full jewelry-shop episode and return per-episode signals.
69
+
70
+ Returns the dict shape TRL's GRPO loop expects: ``prompt_ids``,
71
+ ``completion_ids``, ``logprobs`` (concatenated across turns of the episode)
72
+ plus reward signals consumed by reward functions (``total_reward``,
73
+ ``market_reward``, ``warehouse_reward``, ``showroom_reward``).
74
+ """
75
+ # Late import: trl.experimental.openenv only exists for trl >= 0.17.
76
+ from trl.experimental.openenv import generate_rollout_completions
77
+
78
+ task_id = extract_task_id(dataset_prompt)
79
+ result = sync_env.reset(task_id=task_id)
80
+ obs = result.observation
81
+
82
+ prompt_ids: List[int] = []
83
+ completion_ids: List[int] = []
84
+ logprobs: List[float] = []
85
+
86
+ history: List[str] = []
87
+ last_reward = 0.0
88
+ phase_rewards = {"market": 0.0, "warehouse": 0.0, "showroom": 0.0}
89
+
90
+ for turn in range(1, max_turns + 1):
91
+ if result.done:
92
+ break
93
+
94
+ user_prompt = build_user_prompt(turn, obs, last_reward, history)
95
+ messages = [
96
+ {"role": "system", "content": system_prompt},
97
+ {"role": "user", "content": user_prompt},
98
+ ]
99
+ prompt_text = _apply_chat_template(tokenizer, messages, model_name=model_name)
100
+
101
+ rollout_outputs = generate_rollout_completions(trainer, [prompt_text])[0]
102
+ prompt_ids.extend(rollout_outputs["prompt_ids"])
103
+ completion_ids.extend(rollout_outputs["completion_ids"])
104
+ logprobs.extend(rollout_outputs["logprobs"])
105
+
106
+ completion_text = rollout_outputs.get("text") or tokenizer.decode(
107
+ rollout_outputs["completion_ids"], skip_special_tokens=True
108
+ )
109
+
110
+ current_phase = obs.phase
111
+ action, raw_action_str = parse_model_text_to_action(current_phase, completion_text)
112
+
113
+ result = sync_env.step(action)
114
+ obs = result.observation
115
+ step_reward = float(result.reward or 0.0)
116
+ last_reward = step_reward
117
+
118
+ if current_phase in phase_rewards:
119
+ phase_rewards[current_phase] += step_reward
120
+
121
+ history.append(
122
+ f"Step {turn} ({current_phase}): {raw_action_str!r} -> reward {step_reward:+.2f}"
123
+ )
124
+
125
+ total_reward = float(getattr(obs, "cumulative_reward", sum(phase_rewards.values())))
126
+ total_reward = max(0.0, min(total_reward, 1.0))
127
+
128
+ return {
129
+ "prompt_ids": prompt_ids,
130
+ "completion_ids": completion_ids,
131
+ "logprobs": logprobs,
132
+ "total_reward": total_reward,
133
+ "market_reward": float(phase_rewards["market"]),
134
+ "warehouse_reward": float(phase_rewards["warehouse"]),
135
+ "showroom_reward": float(phase_rewards["showroom"]),
136
+ }
137
+
138
+
139
+ def build_rollout_func(
140
+ *,
141
+ sync_env,
142
+ tokenizer,
143
+ system_prompt: str,
144
+ max_turns: int = 15,
145
+ model_name: str = "",
146
+ ) -> Callable[..., Dict[str, List]]:
147
+ """Return ``rollout_func(prompts, trainer=None)`` closing over the env client.
148
+
149
+ A fresh episode is run for each prompt; the same persistent ``sync_env``
150
+ is reused across all prompts (single WebSocket session — matches Module 5).
151
+ """
152
+
153
+ def rollout_func(prompts: List[str], trainer=None) -> Dict[str, List]:
154
+ episode_prompt_ids: List[List[int]] = []
155
+ episode_completion_ids: List[List[int]] = []
156
+ episode_logprobs: List[List[float]] = []
157
+ total_rewards: List[float] = []
158
+ market_rewards: List[float] = []
159
+ warehouse_rewards: List[float] = []
160
+ showroom_rewards: List[float] = []
161
+
162
+ for prompt_text in prompts:
163
+ ep = rollout_once(
164
+ trainer=trainer,
165
+ sync_env=sync_env,
166
+ tokenizer=tokenizer,
167
+ dataset_prompt=prompt_text,
168
+ system_prompt=system_prompt,
169
+ max_turns=max_turns,
170
+ model_name=model_name,
171
+ )
172
+ episode_prompt_ids.append(ep["prompt_ids"])
173
+ episode_completion_ids.append(ep["completion_ids"])
174
+ episode_logprobs.append(ep["logprobs"])
175
+ total_rewards.append(ep["total_reward"])
176
+ market_rewards.append(ep["market_reward"])
177
+ warehouse_rewards.append(ep["warehouse_reward"])
178
+ showroom_rewards.append(ep["showroom_reward"])
179
+
180
+ return {
181
+ "prompt_ids": episode_prompt_ids,
182
+ "completion_ids": episode_completion_ids,
183
+ "logprobs": episode_logprobs,
184
+ "total_reward": total_rewards,
185
+ "market_reward": market_rewards,
186
+ "warehouse_reward": warehouse_rewards,
187
+ "showroom_reward": showroom_rewards,
188
+ }
189
+
190
+ return rollout_func