File size: 9,026 Bytes
bc35a94
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from __future__ import annotations

import argparse
import json
import random
import statistics
import sys
import time
from dataclasses import asdict
from pathlib import Path
from typing import Callable

from sysadmin_env.tasks import hpc_ood_apache
from sysadmin_env.tasks import hpc_outage


GOLD_TRAJECTORY_OUTAGE = [
    "sinfo",
    "squeue",
    "ssh compute-01",
    "cat /etc/sysconfig/network-scripts/route-eth0",
    f"printf '{hpc_outage.FIXED_ROUTE}' > /etc/sysconfig/network-scripts/route-eth0",
    "systemctl restart slurmd",
    "exit",
    "curl -I http://localhost:8080/",
]

GOLD_TRAJECTORY_MUNGE = [
    "sinfo",
    "ssh compute-01",
    "ls -l /etc/munge/munge.key",
    f"printf '{hpc_outage.FIXED_ROUTE}' > /etc/sysconfig/network-scripts/route-eth0",
    "chmod 0400 /etc/munge/munge.key",
    "systemctl restart munge",
    "systemctl restart slurmd",
    "exit",
    "curl -I http://localhost:8080/",
]

GOLD_TRAJECTORY_PID_STALE = [
    "sinfo",
    "squeue",
    "ssh compute-01",
    "systemctl status slurmd",
    "cat /var/run/slurmd.pid",
    "rm /var/run/slurmd.pid",
    "systemctl restart slurmd",
    "exit",
    "curl -I http://localhost:8080/",
]

GOLD_TRAJECTORY_GPU_ECC = [
    "sinfo",
    "squeue",
    "ssh compute-01",
    "nvidia-smi",
    "nvidia-smi -q -d ECC",
    "nvidia-smi -r -i 0",
    "exit",
    "curl -I http://localhost:8080/",
]

GOLD_TRAJECTORY_NFS_STALE = [
    "sinfo",
    "squeue",
    "ssh compute-01",
    "mount",
    "umount -l /mnt/shared",
    "mount /mnt/shared",
    "systemctl restart slurmd",
    "exit",
    "curl -I http://localhost:8080/",
]

GOLD_TRAJECTORY_OOD_APACHE = [
    "sinfo",
    "systemctl status httpd",
    "cat /etc/httpd/conf/httpd.conf",
    "apachectl configtest",
    f"printf '{hpc_ood_apache.FIXED_HTTPD_CONF}' > /etc/httpd/conf/httpd.conf",
    "apachectl configtest",
    "apachectl graceful",
    "curl -I http://localhost:8081/",
]

RANDOM_POOL = [
    "sinfo",
    "squeue",
    "ssh compute-01",
    "cat /etc/sysconfig/network-scripts/route-eth0",
    f"printf '{hpc_outage.FIXED_ROUTE}' > /etc/sysconfig/network-scripts/route-eth0",
    "echo garbage > /etc/sysconfig/network-scripts/route-eth0",
    "systemctl restart slurmd",
    "systemctl restart munge",
    "chmod 0400 /etc/munge/munge.key",
    "chmod 0777 /etc/munge/munge.key",
    "cat /var/run/slurmd.pid",
    "rm /var/run/slurmd.pid",
    "nvidia-smi",
    "nvidia-smi -r -i 0",
    "mount",
    "umount -l /mnt/shared",
    "mount /mnt/shared",
    "apachectl configtest",
    f"printf '{hpc_ood_apache.FIXED_HTTPD_CONF}' > /etc/httpd/conf/httpd.conf",
    "apachectl graceful",
    "ls /mnt/shared",
    "exit",
    "curl -I http://localhost:8080/",
    "curl -I http://localhost:8081/",
]

BAD_TRAJECTORY = [
    "sinfo",
    "squeue",
    "ls -la /mnt/shared",
    "cat /etc/hostname",
    "exit",
]


def _env_factory(env_urls: list[str] | None, scenarios: list[str]) -> Callable:
    if env_urls:
        from training.remote_env import HttpEnterpriseHPCEnv
        from training.remote_env import RemoteEndpointPool

        pool = RemoteEndpointPool(env_urls)

        def make_env():
            return HttpEnterpriseHPCEnv(env_urls=env_urls, scenario_pool=scenarios, pool=pool)

        return make_env

    from hpc_gym import EnterpriseHPCEnv

    def make_env():
        return EnterpriseHPCEnv(scenario_pool=scenarios)

    return make_env


def _run_policy(
    name: str,
    make_env: Callable,
    scenarios: list[str],
    actions_for: Callable[[str, random.Random], list[str]],
    trials: int,
    seed: int,
) -> list[dict]:
    from training.rollout import run_fixed_policy

    rng = random.Random(seed)
    rows: list[dict] = []
    for scenario in scenarios:
        for trial in range(trials):
            env = make_env()
            try:
                actions = actions_for(scenario, rng)
                record = run_fixed_policy(env, actions, reset_options={"scenario": scenario})
                rows.append(
                    {
                        "policy": name,
                        "scenario": scenario,
                        "trial": trial,
                        "reward": record.reward,
                        "steps": record.steps,
                        "terminated": record.terminated,
                        "grader_health": record.grader_health,
                        "ood_http_code": record.ood_http_code,
                        "task_id": record.task_id,
                    }
                )
            finally:
                try:
                    env.close()
                except Exception:
                    pass
    return rows


def _summarize(rows: list[dict]) -> dict:
    buckets: dict[tuple[str, str], list[dict]] = {}
    for row in rows:
        key = (row["policy"], row["scenario"])
        buckets.setdefault(key, []).append(row)
    summary: list[dict] = []
    for (policy, scenario), items in sorted(buckets.items()):
        rewards = [i["reward"] for i in items]
        summary.append(
            {
                "policy": policy,
                "scenario": scenario,
                "n": len(items),
                "solve_rate": sum(1 for i in items if i.get("terminated")) / len(items),
                "reward_mean": statistics.fmean(rewards),
                "steps_mean": statistics.fmean(i["steps"] for i in items),
                "health_mean": statistics.fmean(i["grader_health"] for i in items),
            }
        )
    return {"rows": rows, "summary": summary}


def _write_markdown(path: Path, summary: dict) -> None:
    lines = [
        "# EnterpriseHPC-v0 eval leaderboard",
        "",
        "| policy | scenario | n | solve_rate | reward_mean | steps_mean | health_mean |",
        "| --- | --- | ---: | ---: | ---: | ---: | ---: |",
    ]
    for row in summary["summary"]:
        lines.append(
            f"| {row['policy']} | {row['scenario']} | {row['n']} | "
            f"{row['solve_rate']:.2f} | {row['reward_mean']:.2f} | "
            f"{row['steps_mean']:.1f} | {row['health_mean']:.2f} |"
        )
    lines.append("")
    lines.append(f"_generated_: unix_{int(time.time())}")
    path.write_text("\n".join(lines))


def main() -> int:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--trials", type=int, default=3)
    parser.add_argument(
        "--scenarios",
        default="hpc_outage,hpc_munge,hpc_pid_stale,hpc_gpu_ecc,hpc_nfs_stale,hpc_ood_apache",
    )
    parser.add_argument("--policies", default="gold,random,bad")
    parser.add_argument("--env-urls", nargs="+", default=None)
    parser.add_argument("--seed", type=int, default=0)
    parser.add_argument("--output-dir", default="./runs/eval")
    args = parser.parse_args()

    scenarios = [s.strip() for s in args.scenarios.split(",") if s.strip()]
    policies = [p.strip() for p in args.policies.split(",") if p.strip()]

    make_env = _env_factory(args.env_urls, scenarios)

    def gold_actions(scenario: str, _: random.Random) -> list[str]:
        if scenario == "hpc_munge":
            return GOLD_TRAJECTORY_MUNGE
        if scenario == "hpc_pid_stale":
            return GOLD_TRAJECTORY_PID_STALE
        if scenario == "hpc_gpu_ecc":
            return GOLD_TRAJECTORY_GPU_ECC
        if scenario == "hpc_nfs_stale":
            return GOLD_TRAJECTORY_NFS_STALE
        if scenario == "hpc_ood_apache":
            return GOLD_TRAJECTORY_OOD_APACHE
        return GOLD_TRAJECTORY_OUTAGE

    def random_actions(_: str, rng: random.Random) -> list[str]:
        return [rng.choice(RANDOM_POOL) for _ in range(12)]

    def bad_actions(_: str, __: random.Random) -> list[str]:
        return BAD_TRAJECTORY

    policy_fns = {"gold": gold_actions, "random": random_actions, "bad": bad_actions}

    rows: list[dict] = []
    for policy in policies:
        if policy not in policy_fns:
            print(f"unknown policy {policy} skipping", file=sys.stderr)
            continue
        rows.extend(
            _run_policy(
                name=policy,
                make_env=make_env,
                scenarios=scenarios,
                actions_for=policy_fns[policy],
                trials=args.trials,
                seed=args.seed + hash(policy) % 997,
            )
        )

    summary = _summarize(rows)
    out = Path(args.output_dir)
    out.mkdir(parents=True, exist_ok=True)
    (out / "eval.jsonl").write_text("\n".join(json.dumps(r) for r in rows) + "\n")
    (out / "eval_summary.json").write_text(json.dumps(summary, indent=2))
    _write_markdown(out / "leaderboard.md", summary)

    for row in summary["summary"]:
        print(
            f"{row['policy']:<8} {row['scenario']:<12} n={row['n']:<3} "
            f"solve={row['solve_rate']:.2f} reward={row['reward_mean']:.2f} "
            f"steps={row['steps_mean']:.1f} health={row['health_mean']:.2f}"
        )
    print(f"\nartifacts written to {out}")
    return 0


if __name__ == "__main__":
    sys.exit(main())