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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
#!/usr/bin/env python3
# Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.

"""
GPUScheduler-Env Inference Script
==================================
Runs an LLM-driven scheduling agent against all three environment tasks
and emits structured stdout logs required by the hackathon evaluator.

MANDATORY ENVIRONMENT VARIABLES
--------------------------------
  HF_TOKEN      β€” HuggingFace / API key for LLM access
  IMAGE_NAME    β€” Docker image tag for the GpuScheduler environment server
  API_BASE_URL  β€” LLM API endpoint  (default: HuggingFace inference router)
  MODEL_NAME    β€” Model identifier  (default: Qwen/Qwen2.5-72B-Instruct)

STDOUT FORMAT (one block per task)
------------------------------------
  [START] task=<name> env=gpu_scheduler model=<model>
  [STEP]  step=<n> action=<str> reward=<0.00> done=<true|false> error=<msg|null>
  [END]   success=<true|false> steps=<n> score=<0.000> rewards=<r1,r2,...>

TASK SCHEDULE
--------------
  smooth_sailing   β€” 24 simulated hours, 24 agent steps  (1 h/step)
  deadline_crunch  β€” 72 simulated hours, 36 agent steps  (2 h/step)
  p0_emergency     β€” 168 simulated hours, 42 agent steps (4 h/step)

The step granularity is intentional: the environment advances the
simulation clock by N hours per step() call, which keeps LLM API
calls within the 20-minute runtime budget while preserving rich
multi-step trajectories.

RUN
----
  IMAGE_NAME=gpu_scheduler-env:latest \\
  HF_TOKEN=hf_...                     \\
  python inference.py
"""

import asyncio
import os
import re
import textwrap
from typing import Dict, List, Optional, Tuple

from openai import OpenAI

# Import typed client + models from the gpu_scheduler package
from gpu_scheduler import (
    GpuSchedulerAction,
    GpuSchedulerEnv,
    GpuSchedulerObservation,
)

# ---------------------------------------------------------------------------
# Environment variables β€” all sensitive config read from shell, never hardcoded
# ---------------------------------------------------------------------------
IMAGE_NAME   = os.getenv("IMAGE_NAME")          # Docker image for the env server
API_KEY      = os.getenv("HF_TOKEN") or os.getenv("API_KEY")
API_BASE_URL = os.getenv("API_BASE_URL", "https://router.huggingface.co/v1")
MODEL_NAME   = os.getenv("MODEL_NAME", "Qwen/Qwen2.5-72B-Instruct")
BENCHMARK    = "gpu_scheduler"

# ---------------------------------------------------------------------------
# Task configuration
# (task_name, max_agent_steps, grader_success_threshold)
#
# max_agent_steps controls how many LLM calls happen per episode.
# The environment internally advances (total_hours / max_steps) simulated
# hours per step, so every step still sees meaningful state changes.
# ---------------------------------------------------------------------------
TASKS: List[Tuple[str, int, float]] = [
    ("smooth_sailing",  24, 0.40),   # Easy:   24h sim,  1 h/step
    ("deadline_crunch", 36, 0.35),   # Medium: 72h sim,  2 h/step
    ("p0_emergency",    42, 0.30),   # Hard:  168h sim,  4 h/step
]

# LLM sampling config β€” lower temperature = more deterministic scheduling
TEMPERATURE = 0.3
MAX_TOKENS  = 200   # Enough for action line + brief chain-of-thought


# ---------------------------------------------------------------------------
# System prompt β€” tells the LLM exactly what it is and how to act
# ---------------------------------------------------------------------------
SYSTEM_PROMPT = textwrap.dedent("""
    You are an AI GPU cluster scheduler. Your goal is to MINIMIZE total
    compute burn (cluster costs $100,000 per day = ~$4,167/hour at full capacity).

    CLUSTER LAYOUT
    ---------------
    8 nodes (node 0–7), each with 8 GPUs = 64 GPUs total.

    JOB PRIORITIES
    ---------------
    P0 β€” mission-critical; NEVER preempt; schedule ASAP even if it blocks others
    P1 β€” high priority; avoid preemption; respect deadlines
    P2 β€” standard; preemption allowed only for P0 emergencies
    P3 β€” low/spot; first to be preempted if resources are needed

    ACTIONS (respond with EXACTLY ONE action per turn, on the first line)
    -----------------------------------------------------------------------
      SCHEDULE <job_id> <node_id>   Place a queued job on node 0–7.
                                    The node must have enough free GPUs.
                                    Jobs needing >8 GPUs span multiple nodes
                                    (e.g. 32-GPU job β†’ any 4 nodes with β‰₯8 free GPUs each).
      PREEMPT <job_id>              Evict a running job. HUGE penalty = 10Γ— remaining runtime cost.
                                    Only use to free space for a P0 job you cannot schedule otherwise.
      WAIT                          Advance the clock. Use when cluster is full, queue is empty,
                                    or you are clearing space for a large incoming job.

    REWARD SIGNALS (continuous, not just end-of-episode)
    ------------------------------------------------------
    + Progress reward:  proportional to job completion per step (weighted by priority)
    βˆ’ Compute burn:     ongoing cost per active GPU per hour
    βˆ’ Preemption burn:  10Γ— (gpu_count Γ— remaining_hours Γ— hourly_rate)
    βˆ’ SLA violation:    large one-time penalty when a job misses its deadline
    βˆ’ Queue delay:      small penalty per hour P0/P1 jobs wait in queue

    STRATEGY TIPS
    --------------
    β€’ Keep GPUs busy β€” idle GPUs still cost money
    β€’ Memory contention > 0.7 on a node degrades all jobs there; spread load
    β€’ For 32-GPU P0 jobs: identify 4 nodes with 8 free GPUs each, then SCHEDULE
    β€’ Watch deadline_hour β€” if a job's deadline is close, prioritise it
    β€’ WAIT is free only when you genuinely have nothing useful to schedule

    OUTPUT FORMAT
    --------------
    Line 1: your action (SCHEDULE / PREEMPT / WAIT)
    Line 2+: optional brief reasoning (ignored by evaluator, useful for debugging)

    Example responses:
      SCHEDULE job_007 3
      PREEMPT job_002
      WAIT
""").strip()


# ---------------------------------------------------------------------------
# Observation formatter β€” converts the rich observation object to plain text
# that the LLM can reason over
# ---------------------------------------------------------------------------

def format_observation(obs: GpuSchedulerObservation, step: int) -> str:
    """
    Render a GpuSchedulerObservation as a compact, human-readable block.

    Structured into four sections the LLM can scan quickly:
      1. Episode header (step, hour, burn)
      2. Node table (GPUs used/free + contention bar)
      3. Running jobs table
      4. Queue table (with deadlines highlighted)

    Args:
        obs:  The observation returned by env.step() or env.reset().
        step: Current agent step number (for the header).

    Returns:
        Multi-line string ready to embed in the LLM user prompt.
    """
    lines: List[str] = []

    # --- Header ---
    hours_left = obs.total_hours - obs.current_hour
    lines += [
        f"=== Step {step} | Hour {obs.current_hour:.0f} / {obs.total_hours:.0f} "
        f"({hours_left:.0f}h remaining) ===",
        f"Task: {obs.task_name} | Compute Burn: ${obs.compute_burn_so_far:,.0f}",
        f"Last action: {obs.last_action_result or '(start of episode)'}",
        "",
    ]

    # --- Node table ---
    lines.append("NODES  (node_id | used/total GPUs | contention | running jobs)")
    for node in obs.nodes:
        # Visual contention bar: β–“ per 10% contention, β–‘ for free headroom
        filled  = int(node.memory_contention * 10)
        bar     = "β–“" * filled + "β–‘" * (10 - filled)
        # Flag nodes that are in the danger zone for contention degradation
        warn    = " ⚠ CONTENTION" if node.memory_contention >= 0.7 else ""
        jobs_str = ", ".join(node.running_jobs) if node.running_jobs else "idle"
        lines.append(
            f"  Node {node.node_id}: {node.used_gpus}/{node.total_gpus} GPUs"
            f" | [{bar}] {node.memory_contention:.2f}{warn}"
            f" | {jobs_str}"
        )

    # --- Running jobs table ---
    lines += ["", "RUNNING JOBS  (job_id | priority | GPUs | progress | deadline)"]
    if obs.active_jobs:
        for job in obs.active_jobs:
            dl   = f"deadline h{job.deadline_hour:.0f}" if job.deadline_hour else "no deadline"
            # Highlight jobs in danger of missing their SLA
            urgent = ""
            if job.deadline_hour and (job.deadline_hour - obs.current_hour) < (job.duration_hours * (1 - job.progress)):
                urgent = " ⚠ AT RISK"
            lines.append(
                f"  {job.job_id:12s} [{job.priority_label}] | {job.gpu_count:2d} GPUs"
                f" | {job.progress:5.1%} done | nodes={job.assigned_nodes}"
                f" | {dl}{urgent}"
            )
    else:
        lines.append("  (no jobs currently running)")

    # --- Queue table ---
    lines += ["", "JOB QUEUE  (job_id | priority | GPUs needed | duration | queued_for | deadline)"]
    if obs.queue:
        for job in obs.queue:
            dl   = f"deadline h{job.deadline_hour:.0f}" if job.deadline_hour else "no deadline"
            lines.append(
                f"  {job.job_id:12s} [{job.priority_label}] | {job.gpu_count:2d} GPUs"
                f" | {job.duration_hours:.0f}h runtime"
                f" | queued {job.hours_in_queue:.1f}h | {dl}"
            )
    else:
        lines.append("  (queue is empty)")

    return "\n".join(lines)


# ---------------------------------------------------------------------------
# Action parser β€” extracts a valid GpuSchedulerAction from raw LLM text
# ---------------------------------------------------------------------------

def parse_action(response: str) -> GpuSchedulerAction:
    """
    Parse the LLM's text response into a typed GpuSchedulerAction.

    Reads only the first line of the response (the rest is optional reasoning).
    Falls back to WAIT on any parse failure so the episode never crashes.

    Patterns recognised (case-insensitive):
        SCHEDULE <job_id> <node_id>
        PREEMPT  <job_id>
        WAIT

    Args:
        response: Raw string from the LLM completion.

    Returns:
        A valid GpuSchedulerAction β€” never raises.
    """
    # Only parse the first line; ignore chain-of-thought below it
    first_line = response.strip().split("\n")[0].strip()

    # SCHEDULE job_id node_id
    m = re.match(r"SCHEDULE\s+(\S+)\s+(\d+)", first_line, re.IGNORECASE)
    if m:
        return GpuSchedulerAction(
            action_type="SCHEDULE",
            job_id=m.group(1).lower(),
            node_id=int(m.group(2)),
        )

    # PREEMPT job_id
    m = re.match(r"PREEMPT\s+(\S+)", first_line, re.IGNORECASE)
    if m:
        return GpuSchedulerAction(
            action_type="PREEMPT",
            job_id=m.group(1).lower(),
        )

    # WAIT (or anything else β€” safe default)
    return GpuSchedulerAction(action_type="WAIT")


# ---------------------------------------------------------------------------
# LLM call β€” builds the full prompt and returns (action, raw_response)
# ---------------------------------------------------------------------------

def get_llm_action(
    client: OpenAI,
    obs: GpuSchedulerObservation,
    step: int,
    history: List[str],
) -> Tuple[GpuSchedulerAction, str]:
    """
    Query the LLM for the next scheduling decision.

    Includes the last 3 history entries so the model can see the recent
    trajectory and avoid repeating useless WAIT actions.

    Args:
        client:  OpenAI-compatible client pointed at the configured endpoint.
        obs:     Current observation from the environment.
        step:    Current agent step index (used in the observation header).
        history: Rolling log of recent (step, action, reward) strings.

    Returns:
        Tuple of (parsed GpuSchedulerAction, raw LLM response string).
    """
    # Build the state block for this step
    state_text = format_observation(obs, step)

    # Append recent trajectory so the LLM sees cause→effect chains
    history_block = "\n".join(history[-3:]) if history else "No prior steps."
    user_prompt = (
        f"{state_text}\n\n"
        f"RECENT TRAJECTORY:\n{history_block}\n\n"
        f"What is your next action?"
    )

    try:
        completion = client.chat.completions.create(
            model=MODEL_NAME,
            messages=[
                {"role": "system", "content": SYSTEM_PROMPT},
                {"role": "user",   "content": user_prompt},
            ],
            temperature=TEMPERATURE,
            max_tokens=MAX_TOKENS,
            stream=False,
        )
        raw = (completion.choices[0].message.content or "WAIT").strip()
        return parse_action(raw), raw

    except Exception as exc:
        # Never crash the episode on an API error β€” just WAIT and log
        print(f"[DEBUG] LLM request failed at step {step}: {exc}", flush=True)
        return GpuSchedulerAction(action_type="WAIT"), "WAIT (api-error fallback)"


# ---------------------------------------------------------------------------
# Structured stdout loggers β€” format required by the hackathon evaluator
# ---------------------------------------------------------------------------

def log_start(task: str, env_name: str, model: str) -> None:
    """Emit the mandatory [START] line at the beginning of each episode."""
    print(f"[START] task={task} env={env_name} model={model}", flush=True)


def log_step(
    step: int,
    action: str,
    reward: float,
    done: bool,
    error: Optional[str],
) -> None:
    """Emit one [STEP] line immediately after env.step() returns."""
    error_val = error if error else "null"
    print(
        f"[STEP] step={step} action={action} "
        f"reward={reward:.2f} done={str(done).lower()} error={error_val}",
        flush=True,
    )


def log_end(
    success: bool,
    steps: int,
    score: float,
    rewards: List[float],
) -> None:
    """Emit the mandatory [END] line after env.close() or episode completion."""
    rewards_str = ",".join(f"{r:.2f}" for r in rewards)
    print(
        f"[END] success={str(success).lower()} steps={steps} "
        f"score={score:.3f} rewards={rewards_str}",
        flush=True,
    )


# ---------------------------------------------------------------------------
# Single task runner
# ---------------------------------------------------------------------------

async def run_task(
    client: OpenAI,
    env: GpuSchedulerEnv,
    task_name: str,
    max_steps: int,
    success_threshold: float,
) -> bool:
    """
    Run one complete episode of the given task and emit structured logs.

    Flow:
        1. Reset the environment (selects the task via GPU_SCHEDULER_TASK env var)
        2. Loop: get LLM action β†’ step env β†’ log β†’ check done
        3. Extract final score from result.info (provided by the task grader)
        4. Emit [END] and return whether score >= success_threshold

    Args:
        client:            OpenAI-compatible LLM client.
        env:               Connected GpuSchedulerEnv instance.
        task_name:         One of: smooth_sailing | deadline_crunch | p0_emergency
        max_steps:         Maximum agent steps before the episode is force-ended.
        success_threshold: Minimum grader score to count as success.

    Returns:
        True if the episode's grader score >= success_threshold.
    """
    rewards:     List[float] = []
    steps_taken: int         = 0
    score:       float       = 0.0
    success:     bool        = False
    history:     List[str]   = []

    log_start(task=task_name, env_name=BENCHMARK, model=MODEL_NAME)

    try:
        # Pass task_name directly so it works inside Docker containers too
        result = await env.reset(task_name=task_name)
        obs: GpuSchedulerObservation = result.observation

        for step in range(1, max_steps + 1):
            # Episode may end early (e.g. all jobs completed ahead of schedule)
            if result.done:
                break

            # --- Get action from LLM ---
            action, raw_response = get_llm_action(client, obs, step, history)
            # Use only the first line as the logged action string
            action_str = raw_response.split("\n")[0].strip()

            # --- Execute action in the environment ---
            result = await env.step(action)
            obs    = result.observation

            reward = result.reward or 0.0
            done   = result.done
            # last_action_result carries validation errors (e.g. "invalid node_id")
            error  = obs.last_action_result if "INVALID" in (obs.last_action_result or "") else None

            rewards.append(reward)
            steps_taken = step

            log_step(step=step, action=action_str, reward=reward, done=done, error=error)

            # Rolling history: compact one-liner per step for the LLM context window
            history.append(
                f"Step {step}: {action_str} β†’ reward {reward:+.2f} | "
                f"h{obs.current_hour:.0f}/{obs.total_hours:.0f} | "
                f"{obs.last_action_result or 'ok'}"
            )

            if done:
                break

        # --- Extract grader score from terminal observation ---
        # The environment's task grader computes a normalised 0.0–1.0 score
        # and stores it in observation.score when done=True (serialised as a
        # plain observation field so it survives OpenEnv's serialize_observation).
        raw_score = getattr(result.observation, "score", None)
        score = float(raw_score) if raw_score is not None else 0.0
        score = max(0.0, min(score, 1.0))   # safety clamp to [0, 1]

        success = score >= success_threshold

    except Exception as exc:
        # Catch unexpected errors; still emit a valid [END] line
        print(f"[DEBUG] Task '{task_name}' crashed: {exc}", flush=True)

    finally:
        log_end(success=success, steps=steps_taken, score=score, rewards=rewards)

    return success


# ---------------------------------------------------------------------------
# Main entry point β€” runs all three tasks sequentially
# ---------------------------------------------------------------------------

async def main() -> None:
    """
    Connect to the GpuScheduler environment container and run all three tasks.

    Tasks run sequentially on the same container instance.  The environment
    server resets its internal state on each env.reset() call, so there is
    no cross-contamination between episodes.

    Total expected runtime: < 15 minutes on a 2-vCPU / 8 GB machine
    (24 + 36 + 42 = 102 LLM calls Γ— ~5 s each β‰ˆ 8.5 minutes + env overhead).
    """
    client = OpenAI(base_url=API_BASE_URL, api_key=API_KEY)

    # from_docker_image() starts the container, waits for /health, returns client
    env = await GpuSchedulerEnv.from_docker_image(IMAGE_NAME)

    try:
        results: Dict[str, bool] = {}

        for task_name, max_steps, threshold in TASKS:
            passed = await run_task(
                client=client,
                env=env,
                task_name=task_name,
                max_steps=max_steps,
                success_threshold=threshold,
            )
            results[task_name] = passed
            # Blank line between task blocks for readability
            print("", flush=True)

        # Final summary (informational β€” not part of the mandatory format)
        all_passed = all(results.values())
        summary    = " | ".join(f"{t}={'PASS' if v else 'FAIL'}" for t, v in results.items())
        print(f"[SUMMARY] {summary} | all_passed={str(all_passed).lower()}", flush=True)

    finally:
        # Always clean up the Docker container, even on exception
        try:
            await env.close()
        except Exception as e:
            print(f"[DEBUG] env.close() error (container cleanup): {e}", flush=True)


if __name__ == "__main__":
    asyncio.run(main())