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
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
"""Generate SlimeBench: one anonymous observation/action conversation per rollout.

See docs/slime-bench.md for isolated setup, generation, and upload commands.
The upstream feedforward CMA-ES policy plays against the built-in recurrent
opponent, explicitly reset each episode. All outcomes are retained. Reservoir
sampling selects one timestep uniformly from each complete rollout. Actions and
observation coordinates have independent, unique, fixed permutations per row.
Only conversations are published; mappings and rollout provenance stay local.
"""

import argparse
import hashlib
import json
import math
import multiprocessing
import os
import random
import subprocess
import sys
from collections import Counter
from concurrent.futures import ProcessPoolExecutor, as_completed
from importlib.metadata import version
from itertools import permutations
from pathlib import Path

# Small matrix multiplies should not create a BLAS thread pool in every worker.
os.environ.setdefault("OPENBLAS_NUM_THREADS", "1")
os.environ.setdefault("OMP_NUM_THREADS", "1")
import numpy as np

UPSTREAM = "https://github.com/hardmaru/slimevolleygym"
REVISION = "8ac22434fc5a587a3395311f7854aeda17d10303"
WEIGHTS = "zoo/cmaes/slimevolley.cma.64.96.best.json"
WEIGHTS_SHA256 = "3523cca6459ea6a979b98b19de8466eba8d5d1318ce6fa71f8f7cd084f38ce9b"
LETTERS = "ABCDEF"
# Upstream SlimeVolleyEnv.action_table: forward, backward, jump buttons.
BUTTONS = ((0, 0, 0), (1, 0, 0), (1, 0, 1), (0, 0, 1), (0, 1, 1), (0, 1, 0))
PRODUCTION = (64, 2048, 100)
ROOT = Path(__file__).resolve().parents[2]


def sha256(path):
    return hashlib.sha256(path.read_bytes()).hexdigest()


def write_json(path, value):
    pending = path.with_suffix(path.suffix + ".partial")
    pending.write_text(json.dumps(value, allow_nan=False) + "\n")
    pending.replace(path)


def row_permutations(seed, count):
    if not 1 <= count <= math.factorial(6):
        raise ValueError("Need 1–720 rows for distinct six-action permutations")
    actions = random.Random(f"actions:{seed}").sample(
        list(permutations(LETTERS)), count
    )
    rng = random.Random(f"observations:{seed}")
    orders, seen = [], set()
    while len(orders) < count:
        order = tuple(rng.sample(range(12), 12))
        if order not in seen:
            orders.append(order)
            seen.add(order)
    return list(zip(actions, orders, strict=True))


def action_from_controls(controls):
    """Use upstream >0 thresholds and merge simultaneous opposite directions."""
    if len(controls) != 3 or not all(math.isfinite(x) for x in controls):
        raise ValueError("Expected three finite teacher controls")
    forward, backward, jump = (x > 0 for x in controls)
    return BUTTONS.index(
        (int(forward and not backward), int(backward and not forward), int(jump))
    )


def conversation(record, action_letters, observation_order):
    values = record["observation"]
    if len(values) != 12 or not all(math.isfinite(x) for x in values):
        raise ValueError("Expected twelve finite observation values")
    action = record["expert_action"]
    if action not in range(6):
        raise ValueError("Expected an action in [0, 5]")
    # Nine significant decimal digits round-trip the teacher's float32 inputs.
    prompt = "[" + ", ".join(f"{values[i]:.9g}" for i in observation_order) + "]"
    return [
        {"role": "user", "content": prompt},
        {"role": "assistant", "content": action_letters[action]},
    ]


def load_runtime(source):
    sys.path.insert(0, str(source))
    import gym
    import slimevolleygym
    from slimevolleygym.mlp import makeSlimePolicy

    if Path(slimevolleygym.__file__).resolve().parent.parent != source:
        raise ValueError("Imported SlimeVolley from an unexpected source directory")
    gym.logger.set_level(gym.logger.ERROR)
    env = slimevolleygym.SlimeVolleyEnv()
    if tuple(map(tuple, env.action_table)) != BUTTONS:
        raise ValueError("Upstream action table changed")
    teacher = makeSlimePolicy(str(source / WEIGHTS))
    return env, teacher


def collect_rollout(env, teacher, episode_seed):
    """One uniformly sampled state from one complete, independently reset game."""
    env.seed(episode_seed)
    env.policy.reset()  # Upstream env.reset() does NOT reset its RNN opponent.
    observation = env.reset()
    rng = random.Random(f"timestep:{episode_seed}")
    selected, total = None, 0.0
    for step in range(env.t_limit):
        observation = np.asarray(observation, dtype=np.float32)
        action = action_from_controls(teacher.predict(observation))
        if rng.randrange(step + 1) == 0:
            selected = {
                "observation": observation.tolist(),
                "expert_action": action,
                "episode_seed": episode_seed,
                "step": step,
            }
        observation, reward, done, info = env.step(BUTTONS[action])
        total += float(reward)
        if done:
            selected.update(
                episode_return=total,
                episode_steps=step + 1,
                time_limit=info["ale.lives"] > 0 and info["ale.otherLives"] > 0,
            )
            return selected
    raise RuntimeError("SlimeVolley did not terminate at its configured time limit")


def split_stats(records, action_letters):
    actions = Counter(item["expert_action"] for item in records)
    returns = [item["episode_return"] for item in records]
    return {
        "rollouts": len(records),
        "mean_return": sum(returns) / len(returns),
        "positive_returns": sum(value > 0 for value in returns),
        "zero_returns": sum(value == 0 for value in returns),
        "negative_returns": sum(value < 0 for value in returns),
        "time_limits": sum(item["time_limit"] for item in records),
        "environment_steps": sum(item["episode_steps"] for item in records),
        "action_counts": [actions[a] for a in range(6)],
        "letter_counts": {action_letters[a]: actions[a] for a in range(6)},
    }


def build_row(args, index, mappings):
    action_letters, observation_order = mappings
    env, teacher = load_runtime(args.source_dir)
    row = {"row_id": index, "num_train": args.num_train, "num_test": args.num_test}
    audit = {
        "row_id": index,
        "action_to_letter": list(action_letters),
        "observation_order": list(observation_order),
        "stats": {},
    }
    next_seed = args.seed + index * (args.num_train + args.num_test)
    try:
        for split, count in (("train", args.num_train), ("test", args.num_test)):
            records = [
                collect_rollout(env, teacher, seed)
                for seed in range(next_seed, next_seed + count)
            ]
            next_seed += count
            random.Random(f"examples:{args.seed}:{index}:{split}").shuffle(records)
            row[split + "_data"] = [
                conversation(record, action_letters, observation_order)
                for record in records
            ]
            audit[split] = records
            audit["stats"][split] = split_stats(records, action_letters)
        write_json(
            args.output_dir / "checkpoints" / f"{index:03d}.json",
            {"row": row, "audit": audit},
        )
    finally:
        env.close()
    return index


def validate_row(row, audit, args, teacher):
    index = row["row_id"]
    letters, order = row_permutations(args.seed, args.rows)[index]
    if (
        audit["row_id"] != index
        or audit["action_to_letter"] != list(letters)
        or audit["observation_order"] != list(order)
    ):
        raise ValueError("Row permutation metadata differs from the seeded schedule")
    first_seed = args.seed + index * (args.num_train + args.num_test)
    prompts = {}
    cross_split_duplicates = 0
    for split, count in (("train", args.num_train), ("test", args.num_test)):
        records, chats = audit[split], row[split + "_data"]
        if row["num_" + split] != count or len(records) != count or len(chats) != count:
            raise ValueError("Incorrect split size")
        seeds = [record["episode_seed"] for record in records]
        if sorted(seeds) != list(range(first_seed, first_seed + count)):
            raise ValueError(
                "Every conversation must come from its own assigned rollout"
            )
        first_seed += count
        for record, chat in zip(records, chats, strict=True):
            if not 0 <= record["step"] < record["episode_steps"] <= 3000:
                raise ValueError("Invalid sampled timestep")
            if chat != conversation(record, letters, order):
                raise ValueError("Conversation does not match its private provenance")
            parsed = np.asarray(json.loads(chat[0]["content"]), dtype=np.float32)
            canonical = np.empty(12, dtype=np.float32)
            canonical[list(order)] = parsed
            if not np.array_equal(
                canonical, np.asarray(record["observation"], dtype=np.float32)
            ):
                raise ValueError("Prompt did not preserve the teacher's input")
            if (
                action_from_controls(teacher.predict(canonical))
                != record["expert_action"]
            ):
                raise ValueError(
                    "Label does not agree with the teacher on the serialized input"
                )
            prompt = chat[0]["content"]
            if split == "test" and prompts.get(prompt) == "train":
                cross_split_duplicates += 1
            prompts.setdefault(prompt, split)
        if audit["stats"][split] != split_stats(records, letters):
            raise ValueError("Incorrect split statistics")
    return cross_split_duplicates


def prepare(args):
    head = subprocess.check_output(
        ["git", "-C", str(args.source_dir), "rev-parse", "HEAD"], text=True
    ).strip()
    if head != REVISION or sha256(args.source_dir / WEIGHTS) != WEIGHTS_SHA256:
        raise ValueError(
            f"Use upstream revision {REVISION} and its original CMA-ES weights"
        )
    subprocess.run(
        [
            "git",
            "-C",
            str(args.source_dir),
            "diff",
            "--exit-code",
            "HEAD",
            "--",
            "slimevolleygym",
            WEIGHTS,
        ],
        check=True,
        stdout=subprocess.DEVNULL,
    )
    config = {
        "rows": args.rows,
        "num_train": args.num_train,
        "num_test": args.num_test,
        "seed": args.seed,
        "upstream_revision": REVISION,
        "weights_sha256": WEIGHTS_SHA256,
        "generator_sha256": sha256(Path(__file__)),
        "versions": {name: version(name) for name in ("numpy", "gym", "datasets")},
        "sampling": "one uniformly sampled timestep per complete rollout; no action or outcome filtering",
        "teacher": "feedforward CMA-ES; float32 observations; >0 button thresholds",
        "opponent": "upstream BaselinePolicy, reset independently every rollout",
    }
    args.output_dir.mkdir(parents=True, exist_ok=True)
    (args.output_dir / "checkpoints").mkdir(exist_ok=True)
    manifest = args.output_dir / "manifest.json"
    if manifest.exists():
        if json.loads(manifest.read_text()) != config:
            raise ValueError(
                "Generation config/source changed; use a new output directory"
            )
    else:
        write_json(manifest, config)


def export(args):
    env, teacher = load_runtime(args.source_dir)
    rows, stats, duplicates = [], [], 0
    output = args.output_dir / "slime_bench.jsonl"
    pending = output.with_suffix(".jsonl.partial")
    try:
        with pending.open("w") as handle:
            for index in range(args.rows):
                checkpoint = json.loads(
                    (args.output_dir / "checkpoints" / f"{index:03d}.json").read_text()
                )
                row, audit = checkpoint["row"], checkpoint["audit"]
                if row["row_id"] != index:
                    raise ValueError("Incorrect checkpoint row ID")
                duplicates += validate_row(row, audit, args, teacher)
                rows.append(row)
                stats.append(audit["stats"])
                handle.write(json.dumps(row, allow_nan=False) + "\n")
    finally:
        env.close()
    pending.replace(output)
    all_stats = [entry[split] for entry in stats for split in ("train", "test")]
    total = sum(entry["rollouts"] for entry in all_stats)
    summary = {
        "rows": len(rows),
        "conversations": total,
        "distinct_rollouts": total,
        "cross_split_duplicate_prompts": duplicates,
        "mean_rollout_return": sum(
            entry["mean_return"] * entry["rollouts"] for entry in all_stats
        )
        / total,
        "action_counts": [
            sum(entry["action_counts"][a] for entry in all_stats) for a in range(6)
        ],
        "environment_steps": sum(entry["environment_steps"] for entry in all_stats),
        "jsonl_sha256": sha256(output),
        "per_row": stats,
    }
    write_json(args.output_dir / "validation.json", summary)
    print(json.dumps({k: v for k, v in summary.items() if k != "per_row"}), flush=True)
    return rows, summary


def upload(args, rows, summary):
    from datasets import Dataset, Features, Value
    from huggingface_hub import HfApi

    if (args.rows, args.num_train, args.num_test) != PRODUCTION:
        raise ValueError(
            "Upload requires exactly 64 rows, 2048 train and 100 test examples"
        )
    message = {"role": Value("string"), "content": Value("string")}
    features = Features(
        {
            "row_id": Value("int64"),
            "num_train": Value("int64"),
            "num_test": Value("int64"),
            "train_data": [[message]],
            "test_data": [[message]],
        }
    )
    dataset = Dataset.from_list(rows, features=features)
    result = dataset.push_to_hub(
        args.output_dataset, config_name="default", split="train"
    )
    api = HfApi()
    # Preserve the dataset library's generated YAML schema while adding the card.
    from huggingface_hub import DatasetCard

    card = DatasetCard.load(args.output_dataset)
    guide = ROOT / "docs" / "slime-bench.md"
    body = guide.read_text().replace(
        "../data_preparation/benchmarks/slime_bench.py", "./slime_bench.py"
    )
    card.text = body + (
        f"\n## Published run\n\n"
        f"- {summary['conversations']:,} conversations from distinct rollouts.\n"
        f"- Mean teacher rollout return: {summary['mean_rollout_return']:.4f}.\n"
        f"- Exact train/test prompt overlaps within rows: {summary['cross_split_duplicate_prompts']}.\n"
        f"- Generation seed: {args.seed}.\n"
        f"- JSONL SHA-256: `{summary['jsonl_sha256']}`.\n"
    )
    card.push_to_hub(args.output_dataset, repo_type="dataset")
    api.upload_file(
        path_or_fileobj=str(Path(__file__)),
        path_in_repo="slime_bench.py",
        repo_id=args.output_dataset,
        repo_type="dataset",
    )
    revision = api.dataset_info(args.output_dataset).sha
    write_json(
        args.output_dir / "upload.json",
        {
            "repository": args.output_dataset,
            "revision": revision,
            "data_commit": str(result),
        },
    )
    print(
        f"Uploaded https://huggingface.co/datasets/{args.output_dataset}/tree/{revision}",
        flush=True,
    )


def parse_args(argv=None):
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument(
        "--source-dir",
        type=Path,
        required=True,
        help="Pinned upstream SlimeVolley checkout",
    )
    parser.add_argument(
        "--output-dir", type=Path, default=ROOT / "local_data" / "slime_bench"
    )
    parser.add_argument("--rows", type=int, default=64)
    parser.add_argument("--num-train", type=int, default=2048)
    parser.add_argument("--num-test", type=int, default=100)
    parser.add_argument("--seed", type=int, default=42)
    parser.add_argument("--workers", type=int, default=8)
    parser.add_argument("--upload", action="store_true")
    parser.add_argument("--output-dataset", default="aklein4/SlimeBench")
    args = parser.parse_args(argv)
    if (
        not 1 <= args.rows <= 720
        or min(args.num_train, args.num_test, args.workers) < 1
        or args.seed < 0
    ):
        parser.error(
            "Need 1–720 rows, positive split sizes/workers, and a nonnegative seed"
        )
    args.source_dir = args.source_dir.resolve()
    args.output_dir = args.output_dir.resolve()
    if args.upload and (args.rows, args.num_train, args.num_test) != PRODUCTION:
        parser.error("Only the full 64 × (2048 + 100) dataset may be uploaded")
    return args


def main():
    args = parse_args()
    from dotenv import load_dotenv

    load_dotenv(ROOT / ".env")
    prepare(args)
    mappings = row_permutations(args.seed, args.rows)
    missing = [
        i
        for i in range(args.rows)
        if not (args.output_dir / "checkpoints" / f"{i:03d}.json").exists()
    ]
    if args.workers == 1:
        for index in missing:
            build_row(args, index, mappings[index])
            print(f"Completed row {index + 1}/{args.rows}", flush=True)
    elif missing:
        with ProcessPoolExecutor(
            max_workers=min(args.workers, len(missing)),
            mp_context=multiprocessing.get_context("spawn"),
        ) as pool:
            futures = [
                pool.submit(build_row, args, index, mappings[index])
                for index in missing
            ]
            for future in as_completed(futures):
                index = future.result()
                print(f"Completed row {index + 1}/{args.rows}", flush=True)
    rows, summary = export(args)
    if args.upload:
        upload(args, rows, summary)


if __name__ == "__main__":
    main()