amanmurari commited on
Commit
674a510
·
verified ·
1 Parent(s): a1a27eb

Upload folder using huggingface_hub

Browse files
Files changed (1) hide show
  1. inference.py +308 -124
inference.py CHANGED
@@ -33,15 +33,36 @@ API_BASE_URL = os.getenv("API_BASE_URL") or "https://router.huggingface.co/v1"
33
  MODEL_NAME = os.getenv("MODEL_NAME") or "Qwen/Qwen2.5-72B-Instruct"
34
  SERVER_URL = os.getenv("SERVER_URL", "http://localhost:7860")
35
  SEED = 42
36
- MAX_TOKENS = 256 # enough for chain-of-thought + JSON
37
- TEMPERATURE = 0.0
38
-
39
- # Minimum green hold steps (ensures stability_bonus in grading)
40
- MIN_GREEN_HOLD = 4
 
 
 
 
41
 
42
  # Task max_steps for score projection
43
  TASK_MAX_STEPS = {"basic_flow": 200, "emergency_priority": 300, "dynamic_scenarios": 400}
44
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
45
 
46
  # ---------------------------------------------------------------------------
47
  # Heuristic core — uses actual environment reward formula
@@ -72,84 +93,149 @@ def _compute_pressures(obs: TrafficObservation) -> Tuple[float, float]:
72
  return ns_p, ew_p
73
 
74
 
75
- def _dynamic_hold_time(obs: TrafficObservation) -> int:
76
  """
77
- Adaptive minimum hold: longer when current direction has more traffic
78
- so we don't leave vehicles stranded mid-queue.
79
  """
80
- current = obs.current_phase
81
- if current in (0, 3): # NS_GREEN / NS_YELLOW
 
82
  q = obs.queue_lengths[0] + obs.queue_lengths[1]
83
- elif current in (1, 4): # EW_GREEN / EW_YELLOW
84
  q = obs.queue_lengths[2] + obs.queue_lengths[3]
85
  else:
86
- return MIN_GREEN_HOLD
87
- # Hold longer if queue is deep (drain rate ~3 veh/step)
88
- return max(MIN_GREEN_HOLD, min(q // 3, 10))
 
 
 
 
 
 
 
 
 
89
 
90
 
91
- def _heuristic_phase(obs: TrafficObservation) -> int:
92
  """
93
  Mathematically optimal phase recommendation.
 
 
94
  Priority order:
95
- 1. Critical emergency (urgency 8) clear NOW
96
- 2. Moderate emergency (urgency 5-7) — prioritise unless other side is worse
97
- 3. Hysteresis don't switch if hold time not reached
98
- 4. Queue pressure switch to higher pressure direction
99
- 5. Default — hold current
 
 
100
  """
101
  ns_em = obs.emergency_queue[0] + obs.emergency_queue[1]
102
  ew_em = obs.emergency_queue[2] + obs.emergency_queue[3]
103
  ns_urg = max(obs.emergency_urgency[0], obs.emergency_urgency[1])
104
  ew_urg = max(obs.emergency_urgency[2], obs.emergency_urgency[3])
105
  cur = obs.current_phase
 
 
 
 
 
 
 
 
 
 
 
 
 
106
 
107
- # 1. Critical emergency
108
  if ns_em > 0 and ns_urg >= 8 and ew_em > 0 and ew_urg >= 8:
109
- return 2 # ALL_RED: both critical, momentary pause to avoid collision
110
  if ns_em > 0 and ns_urg >= 8:
111
- return 0
112
  if ew_em > 0 and ew_urg >= 8:
113
- return 1
114
 
115
- # 2. Moderate emergencyswitch if other side isn't also urgent
 
 
 
 
 
 
 
 
 
 
 
 
 
116
  if ns_em > 0 and ns_urg >= 5:
117
  if ew_em == 0 or ns_urg >= ew_urg:
118
- return 0
119
  if ew_em > 0 and ew_urg >= 5:
120
- return 1
121
 
122
- # 3. Hysteresis
123
- hold = _dynamic_hold_time(obs)
 
124
  if obs.time_in_phase < hold:
125
- if cur in (0, 3): return 0
126
- if cur in (1, 4): return 1
127
 
128
- # 4. Queue pressure
129
  ns_p, ew_p = _compute_pressures(obs)
130
- if ns_p > ew_p * 1.3:
131
- return 0
132
- if ew_p > ns_p * 1.3:
133
- return 1
 
 
 
 
 
134
 
135
- # 5. Hold current
136
- if cur in (0, 3): return 0
137
- if cur in (1, 4): return 1
138
- return 0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
139
 
140
 
141
  # ---------------------------------------------------------------------------
142
- # Live grade projection (shows LLM how its decisions impact the final score)
143
  # ---------------------------------------------------------------------------
144
 
145
  def _project_score(task: str, state: Optional[TrafficState], step: int) -> str:
146
- """Compute projected grading scores from current episode state."""
147
  if state is None or step == 0:
148
  return "(no data yet)"
149
 
150
  s = state
151
  steps = max(s.step_count, 1)
152
- max_s = TASK_MAX_STEPS.get(task, 300)
153
 
154
  throughput_per_step = s.total_vehicles_passed / steps
155
  em_rate = s.total_emergency_passed / steps
@@ -161,10 +247,11 @@ def _project_score(task: str, state: Optional[TrafficState], step: int) -> str:
161
  sw = s.total_phase_changes / steps
162
  stab = max(0.0, 0.05 * (1.0 - min(sw * 4, 1.0)))
163
  proj = tput * 0.6 + eff * 0.4 + stab
 
164
  return (
165
- f"throughput={tput:.2f}(×0.6) eff={eff:.2f}(×0.4) stability={stab:.3f} "
166
- f"→ projected={proj:.3f} "
167
- f"[veh/step={throughput_per_step:.2f} target=1.8, switch_rate={sw:.2f} target<0.25]"
168
  )
169
 
170
  if task == "emergency_priority":
@@ -172,14 +259,17 @@ def _project_score(task: str, state: Optional[TrafficState], step: int) -> str:
172
  em_score = min(em_rate / (1.0 / 20.0), 1.0)
173
  if s.total_emergency_passed > 0:
174
  delay = max(0.0, 1.0 - (s.total_emergency_delay / s.total_emergency_passed) / 12.0)
 
175
  else:
176
  delay = 0.5
 
177
  eff = 1.0 / (1.0 + avg_wait * 0.05)
178
  proj = tput * 0.30 + em_score * 0.35 + delay * 0.20 + eff * 0.15
179
  return (
180
- f"tput={tput:.2f}(×0.30) em_rate={em_score:.2f}(×0.35) "
181
- f"delay={delay:.2f}(×0.20) eff={eff:.2f}(×0.15) → projected={proj:.3f} "
182
- f"[em_cleared={s.total_emergency_passed} need≥{steps//20}]"
 
183
  )
184
 
185
  if task == "dynamic_scenarios":
@@ -187,102 +277,151 @@ def _project_score(task: str, state: Optional[TrafficState], step: int) -> str:
187
  em_score = min(em_rate / (1.0 / 15.0), 1.0)
188
  if s.total_emergency_passed > 0:
189
  delay = max(0.0, 1.0 - (s.total_emergency_delay / s.total_emergency_passed) / 5.0)
 
190
  else:
191
  delay = 0.0
 
192
  eff = 1.0 / (1.0 + avg_wait * 0.08)
193
  adapt = 1.0 / (1.0 + (s.total_phase_changes / steps) * 0.5)
194
  proj = tput * 0.25 + em_score * 0.30 + delay * 0.20 + eff * 0.15 + adapt * 0.10
195
  return (
196
- f"tput={tput:.2f}(×0.25) em={em_score:.2f}(×0.30) delay={delay:.2f}(×0.20) "
197
- f"eff={eff:.2f}(×0.15) adapt={adapt:.2f}(×0.10) → projected={proj:.3f}"
 
198
  )
199
 
200
  return "(unknown task)"
201
 
202
 
203
  # ---------------------------------------------------------------------------
204
- # LLM prompt
205
  # ---------------------------------------------------------------------------
206
 
207
- SYSTEM_PROMPT = """You are an expert Autonomous Traffic Signal Controller optimising a 4-way intersection.
208
 
209
  PHASES: 0=NS_GREEN 1=EW_GREEN 2=ALL_RED
 
210
 
211
- REWARD FUNCTION (per step):
212
  +0.30 × regular vehicles cleared
213
  +12.0 × emergency vehicles cleared
214
- -(urgency^1.5)×0.5 per waiting emergency vehicle (EVERY step it waits!)
 
215
  -0.08 × total vehicles waiting
216
- -0.5 to -2.0 for unnecessary phase switch (proportional to how empty the new direction is)
217
  +0.05 stability bonus when traffic flows without switching
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
218
 
219
- GRADING WEIGHTS:
220
- basic_flow: throughput×0.60 efficiency×0.40 stability_bonus
221
- emergency_priority: throughput×0.30 em_rate×0.35 delay×0.20 efficiency×0.15
222
- dynamic_scenarios: throughput×0.25 em_rate×0.30 delay×0.20 efficiency×0.15 adaptability×0.10
223
 
224
- DECISION RULES (follow strictly):
225
- 1. Urgency 8 emergencyswitch to that direction IMMEDIATELY
226
- 2. Urgency 5-7 emergency → switch unless other side is equally urgent
227
- 3. Hold current phase 4 steps before switching (preserves stability bonus)
228
- 4. Switch only when pressure ratio > 1.3× (avoid unnecessary switches)
229
- 5. ALL_RED only when both directions have simultaneous critical emergencies
 
230
 
231
- Think step by step, then output ONLY valid JSON on the last line: {"light_phase": 0}"""
 
232
 
233
 
 
 
 
 
 
 
 
 
 
234
  def _build_prompt(
235
  obs: TrafficObservation,
236
  step: int,
237
  task: str,
238
  history: Deque[str],
239
  heuristic: int,
 
240
  score_projection: str,
241
  ) -> str:
242
  ns_p, ew_p = _compute_pressures(obs)
243
- ns_q = obs.queue_lengths[0] + obs.queue_lengths[1]
244
- ew_q = obs.queue_lengths[2] + obs.queue_lengths[3]
245
- ns_em = obs.emergency_queue[0] + obs.emergency_queue[1]
246
- ew_em = obs.emergency_queue[2] + obs.emergency_queue[3]
247
  ns_urg = max(obs.emergency_urgency[0], obs.emergency_urgency[1])
248
  ew_urg = max(obs.emergency_urgency[2], obs.emergency_urgency[3])
 
249
 
250
- phase_name = {0:"NS_GREEN",1:"EW_GREEN",2:"ALL_RED",3:"NS_YELLOW",4:"EW_YELLOW"}
251
- hint_name = {0:"NS_GREEN (0)",1:"EW_GREEN (1)",2:"ALL_RED (2)"}
252
  trend_str = f"[{obs.queue_trend[0]:+d},{obs.queue_trend[1]:+d},{obs.queue_trend[2]:+d},{obs.queue_trend[3]:+d}]"
253
 
 
 
 
 
 
 
 
 
254
  history_str = "\n".join(history) if history else " (episode start)"
255
 
256
  return (
257
- f"TASK: {task} | Step {step} | Current phase: {phase_name.get(obs.current_phase,'?')} (held {obs.time_in_phase} steps)\n"
 
258
  f"\n"
259
- f"STATE:\n"
260
- f" NS: {ns_q} regular + {ns_em} emergency(urgency={ns_urg}) pressure={ns_p:.1f}\n"
261
- f" EW: {ew_q} regular + {ew_em} emergency(urgency={ew_urg}) pressure={ew_p:.1f}\n"
262
- f" Queues [N,S,E,W]: {list(obs.queue_lengths)} trend={trend_str}\n"
263
- f" Avg wait: {obs.avg_wait_time:.1f} steps | Collision: {obs.collision}\n"
264
  f"\n"
265
- f"LIVE SCORE PROJECTION:\n {score_projection}\n"
266
  f"\n"
267
- f"RECENT HISTORY (last {len(history)} steps):\n{history_str}\n"
268
  f"\n"
269
- f"Heuristic recommendation: {hint_name[heuristic]}\n"
270
- f"Reason through the decision, then output JSON on the last line."
271
  )
272
 
273
 
274
  # ---------------------------------------------------------------------------
275
- # Parse + LLM call
276
  # ---------------------------------------------------------------------------
277
 
278
- def _sanitize(s: str) -> str:
279
- return s.replace('"', "'").replace("\n", " ")
280
-
281
-
282
  def _parse_phase(raw: str) -> Optional[int]:
283
  """Extract phase from LLM chain-of-thought output (JSON on last line)."""
284
  import re
285
- # Try last non-empty line first (chain-of-thought ends with JSON)
286
  lines = [l.strip() for l in raw.split("\n") if l.strip()]
287
  for line in reversed(lines):
288
  try:
@@ -292,7 +431,6 @@ def _parse_phase(raw: str) -> Optional[int]:
292
  return p
293
  except Exception:
294
  pass
295
- # Fallback: regex anywhere
296
  m = re.search(r'"light_phase"\s*:\s*([012])', raw)
297
  if m:
298
  return int(m.group(1))
@@ -302,34 +440,58 @@ def _parse_phase(raw: str) -> Optional[int]:
302
  return None
303
 
304
 
305
- def get_llm_action(
 
 
 
 
 
 
 
 
306
  client: OpenAI,
307
  obs: TrafficObservation,
308
  step: int,
309
  task: str,
310
  history: Deque[str],
311
  state: Optional[TrafficState],
312
- ) -> TrafficAction:
313
- heuristic = _heuristic_phase(obs)
314
- score_proj = _project_score(task, state, step)
 
 
 
 
 
315
 
316
- resp = client.chat.completions.create(
317
- model=MODEL_NAME,
318
- messages=[
319
- {"role": "system", "content": SYSTEM_PROMPT},
320
- {"role": "user", "content": _build_prompt(obs, step, task, history, heuristic, score_proj)},
321
- ],
322
- temperature=TEMPERATURE,
323
- max_tokens=MAX_TOKENS,
324
- )
325
- raw = resp.choices[0].message.content.strip()
326
- phase = _parse_phase(raw)
327
 
328
- # Fallback to heuristic if LLM output is unparseable or clearly wrong
329
- if phase is None:
330
- phase = heuristic
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
331
 
332
- return TrafficAction(light_phase=phase)
 
333
 
334
 
335
  # ---------------------------------------------------------------------------
@@ -357,12 +519,16 @@ def _wait_for_server(url: str, timeout: int = 60) -> None:
357
  def run_task(task: str, client: OpenAI) -> dict:
358
  print(f'[START] task={task} env=traffic_control model={MODEL_NAME}', flush=True)
359
 
360
- rewards: List[float] = []
361
- history: Deque[str] = deque(maxlen=6)
362
- step = 0
363
- last_error: Optional[str] = None
364
- done = False
365
- state: Optional[TrafficState] = None
 
 
 
 
366
 
367
  try:
368
  with TrafficControlEnv(base_url=SERVER_URL).sync() as env:
@@ -373,15 +539,27 @@ def run_task(task: str, client: OpenAI) -> dict:
373
  while not done:
374
  step += 1
375
 
376
- # Refresh cumulative state every 10 steps for score projection
377
- if step % 10 == 1:
378
  try:
379
  state = env.state()
380
  except Exception:
381
  pass
382
 
383
- action = get_llm_action(client, obs, step, task, history, state)
384
- action_str = f"light_phase={action.light_phase}"
 
 
 
 
 
 
 
 
 
 
 
 
385
 
386
  try:
387
  result = env.step(action)
@@ -391,13 +569,18 @@ def run_task(task: str, client: OpenAI) -> dict:
391
  done = result.done
392
  last_error = None
393
 
394
- phase_name = {0:"NS",1:"EW",2:"AR",3:"NSy",4:"EWy"}
 
 
 
 
 
395
  history.append(
396
- f" s{step}: →{action.light_phase}"
397
  f" clr={obs.vehicles_passed}r+{obs.emergency_passed}em"
398
  f" r={reward_val:+.1f}"
399
- f" now={phase_name.get(obs.current_phase,'?')}"
400
- f" queues={list(obs.queue_lengths)}"
401
  )
402
  except Exception as exc:
403
  reward_val = 0.0
@@ -426,7 +609,8 @@ def run_task(task: str, client: OpenAI) -> dict:
426
 
427
  print(
428
  f'[END] success={str(success).lower()} steps={step} '
429
- f'score={score:.3f} rewards={rewards_str}',
 
430
  flush=True,
431
  )
432
 
 
33
  MODEL_NAME = os.getenv("MODEL_NAME") or "Qwen/Qwen2.5-72B-Instruct"
34
  SERVER_URL = os.getenv("SERVER_URL", "http://localhost:7860")
35
  SEED = 42
36
+ MAX_TOKENS = 200 # shorter = faster response
37
+ TEMPERATURE = 0.0
38
+ LLM_TIMEOUT_S = 12 # per-call timeout (seconds)
39
+ LLM_CALL_EVERY = 5 # only call LLM every N steps (heuristic fills the rest)
40
+ TASK_BUDGET_S = { # hard wall-clock budget per task (seconds)
41
+ "basic_flow": 480,
42
+ "emergency_priority": 720,
43
+ "dynamic_scenarios": 960,
44
+ }
45
 
46
  # Task max_steps for score projection
47
  TASK_MAX_STEPS = {"basic_flow": 200, "emergency_priority": 300, "dynamic_scenarios": 400}
48
 
49
+ # Task-specific minimum green hold (steps before switching is even considered).
50
+ # basic_flow: stability bonus requires low switch rate — hold longer.
51
+ # emergency tasks: react fast to emergencies — hold shorter.
52
+ MIN_HOLD_BY_TASK = {
53
+ "basic_flow": 6,
54
+ "emergency_priority": 3,
55
+ "dynamic_scenarios": 3,
56
+ }
57
+ DEFAULT_MIN_HOLD = 4
58
+
59
+ # Pressure ratio required to justify a switch (avoid switching-penalty)
60
+ # Higher for basic_flow (graded on stability), lower for emergency tasks
61
+ SWITCH_RATIO_BY_TASK = {
62
+ "basic_flow": 1.5,
63
+ "emergency_priority": 1.2,
64
+ "dynamic_scenarios": 1.2,
65
+ }
66
 
67
  # ---------------------------------------------------------------------------
68
  # Heuristic core — uses actual environment reward formula
 
93
  return ns_p, ew_p
94
 
95
 
96
+ def _dynamic_hold_time(obs: TrafficObservation, task: str) -> int:
97
  """
98
+ Adaptive minimum hold: longer when current direction has more traffic,
99
+ scaled by task type (basic_flow needs more stability).
100
  """
101
+ base = MIN_HOLD_BY_TASK.get(task, DEFAULT_MIN_HOLD)
102
+ cur = obs.current_phase
103
+ if cur in (0, 3): # NS_GREEN / NS_YELLOW
104
  q = obs.queue_lengths[0] + obs.queue_lengths[1]
105
+ elif cur in (1, 4): # EW_GREEN / EW_YELLOW
106
  q = obs.queue_lengths[2] + obs.queue_lengths[3]
107
  else:
108
+ return base
109
+ # Hold longer if queue is deep (drain rate ~3 veh/step), cap at 12
110
+ return max(base, min(q // 3, 12))
111
+
112
+
113
+ def _collision_risk(obs: TrafficObservation) -> bool:
114
+ """
115
+ Detect gridlock risk early (environment triggers -200 at total_queued>40 AND time>20).
116
+ We act at 70% of threshold so we can clear before the penalty triggers.
117
+ """
118
+ total_q = sum(obs.queue_lengths)
119
+ return total_q > 28 and obs.time_in_phase > 14
120
 
121
 
122
+ def _heuristic_phase(obs: TrafficObservation, task: str) -> Tuple[int, str]:
123
  """
124
  Mathematically optimal phase recommendation.
125
+ Returns (phase, reason) so caller can log it.
126
+
127
  Priority order:
128
+ 1. Collision risk proactively rotate to drain largest queue
129
+ 2. Critical emergency (urgency ≥ 8) — clear NOW
130
+ 3. Pre-emptive emergency (urgency 6-7) clear before escalation
131
+ 4. Moderate emergency (urgency 5)
132
+ 5. Hysteresisdon't switch if hold time not reached
133
+ 6. Queue pressure — switch to higher pressure direction
134
+ 7. Default — hold current
135
  """
136
  ns_em = obs.emergency_queue[0] + obs.emergency_queue[1]
137
  ew_em = obs.emergency_queue[2] + obs.emergency_queue[3]
138
  ns_urg = max(obs.emergency_urgency[0], obs.emergency_urgency[1])
139
  ew_urg = max(obs.emergency_urgency[2], obs.emergency_urgency[3])
140
  cur = obs.current_phase
141
+ ns_q = obs.queue_lengths[0] + obs.queue_lengths[1]
142
+ ew_q = obs.queue_lengths[2] + obs.queue_lengths[3]
143
+
144
+ # 1. Collision risk — switch to whichever direction has more vehicles
145
+ if _collision_risk(obs):
146
+ if cur in (0, 3):
147
+ if ew_q > ns_q:
148
+ return 1, "collision-risk-rotate-EW"
149
+ return 0, "collision-risk-hold-NS"
150
+ else:
151
+ if ns_q > ew_q:
152
+ return 0, "collision-risk-rotate-NS"
153
+ return 1, "collision-risk-hold-EW"
154
 
155
+ # 2. Critical emergency (urgency ≥ 8)
156
  if ns_em > 0 and ns_urg >= 8 and ew_em > 0 and ew_urg >= 8:
157
+ return 2, "ALL_RED-dual-critical"
158
  if ns_em > 0 and ns_urg >= 8:
159
+ return 0, f"critical-NS-urgency={ns_urg}"
160
  if ew_em > 0 and ew_urg >= 8:
161
+ return 1, f"critical-EW-urgency={ew_urg}"
162
 
163
+ # 3. Pre-emptive: urgency 6-7 clear NOW, penalty is already 6^1.5×0.5=11.6/step
164
+ # Skip if current direction is already serving it
165
+ if ns_em > 0 and ns_urg >= 6:
166
+ if cur in (0, 3):
167
+ return 0, f"preemptive-NS-hold(urg={ns_urg})"
168
+ if ew_em == 0 or ns_urg >= ew_urg:
169
+ return 0, f"preemptive-NS-switch(urg={ns_urg})"
170
+ if ew_em > 0 and ew_urg >= 6:
171
+ if cur in (1, 4):
172
+ return 1, f"preemptive-EW-hold(urg={ew_urg})"
173
+ if ns_em == 0 or ew_urg >= ns_urg:
174
+ return 1, f"preemptive-EW-switch(urg={ew_urg})"
175
+
176
+ # 4. Moderate emergency (urgency 5)
177
  if ns_em > 0 and ns_urg >= 5:
178
  if ew_em == 0 or ns_urg >= ew_urg:
179
+ return 0, f"moderate-NS(urg={ns_urg})"
180
  if ew_em > 0 and ew_urg >= 5:
181
+ return 1, f"moderate-EW(urg={ew_urg})"
182
 
183
+ # 5. Hysteresis
184
+ hold = _dynamic_hold_time(obs, task)
185
+ ratio = SWITCH_RATIO_BY_TASK.get(task, 1.3)
186
  if obs.time_in_phase < hold:
187
+ if cur in (0, 3): return 0, f"hysteresis-NS(held={obs.time_in_phase}<{hold})"
188
+ if cur in (1, 4): return 1, f"hysteresis-EW(held={obs.time_in_phase}<{hold})"
189
 
190
+ # 6. Queue pressure
191
  ns_p, ew_p = _compute_pressures(obs)
192
+ if ns_p > ew_p * ratio:
193
+ return 0, f"pressure-NS({ns_p:.1f}>{ew_p:.1f}×{ratio})"
194
+ if ew_p > ns_p * ratio:
195
+ return 1, f"pressure-EW({ew_p:.1f}>{ns_p:.1f}×{ratio})"
196
+
197
+ # 7. Hold current
198
+ if cur in (0, 3): return 0, "hold-NS"
199
+ if cur in (1, 4): return 1, "hold-EW"
200
+ return 0, "default-NS"
201
 
202
+
203
+ def _should_skip_llm(obs: TrafficObservation, heuristic_phase: int, reason: str, step: int) -> bool:
204
+ """
205
+ Skip the LLM call when the decision is mathematically obvious OR outside the LLM cadence.
206
+ LLM is only called every LLM_CALL_EVERY steps AND only for genuinely ambiguous pressure cases.
207
+ """
208
+ # Rate-limit: only consider LLM every N steps
209
+ if step % LLM_CALL_EVERY != 0:
210
+ return True
211
+ # Always skip for time-critical or clear-cut decisions
212
+ if "collision-risk" in reason:
213
+ return True
214
+ if "critical" in reason or "preemptive" in reason:
215
+ return True
216
+ if "hysteresis" in reason:
217
+ return True
218
+ if "hold" in reason:
219
+ return True
220
+ # Skip when pressure ratio is clear (> 2×) — heuristic is strictly better here
221
+ ns_p, ew_p = _compute_pressures(obs)
222
+ max_p = max(ns_p, ew_p, 0.01)
223
+ min_p = min(ns_p, ew_p, 0.01)
224
+ if max_p / min_p > 2.0:
225
+ return True
226
+ return False
227
 
228
 
229
  # ---------------------------------------------------------------------------
230
+ # Live grade projection
231
  # ---------------------------------------------------------------------------
232
 
233
  def _project_score(task: str, state: Optional[TrafficState], step: int) -> str:
 
234
  if state is None or step == 0:
235
  return "(no data yet)"
236
 
237
  s = state
238
  steps = max(s.step_count, 1)
 
239
 
240
  throughput_per_step = s.total_vehicles_passed / steps
241
  em_rate = s.total_emergency_passed / steps
 
247
  sw = s.total_phase_changes / steps
248
  stab = max(0.0, 0.05 * (1.0 - min(sw * 4, 1.0)))
249
  proj = tput * 0.6 + eff * 0.4 + stab
250
+ gap = max(0.0, 1.8 - throughput_per_step)
251
  return (
252
+ f"projected={proj:.3f} | "
253
+ f"throughput={tput:.2f}(×0.6, {throughput_per_step:.2f}veh/step, need +{gap:.2f}) "
254
+ f"eff={eff:.2f}(×0.4) stab={stab:.3f}(switch={sw:.2f}/step, want<0.25)"
255
  )
256
 
257
  if task == "emergency_priority":
 
259
  em_score = min(em_rate / (1.0 / 20.0), 1.0)
260
  if s.total_emergency_passed > 0:
261
  delay = max(0.0, 1.0 - (s.total_emergency_delay / s.total_emergency_passed) / 12.0)
262
+ avg_d = s.total_emergency_delay / s.total_emergency_passed
263
  else:
264
  delay = 0.5
265
+ avg_d = float("inf")
266
  eff = 1.0 / (1.0 + avg_wait * 0.05)
267
  proj = tput * 0.30 + em_score * 0.35 + delay * 0.20 + eff * 0.15
268
  return (
269
+ f"projected={proj:.3f} | "
270
+ f"em_rate={em_score:.2f}(×0.35, need 1em/20steps) "
271
+ f"delay={delay:.2f}(×0.20, avg={avg_d:.1f}steps, want<3) "
272
+ f"tput={tput:.2f}(×0.30) eff={eff:.2f}(×0.15)"
273
  )
274
 
275
  if task == "dynamic_scenarios":
 
277
  em_score = min(em_rate / (1.0 / 15.0), 1.0)
278
  if s.total_emergency_passed > 0:
279
  delay = max(0.0, 1.0 - (s.total_emergency_delay / s.total_emergency_passed) / 5.0)
280
+ avg_d = s.total_emergency_delay / s.total_emergency_passed
281
  else:
282
  delay = 0.0
283
+ avg_d = float("inf")
284
  eff = 1.0 / (1.0 + avg_wait * 0.08)
285
  adapt = 1.0 / (1.0 + (s.total_phase_changes / steps) * 0.5)
286
  proj = tput * 0.25 + em_score * 0.30 + delay * 0.20 + eff * 0.15 + adapt * 0.10
287
  return (
288
+ f"projected={proj:.3f} | "
289
+ f"em_rate={em_score:.2f}(×0.30) delay={delay:.2f}(×0.20,avg={avg_d:.1f}) "
290
+ f"tput={tput:.2f}(×0.25) eff={eff:.2f}(×0.15) adapt={adapt:.2f}(×0.10)"
291
  )
292
 
293
  return "(unknown task)"
294
 
295
 
296
  # ---------------------------------------------------------------------------
297
+ # System prompts (task-specific)
298
  # ---------------------------------------------------------------------------
299
 
300
+ _SYSTEM_BASE = """You are an expert Autonomous Traffic Signal Controller for a 4-way intersection.
301
 
302
  PHASES: 0=NS_GREEN 1=EW_GREEN 2=ALL_RED
303
+ FLOW RATES: NS_GREEN clears ~3 NS vehicles/step, EW_GREEN clears ~3 EW vehicles/step, ALL_RED clears 0.
304
 
305
+ REWARD PER STEP:
306
  +0.30 × regular vehicles cleared
307
  +12.0 × emergency vehicles cleared
308
+ -(urgency^1.5)×0.5 per WAITING emergency vehicle (compounds EVERY step it waits!)
309
+ urgency=5 → 5.59/step, urgency=7 → 9.26/step, urgency=8 → 11.31/step
310
  -0.08 × total vehicles waiting
311
+ -0.5 to -2.0 for unnecessary phase switch (proportional to empty-queue ratio)
312
  +0.05 stability bonus when traffic flows without switching
313
+ -200 for gridlock collision (episode ends immediately!)
314
+
315
+ SWITCHING COST vs BENEFIT:
316
+ Never switch to an empty direction (full -2.0 penalty, zero gain).
317
+ Each unnecessary switch also hurts stability/adaptability scores.
318
+ A switch is justified ONLY when:
319
+ (a) emergency vehicle in new direction, OR
320
+ (b) new direction pressure > current direction pressure × task_ratio
321
+
322
+ TASK-SPECIFIC GRADING:"""
323
+
324
+ _SYSTEM_TASK_HINTS = {
325
+ "basic_flow": """
326
+ basic_flow weights: throughput×0.60 efficiency×0.40 stability_bonus
327
+ TARGET: 1.8 vehicles/step throughput. Switch rate < 0.25/step for stability bonus.
328
+ STRATEGY: Hold green phases 5-8 steps. Only switch when NS/EW queue imbalance > 50%.
329
+ DO NOT switch to a direction with 0 vehicles — full penalty, zero reward.""",
330
+
331
+ "emergency_priority": """
332
+ emergency_priority weights: em_rate×0.35 throughput×0.30 delay×0.20 efficiency×0.15
333
+ TARGET: Clear 1 emergency per 20 steps. Keep avg emergency delay < 3 steps.
334
+ STRATEGY: Pre-clear any urgency≥6 direction IMMEDIATELY — at urgency=6, cost is 11.7/step.
335
+ Emergency waiting one extra step costs more than 30 regular vehicles cleared.""",
336
+
337
+ "dynamic_scenarios": """
338
+ dynamic_scenarios weights: em_rate×0.30 throughput×0.25 delay×0.20 efficiency×0.15 adaptability×0.10
339
+ TARGET: 2.0 vehicles/step throughput + clear all emergencies fast. Zero collisions.
340
+ STRATEGY: Balance throughput and emergency response. Watch for surge traffic (queue growth > +3/step).
341
+ Adaptability penalises OVER-switching — switch only when needed, not on impulse.""",
342
+ }
343
 
344
+ _SYSTEM_SUFFIX = """
 
 
 
345
 
346
+ DECISION RULES (strictly in order):
347
+ 1. Total queued > 28 AND held > 14 steps rotate to larger queue (collision prevention!)
348
+ 2. Any urgency ≥ 8 emergency → switch to that direction IMMEDIATELY
349
+ 3. Any urgency6 emergency in other direction switch to clear before escalation
350
+ 4. Hold current phase until dynamic hold time (varies by queue depth)
351
+ 5. Switch only when other direction pressure > current × task_ratio
352
+ 6. ALL_RED ONLY when BOTH directions have critical emergencies simultaneously
353
 
354
+ Think step by step about (a) emergencies, (b) collision risk, (c) throughput/score impact.
355
+ Output ONLY valid JSON on the last line: {"light_phase": 0}"""
356
 
357
 
358
+ def _get_system_prompt(task: str) -> str:
359
+ hint = _SYSTEM_TASK_HINTS.get(task, "")
360
+ return _SYSTEM_BASE + hint + _SYSTEM_SUFFIX
361
+
362
+
363
+ # ---------------------------------------------------------------------------
364
+ # LLM prompt builder
365
+ # ---------------------------------------------------------------------------
366
+
367
  def _build_prompt(
368
  obs: TrafficObservation,
369
  step: int,
370
  task: str,
371
  history: Deque[str],
372
  heuristic: int,
373
+ heuristic_reason: str,
374
  score_projection: str,
375
  ) -> str:
376
  ns_p, ew_p = _compute_pressures(obs)
377
+ ns_q = obs.queue_lengths[0] + obs.queue_lengths[1]
378
+ ew_q = obs.queue_lengths[2] + obs.queue_lengths[3]
379
+ ns_em = obs.emergency_queue[0] + obs.emergency_queue[1]
380
+ ew_em = obs.emergency_queue[2] + obs.emergency_queue[3]
381
  ns_urg = max(obs.emergency_urgency[0], obs.emergency_urgency[1])
382
  ew_urg = max(obs.emergency_urgency[2], obs.emergency_urgency[3])
383
+ total_q = sum(obs.queue_lengths)
384
 
385
+ phase_name = {0: "NS_GREEN", 1: "EW_GREEN", 2: "ALL_RED", 3: "NS_YELLOW", 4: "EW_YELLOW"}
386
+ hint_name = {0: "NS_GREEN (0)", 1: "EW_GREEN (1)", 2: "ALL_RED (2)"}
387
  trend_str = f"[{obs.queue_trend[0]:+d},{obs.queue_trend[1]:+d},{obs.queue_trend[2]:+d},{obs.queue_trend[3]:+d}]"
388
 
389
+ # Emergency penalty cost — helps LLM quantify urgency
390
+ ns_em_cost = f"{ns_em * (max(ns_urg,1)**1.5)*0.5:.1f}/step" if ns_em > 0 else "none"
391
+ ew_em_cost = f"{ew_em * (max(ew_urg,1)**1.5)*0.5:.1f}/step" if ew_em > 0 else "none"
392
+
393
+ collision_warn = ""
394
+ if _collision_risk(obs):
395
+ collision_warn = f"\n ⚠ COLLISION RISK: {total_q} vehicles queued, held {obs.time_in_phase} steps!"
396
+
397
  history_str = "\n".join(history) if history else " (episode start)"
398
 
399
  return (
400
+ f"TASK: {task} | Step {step}\n"
401
+ f"Phase: {phase_name.get(obs.current_phase, '?')} held {obs.time_in_phase} steps{collision_warn}\n"
402
  f"\n"
403
+ f"CURRENT STATE:\n"
404
+ f" NS: {ns_q} regular + {ns_em} emergency(urgency={ns_urg}, cost={ns_em_cost}) pressure={ns_p:.1f}\n"
405
+ f" EW: {ew_q} regular + {ew_em} emergency(urgency={ew_urg}, cost={ew_em_cost}) pressure={ew_p:.1f}\n"
406
+ f" Total queued: {total_q} Trend [N,S,E,W]: {trend_str}\n"
407
+ f" Avg wait: {obs.avg_wait_time:.1f} steps | Collision flag: {obs.collision}\n"
408
  f"\n"
409
+ f"LIVE SCORE:\n {score_projection}\n"
410
  f"\n"
411
+ f"RECENT STEPS:\n{history_str}\n"
412
  f"\n"
413
+ f"Heuristic says: {hint_name.get(heuristic, str(heuristic))} ({heuristic_reason})\n"
414
+ f"Reason through, then output JSON on the last line."
415
  )
416
 
417
 
418
  # ---------------------------------------------------------------------------
419
+ # Parse LLM output
420
  # ---------------------------------------------------------------------------
421
 
 
 
 
 
422
  def _parse_phase(raw: str) -> Optional[int]:
423
  """Extract phase from LLM chain-of-thought output (JSON on last line)."""
424
  import re
 
425
  lines = [l.strip() for l in raw.split("\n") if l.strip()]
426
  for line in reversed(lines):
427
  try:
 
431
  return p
432
  except Exception:
433
  pass
 
434
  m = re.search(r'"light_phase"\s*:\s*([012])', raw)
435
  if m:
436
  return int(m.group(1))
 
440
  return None
441
 
442
 
443
+ def _sanitize(s: str) -> str:
444
+ return s.replace('"', "'").replace("\n", " ")
445
+
446
+
447
+ # ---------------------------------------------------------------------------
448
+ # Action selection
449
+ # ---------------------------------------------------------------------------
450
+
451
+ def get_action(
452
  client: OpenAI,
453
  obs: TrafficObservation,
454
  step: int,
455
  task: str,
456
  history: Deque[str],
457
  state: Optional[TrafficState],
458
+ force_heuristic: bool,
459
+ ) -> Tuple[TrafficAction, str]:
460
+ """
461
+ Returns (action, source) where source is "heuristic", "llm", or "fallback".
462
+ Uses LLM only for ambiguous cases at the LLM cadence; pure heuristic otherwise.
463
+ force_heuristic=True when task time budget is nearly exhausted.
464
+ """
465
+ heuristic, reason = _heuristic_phase(obs, task)
466
 
467
+ # Fast path — skip LLM (obvious decision, wrong cadence, or budget exhausted)
468
+ if force_heuristic or _should_skip_llm(obs, heuristic, reason, step):
469
+ return TrafficAction(light_phase=heuristic), f"heuristic({reason})"
 
 
 
 
 
 
 
 
470
 
471
+ # Ambiguous case call LLM with a hard per-call timeout
472
+ score_proj = _project_score(task, state, step)
473
+ try:
474
+ resp = client.chat.completions.create(
475
+ model=MODEL_NAME,
476
+ messages=[
477
+ {"role": "system", "content": _get_system_prompt(task)},
478
+ {"role": "user", "content": _build_prompt(
479
+ obs, step, task, history, heuristic, reason, score_proj
480
+ )},
481
+ ],
482
+ temperature=TEMPERATURE,
483
+ max_tokens=MAX_TOKENS,
484
+ timeout=LLM_TIMEOUT_S,
485
+ )
486
+ raw = resp.choices[0].message.content.strip()
487
+ phase = _parse_phase(raw)
488
+ if phase is not None:
489
+ return TrafficAction(light_phase=phase), "llm"
490
+ except Exception:
491
+ pass
492
 
493
+ # Fallback to heuristic if LLM fails or times out
494
+ return TrafficAction(light_phase=heuristic), f"fallback({reason})"
495
 
496
 
497
  # ---------------------------------------------------------------------------
 
519
  def run_task(task: str, client: OpenAI) -> dict:
520
  print(f'[START] task={task} env=traffic_control model={MODEL_NAME}', flush=True)
521
 
522
+ rewards: List[float] = []
523
+ history: Deque[str] = deque(maxlen=8)
524
+ step = 0
525
+ last_error: Optional[str] = None
526
+ done = False
527
+ state: Optional[TrafficState] = None
528
+ llm_calls = 0
529
+ heur_calls = 0
530
+ task_start_time = time.time()
531
+ budget_s = TASK_BUDGET_S.get(task, 600)
532
 
533
  try:
534
  with TrafficControlEnv(base_url=SERVER_URL).sync() as env:
 
539
  while not done:
540
  step += 1
541
 
542
+ # Refresh cumulative state every 5 steps for score projection
543
+ if step % 5 == 1:
544
  try:
545
  state = env.state()
546
  except Exception:
547
  pass
548
 
549
+ # Switch to pure heuristic if we're within 60s of the task budget
550
+ elapsed = time.time() - task_start_time
551
+ force_heuristic = elapsed > budget_s - 60
552
+
553
+ action, source = get_action(
554
+ client, obs, step, task, history, state,
555
+ force_heuristic,
556
+ )
557
+ action_str = f"light_phase={action.light_phase}"
558
+
559
+ if source.startswith("llm"):
560
+ llm_calls += 1
561
+ else:
562
+ heur_calls += 1
563
 
564
  try:
565
  result = env.step(action)
 
569
  done = result.done
570
  last_error = None
571
 
572
+ phase_name = {0: "NS", 1: "EW", 2: "AR", 3: "NSy", 4: "EWy"}
573
+ ns_urg = max(obs.emergency_urgency[0], obs.emergency_urgency[1])
574
+ ew_urg = max(obs.emergency_urgency[2], obs.emergency_urgency[3])
575
+ em_info = ""
576
+ if any(q > 0 for q in obs.emergency_queue):
577
+ em_info = f" EM[{obs.emergency_queue[0]+obs.emergency_queue[1]}u{ns_urg}|{obs.emergency_queue[2]+obs.emergency_queue[3]}u{ew_urg}]"
578
  history.append(
579
+ f" s{step}: {source[:4]}→{action.light_phase}"
580
  f" clr={obs.vehicles_passed}r+{obs.emergency_passed}em"
581
  f" r={reward_val:+.1f}"
582
+ f" ph={phase_name.get(obs.current_phase, '?')}"
583
+ f" q={list(obs.queue_lengths)}{em_info}"
584
  )
585
  except Exception as exc:
586
  reward_val = 0.0
 
609
 
610
  print(
611
  f'[END] success={str(success).lower()} steps={step} '
612
+ f'score={score:.3f} rewards={rewards_str} '
613
+ f'llm_calls={llm_calls} heuristic_calls={heur_calls}',
614
  flush=True,
615
  )
616