Download slime_bench.py from aklein4/SlimeBench: direct link, hf CLI and curl.
- Browser
- Download file 17.9 kB
-
https://huggingface.co/datasets/aklein4/SlimeBench/resolve/main/slime_bench.py
- Command line
-
hf download hf://datasets/aklein4/SlimeBench/slime_bench.py
-
curl -L -o slime_bench.py https://huggingface.co/datasets/aklein4/SlimeBench/resolve/main/slime_bench.py
17.9 kB
| """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() | |