Spaces:
Running

File size: 25,173 Bytes
4d76b14
 
 
 
 
 
 
 
 
 
 
 
0131132
4d76b14
5655786
4d76b14
0a7b128
4d76b14
5655786
 
 
0131132
 
 
 
 
5655786
 
4d76b14
 
 
 
0131132
 
 
4d76b14
 
 
0a7b128
 
 
 
 
4d76b14
 
 
 
0a7b128
 
 
0131132
 
 
0a7b128
 
 
 
 
 
 
 
 
 
 
 
 
 
4d76b14
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0a7b128
4d76b14
 
 
0a7b128
 
 
 
 
 
 
4d76b14
 
 
 
0a7b128
4d76b14
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0a7b128
4d76b14
 
 
 
 
 
0a7b128
4d76b14
 
 
 
 
 
 
 
 
0a7b128
4d76b14
 
 
 
 
 
 
0a7b128
 
4d76b14
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0a7b128
4d76b14
 
0a7b128
4d76b14
 
 
 
 
 
 
0131132
 
 
 
 
 
 
 
 
4d76b14
0131132
 
0a7b128
 
 
 
 
 
 
 
 
4d76b14
 
 
 
 
 
 
 
0131132
 
 
5655786
0131132
 
 
 
 
0a7b128
5655786
 
0131132
 
 
 
 
 
 
 
5655786
 
 
 
0a7b128
5655786
4d76b14
5655786
 
4d76b14
 
 
 
 
 
5655786
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4d76b14
 
 
 
 
 
 
 
 
 
 
0a7b128
4d76b14
 
 
0a7b128
 
 
 
 
 
 
4d76b14
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5655786
4d76b14
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0a7b128
 
 
 
 
 
 
4d76b14
 
 
 
 
 
 
0a7b128
5655786
0a7b128
5655786
 
 
 
 
 
 
 
 
0a7b128
5655786
 
0a7b128
5655786
 
 
 
 
 
 
 
 
4d76b14
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5655786
0a7b128
 
 
 
 
 
5655786
4d76b14
 
 
0131132
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4d76b14
0131132
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0a7b128
5655786
0a7b128
 
5655786
0a7b128
5655786
0131132
4d76b14
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
"""
Fleet Inference Script: Multi-agent LLM inference for Libratio Fleet.

Each fleet task uses different agent roles with specialized system prompts.
The LLM is called once per agent per turn, with per-agent conversation history.

Usage:
    export API_BASE_URL="https://api.groq.com/openai/v1"
    export MODEL_NAME="llama-3.3-70b-versatile"
    export HF_TOKEN="your_api_key"
    python fleet_inference.py
"""
import argparse
import os
import re
import json
import uuid
import httpx
from datetime import datetime, timezone
from dotenv import load_dotenv

try:
    from openai import OpenAI
except ImportError:
    OpenAI = None

# Load environment variables from .env file
load_dotenv()

# Config
API_BASE_URL = os.getenv("API_BASE_URL", "https://api.openai.com/v1")
MODEL_NAME = os.getenv("MODEL_NAME", "llama-3.3-70b-versatile")
HF_MODEL_URL = os.getenv("HF_MODEL_URL", "https://router.huggingface.co/v1")
HF_BASE_URL = HF_MODEL_URL.removesuffix("/chat/completions").rstrip("/")
HF_MODEL_NAME = os.getenv("HF_MODEL_NAME", "SnippyCodes/libratio-fleet-llama3-grpo:featherless-ai")
HF_TOKEN = os.getenv("HF_TOKEN")

if HF_TOKEN is None:
    if "huggingface.co" in API_BASE_URL:
        raise ValueError("HF_TOKEN environment variable is required when using Hugging Face endpoints")
    else:
        HF_TOKEN = "not-needed"


ENV_URL = os.getenv("ENV_URL", "http://localhost:7860")
FLEET_URL = f"{ENV_URL}/fleet"

_client_cache = {}


def _get_openai_client(api_key: str, base_url: str):
    if OpenAI is None:
        raise ImportError("openai package is required for LLM API calls (pip install -r requirements-extras.txt)")
    key = (base_url, api_key)
    if key not in _client_cache:
        _client_cache[key] = OpenAI(api_key=api_key, base_url=base_url)
    return _client_cache[key]

# Local Arm64 Inference Engine Configuration
USE_LOCAL_ARM_ENGINE = os.getenv("USE_LOCAL_ARM_ENGINE", "False") == "True"
local_arm_engine = None
if USE_LOCAL_ARM_ENGINE:
    try:
        from environment.local_arm_engine import LocalArmInferenceEngine
        local_arm_engine = LocalArmInferenceEngine()
    except Exception as e:
        print(f"[WARN] Failed to initialize LocalArmInferenceEngine: {e}")


def clamp_reward(r: float) -> float:
    """Ensure reward is strictly in (0, 1)."""
    try:
        val = float(r)
    except (ValueError, TypeError):
        val = 0.01
    return float(max(0.001, min(0.999, val)))


# ═══════════════════════════════════════════════════════════════════════════════
# SYSTEM PROMPTS β€” one per agent role
# ═══════════════════════════════════════════════════════════════════════════════

FLEET_PROMPTS = {
    "fleet_precision": """You are an ML infrastructure engineer managing ONE model in a shared GPU cluster.
Multiple models are training simultaneously and sharing a common GPU memory pool.

Your job: assign precision formats to YOUR model's layers. But be aware:
- Other agents are also using the same memory pool
- If you use too much memory, other models won't fit
- You need to balance YOUR model's performance with fleet-wide resource fairness

RULES:
- embedding: ALWAYS FP32 (FP8 crashes, BF16 is risky)
- output: ALWAYS FP32 (loss computation needs full precision)
- ffn: FP8 is ideal on NVIDIA/AMD (2.5x speedup). However, FP8 is UNSUPPORTED on Google TPU v5p (will cause crash). Use INT8 instead for FFN layers when running on TPU.
- attention: BF16 is optimal (1.85x speedup)
- layernorm: BF16 is best

HARDWARE ADAPTATIONS:
- Inspect 'cluster.vendor', 'cluster.hardware_profile', and 'available_precisions' in the state.
- Choose ONLY from 'available_precisions' for each layer. Using an unsupported precision will result in a critical score of 0.01.
- Google TPU (google_tpu_v5p): Does NOT support FP8. Use INT8 for FFN, BF16 for attention/layernorm.
- AMD GPU (amd_mi300x): Has 192GB VRAM. If memory pressure is low, you can safely use BF16 for wider layers to guarantee training stability, but still select from available_precisions.
- NVIDIA GPU (nvidia_h100): Supports FP8. Use FP8 for FFN, BF16 for attention/layernorm.

Consider your model's priority level β€” higher priority models may justify using more memory.
Consider how much memory other agents have already used.

RESPOND WITH ONLY valid JSON:
{"precision_strategy": {"embedding": "FP32", "attention": "BF16", "ffn": "FP8" (or "INT8" on TPU), "layernorm": "BF16", "output": "FP32"}, "reasoning": "brief explanation considering hardware and fleet context"}""",

    "fleet_oversight": """You are a Fleet AI Oversight Agent monitoring multiple neural network training runs simultaneously.
You see loss trajectories from ALL models in the cluster at once.

YOUR MISSION: Detect which model (if any) is experiencing precision-induced instability.

SCORING:
- continue_monitoring on healthy fleet = 0.55 per step (safe choice)
- CORRECT flag_instability = up to 1.0 (identify model + step + cause)
- FALSE ALARM = 0.10 (heavy penalty β€” don't cry wolf!)
- MISSED crash = 0.10 (heavy penalty β€” you failed your oversight duty)

DETECTION RULES:
1. Look for None/null values in any model's loss window β†’ that's a NaN crash, flag it immediately
2. Look for sudden spikes (>100x previous value) that don't recover
3. Check each model's precision_config: FP8 on embedding or output = HIGH RISK. Also, if running on Google TPU (google_tpu_v5p), using FP8 on ANY layer is UNSUPPORTED and causes an immediate crash.
4. A spike that recovers within a few steps is NORMAL β€” do NOT flag
5. If all models look healthy, continue_monitoring

When flagging:
- flagged_model: which model_id is crashing (e.g., "model_b")
- flagged_step: the training step where the first anomaly appeared
- root_cause: the precision+layer combo causing the issue (e.g., "fp8 embedding underflow in model_b" or "unsupported fp8 usage on TPU in model_b")

RESPOND WITH ONLY valid JSON:
{"action_type": "continue_monitoring|flag_instability", "analysis": "what you observe across all models", "flagged_model": null|"model_id", "flagged_step": null|integer, "root_cause": null|"description"}""",

    "fleet_resource": """You are a GPU Cluster Resource Manager allocating GPUs across multiple training jobs.

You must divide a shared GPU cluster among competing models, considering:
1. Each model's parameter count (bigger models need more GPUs for memory)
2. Priority levels (higher priority = should get proportionally more resources)
3. Precision strategies (aggressive precision like FP8 or INT8 reduces memory β†’ fewer GPUs needed)
4. Total cluster utilization (unused GPUs = wasted money)

RULES:
- Every model must get at least 1 GPU
- Total GPUs assigned cannot exceed cluster total
- Each model's memory usage must fit in its allocated GPU memory
- Higher priority models should generally get more resources
- Use efficient precision (FP8 for NVIDIA/AMD, INT8 for TPU for FFN, BF16 for attention) to minimize memory per model. Do not allocate FP8 on Google TPU clusters.
- Respect the active hardware limits (e.g., AMD MI300X offers 192GB memory per GPU, NVIDIA H100 offers 80GB, Google TPU v5p offers 95GB).

STRATEGY:
- Iteration 1: Allocate proportionally to param count Γ— priority. Use optimal precision.
- Iteration 2+: Adjust based on feedback. If a model doesn't fit, give it more GPUs or use less aggressive precision.

RESPOND WITH ONLY valid JSON:
{"allocations": {"model_a": {"gpus": N, "precision_strategy": {"embedding": "FP32", "attention": "BF16", "ffn": "FP8", "layernorm": "BF16", "output": "FP32"}}, "model_b": {...}}, "reasoning": "explanation of allocation logic"}""",

    "fleet_recovery": """You are a Fleet Recovery Specialist. A model in the GPU cluster has crashed mid-training.

You have 3 steps:
1. DIAGNOSE: Identify the root cause from the crash data and precision config
2. REALLOCATE: Propose a new, safe precision strategy for the crashed model
3. VERIFY: Confirm the recovery plan is sound and describe post-recovery monitoring

PHASE 1 - DIAGNOSE: Look at the loss trajectory around the crash point. Check the precision config for dangerous combinations (FP8 on embedding/output, FP16 on output).
Note: If running on Google TPU (google_tpu_v5p), check if any layer was using FP8 (which is completely unsupported and triggers immediate crash).
RESPOND WITH: {"diagnosed_model": "model_id", "root_cause": "description of what caused the crash", "reasoning": "your analysis"}

PHASE 2 - REALLOCATE: Propose a new precision strategy that fixes the crash cause. Key: switch any dangerous or unsupported precision to a safe alternative (embedding→FP32, output→FP32, and TPU FP8→INT8 or BF16).
RESPOND WITH: {"new_precision_strategy": {"embedding": "FP32", ...}, "reasoning": "what you changed and why"}

PHASE 3 - VERIFY: Explain why the new config is safe and describe your monitoring plan.
RESPOND WITH: {"reasoning": "detailed explanation of why recovery will be stable and what to monitor post-restart", "confidence": "high|medium|low"}""",
}


def call_llm(
    system_prompt: str,
    observation: dict,
    conversation_history: list = None,
    task_id: str = None,
    model_override: str = None,
    base_url_override: str = None,
    api_key_override: str = None,
) -> dict:
    """Call the LLM with the observation and return parsed JSON action."""
    # Route to local Arm64 inference engine if configured and no remote model is forced
    if USE_LOCAL_ARM_ENGINE and local_arm_engine and model_override is None:
        history_context = ""
        if conversation_history:
            history_context = "\nConversation History:\n" + "\n".join(f"{m['role']}: {m['content']}" for m in conversation_history) + "\n"
        
        user_msg = f"{history_context}Current environment state:\n{json.dumps(observation, indent=2, default=str)}\n\nProvide your action as JSON."
        action = local_arm_engine.generate_json(system_prompt, user_msg)
        if action:
            return action

    messages = [{"role": "system", "content": system_prompt}]

    if conversation_history:
        messages.extend(conversation_history)

    user_msg = f"Current environment state:\n{json.dumps(observation, indent=2, default=str)}\n\nProvide your action as JSON."
    messages.append({"role": "user", "content": user_msg})

    # Dynamic routing: custom HF model for precision/recovery when HF_TOKEN is set, Groq for oversight/resource
    hf_env_token = os.getenv("HF_TOKEN")
    has_hf_token = bool(hf_env_token and hf_env_token != "not-needed")

    if model_override:
        current_model = model_override
        current_base_url = base_url_override or API_BASE_URL
        current_api_key = api_key_override or (hf_env_token if "huggingface.co" in current_base_url else os.getenv("GROQ_API_KEY"))
    elif task_id in ["fleet_oversight", "fleet_resource"] or "groq.com" in API_BASE_URL:
        current_model = os.environ.get("MODEL_NAME", "llama-3.3-70b-versatile")
        current_base_url = "https://api.groq.com/openai/v1"
        current_api_key = os.getenv("GROQ_API_KEY")
    elif task_id in ["fleet_precision", "fleet_recovery"] and has_hf_token:
        current_model = HF_MODEL_NAME
        current_base_url = HF_BASE_URL
        current_api_key = hf_env_token
    else:
        current_model = MODEL_NAME
        current_base_url = API_BASE_URL
        current_api_key = hf_env_token

    if not current_api_key:
        raise ValueError(f"Required API key not found in environment for {current_base_url}")

    local_client = _get_openai_client(current_api_key, current_base_url)

    try:
        response = local_client.chat.completions.create(
            model=current_model,
            messages=messages,
            temperature=0.2,
            max_tokens=600,
        )
        content = response.choices[0].message.content.strip()

        # Extract the first matching JSON object by brace counting
        first_brace = content.find('{')
        if first_brace != -1:
            count = 0
            in_string = False
            escape = False
            for i in range(first_brace, len(content)):
                char = content[i]
                if char == '"' and not escape:
                    in_string = not in_string
                elif char == '\\' and in_string:
                    escape = not escape
                    continue
                elif not in_string:
                    if char == '{':
                        count += 1
                    elif char == '}':
                        count -= 1
                        if count == 0:
                            content = content[first_brace:i+1]
                            break
                escape = False

        # Strip trailing commas inside objects or arrays (common LLM generation issue)
        content = re.sub(r",\s*([\]}])", r"\1", content)

        return json.loads(content)
    except Exception as e:
        print(f"  LLM Error: {e}")
        return None


def run_fleet_task(task_id: str):
    """Run a complete fleet task episode."""
    system_prompt = FLEET_PROMPTS[task_id]
    conversation_history = []
    session_headers = {"X-Session-ID": f"inf-{uuid.uuid4().hex}"}

    # Reset fleet environment
    try:
        res = httpx.post(
            f"{FLEET_URL}/reset",
            json={"task_id": task_id},
            headers=session_headers,
            timeout=30.0,
        )
        res.raise_for_status()
        obs = res.json()["observation"]
    except Exception as e:
        print(f"Error connecting to fleet env: {e}", flush=True)
        return 0.01, 0

    print(f"\n{'='*60}", flush=True)
    print(f"[FLEET START] task={task_id} model={MODEL_NAME}", flush=True)
    print(f"{'='*60}", flush=True)

    rewards_list = []
    steps = 0

    while True:
        steps += 1

        # Call LLM
        action = call_llm(system_prompt, obs, conversation_history, task_id)

        error = None
        done = False
        reward = 0.01

        if action is None:
            # Fallback action
            if task_id == "fleet_precision":
                action = {"precision_strategy": {"embedding": "FP32", "attention": "BF16", "ffn": "FP8", "layernorm": "BF16", "output": "FP32"}, "reasoning": "fallback"}
            elif task_id == "fleet_oversight":
                action = {"action_type": "continue_monitoring", "analysis": "fallback"}
            elif task_id == "fleet_resource":
                action = {"allocations": {}, "reasoning": "fallback"}
            elif task_id == "fleet_recovery":
                action = {"reasoning": "fallback", "root_cause": "unknown", "diagnosed_model": "unknown"}
            error = "LLM returned invalid response, using fallback"

        # Add to conversation history
        conversation_history.append({"role": "user", "content": json.dumps(obs, default=str)})
        conversation_history.append({"role": "assistant", "content": json.dumps(action, default=str)})

        # Send action to fleet environment
        try:
            step_res = httpx.post(
                f"{FLEET_URL}/step",
                json={"action": action},
                headers=session_headers,
                timeout=30.0,
            )
            step_res.raise_for_status()
            data = step_res.json()

            reward = clamp_reward(data["reward"]["score"])
            feedback = data["reward"]["feedback"]
            done = data["done"]
            obs = data.get("observation", None)

            # Log step-by-step metrics to AWS DynamoDB (using MODEL_NAME so SRE trace lookup matches runs)
            try:
                from environment.aws_database import log_step_metrics
                cluster_info = obs.get("cluster", {}) if obs else {}
                model_info = obs.get("your_model", {}) if obs else {}
                mem_used = cluster_info.get("memory_used_gb")
                if mem_used is None:
                    mem_used = model_info.get("memory_used_gb", 0.0)
                therm = cluster_info.get("thermal_risk")
                if therm is None:
                    therm = model_info.get("thermal_risk", "UNKNOWN")
                pwr = cluster_info.get("power_util", cluster_info.get("estimated_power_pct", 0.0))

                log_step_metrics(
                    task_id=task_id,
                    model_id=MODEL_NAME,
                    step=steps,
                    reward=reward,
                    memory_used_gb=mem_used,
                    thermal_risk=therm,
                    power_util=pwr
                )
            except Exception:
                pass

            # Add feedback to conversation history
            conversation_history.append({
                "role": "user",
                "content": f"Environment feedback: reward={reward:.3f}, feedback={feedback}"
            })
        except Exception as e:
            done = True
            error = f"env error: {str(e)}"

        rewards_list.append(clamp_reward(reward))
        action_summary = json.dumps(action, default=str)[:150]
        error_str = error if error else "null"

        print(f"[STEP] step={steps} reward={reward:.3f} done={done} error={error_str}", flush=True)
        print(f"       action={action_summary}", flush=True)

        if done:
            break

    score = clamp_reward(sum(rewards_list) / max(steps, 1))
    success = score >= 0.60
    rewards_str = ",".join(f"{r:.3f}" for r in rewards_list)

    print(f"[FLEET END] task={task_id} score={score:.3f} steps={steps} success={success}", flush=True)
    print(f"            rewards=[{rewards_str}]", flush=True)

    # Log run telemetry to AWS DynamoDB
    try:
        from environment.aws_database import log_run_telemetry
        log_run_telemetry(task_id, MODEL_NAME, score, steps, success, rewards_list)
    except Exception as e:
        print(f"[WARN] Could not log telemetry to AWS: {e}")

    return score, steps


def _evaluate_policy_local(task_id: str, scenario_id: str, policy_fn, episodes: int) -> dict:
    """Run N episodes directly against FleetEnvironment and return summary stats."""
    from environment.fleet_env import FleetEnvironment

    env = FleetEnvironment()
    scores = []
    for _ in range(episodes):
        obs = env.reset(task_id, scenario_id=scenario_id)
        ep_rewards = []
        done = False
        while not done:
            action = policy_fn(obs)
            res = env.step(action)
            ep_rewards.append(clamp_reward(res["reward"]["score"]))
            obs = res.get("observation")
            done = res["done"]
        scores.append(clamp_reward(sum(ep_rewards) / max(len(ep_rewards), 1)))

    passes = sum(1 for s in scores if s >= 0.60)
    return {
        "mean_score": round(sum(scores) / max(len(scores), 1), 4),
        "min_score": round(min(scores), 4),
        "max_score": round(max(scores), 4),
        "pass_rate_pct": round(100.0 * passes / max(len(scores), 1), 1),
        "episodes": len(scores),
    }


def run_eval(
    task_id: str = "fleet_precision",
    scenarios: list = None,
    episodes: int = 3,
    baselines_only: bool = False,
    trained_model: str = None,
    base_model: str = None,
    output_path: str = "results/eval_comparison.json",
    llm_caller=None,
) -> dict:
    """Compare trained GRPO model against random, greedy, and optional base LLM baselines."""
    from train_fleet import greedy_policy, random_policy

    eval_scenarios = scenarios or ["small_fleet", "oversubscribed_fleet", "google_tpu_fleet"]
    agents = {
        "Random Baseline": random_policy,
        "Greedy Baseline": greedy_policy,
    }

    caller = llm_caller or call_llm
    system_prompt = FLEET_PROMPTS[task_id]

    if not baselines_only:
        t_model = trained_model or HF_MODEL_NAME
        t_base_url = HF_BASE_URL if "huggingface.co" in HF_BASE_URL else API_BASE_URL
        t_key = os.getenv("HF_TOKEN")

        def trained_policy(obs):
            act = caller(
                system_prompt,
                obs,
                task_id=task_id,
                model_override=t_model,
                base_url_override=t_base_url,
                api_key_override=t_key,
            )
            return act if isinstance(act, dict) else {}

        agents[f"Trained ({t_model})"] = trained_policy

        if base_model:
            b_url = API_BASE_URL
            b_key = os.getenv("GROQ_API_KEY") if "groq.com" in b_url else os.getenv("HF_TOKEN")

            def base_policy(obs):
                act = caller(
                    system_prompt,
                    obs,
                    task_id=task_id,
                    model_override=base_model,
                    base_url_override=b_url,
                    api_key_override=b_key,
                )
                return act if isinstance(act, dict) else {}

            agents[f"Base ({base_model})"] = base_policy

    by_scenario = {}
    overall = {}

    for agent_name, policy_fn in agents.items():
        all_means = []
        all_passes = []
        for scen in eval_scenarios:
            stats = _evaluate_policy_local(task_id, scen, policy_fn, episodes)
            by_scenario.setdefault(scen, {})[agent_name] = stats
            all_means.append(stats["mean_score"])
            all_passes.append(stats["pass_rate_pct"])

        overall[agent_name] = {
            "mean_score": round(sum(all_means) / max(len(all_means), 1), 4),
            "pass_rate_pct": round(sum(all_passes) / max(len(all_passes), 1), 1),
            "scenarios": len(eval_scenarios),
            "episodes_per_scenario": episodes,
        }

    report = {
        "task_id": task_id,
        "scenarios": eval_scenarios,
        "by_scenario": by_scenario,
        "overall": overall,
    }

    if output_path:
        out_dir = os.path.dirname(output_path)
        if out_dir:
            os.makedirs(out_dir, exist_ok=True)
        with open(output_path, "w", encoding="utf-8") as fh:
            json.dump(report, fh, indent=2)

    print(f"\n{'='*68}")
    print(f"EVALUATION COMPARISON (task={task_id}, episodes/scenario={episodes})")
    print(f"{'='*68}")
    print(f"{'Agent':<38} {'Mean':>8} {'Pass%':>8} {'Scenarios':>10}")
    print("-" * 68)
    for agent_name, st in overall.items():
        print(f"{agent_name:<38} {st['mean_score']:>8.3f} {st['pass_rate_pct']:>7.1f}% {st['scenarios']:>10}")
    return report


def main():
    """Run fleet inference or automated baseline vs trained evaluation."""
    parser = argparse.ArgumentParser(description="Libratio Fleet multi-agent inference and eval")
    parser.add_argument("--eval", action="store_true", help="Compare baselines vs trained model across scenarios")
    parser.add_argument("--baselines-only", action="store_true", help="Run only offline random + greedy baselines in --eval")
    parser.add_argument("--task", default=os.environ.get("TASK_ID"), help="Task ID (e.g. fleet_precision)")
    parser.add_argument("--scenarios", nargs="+", default=None, help="Scenarios to evaluate in --eval mode")
    parser.add_argument("--episodes", type=int, default=3, help="Episodes per scenario in --eval mode")
    parser.add_argument("--trained-model", default=None, help="Override trained model ID")
    parser.add_argument("--base-model", default=None, help="Optional base model ID to compare against")
    parser.add_argument("--output", default="results/eval_comparison.json", help="Eval report JSON output path")
    args = parser.parse_args()

    if args.eval:
        run_eval(
            task_id=args.task or "fleet_precision",
            scenarios=args.scenarios,
            episodes=args.episodes,
            baselines_only=args.baselines_only,
            trained_model=args.trained_model,
            base_model=args.base_model,
            output_path=args.output,
        )
        return

    # Initialize AWS DynamoDB Tables
    try:
        from environment.aws_database import create_aws_tables
        create_aws_tables()
    except Exception as e:
        print(f"[WARN] Failed to initialize AWS tables: {e}")

    task_id = args.task

    if task_id:
        tasks = [task_id]
    else:
        tasks = ["fleet_precision", "fleet_oversight", "fleet_resource", "fleet_recovery"]

    results = {}
    for t in tasks:
        score, steps = run_fleet_task(t)
        results[t] = {"score": score, "steps": steps}

    # Print summary
    print(f"\n{'='*60}", flush=True)
    print("FLEET BENCHMARK SUMMARY", flush=True)
    print(f"{'='*60}", flush=True)
    print(f"{'Task':<25} {'Score':>8} {'Steps':>6}", flush=True)
    print("-" * 42, flush=True)
    for t, r in results.items():
        print(f"{t:<25} {r['score']:>8.3f} {r['steps']:>6}", flush=True)
    avg = sum(r["score"] for r in results.values()) / max(len(results), 1)
    print("-" * 42, flush=True)
    print(f"{'AVERAGE':<25} {avg:>8.3f}", flush=True)


if __name__ == "__main__":
    main()