aklein4 commited on
Commit
00f4bef
·
verified ·
1 Parent(s): 9aefd25

Upload slime_bench.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. slime_bench.py +459 -0
slime_bench.py ADDED
@@ -0,0 +1,459 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Generate SlimeBench: one anonymous observation/action conversation per rollout.
2
+
3
+ See docs/slime-bench.md for isolated setup, generation, and upload commands.
4
+ The upstream feedforward CMA-ES policy plays against the built-in recurrent
5
+ opponent, explicitly reset each episode. All outcomes are retained. Reservoir
6
+ sampling selects one timestep uniformly from each complete rollout. Actions and
7
+ observation coordinates have independent, unique, fixed permutations per row.
8
+ Only conversations are published; mappings and rollout provenance stay local.
9
+ """
10
+
11
+ import argparse
12
+ import hashlib
13
+ import json
14
+ import math
15
+ import multiprocessing
16
+ import os
17
+ import random
18
+ import subprocess
19
+ import sys
20
+ from collections import Counter
21
+ from concurrent.futures import ProcessPoolExecutor, as_completed
22
+ from importlib.metadata import version
23
+ from itertools import permutations
24
+ from pathlib import Path
25
+
26
+ # Small matrix multiplies should not create a BLAS thread pool in every worker.
27
+ os.environ.setdefault("OPENBLAS_NUM_THREADS", "1")
28
+ os.environ.setdefault("OMP_NUM_THREADS", "1")
29
+ import numpy as np
30
+
31
+ UPSTREAM = "https://github.com/hardmaru/slimevolleygym"
32
+ REVISION = "8ac22434fc5a587a3395311f7854aeda17d10303"
33
+ WEIGHTS = "zoo/cmaes/slimevolley.cma.64.96.best.json"
34
+ WEIGHTS_SHA256 = "3523cca6459ea6a979b98b19de8466eba8d5d1318ce6fa71f8f7cd084f38ce9b"
35
+ LETTERS = "ABCDEF"
36
+ # Upstream SlimeVolleyEnv.action_table: forward, backward, jump buttons.
37
+ BUTTONS = ((0, 0, 0), (1, 0, 0), (1, 0, 1), (0, 0, 1), (0, 1, 1), (0, 1, 0))
38
+ PRODUCTION = (64, 2048, 100)
39
+ ROOT = Path(__file__).resolve().parents[2]
40
+
41
+
42
+ def sha256(path):
43
+ return hashlib.sha256(path.read_bytes()).hexdigest()
44
+
45
+
46
+ def write_json(path, value):
47
+ pending = path.with_suffix(path.suffix + ".partial")
48
+ pending.write_text(json.dumps(value, allow_nan=False) + "\n")
49
+ pending.replace(path)
50
+
51
+
52
+ def row_permutations(seed, count):
53
+ if not 1 <= count <= math.factorial(6):
54
+ raise ValueError("Need 1–720 rows for distinct six-action permutations")
55
+ actions = random.Random(f"actions:{seed}").sample(
56
+ list(permutations(LETTERS)), count
57
+ )
58
+ rng = random.Random(f"observations:{seed}")
59
+ orders, seen = [], set()
60
+ while len(orders) < count:
61
+ order = tuple(rng.sample(range(12), 12))
62
+ if order not in seen:
63
+ orders.append(order)
64
+ seen.add(order)
65
+ return list(zip(actions, orders, strict=True))
66
+
67
+
68
+ def action_from_controls(controls):
69
+ """Use upstream >0 thresholds and merge simultaneous opposite directions."""
70
+ if len(controls) != 3 or not all(math.isfinite(x) for x in controls):
71
+ raise ValueError("Expected three finite teacher controls")
72
+ forward, backward, jump = (x > 0 for x in controls)
73
+ return BUTTONS.index(
74
+ (int(forward and not backward), int(backward and not forward), int(jump))
75
+ )
76
+
77
+
78
+ def conversation(record, action_letters, observation_order):
79
+ values = record["observation"]
80
+ if len(values) != 12 or not all(math.isfinite(x) for x in values):
81
+ raise ValueError("Expected twelve finite observation values")
82
+ action = record["expert_action"]
83
+ if action not in range(6):
84
+ raise ValueError("Expected an action in [0, 5]")
85
+ # Nine significant decimal digits round-trip the teacher's float32 inputs.
86
+ prompt = "[" + ", ".join(f"{values[i]:.9g}" for i in observation_order) + "]"
87
+ return [
88
+ {"role": "user", "content": prompt},
89
+ {"role": "assistant", "content": action_letters[action]},
90
+ ]
91
+
92
+
93
+ def load_runtime(source):
94
+ sys.path.insert(0, str(source))
95
+ import gym
96
+ import slimevolleygym
97
+ from slimevolleygym.mlp import makeSlimePolicy
98
+
99
+ if Path(slimevolleygym.__file__).resolve().parent.parent != source:
100
+ raise ValueError("Imported SlimeVolley from an unexpected source directory")
101
+ gym.logger.set_level(gym.logger.ERROR)
102
+ env = slimevolleygym.SlimeVolleyEnv()
103
+ if tuple(map(tuple, env.action_table)) != BUTTONS:
104
+ raise ValueError("Upstream action table changed")
105
+ teacher = makeSlimePolicy(str(source / WEIGHTS))
106
+ return env, teacher
107
+
108
+
109
+ def collect_rollout(env, teacher, episode_seed):
110
+ """One uniformly sampled state from one complete, independently reset game."""
111
+ env.seed(episode_seed)
112
+ env.policy.reset() # Upstream env.reset() does NOT reset its RNN opponent.
113
+ observation = env.reset()
114
+ rng = random.Random(f"timestep:{episode_seed}")
115
+ selected, total = None, 0.0
116
+ for step in range(env.t_limit):
117
+ observation = np.asarray(observation, dtype=np.float32)
118
+ action = action_from_controls(teacher.predict(observation))
119
+ if rng.randrange(step + 1) == 0:
120
+ selected = {
121
+ "observation": observation.tolist(),
122
+ "expert_action": action,
123
+ "episode_seed": episode_seed,
124
+ "step": step,
125
+ }
126
+ observation, reward, done, info = env.step(BUTTONS[action])
127
+ total += float(reward)
128
+ if done:
129
+ selected.update(
130
+ episode_return=total,
131
+ episode_steps=step + 1,
132
+ time_limit=info["ale.lives"] > 0 and info["ale.otherLives"] > 0,
133
+ )
134
+ return selected
135
+ raise RuntimeError("SlimeVolley did not terminate at its configured time limit")
136
+
137
+
138
+ def split_stats(records, action_letters):
139
+ actions = Counter(item["expert_action"] for item in records)
140
+ returns = [item["episode_return"] for item in records]
141
+ return {
142
+ "rollouts": len(records),
143
+ "mean_return": sum(returns) / len(returns),
144
+ "positive_returns": sum(value > 0 for value in returns),
145
+ "zero_returns": sum(value == 0 for value in returns),
146
+ "negative_returns": sum(value < 0 for value in returns),
147
+ "time_limits": sum(item["time_limit"] for item in records),
148
+ "environment_steps": sum(item["episode_steps"] for item in records),
149
+ "action_counts": [actions[a] for a in range(6)],
150
+ "letter_counts": {action_letters[a]: actions[a] for a in range(6)},
151
+ }
152
+
153
+
154
+ def build_row(args, index, mappings):
155
+ action_letters, observation_order = mappings
156
+ env, teacher = load_runtime(args.source_dir)
157
+ row = {"row_id": index, "num_train": args.num_train, "num_test": args.num_test}
158
+ audit = {
159
+ "row_id": index,
160
+ "action_to_letter": list(action_letters),
161
+ "observation_order": list(observation_order),
162
+ "stats": {},
163
+ }
164
+ next_seed = args.seed + index * (args.num_train + args.num_test)
165
+ try:
166
+ for split, count in (("train", args.num_train), ("test", args.num_test)):
167
+ records = [
168
+ collect_rollout(env, teacher, seed)
169
+ for seed in range(next_seed, next_seed + count)
170
+ ]
171
+ next_seed += count
172
+ random.Random(f"examples:{args.seed}:{index}:{split}").shuffle(records)
173
+ row[split + "_data"] = [
174
+ conversation(record, action_letters, observation_order)
175
+ for record in records
176
+ ]
177
+ audit[split] = records
178
+ audit["stats"][split] = split_stats(records, action_letters)
179
+ write_json(
180
+ args.output_dir / "checkpoints" / f"{index:03d}.json",
181
+ {"row": row, "audit": audit},
182
+ )
183
+ finally:
184
+ env.close()
185
+ return index
186
+
187
+
188
+ def validate_row(row, audit, args, teacher):
189
+ index = row["row_id"]
190
+ letters, order = row_permutations(args.seed, args.rows)[index]
191
+ if (
192
+ audit["row_id"] != index
193
+ or audit["action_to_letter"] != list(letters)
194
+ or audit["observation_order"] != list(order)
195
+ ):
196
+ raise ValueError("Row permutation metadata differs from the seeded schedule")
197
+ first_seed = args.seed + index * (args.num_train + args.num_test)
198
+ prompts = {}
199
+ cross_split_duplicates = 0
200
+ for split, count in (("train", args.num_train), ("test", args.num_test)):
201
+ records, chats = audit[split], row[split + "_data"]
202
+ if row["num_" + split] != count or len(records) != count or len(chats) != count:
203
+ raise ValueError("Incorrect split size")
204
+ seeds = [record["episode_seed"] for record in records]
205
+ if sorted(seeds) != list(range(first_seed, first_seed + count)):
206
+ raise ValueError(
207
+ "Every conversation must come from its own assigned rollout"
208
+ )
209
+ first_seed += count
210
+ for record, chat in zip(records, chats, strict=True):
211
+ if not 0 <= record["step"] < record["episode_steps"] <= 3000:
212
+ raise ValueError("Invalid sampled timestep")
213
+ if chat != conversation(record, letters, order):
214
+ raise ValueError("Conversation does not match its private provenance")
215
+ parsed = np.asarray(json.loads(chat[0]["content"]), dtype=np.float32)
216
+ canonical = np.empty(12, dtype=np.float32)
217
+ canonical[list(order)] = parsed
218
+ if not np.array_equal(
219
+ canonical, np.asarray(record["observation"], dtype=np.float32)
220
+ ):
221
+ raise ValueError("Prompt did not preserve the teacher's input")
222
+ if (
223
+ action_from_controls(teacher.predict(canonical))
224
+ != record["expert_action"]
225
+ ):
226
+ raise ValueError(
227
+ "Label does not agree with the teacher on the serialized input"
228
+ )
229
+ prompt = chat[0]["content"]
230
+ if split == "test" and prompts.get(prompt) == "train":
231
+ cross_split_duplicates += 1
232
+ prompts.setdefault(prompt, split)
233
+ if audit["stats"][split] != split_stats(records, letters):
234
+ raise ValueError("Incorrect split statistics")
235
+ return cross_split_duplicates
236
+
237
+
238
+ def prepare(args):
239
+ head = subprocess.check_output(
240
+ ["git", "-C", str(args.source_dir), "rev-parse", "HEAD"], text=True
241
+ ).strip()
242
+ if head != REVISION or sha256(args.source_dir / WEIGHTS) != WEIGHTS_SHA256:
243
+ raise ValueError(
244
+ f"Use upstream revision {REVISION} and its original CMA-ES weights"
245
+ )
246
+ subprocess.run(
247
+ [
248
+ "git",
249
+ "-C",
250
+ str(args.source_dir),
251
+ "diff",
252
+ "--exit-code",
253
+ "HEAD",
254
+ "--",
255
+ "slimevolleygym",
256
+ WEIGHTS,
257
+ ],
258
+ check=True,
259
+ stdout=subprocess.DEVNULL,
260
+ )
261
+ config = {
262
+ "rows": args.rows,
263
+ "num_train": args.num_train,
264
+ "num_test": args.num_test,
265
+ "seed": args.seed,
266
+ "upstream_revision": REVISION,
267
+ "weights_sha256": WEIGHTS_SHA256,
268
+ "generator_sha256": sha256(Path(__file__)),
269
+ "versions": {name: version(name) for name in ("numpy", "gym", "datasets")},
270
+ "sampling": "one uniformly sampled timestep per complete rollout; no action or outcome filtering",
271
+ "teacher": "feedforward CMA-ES; float32 observations; >0 button thresholds",
272
+ "opponent": "upstream BaselinePolicy, reset independently every rollout",
273
+ }
274
+ args.output_dir.mkdir(parents=True, exist_ok=True)
275
+ (args.output_dir / "checkpoints").mkdir(exist_ok=True)
276
+ manifest = args.output_dir / "manifest.json"
277
+ if manifest.exists():
278
+ if json.loads(manifest.read_text()) != config:
279
+ raise ValueError(
280
+ "Generation config/source changed; use a new output directory"
281
+ )
282
+ else:
283
+ write_json(manifest, config)
284
+
285
+
286
+ def export(args):
287
+ env, teacher = load_runtime(args.source_dir)
288
+ rows, stats, duplicates = [], [], 0
289
+ output = args.output_dir / "slime_bench.jsonl"
290
+ pending = output.with_suffix(".jsonl.partial")
291
+ try:
292
+ with pending.open("w") as handle:
293
+ for index in range(args.rows):
294
+ checkpoint = json.loads(
295
+ (args.output_dir / "checkpoints" / f"{index:03d}.json").read_text()
296
+ )
297
+ row, audit = checkpoint["row"], checkpoint["audit"]
298
+ if row["row_id"] != index:
299
+ raise ValueError("Incorrect checkpoint row ID")
300
+ duplicates += validate_row(row, audit, args, teacher)
301
+ rows.append(row)
302
+ stats.append(audit["stats"])
303
+ handle.write(json.dumps(row, allow_nan=False) + "\n")
304
+ finally:
305
+ env.close()
306
+ pending.replace(output)
307
+ all_stats = [entry[split] for entry in stats for split in ("train", "test")]
308
+ total = sum(entry["rollouts"] for entry in all_stats)
309
+ summary = {
310
+ "rows": len(rows),
311
+ "conversations": total,
312
+ "distinct_rollouts": total,
313
+ "cross_split_duplicate_prompts": duplicates,
314
+ "mean_rollout_return": sum(
315
+ entry["mean_return"] * entry["rollouts"] for entry in all_stats
316
+ )
317
+ / total,
318
+ "action_counts": [
319
+ sum(entry["action_counts"][a] for entry in all_stats) for a in range(6)
320
+ ],
321
+ "environment_steps": sum(entry["environment_steps"] for entry in all_stats),
322
+ "jsonl_sha256": sha256(output),
323
+ "per_row": stats,
324
+ }
325
+ write_json(args.output_dir / "validation.json", summary)
326
+ print(json.dumps({k: v for k, v in summary.items() if k != "per_row"}), flush=True)
327
+ return rows, summary
328
+
329
+
330
+ def upload(args, rows, summary):
331
+ from datasets import Dataset, Features, Value
332
+ from huggingface_hub import HfApi
333
+
334
+ if (args.rows, args.num_train, args.num_test) != PRODUCTION:
335
+ raise ValueError(
336
+ "Upload requires exactly 64 rows, 2048 train and 100 test examples"
337
+ )
338
+ message = {"role": Value("string"), "content": Value("string")}
339
+ features = Features(
340
+ {
341
+ "row_id": Value("int64"),
342
+ "num_train": Value("int64"),
343
+ "num_test": Value("int64"),
344
+ "train_data": [[message]],
345
+ "test_data": [[message]],
346
+ }
347
+ )
348
+ dataset = Dataset.from_list(rows, features=features)
349
+ result = dataset.push_to_hub(
350
+ args.output_dataset, config_name="default", split="train"
351
+ )
352
+ api = HfApi()
353
+ # Preserve the dataset library's generated YAML schema while adding the card.
354
+ from huggingface_hub import DatasetCard
355
+
356
+ card = DatasetCard.load(args.output_dataset)
357
+ guide = ROOT / "docs" / "slime-bench.md"
358
+ body = guide.read_text().replace(
359
+ "../data_preparation/benchmarks/slime_bench.py", "./slime_bench.py"
360
+ )
361
+ card.text = body + (
362
+ f"\n## Published run\n\n"
363
+ f"- {summary['conversations']:,} conversations from distinct rollouts.\n"
364
+ f"- Mean teacher rollout return: {summary['mean_rollout_return']:.4f}.\n"
365
+ f"- Exact train/test prompt overlaps within rows: {summary['cross_split_duplicate_prompts']}.\n"
366
+ f"- Generation seed: {args.seed}.\n"
367
+ f"- JSONL SHA-256: `{summary['jsonl_sha256']}`.\n"
368
+ )
369
+ card.push_to_hub(args.output_dataset, repo_type="dataset")
370
+ api.upload_file(
371
+ path_or_fileobj=str(Path(__file__)),
372
+ path_in_repo="slime_bench.py",
373
+ repo_id=args.output_dataset,
374
+ repo_type="dataset",
375
+ )
376
+ revision = api.dataset_info(args.output_dataset).sha
377
+ write_json(
378
+ args.output_dir / "upload.json",
379
+ {
380
+ "repository": args.output_dataset,
381
+ "revision": revision,
382
+ "data_commit": str(result),
383
+ },
384
+ )
385
+ print(
386
+ f"Uploaded https://huggingface.co/datasets/{args.output_dataset}/tree/{revision}",
387
+ flush=True,
388
+ )
389
+
390
+
391
+ def parse_args(argv=None):
392
+ parser = argparse.ArgumentParser(description=__doc__)
393
+ parser.add_argument(
394
+ "--source-dir",
395
+ type=Path,
396
+ required=True,
397
+ help="Pinned upstream SlimeVolley checkout",
398
+ )
399
+ parser.add_argument(
400
+ "--output-dir", type=Path, default=ROOT / "local_data" / "slime_bench"
401
+ )
402
+ parser.add_argument("--rows", type=int, default=64)
403
+ parser.add_argument("--num-train", type=int, default=2048)
404
+ parser.add_argument("--num-test", type=int, default=100)
405
+ parser.add_argument("--seed", type=int, default=42)
406
+ parser.add_argument("--workers", type=int, default=8)
407
+ parser.add_argument("--upload", action="store_true")
408
+ parser.add_argument("--output-dataset", default="aklein4/SlimeBench")
409
+ args = parser.parse_args(argv)
410
+ if (
411
+ not 1 <= args.rows <= 720
412
+ or min(args.num_train, args.num_test, args.workers) < 1
413
+ or args.seed < 0
414
+ ):
415
+ parser.error(
416
+ "Need 1–720 rows, positive split sizes/workers, and a nonnegative seed"
417
+ )
418
+ args.source_dir = args.source_dir.resolve()
419
+ args.output_dir = args.output_dir.resolve()
420
+ if args.upload and (args.rows, args.num_train, args.num_test) != PRODUCTION:
421
+ parser.error("Only the full 64 × (2048 + 100) dataset may be uploaded")
422
+ return args
423
+
424
+
425
+ def main():
426
+ args = parse_args()
427
+ from dotenv import load_dotenv
428
+
429
+ load_dotenv(ROOT / ".env")
430
+ prepare(args)
431
+ mappings = row_permutations(args.seed, args.rows)
432
+ missing = [
433
+ i
434
+ for i in range(args.rows)
435
+ if not (args.output_dir / "checkpoints" / f"{i:03d}.json").exists()
436
+ ]
437
+ if args.workers == 1:
438
+ for index in missing:
439
+ build_row(args, index, mappings[index])
440
+ print(f"Completed row {index + 1}/{args.rows}", flush=True)
441
+ elif missing:
442
+ with ProcessPoolExecutor(
443
+ max_workers=min(args.workers, len(missing)),
444
+ mp_context=multiprocessing.get_context("spawn"),
445
+ ) as pool:
446
+ futures = [
447
+ pool.submit(build_row, args, index, mappings[index])
448
+ for index in missing
449
+ ]
450
+ for future in as_completed(futures):
451
+ index = future.result()
452
+ print(f"Completed row {index + 1}/{args.rows}", flush=True)
453
+ rows, summary = export(args)
454
+ if args.upload:
455
+ upload(args, rows, summary)
456
+
457
+
458
+ if __name__ == "__main__":
459
+ main()