garg-tejas commited on
Commit
ffe032d
·
1 Parent(s): 632f68b

feat(training): proper TRL v1.0 GRPO integration, eval fixes, deps update

Browse files

- Add server/grpo_env_wrapper.py: DeadAirGRPOEnv wrapper exposing dispatch
actions as tools for TRL environment_factory
- Rewrite train_grpo.py: uses GRPOTrainer with environment_factory,
GRPOConfig with vLLM colocate, batch reward scaling, beta=0
- Rewrite train.py: clean rollout collection script (no fake training)
- Fix eval.py: use env.step() reward directly instead of recomputing
- Fix inference.py: clean imports, use collect_rollout from train.py
- Add tests/__init__.py for proper package imports
- Update pyproject.toml: openenv-core>=0.2.3, trl>=1.0.0,
transformers>=5.2.0 (required for environment_factory)

Files changed (7) hide show
  1. eval.py +10 -16
  2. inference.py +5 -4
  3. pyproject.toml +3 -3
  4. server/grpo_env_wrapper.py +186 -0
  5. tests/__init__.py +0 -0
  6. train.py +41 -25
  7. train_grpo.py +90 -180
eval.py CHANGED
@@ -13,7 +13,7 @@ def greedy_agent_step(obs: Dict[str, Any]) -> Dict[str, Any]:
13
  if not active_calls:
14
  return {"action_type": "hold"}
15
 
16
- # Prioritize by reported type severity (simplified)
17
  priority = {"cardiac": 3, "trauma": 2, "fire": 1, "false_alarm": 0}
18
  sorted_calls = sorted(
19
  active_calls,
@@ -25,12 +25,11 @@ def greedy_agent_step(obs: Dict[str, Any]) -> Dict[str, Any]:
25
  call_id = call["call_id"]
26
  call_loc = call["location"]
27
 
28
- # Find closest idle unit
29
  best_unit = None
30
  best_dist = float("inf")
31
  for u in unit_statuses:
32
  if u.get("last_known_status") == "idle":
33
- # Use unit location as proxy for distance
34
  dist = abs(u.get("last_known_location", 0) - call_loc)
35
  if dist < best_dist:
36
  best_dist = dist
@@ -46,11 +45,12 @@ def run_episodes(
46
  env: DispatcherEnvironment,
47
  num_episodes: int = 10,
48
  agent_type: str = "greedy",
 
49
  ) -> List[float]:
50
  """Run episodes and return rewards."""
51
  rewards = []
52
  for ep in range(num_episodes):
53
- obs = env.reset(difficulty="learning")
54
  done = False
55
  step_count = 0
56
  while not done and step_count < 100:
@@ -61,24 +61,18 @@ def run_episodes(
61
  obs = env.step(action)
62
  done = obs.get("done", False)
63
  step_count += 1
64
- # Compute reward at end
65
- from dead_air.server.reward import RewardComputer
66
- rc = RewardComputer(env.city_graph)
67
- gt = env.get_ground_truth()
68
- result = rc.compute_episode_reward(
69
- calls=gt["calls"],
70
- units=env.units,
71
- oracle_assignments=gt["optimal_assignments"],
72
- )
73
- rewards.append(result["episode_reward"])
74
  return rewards
75
 
76
 
77
  def main():
78
  print("Running Greedy Baseline Evaluation...")
79
  env = DispatcherEnvironment(seed=42)
80
- rewards = run_episodes(env, num_episodes=10, agent_type="greedy")
81
- print(f"Mean reward over 10 episodes: {sum(rewards)/len(rewards):.3f}")
 
82
  print(f"Rewards: {[round(r, 3) for r in rewards]}")
83
 
84
 
 
13
  if not active_calls:
14
  return {"action_type": "hold"}
15
 
16
+ # Prioritize by reported type severity
17
  priority = {"cardiac": 3, "trauma": 2, "fire": 1, "false_alarm": 0}
18
  sorted_calls = sorted(
19
  active_calls,
 
25
  call_id = call["call_id"]
26
  call_loc = call["location"]
27
 
28
+ # Find closest idle unit using node distance (proxy for graph distance)
29
  best_unit = None
30
  best_dist = float("inf")
31
  for u in unit_statuses:
32
  if u.get("last_known_status") == "idle":
 
33
  dist = abs(u.get("last_known_location", 0) - call_loc)
34
  if dist < best_dist:
35
  best_dist = dist
 
45
  env: DispatcherEnvironment,
46
  num_episodes: int = 10,
47
  agent_type: str = "greedy",
48
+ difficulty: str = "learning",
49
  ) -> List[float]:
50
  """Run episodes and return rewards."""
51
  rewards = []
52
  for ep in range(num_episodes):
53
+ obs = env.reset(difficulty=difficulty)
54
  done = False
55
  step_count = 0
56
  while not done and step_count < 100:
 
61
  obs = env.step(action)
62
  done = obs.get("done", False)
63
  step_count += 1
64
+ # Reward is set by env.step() at episode end
65
+ reward = obs.get("reward", 0.0) or 0.0
66
+ rewards.append(reward)
 
 
 
 
 
 
 
67
  return rewards
68
 
69
 
70
  def main():
71
  print("Running Greedy Baseline Evaluation...")
72
  env = DispatcherEnvironment(seed=42)
73
+ rewards = run_episodes(env, num_episodes=10, agent_type="greedy", difficulty="learning")
74
+ mean_reward = sum(rewards) / len(rewards) if rewards else 0.0
75
+ print(f"Mean reward over {len(rewards)} episodes: {mean_reward:.3f}")
76
  print(f"Rewards: {[round(r, 3) for r in rewards]}")
77
 
78
 
inference.py CHANGED
@@ -3,9 +3,6 @@
3
  import argparse
4
  import json
5
 
6
- import torch
7
- from transformers import AutoModelForCausalLM, AutoTokenizer
8
-
9
  from dead_air.server.dispatcher_environment import DispatcherEnvironment
10
  from train import collect_rollout
11
 
@@ -14,11 +11,14 @@ def main():
14
  parser = argparse.ArgumentParser()
15
  parser.add_argument("--model-path", type=str, required=True)
16
  parser.add_argument("--episodes", type=int, default=5)
17
- parser.add_argument("--device", type=str, default="cuda" if torch.cuda.is_available() else "cpu")
18
  parser.add_argument("--output", type=str, default="inference_results.json")
19
  parser.add_argument("--difficulty", type=str, default="expert")
20
  args = parser.parse_args()
21
 
 
 
 
22
  print(f"Loading model from {args.model_path}...")
23
  tokenizer = AutoTokenizer.from_pretrained(args.model_path, trust_remote_code=True)
24
  model = AutoModelForCausalLM.from_pretrained(
@@ -32,6 +32,7 @@ def main():
32
  results = []
33
 
34
  for ep in range(args.episodes):
 
35
  rollout = collect_rollout(env, model, tokenizer, device=args.device)
36
  results.append({
37
  "episode": ep + 1,
 
3
  import argparse
4
  import json
5
 
 
 
 
6
  from dead_air.server.dispatcher_environment import DispatcherEnvironment
7
  from train import collect_rollout
8
 
 
11
  parser = argparse.ArgumentParser()
12
  parser.add_argument("--model-path", type=str, required=True)
13
  parser.add_argument("--episodes", type=int, default=5)
14
+ parser.add_argument("--device", type=str, default="cuda")
15
  parser.add_argument("--output", type=str, default="inference_results.json")
16
  parser.add_argument("--difficulty", type=str, default="expert")
17
  args = parser.parse_args()
18
 
19
+ import torch
20
+ from transformers import AutoModelForCausalLM, AutoTokenizer
21
+
22
  print(f"Loading model from {args.model_path}...")
23
  tokenizer = AutoTokenizer.from_pretrained(args.model_path, trust_remote_code=True)
24
  model = AutoModelForCausalLM.from_pretrained(
 
32
  results = []
33
 
34
  for ep in range(args.episodes):
35
+ env.reset(difficulty=args.difficulty)
36
  rollout = collect_rollout(env, model, tokenizer, device=args.device)
37
  results.append({
38
  "episode": ep + 1,
pyproject.toml CHANGED
@@ -14,7 +14,7 @@ version = "0.1.0"
14
  description = "Dead Air: Emergency Dispatch RL Environment for OpenEnv"
15
  requires-python = ">=3.10"
16
  dependencies = [
17
- "openenv-core[core]>=0.2.2",
18
  "numpy>=1.24.0",
19
  "networkx>=3.0",
20
  "matplotlib>=3.7.0",
@@ -23,8 +23,8 @@ dependencies = [
23
 
24
  [project.optional-dependencies]
25
  train = [
26
- "trl>=0.29.0",
27
- "transformers>=4.40.0",
28
  "accelerate>=0.30.0",
29
  "datasets>=2.19.0",
30
  "torch>=2.2.0",
 
14
  description = "Dead Air: Emergency Dispatch RL Environment for OpenEnv"
15
  requires-python = ">=3.10"
16
  dependencies = [
17
+ "openenv-core[core]>=0.2.3",
18
  "numpy>=1.24.0",
19
  "networkx>=3.0",
20
  "matplotlib>=3.7.0",
 
23
 
24
  [project.optional-dependencies]
25
  train = [
26
+ "trl>=1.0.0",
27
+ "transformers>=5.2.0",
28
  "accelerate>=0.30.0",
29
  "datasets>=2.19.0",
30
  "torch>=2.2.0",
server/grpo_env_wrapper.py ADDED
@@ -0,0 +1,186 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """GRPO-compatible environment wrapper for Dead Air.
2
+
3
+ Exposes Dead Air dispatch actions as tools for TRL's GRPOTrainer
4
+ with environment_factory support.
5
+ """
6
+
7
+ from typing import Any, Dict, Optional
8
+
9
+ from .constants import MAX_STEPS
10
+ from .dispatcher_environment import DispatcherEnvironment
11
+
12
+
13
+ class DeadAirGRPOEnv:
14
+ """Wrapper that exposes Dead Air as a tool-using environment for TRL GRPO.
15
+
16
+ Each public method becomes a tool the LLM can call. The episode advances
17
+ one step per tool call (except verify, which is free).
18
+ """
19
+
20
+ def __init__(self, seed: Optional[int] = None, difficulty: str = "learning"):
21
+ self._env = DispatcherEnvironment(seed=seed)
22
+ self._difficulty = difficulty
23
+ self._obs: Optional[Dict[str, Any]] = None
24
+ self._episode_reward: Optional[float] = None
25
+ self._events_log: list = []
26
+
27
+ def reset(self, **kwargs: Any) -> str:
28
+ """Reset the environment and return the initial prompt string.
29
+
30
+ Args:
31
+ **kwargs: Passed from dataset row (e.g., prompt, seed).
32
+
33
+ Returns:
34
+ Initial observation formatted as a text prompt.
35
+ """
36
+ seed = kwargs.get("seed")
37
+ diff = kwargs.get("difficulty", self._difficulty)
38
+ self._obs = self._env.reset(difficulty=diff)
39
+ if seed is not None:
40
+ self._env.rng = __import__("numpy").random.default_rng(seed)
41
+ self._episode_reward = None
42
+ self._events_log.clear()
43
+ return self._format_prompt(self._obs)
44
+
45
+ def _step(self, action: Dict[str, Any]) -> str:
46
+ """Internal step wrapper. Returns event summary."""
47
+ if self._obs and self._obs.get("done"):
48
+ return "Episode has already ended."
49
+ self._obs = self._env.step(action)
50
+ events = self._obs.get("recent_events", [])
51
+ self._events_log.extend(events)
52
+ if self._obs.get("reward") is not None:
53
+ self._episode_reward = self._obs["reward"]
54
+ return "\n".join(events) if events else "Action executed."
55
+
56
+ def _format_prompt(self, obs: Dict[str, Any]) -> str:
57
+ """Format observation into a prompt for the LLM."""
58
+ lines = [
59
+ "# Emergency Dispatch Commander",
60
+ f"Step {obs['step_number']}/{obs['max_steps']}",
61
+ "",
62
+ "## Units",
63
+ ]
64
+ for u in obs.get("unit_statuses", []):
65
+ call_info = f" -> Call {u['current_call']}" if u.get("current_call") else ""
66
+ lines.append(
67
+ f"- Unit {u['unit_id']}: {u['last_known_status']} at Node {u['last_known_location']}{call_info}"
68
+ )
69
+ lines.append("")
70
+ lines.append("## Active Calls")
71
+ for c in obs.get("active_calls", []):
72
+ assigned = f" (Unit {c['assigned_unit']})" if c.get("assigned_unit") else ""
73
+ lines.append(
74
+ f"- Call {c['call_id']}: {c['reported_type']} at Node {c['location']} ({c['caller_tone']}) elapsed={c['time_elapsed']}min{assigned}"
75
+ )
76
+ lines.append("")
77
+ lines.append("## Traffic & Hospitals")
78
+ for alert in obs.get("traffic_alerts", []):
79
+ lines.append(f"- {alert}")
80
+ for h in obs.get("hospital_statuses", []):
81
+ lines.append(f"- Hospital {h['hospital_id']}: {h['reported_status']}")
82
+ lines.append("")
83
+ lines.append(f"Mutual aid remaining: {obs['mutual_aid_remaining']}")
84
+ lines.append("")
85
+ lines.append("Choose your next action using the available tools.")
86
+ return "\n".join(lines)
87
+
88
+ def dispatch(self, unit_id: int, call_id: int) -> str:
89
+ """Dispatch an idle unit to an active call.
90
+
91
+ Args:
92
+ unit_id: The unit to dispatch.
93
+ call_id: The call to respond to.
94
+
95
+ Returns:
96
+ Event summary string.
97
+ """
98
+ return self._step({"action_type": "dispatch", "unit_id": unit_id, "call_id": call_id})
99
+
100
+ def reroute(self, unit_id: int, call_id: int) -> str:
101
+ """Reroute a unit currently en route to a different call.
102
+
103
+ Args:
104
+ unit_id: The unit to reroute.
105
+ call_id: The new call to respond to.
106
+
107
+ Returns:
108
+ Event summary string.
109
+ """
110
+ return self._step({"action_type": "reroute", "unit_id": unit_id, "call_id": call_id})
111
+
112
+ def stage(self, unit_id: int, location_node: int) -> str:
113
+ """Pre-position an idle unit at a specific node.
114
+
115
+ Args:
116
+ unit_id: The unit to move.
117
+ location_node: The node to stage at.
118
+
119
+ Returns:
120
+ Event summary string.
121
+ """
122
+ return self._step({"action_type": "stage", "unit_id": unit_id, "location_node": location_node})
123
+
124
+ def hold(self) -> str:
125
+ """Wait one step without taking action.
126
+
127
+ Returns:
128
+ Event summary string.
129
+ """
130
+ return self._step({"action_type": "hold"})
131
+
132
+ def request_mutual_aid(self) -> str:
133
+ """Request external backup unit.
134
+
135
+ Returns:
136
+ Event summary string.
137
+ """
138
+ return self._step({"action_type": "request_mutual_aid"})
139
+
140
+ def divert(self, unit_id: int, hospital_id: int) -> str:
141
+ """Divert a unit to a specific hospital.
142
+
143
+ Args:
144
+ unit_id: The unit to divert.
145
+ hospital_id: The hospital to route to.
146
+
147
+ Returns:
148
+ Event summary string.
149
+ """
150
+ return self._step({"action_type": "divert", "unit_id": unit_id, "hospital_id": hospital_id})
151
+
152
+ def log(self, note: str) -> str:
153
+ """Append a note to the dispatch log.
154
+
155
+ Args:
156
+ note: The note to record.
157
+
158
+ Returns:
159
+ Event summary string.
160
+ """
161
+ return self._step({"action_type": "log", "note": note})
162
+
163
+ def verify(self, call_id: int) -> str:
164
+ """Run a background check on a call (free action, does not advance time).
165
+
166
+ Args:
167
+ call_id: The call to verify.
168
+
169
+ Returns:
170
+ Confidence level string.
171
+ """
172
+ if self._obs and self._obs.get("done"):
173
+ return "Episode has already ended."
174
+ self._obs = self._env.step({"action_type": "verify", "call_id": call_id})
175
+ events = self._obs.get("recent_events", [])
176
+ return "\n".join(events) if events else "Verified."
177
+
178
+ @property
179
+ def reward(self) -> Optional[float]:
180
+ """Episode reward (available after episode ends)."""
181
+ return self._episode_reward
182
+
183
+ @property
184
+ def env(self) -> DispatcherEnvironment:
185
+ """Access the underlying environment."""
186
+ return self._env
tests/__init__.py ADDED
File without changes
train.py CHANGED
@@ -1,13 +1,18 @@
1
- """GRPO training script for Dead Air using HF TRL."""
 
 
 
 
 
 
 
 
2
 
3
  import argparse
4
  import json
5
  import os
6
  from typing import Any, Dict, List
7
 
8
- import torch
9
- from transformers import AutoModelForCausalLM, AutoTokenizer
10
-
11
  from dead_air.server.dispatcher_environment import DispatcherEnvironment
12
 
13
 
@@ -31,7 +36,7 @@ def format_prompt(obs: Dict[str, Any]) -> str:
31
  lines.append(f"- {e}")
32
  lines.append("")
33
  lines.append("## Dispatch Log")
34
- lines.append(obs.get("dispatch_log", "(empty)"))
35
  lines.append("")
36
  lines.append("Choose action: dispatch, reroute, stage, request_mutual_aid, divert, hold, log, verify")
37
  lines.append("Respond with JSON: {\"action_type\": ..., \"unit_id\": ..., \"call_id\": ...}")
@@ -41,7 +46,6 @@ def format_prompt(obs: Dict[str, Any]) -> str:
41
  def parse_action(text: str) -> Dict[str, Any]:
42
  """Parse LLM output into structured action."""
43
  import re
44
- # Try to find JSON in the output
45
  json_match = re.search(r'\{.*?\}', text, re.DOTALL)
46
  if json_match:
47
  try:
@@ -50,18 +54,18 @@ def parse_action(text: str) -> Dict[str, Any]:
50
  return action
51
  except json.JSONDecodeError:
52
  pass
53
- # Fallback to hold
54
  return {"action_type": "hold"}
55
 
56
 
57
  def collect_rollout(env: DispatcherEnvironment, model, tokenizer, device: str = "cuda") -> Dict[str, Any]:
58
  """Collect one episode rollout."""
 
59
  obs = env.reset(difficulty="learning")
60
  done = False
61
  steps = 0
62
  total_reward = 0.0
63
- prompts = []
64
- completions = []
65
 
66
  while not done and steps < 100:
67
  prompt = format_prompt(obs)
@@ -75,6 +79,7 @@ def collect_rollout(env: DispatcherEnvironment, model, tokenizer, device: str =
75
  temperature=0.7,
76
  top_p=0.9,
77
  do_sample=True,
 
78
  )
79
  completion = tokenizer.decode(outputs[0][inputs["input_ids"].shape[1]:], skip_special_tokens=True)
80
  completions.append(completion)
@@ -98,13 +103,19 @@ def main():
98
  parser = argparse.ArgumentParser()
99
  parser.add_argument("--model", type=str, default="Qwen/Qwen3-1.7B")
100
  parser.add_argument("--episodes", type=int, default=50)
101
- parser.add_argument("--device", type=str, default="cuda" if torch.cuda.is_available() else "cpu")
102
- parser.add_argument("--output-dir", type=str, default="./outputs")
103
- parser.add_argument("--dry-run", action="store_true")
104
  args = parser.parse_args()
105
 
 
 
 
106
  print(f"Loading model {args.model} on {args.device}...")
107
  tokenizer = AutoTokenizer.from_pretrained(args.model, trust_remote_code=True)
 
 
 
108
  model = AutoModelForCausalLM.from_pretrained(
109
  args.model,
110
  torch_dtype=torch.bfloat16,
@@ -114,25 +125,30 @@ def main():
114
  if args.device == "cpu":
115
  model = model.to("cpu")
116
 
117
- print(f"Model loaded. Starting {args.episodes} episodes...")
118
  env = DispatcherEnvironment(seed=42)
119
- rewards = []
120
 
 
121
  for ep in range(args.episodes):
 
 
 
 
122
  rollout = collect_rollout(env, model, tokenizer, device=args.device)
123
- rewards.append(rollout["reward"])
124
- print(f"Episode {ep+1}/{args.episodes}: reward={rollout['reward']:.3f}, steps={rollout['steps']}")
 
 
 
125
 
126
- print(f"\nMean reward: {sum(rewards)/len(rewards):.3f}")
 
 
127
 
128
- os.makedirs(args.output_dir, exist_ok=True)
129
- with open(os.path.join(args.output_dir, "rewards.json"), "w") as f:
130
- json.dump({"rewards": rewards}, f)
131
-
132
- if not args.dry_run:
133
- print(f"Saving model to {args.output_dir}")
134
- model.save_pretrained(args.output_dir)
135
- tokenizer.save_pretrained(args.output_dir)
136
 
137
 
138
  if __name__ == "__main__":
 
1
+ """Rollout collection script for Dead Air.
2
+
3
+ Collects episodes by running the LLM against the environment.
4
+ Useful for warm-start data generation or debugging before GRPO training.
5
+
6
+ Usage:
7
+ uv sync --extra train
8
+ python train.py --model Qwen/Qwen3-1.7B --episodes 50 --output-dir ./outputs/rollouts
9
+ """
10
 
11
  import argparse
12
  import json
13
  import os
14
  from typing import Any, Dict, List
15
 
 
 
 
16
  from dead_air.server.dispatcher_environment import DispatcherEnvironment
17
 
18
 
 
36
  lines.append(f"- {e}")
37
  lines.append("")
38
  lines.append("## Dispatch Log")
39
+ lines.append(obs.get("dispatch_log", "(empty)")[-500:] if obs.get("dispatch_log") else "(empty)")
40
  lines.append("")
41
  lines.append("Choose action: dispatch, reroute, stage, request_mutual_aid, divert, hold, log, verify")
42
  lines.append("Respond with JSON: {\"action_type\": ..., \"unit_id\": ..., \"call_id\": ...}")
 
46
  def parse_action(text: str) -> Dict[str, Any]:
47
  """Parse LLM output into structured action."""
48
  import re
 
49
  json_match = re.search(r'\{.*?\}', text, re.DOTALL)
50
  if json_match:
51
  try:
 
54
  return action
55
  except json.JSONDecodeError:
56
  pass
 
57
  return {"action_type": "hold"}
58
 
59
 
60
  def collect_rollout(env: DispatcherEnvironment, model, tokenizer, device: str = "cuda") -> Dict[str, Any]:
61
  """Collect one episode rollout."""
62
+ import torch
63
  obs = env.reset(difficulty="learning")
64
  done = False
65
  steps = 0
66
  total_reward = 0.0
67
+ prompts: List[str] = []
68
+ completions: List[str] = []
69
 
70
  while not done and steps < 100:
71
  prompt = format_prompt(obs)
 
79
  temperature=0.7,
80
  top_p=0.9,
81
  do_sample=True,
82
+ pad_token_id=tokenizer.eos_token_id,
83
  )
84
  completion = tokenizer.decode(outputs[0][inputs["input_ids"].shape[1]:], skip_special_tokens=True)
85
  completions.append(completion)
 
103
  parser = argparse.ArgumentParser()
104
  parser.add_argument("--model", type=str, default="Qwen/Qwen3-1.7B")
105
  parser.add_argument("--episodes", type=int, default=50)
106
+ parser.add_argument("--device", type=str, default="cuda")
107
+ parser.add_argument("--output-dir", type=str, default="./outputs/rollouts")
108
+ parser.add_argument("--difficulty", type=str, default="learning")
109
  args = parser.parse_args()
110
 
111
+ import torch
112
+ from transformers import AutoModelForCausalLM, AutoTokenizer
113
+
114
  print(f"Loading model {args.model} on {args.device}...")
115
  tokenizer = AutoTokenizer.from_pretrained(args.model, trust_remote_code=True)
116
+ if tokenizer.pad_token is None:
117
+ tokenizer.pad_token = tokenizer.eos_token
118
+
119
  model = AutoModelForCausalLM.from_pretrained(
120
  args.model,
121
  torch_dtype=torch.bfloat16,
 
125
  if args.device == "cpu":
126
  model = model.to("cpu")
127
 
128
+ print(f"Model loaded. Collecting {args.episodes} rollouts...")
129
  env = DispatcherEnvironment(seed=42)
130
+ os.makedirs(args.output_dir, exist_ok=True)
131
 
132
+ all_rollouts = []
133
  for ep in range(args.episodes):
134
+ if args.difficulty == "curriculum":
135
+ diff = env.curriculum.phase
136
+ else:
137
+ diff = args.difficulty
138
  rollout = collect_rollout(env, model, tokenizer, device=args.device)
139
+ rollout["episode"] = ep + 1
140
+ rollout["difficulty"] = diff
141
+ all_rollouts.append(rollout)
142
+ if (ep + 1) % 10 == 0:
143
+ print(f"Episode {ep+1}/{args.episodes}: reward={rollout['reward']:.3f}, steps={rollout['steps']}")
144
 
145
+ # Save rollouts
146
+ with open(os.path.join(args.output_dir, "rollouts.json"), "w") as f:
147
+ json.dump(all_rollouts, f, indent=2)
148
 
149
+ rewards = [r["reward"] for r in all_rollouts]
150
+ print(f"\nMean reward: {sum(rewards)/len(rewards):.3f}")
151
+ print(f"Rollouts saved to {args.output_dir}/rollouts.json")
 
 
 
 
 
152
 
153
 
154
  if __name__ == "__main__":
train_grpo.py CHANGED
@@ -2,214 +2,124 @@
2
 
3
  Usage (on Lightning AI L4 or H100):
4
  uv sync --extra train
5
- python train_grpo.py --model Qwen/Qwen3-1.7B --episodes 200
6
 
7
  Requirements:
8
  - torch>=2.2.0
9
- - trl>=0.29.0
10
- - transformers>=4.40.0
11
  - accelerate>=0.30.0
12
  """
13
 
14
  import argparse
15
  import json
16
  import os
17
- from typing import Any, Dict, List
18
-
19
- import torch
20
- from transformers import AutoModelForCausalLM, AutoTokenizer
21
-
22
- from dead_air.server.dispatcher_environment import DispatcherEnvironment
23
-
24
-
25
- def format_prompt(obs: Dict[str, Any]) -> str:
26
- """Format observation into a text prompt for the LLM."""
27
- lines = [
28
- "# Emergency Dispatch Commander",
29
- f"Step {obs['step_number']}/{obs['max_steps']}",
30
- "",
31
- "## Units",
32
- ]
33
- for u in obs.get("unit_statuses", []):
34
- lines.append(f"- Unit {u['unit_id']}: {u['last_known_status']} at Node {u['last_known_location']}")
35
- lines.append("")
36
- lines.append("## Active Calls")
37
- for c in obs.get("active_calls", []):
38
- lines.append(f"- Call {c['call_id']}: {c['reported_type']} at Node {c['location']} ({c['caller_tone']}) elapsed={c['time_elapsed']}min")
39
- lines.append("")
40
- lines.append("## Recent Events")
41
- for e in obs.get("recent_events", [])[-5:]:
42
- lines.append(f"- {e}")
43
- lines.append("")
44
- lines.append("## Dispatch Log")
45
- lines.append(obs.get("dispatch_log", "(empty)")[-500:] if obs.get("dispatch_log") else "(empty)")
46
- lines.append("")
47
- lines.append("Choose action: dispatch, reroute, stage, request_mutual_aid, divert, hold, log, verify")
48
- lines.append("Respond with JSON: {\"action_type\": ..., \"unit_id\": ..., \"call_id\": ...}")
49
- return "\n".join(lines)
50
-
51
-
52
- def parse_action(text: str) -> Dict[str, Any]:
53
- """Parse LLM output into structured action."""
54
- import re
55
- # Try to find JSON in the output
56
- json_match = re.search(r'\{.*?\}', text, re.DOTALL)
57
- if json_match:
58
- try:
59
- action = json.loads(json_match.group())
60
- if "action_type" in action:
61
- return action
62
- except json.JSONDecodeError:
63
- pass
64
- # Fallback to hold
65
- return {"action_type": "hold"}
66
-
67
-
68
- def run_episode(env: DispatcherEnvironment, model, tokenizer, device: str = "cuda", max_steps: int = 100) -> Dict[str, Any]:
69
- """Run one episode and collect trajectory."""
70
- obs = env.reset(difficulty="learning")
71
- done = False
72
- steps = 0
73
- total_reward = 0.0
74
- prompts = []
75
- completions = []
76
- rewards_per_step = []
77
-
78
- while not done and steps < max_steps:
79
- prompt = format_prompt(obs)
80
- prompts.append(prompt)
81
-
82
- inputs = tokenizer(prompt, return_tensors="pt", truncation=True, max_length=2048).to(device)
83
- with torch.no_grad():
84
- outputs = model.generate(
85
- **inputs,
86
- max_new_tokens=128,
87
- temperature=0.7,
88
- top_p=0.9,
89
- do_sample=True,
90
- pad_token_id=tokenizer.eos_token_id,
91
- )
92
- completion = tokenizer.decode(outputs[0][inputs["input_ids"].shape[1]:], skip_special_tokens=True)
93
- completions.append(completion)
94
-
95
- action = parse_action(completion)
96
- obs = env.step(action)
97
- done = obs.get("done", False)
98
- if obs.get("reward") is not None:
99
- total_reward = obs["reward"]
100
- steps += 1
101
-
102
- # Assign episode reward to all steps (sparse reward)
103
- rewards_per_step = [total_reward] * len(prompts)
104
-
105
- return {
106
- "prompts": prompts,
107
- "completions": completions,
108
- "rewards": rewards_per_step,
109
- "episode_reward": total_reward,
110
- "steps": steps,
111
- }
112
 
113
 
114
  def main():
115
  parser = argparse.ArgumentParser()
116
  parser.add_argument("--model", type=str, default="Qwen/Qwen3-1.7B")
117
  parser.add_argument("--episodes", type=int, default=200)
118
- parser.add_argument("--device", type=str, default="cuda" if torch.cuda.is_available() else "cpu")
119
  parser.add_argument("--output-dir", type=str, default="./outputs/grpo")
120
  parser.add_argument("--save-every", type=int, default=50)
121
- parser.add_argument("--difficulty", type=str, default="curriculum")
 
 
 
 
122
  args = parser.parse_args()
123
 
124
- print(f"=" * 60)
125
- print(f"Dead Air GRPO Training")
126
  print(f"Model: {args.model}")
127
  print(f"Episodes: {args.episodes}")
128
- print(f"Device: {args.device}")
129
- print(f"=" * 60)
130
 
131
- # Check if TRL is available
132
  try:
133
  from trl import GRPOConfig, GRPOTrainer
134
- print("TRL loaded successfully")
135
- except ImportError:
136
- print("WARNING: TRL not installed. Install with: uv sync --extra train")
137
- print("Falling back to basic rollout collection (no training)")
138
- GRPOTrainer = None
139
-
140
- print(f"\nLoading model {args.model}...")
141
- tokenizer = AutoTokenizer.from_pretrained(args.model, trust_remote_code=True)
142
- if tokenizer.pad_token is None:
143
- tokenizer.pad_token = tokenizer.eos_token
144
-
145
- model = AutoModelForCausalLM.from_pretrained(
146
- args.model,
147
- torch_dtype=torch.bfloat16,
148
- device_map="auto" if args.device == "cuda" else None,
149
- trust_remote_code=True,
150
  )
151
- if args.device == "cpu":
152
- model = model.to("cpu")
153
-
154
- print("Model loaded.\n")
155
-
156
- env = DispatcherEnvironment(seed=42)
157
- os.makedirs(args.output_dir, exist_ok=True)
158
-
159
- all_rewards = []
160
-
161
- for ep in range(args.episodes):
162
- # Update difficulty based on curriculum
163
- if args.difficulty == "curriculum":
164
- diff = env.curriculum.phase
165
- else:
166
- diff = args.difficulty
167
-
168
- rollout = run_episode(env, model, tokenizer, device=args.device)
169
- reward = rollout["episode_reward"]
170
- all_rewards.append(reward)
171
-
172
- # Update curriculum
173
- env.curriculum.record_reward(reward)
174
- new_phase = env.curriculum.update_phase()
175
-
176
- if (ep + 1) % 10 == 0:
177
- recent_rewards = all_rewards[-10:]
178
- mean_reward = sum(recent_rewards) / len(recent_rewards)
179
- print(f"Episode {ep+1:3d}/{args.episodes} | Phase: {new_phase:8s} | "
180
- f"Reward: {reward:.3f} | Mean(10): {mean_reward:.3f} | Steps: {rollout['steps']}")
181
-
182
- # Save checkpoint periodically
183
- if (ep + 1) % args.save_every == 0:
184
- save_path = os.path.join(args.output_dir, f"checkpoint-{ep+1}")
185
- os.makedirs(save_path, exist_ok=True)
186
- model.save_pretrained(save_path)
187
- tokenizer.save_pretrained(save_path)
188
-
189
- # Save rewards
190
- with open(os.path.join(args.output_dir, "rewards.json"), "w") as f:
191
- json.dump({
192
- "rewards": all_rewards,
193
- "mean_reward": sum(all_rewards) / len(all_rewards),
194
- "max_reward": max(all_rewards),
195
- "min_reward": min(all_rewards),
196
- }, f, indent=2)
197
-
198
- print(f" -> Saved checkpoint to {save_path}")
199
-
200
- # Final save
201
- print("\n" + "=" * 60)
202
- print("Training complete!")
203
- print(f"Mean reward: {sum(all_rewards)/len(all_rewards):.3f}")
204
- print(f"Max reward: {max(all_rewards):.3f}")
205
- print(f"Final phase: {env.curriculum.phase}")
206
- print("=" * 60)
207
 
 
208
  final_path = os.path.join(args.output_dir, "final")
209
  os.makedirs(final_path, exist_ok=True)
210
- model.save_pretrained(final_path)
211
- tokenizer.save_pretrained(final_path)
212
- print(f"Final model saved to {final_path}")
213
 
214
 
215
  if __name__ == "__main__":
 
2
 
3
  Usage (on Lightning AI L4 or H100):
4
  uv sync --extra train
5
+ accelerate launch train_grpo.py --model Qwen/Qwen3-1.7B --episodes 200
6
 
7
  Requirements:
8
  - torch>=2.2.0
9
+ - trl>=1.0.0
10
+ - transformers>=5.2.0 (required for environment_factory)
11
  - accelerate>=0.30.0
12
  """
13
 
14
  import argparse
15
  import json
16
  import os
17
+ from typing import Any, Dict, List, Optional
18
+
19
+ from datasets import Dataset
20
+
21
+
22
+ def make_reward_func(difficulty: str = "learning"):
23
+ """Create a reward function that reads episode reward from environment state."""
24
+
25
+ def reward_func(environments: List[Any], **kwargs: Any) -> List[float]:
26
+ """Return episode reward for each environment instance."""
27
+ rewards = []
28
+ for env in environments:
29
+ r = env.reward
30
+ if r is None:
31
+ # Episode hasn't ended yet — penalize incomplete episodes
32
+ rewards.append(0.0)
33
+ else:
34
+ rewards.append(float(r))
35
+ return rewards
36
+
37
+ return reward_func
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
38
 
39
 
40
  def main():
41
  parser = argparse.ArgumentParser()
42
  parser.add_argument("--model", type=str, default="Qwen/Qwen3-1.7B")
43
  parser.add_argument("--episodes", type=int, default=200)
44
+ parser.add_argument("--difficulty", type=str, default="curriculum")
45
  parser.add_argument("--output-dir", type=str, default="./outputs/grpo")
46
  parser.add_argument("--save-every", type=int, default=50)
47
+ parser.add_argument("--num-generations", type=int, default=8)
48
+ parser.add_argument("--max-completion-length", type=int, default=512)
49
+ parser.add_argument("--max-prompt-length", type=int, default=2048)
50
+ parser.add_argument("--learning-rate", type=float, default=5e-6)
51
+ parser.add_argument("--seed", type=int, default=42)
52
  args = parser.parse_args()
53
 
54
+ print("=" * 60)
55
+ print("Dead Air GRPO Training")
56
  print(f"Model: {args.model}")
57
  print(f"Episodes: {args.episodes}")
58
+ print("=" * 60)
 
59
 
60
+ # Imports here so script can be parsed even without TRL installed
61
  try:
62
  from trl import GRPOConfig, GRPOTrainer
63
+ except ImportError as e:
64
+ raise ImportError(
65
+ "TRL is required for training. Install with: uv sync --extra train"
66
+ ) from e
67
+
68
+ # Create dummy dataset with repeated prompts.
69
+ # The actual state is injected by environment.reset() each episode.
70
+ system_prompt = (
71
+ "You are an emergency dispatch commander for a 20-node city. "
72
+ "You have 6 units and must respond to emergency calls. "
73
+ "Use the available tools to dispatch units, stage them, verify suspicious calls, "
74
+ "request mutual aid, or hold. Minimize fatalities and response time. "
75
+ "Think step by step before acting."
 
 
 
76
  )
77
+ dataset = Dataset.from_dict({
78
+ "prompt": [system_prompt] * args.episodes,
79
+ "difficulty": [args.difficulty] * args.episodes,
80
+ })
81
+
82
+ training_args = GRPOConfig(
83
+ output_dir=args.output_dir,
84
+ num_generations=args.num_generations,
85
+ max_completion_length=args.max_completion_length,
86
+ max_prompt_length=args.max_prompt_length,
87
+ per_device_train_batch_size=1,
88
+ gradient_accumulation_steps=8,
89
+ learning_rate=args.learning_rate,
90
+ num_train_epochs=1,
91
+ logging_steps=10,
92
+ save_steps=args.save_every,
93
+ # L4 24GB VRAM settings
94
+ use_vllm=True,
95
+ vllm_gpu_memory_utilization=0.7,
96
+ # Reward scaling: batch-level std reduces difficulty bias
97
+ scale_rewards="batch",
98
+ # Disable KL penalty (standard practice in modern GRPO)
99
+ beta=0.0,
100
+ )
101
+
102
+ # Import wrapper inside main to avoid import errors when TRL not installed
103
+ from dead_air.server.grpo_env_wrapper import DeadAirGRPOEnv
104
+
105
+ reward_func = make_reward_func(difficulty=args.difficulty)
106
+
107
+ trainer = GRPOTrainer(
108
+ model=args.model,
109
+ args=training_args,
110
+ train_dataset=dataset,
111
+ reward_funcs=reward_func,
112
+ environment_factory=DeadAirGRPOEnv,
113
+ )
114
+
115
+ print("\nStarting training...")
116
+ trainer.train()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
117
 
118
+ # Save final model
119
  final_path = os.path.join(args.output_dir, "final")
120
  os.makedirs(final_path, exist_ok=True)
121
+ trainer.save_model(final_path)
122
+ print(f"\nFinal model saved to {final_path}")
 
123
 
124
 
125
  if __name__ == "__main__":