Spaces:
Sleeping

arrow072 commited on
Commit
c8f6f13
·
verified ·
1 Parent(s): 8a41606

Upload inference.py

Browse files
Files changed (1) hide show
  1. inference.py +272 -0
inference.py ADDED
@@ -0,0 +1,272 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ inference.py — Traffic Signal Optimization · OpenEnv Hackathon Submission
3
+ ============================================================================
4
+
5
+ Env variables expected by the evaluator
6
+ ----------------------------------------
7
+ API_BASE_URL Base URL of the LLM endpoint (e.g. https://router.huggingface.co/v1)
8
+ MODEL_NAME Model identifier (e.g. meta-llama/Llama-3.2-3B-Instruct)
9
+ HF_TOKEN HuggingFace / API key
10
+
11
+ stdout log format (parsed by the OpenEnv validator)
12
+ -----------------------------------------------------
13
+ [START]
14
+ [STEP] step=0, score=0.512300, reward=0.024600, done=False
15
+ ...
16
+ [END]
17
+
18
+ HTTP endpoints (OpenEnv spec: reset / step / state)
19
+ ----------------------------------------------------
20
+ GET / — UI
21
+ GET /health — liveness probe
22
+ GET /state — current env state (required by OpenEnv spec)
23
+ GET /tasks — enumerate tasks (required by validator)
24
+ POST /reset — start new episode
25
+ POST /step — advance one step
26
+ POST /auto_step — agent picks + steps
27
+ POST /grader — run baseline on all tasks, return scores
28
+ """
29
+
30
+ import os
31
+ import sys
32
+
33
+ from fastapi import FastAPI
34
+ from fastapi.responses import HTMLResponse
35
+ from pydantic import BaseModel
36
+ from env import TrafficEnv
37
+ from tasks import get_config
38
+ from baseline_agent import RuleBasedAgent
39
+ import openai
40
+
41
+
42
+ # ---------------------------------------------------------------------------
43
+ # LLM Agent
44
+ # ---------------------------------------------------------------------------
45
+
46
+ class LLMAgent:
47
+ """
48
+ OpenAI-compatible LLM agent with a rule-based fallback.
49
+ Reads API_BASE_URL / MODEL_NAME / HF_TOKEN from the environment.
50
+ """
51
+
52
+ def __init__(self) -> None:
53
+ api_base = os.environ.get("API_BASE_URL", "").strip()
54
+ api_key = os.environ.get("HF_TOKEN", "not-needed")
55
+ self.model = os.environ.get("MODEL_NAME", "gpt-3.5-turbo")
56
+
57
+ self.client = None
58
+ if api_base:
59
+ try:
60
+ self.client = openai.OpenAI(base_url=api_base, api_key=api_key)
61
+ except Exception:
62
+ self.client = None
63
+
64
+ self.fallback = RuleBasedAgent()
65
+
66
+ def select_action(self, state: dict) -> int:
67
+ if self.client is not None:
68
+ prompt = (
69
+ f"Traffic intersection state:\n{state}\n\n"
70
+ "You control the traffic signal. Reply with ONLY 0 or 1.\n"
71
+ "0 = keep current green phase\n"
72
+ "1 = switch to the other phase"
73
+ )
74
+ try:
75
+ resp = self.client.chat.completions.create(
76
+ model=self.model,
77
+ messages=[
78
+ {"role": "system", "content": "You are a traffic signal controller. Output only 0 or 1."},
79
+ {"role": "user", "content": prompt},
80
+ ],
81
+ max_tokens=5,
82
+ temperature=0.0,
83
+ )
84
+ content = resp.choices[0].message.content.strip()
85
+ self.fallback.select_action(state) # keep step counter in sync
86
+ return 1 if "1" in content else 0
87
+ except Exception:
88
+ pass
89
+ return self.fallback.select_action(state)
90
+
91
+ def reset(self) -> None:
92
+ self.fallback.reset()
93
+
94
+
95
+ # ---------------------------------------------------------------------------
96
+ # Shared server-level env / agent (used by HTTP endpoints)
97
+ # ---------------------------------------------------------------------------
98
+
99
+ _env = TrafficEnv(get_config("medium"))
100
+ _agent = LLMAgent()
101
+
102
+
103
+ # ---------------------------------------------------------------------------
104
+ # FastAPI application
105
+ # ---------------------------------------------------------------------------
106
+
107
+ app = FastAPI(
108
+ title="Traffic Signal Optimization — OpenEnv",
109
+ description="4-way intersection RL environment · Meta × PyTorch OpenEnv Hackathon",
110
+ version="1.0.0",
111
+ )
112
+
113
+
114
+ # ── Meta / liveness ─────────────────────────────────────────────────────────
115
+
116
+ @app.get("/", response_class=HTMLResponse)
117
+ def root() -> str:
118
+ with open("index.html", "r", encoding="utf-8") as fh:
119
+ return fh.read()
120
+
121
+
122
+ @app.get("/health")
123
+ def health() -> dict:
124
+ """Liveness probe — must return 200."""
125
+ return {"status": "ok"}
126
+
127
+
128
+ @app.get("/tasks")
129
+ def list_tasks() -> dict:
130
+ """Enumerate the 3 difficulty tasks for the validator."""
131
+ return {
132
+ "tasks": [
133
+ {
134
+ "id": "easy",
135
+ "description": "Stable low-volume traffic, rare emergencies (1%)",
136
+ "max_steps": 50,
137
+ "arrival_rate": [0, 1],
138
+ "emergency_prob": 0.01,
139
+ },
140
+ {
141
+ "id": "medium",
142
+ "description": "Moderate traffic with 10% burst events, 5% emergency",
143
+ "max_steps": 100,
144
+ "arrival_rate": [1, 3],
145
+ "emergency_prob": 0.05,
146
+ },
147
+ {
148
+ "id": "hard",
149
+ "description": "High-intensity traffic, 20% bursts, 15% emergency, strict fairness",
150
+ "max_steps": 200,
151
+ "arrival_rate": [2, 5],
152
+ "emergency_prob": 0.15,
153
+ },
154
+ ]
155
+ }
156
+
157
+
158
+ # ── Core OpenEnv API ─────────────────────────────────────────────────────────
159
+
160
+ @app.post("/reset")
161
+ def reset_env() -> dict:
162
+ state = _env.reset()
163
+ _agent.reset()
164
+ return {"state": state}
165
+
166
+
167
+ class Action(BaseModel):
168
+ action: int
169
+
170
+
171
+ @app.post("/step")
172
+ def step_env(data: Action) -> dict:
173
+ state, reward, done, info = _env.step(data.action)
174
+ score = round(max(1e-6, min(1.0 - 1e-6, (reward + 1.0) / 2.0)), 6)
175
+ return {"state": state, "reward": reward, "score": score, "done": done, "info": info}
176
+
177
+
178
+ @app.get("/state")
179
+ def get_state() -> dict:
180
+ """
181
+ Return current environment state.
182
+ Required by OpenEnv spec (the reset / step / state triple).
183
+ """
184
+ return {"state": _env.get_state()}
185
+
186
+
187
+ # ── Convenience endpoints ────────────────────────────────────────────────────
188
+
189
+ @app.post("/auto_step")
190
+ def auto_step() -> dict:
191
+ state_dict = _env.get_state()
192
+ action = _agent.select_action(state_dict)
193
+ state, reward, done, info = _env.step(action)
194
+ score = round(max(1e-6, min(1.0 - 1e-6, (reward + 1.0) / 2.0)), 6)
195
+ return {"state": state, "reward": reward, "score": score,
196
+ "done": done, "info": info, "action_taken": action}
197
+
198
+
199
+ @app.post("/grader")
200
+ def grader() -> dict:
201
+ """
202
+ Run the rule-based baseline on all 3 tasks and return per-task scores
203
+ normalised to open interval (0, 1) as required by the validator.
204
+ Returns flat structure: {"easy": score, "medium": score, "hard": score}
205
+ """
206
+ results: dict = {}
207
+ for task_id in ("easy", "medium", "hard"):
208
+ cfg = get_config(task_id)
209
+ eval_env = TrafficEnv(cfg)
210
+ agent = RuleBasedAgent()
211
+ state = eval_env.reset()
212
+ agent.reset()
213
+
214
+ total_reward = 0.0
215
+ steps = 0
216
+ done = False
217
+
218
+ while not done:
219
+ action = agent.select_action(state)
220
+ state, reward, done, info = eval_env.step(action)
221
+ total_reward += reward
222
+ steps += 1
223
+
224
+ mean_reward = total_reward / max(1, steps)
225
+ # Strictly open interval (0, 1) — never exactly 0.0 or 1.0
226
+ score = round(max(1e-6, min(1.0 - 1e-6, (mean_reward + 1.0) / 2.0)), 6)
227
+ results[task_id] = score
228
+ return results
229
+
230
+
231
+ # ---------------------------------------------------------------------------
232
+ # CLI entry-point — produces structured stdout for the OpenEnv validator
233
+ # ---------------------------------------------------------------------------
234
+
235
+ if __name__ == "__main__":
236
+ tasks_to_run = ["easy", "medium", "hard"]
237
+
238
+ if len(sys.argv) > 1:
239
+ raw = sys.argv[1].replace("--task=", "").replace("--task", "").strip()
240
+ if raw in tasks_to_run:
241
+ tasks_to_run = [raw]
242
+
243
+ for task_name in tasks_to_run:
244
+ config = get_config(task_name)
245
+ eval_env = TrafficEnv(config)
246
+ eval_agent = LLMAgent()
247
+
248
+ state = eval_env.reset()
249
+ eval_agent.reset()
250
+
251
+ print("[START]", flush=True)
252
+
253
+ done = False
254
+ step_idx = 0
255
+ total_reward = 0.0
256
+
257
+ while not done:
258
+ action = eval_agent.select_action(state)
259
+ state, reward, done, info = eval_env.step(action)
260
+ total_reward += reward
261
+
262
+ # score: reward normalised to open interval (0, 1)
263
+ score = round(max(1e-6, min(1.0 - 1e-6, (reward + 1.0) / 2.0)), 6)
264
+
265
+ print(
266
+ f"[STEP] step={step_idx}, score={score}, "
267
+ f"reward={round(reward, 6)}, done={done}",
268
+ flush=True,
269
+ )
270
+ step_idx += 1
271
+
272
+ print("[END]", flush=True)