Download faisi/W4-01-external-baselines/src/baselines/prepare.py from ppJustin/micro: direct link, hf CLI and curl.
- Browser
- Download file 9.62 kB
-
https://huggingface.co/datasets/ppJustin/micro/resolve/main/faisi/W4-01-external-baselines/src/baselines/prepare.py
- Command line
-
hf download hf://datasets/ppJustin/micro/faisi/W4-01-external-baselines/src/baselines/prepare.py
-
curl -L -o prepare.py https://huggingface.co/datasets/ppJustin/micro/resolve/main/faisi/W4-01-external-baselines/src/baselines/prepare.py
9.62 kB
| """Prepare disjoint read-only snapshot views and train-only induction examples.""" | |
| import argparse | |
| from collections import defaultdict | |
| import hashlib | |
| import json | |
| import os | |
| from pathlib import Path | |
| import random | |
| import re | |
| import shutil | |
| import pyarrow as pa | |
| import pyarrow.parquet as pq | |
| from checkers.generation import synopsis | |
| from checkers.inventory import ALLOWLIST_SHA256, train_allowlist | |
| from checkers.context_api import TrajectoryContext | |
| from data_engine.adapters import case_id | |
| from sandbox.snapshot import FILES | |
| from rl_env.data_plan import parquet_row | |
| SPLITS = ("train", "id_test", "ood_test", "ood_all") | |
| SYSTEM_HEADER = re.compile( | |
| rb'^\{"name":\s*("(?:[^"\\]|\\.)*"),\s*"source":\s*"(?:[^"\\]|\\.)*",' | |
| rb'\s*"system":\s*("(?:[^"\\]|\\.)*")' | |
| ) | |
| def dump(path, value): | |
| path.write_text(json.dumps(value, separators=(",", ":"), allow_nan=False) + "\n") | |
| def system_metadata(raw, allowed): | |
| """Project only the system stratum from compiler IDs and published metadata.""" | |
| systems = {key: "TrainTicket" for key in allowed if key[0] == "propagation_bench"} | |
| for system in ("Bank", "Telecom"): | |
| # OpenRCA v1 has 335 cases overall. Compiler source indices restart per system. | |
| for index in range(335): | |
| key = "openrca_v1", case_id("openrca_v1", f"{system}/{index}") | |
| if key in allowed: | |
| systems[key] = system | |
| with (raw / "openrca_v2/manifest.jsonl").open("rb") as stream: | |
| for line in stream: | |
| match = SYSTEM_HEADER.match(line) | |
| if match is None: | |
| raise ValueError("openrca_v2_system_header_layout_changed") | |
| key = "openrca_v2", case_id("openrca_v2", json.loads(match[1])) | |
| if key in allowed: | |
| system = json.loads(match[2]) | |
| if key in systems or system not in ("ts", "otel-demo"): | |
| raise ValueError("unexpected_openrca_v2_train_system") | |
| systems[key] = system | |
| if systems.keys() != allowed: | |
| raise ValueError("missing_train_system_metadata") | |
| return systems | |
| def stratify(systems, dev_size=124, seed=42): | |
| strata = defaultdict(list) | |
| for (dataset, case), system in sorted(systems.items()): | |
| strata[dataset, system].append((dataset, case)) | |
| quotients = { | |
| key: divmod(len(rows) * dev_size, len(systems)) for key, rows in strata.items() | |
| } | |
| remaining = dev_size - sum(count for count, _ in quotients.values()) | |
| extras = set(sorted(strata, key=lambda k: (-quotients[k][1], k))[:remaining]) | |
| dev, induction, counts = [], [], {} | |
| rng = random.Random(seed) | |
| for key, rows in sorted(strata.items()): | |
| rng.shuffle(rows) | |
| count = quotients[key][0] + (key in extras) | |
| dev.extend(rows[:count]) | |
| induction.extend(rows[count:]) | |
| counts["/".join(key)] = {"induction": len(rows) - count, "dev": count} | |
| return sorted(induction), sorted(dev), counts | |
| def snapshot_view(path, plan, snapshots, windows): | |
| path.mkdir(parents=True, exist_ok=True) | |
| keys = {tuple(row) for name in SPLITS for row in plan[name]} | |
| relevant_windows = defaultdict(dict) | |
| for dataset, case in sorted(keys): | |
| source = snapshots / dataset / case | |
| target = path / "snapshots" / dataset / case | |
| target.mkdir(parents=True, exist_ok=True) | |
| if source.is_symlink() or set(p.name for p in source.iterdir()) != FILES: | |
| raise ValueError("invalid_snapshot_layout") | |
| for name in FILES: | |
| original, copy = source / name, target / name | |
| if original.is_symlink() or not original.is_file(): | |
| raise ValueError("invalid_snapshot_file") | |
| if not copy.is_file(): | |
| os.link(original, copy) | |
| elif not os.path.samefile(original, copy): | |
| raise ValueError("snapshot_view_changed") | |
| relevant_windows[dataset][case] = windows[dataset][case] | |
| if {(p.parent.name, p.name) for p in (path / "snapshots").glob("*/*")} != keys: | |
| raise ValueError("unapproved_snapshot_view") | |
| dump(path / "windows.json", {"version": 1, "windows": relevant_windows}) | |
| dump(path / "allowlists.json", plan) | |
| def compact(ctx): | |
| obs = synopsis(ctx) | |
| obs["overview"] = obs["overview"][:4] | |
| obs["path"] = obs["path"][:6] | |
| obs["metrics_group_z_onset_count"] = { | |
| entity: scores[:2] | |
| for entity, scores in list(obs["metrics_group_z_onset_count"].items())[:4] | |
| } | |
| obs["queried_entities"] = obs["queried_entities"][:10] | |
| obs["queried_topology"] = obs["queried_topology"][:10] | |
| return obs | |
| def induction_pairs(history, allowed, induction): | |
| groups = defaultdict(lambda: {True: [], False: []}) | |
| seen = set() | |
| with history.open("rb") as stream: | |
| for line in stream: | |
| row = json.loads(line) | |
| key = row["dataset"], row["case_id"] | |
| if key not in allowed: | |
| raise ValueError("history_outside_train_allowlist") | |
| if key not in induction or row["model"] != "Qwen2.5-7B-Instruct": | |
| continue | |
| slot = key, row["sample_idx"] | |
| if slot in seen or type(row["canonical_root_hit"]) is not bool: | |
| raise ValueError("invalid_train_history") | |
| seen.add(slot) | |
| groups[key][row["canonical_root_hit"]].append(row) | |
| if len(seen) != 8 * len(induction): | |
| raise ValueError("incomplete_induction_input") | |
| rng = random.Random(42) | |
| items = [] | |
| for group in groups.values(): | |
| if group[True] and group[False]: | |
| items.append( | |
| { | |
| "hit": compact( | |
| TrajectoryContext.from_trace(rng.choice(group[True])) | |
| ), | |
| "miss": compact( | |
| TrajectoryContext.from_trace(rng.choice(group[False])) | |
| ), | |
| } | |
| ) | |
| rng.shuffle(items) | |
| return items | |
| def main(base, prior, work, history, windows_path): | |
| base.mkdir(mode=0o700, parents=True, exist_ok=True) | |
| base.chmod(0o700) | |
| allow_path = prior / "data/allowlists.json" | |
| allowed = train_allowlist(allow_path) | |
| plan = json.loads(allow_path.read_bytes()) | |
| if list(map(lambda k: len(plan[k]), SPLITS)) != [621, 468, 75, 300]: | |
| raise ValueError("evaluation_scope_changed") | |
| snapshots = work / "runtime_snapshots" | |
| windows = json.loads(windows_path.read_bytes())["windows"] | |
| views = base / "views" | |
| for scope in ("train", "eval"): | |
| selected = { | |
| key: rows if (key == "train") == (scope == "train") else [] | |
| for key, rows in plan.items() | |
| } | |
| snapshot_view(views / scope, selected, snapshots, windows) | |
| systems = system_metadata(work / "datasets_raw", allowed) | |
| induction, dev, counts = stratify(systems) | |
| assert len(induction) == 497 and len(dev) == 124 and set(induction).isdisjoint(dev) | |
| snapshot_view( | |
| views / "dev", | |
| {"train": dev, "id_test": [], "ood_test": [], "ood_all": []}, | |
| snapshots, | |
| windows, | |
| ) | |
| roots = json.loads((prior / "roots/train_roots.json").read_bytes()) | |
| if {(d, c) for d, v in roots.items() for c in v} != allowed: | |
| raise ValueError("training_roots_changed") | |
| for scope, keys in (("train", allowed), ("dev", set(dev))): | |
| path = views / scope / "train_roots.json" | |
| dump( | |
| path, | |
| { | |
| d: {c: r for c, r in tab.items() if (d, c) in keys} | |
| for d, tab in roots.items() | |
| }, | |
| ) | |
| path.chmod(0o444) | |
| private = base / "private" | |
| private.mkdir(parents=True, exist_ok=True) | |
| dump(private / "induction.json", induction_pairs(history, allowed, set(induction))) | |
| names = set() | |
| for d, c in sorted(allowed): | |
| topology = json.loads((snapshots / d / c / "topology.json").read_bytes()) | |
| names.update(node["id"].casefold() for node in topology["nodes"]) | |
| dump(private / "disallowed_entity_names.json", sorted(names)) | |
| dump( | |
| base / "split_evidence.json", | |
| { | |
| "allowlist_sha256": ALLOWLIST_SHA256, | |
| "counts": dict(zip(SPLITS, [621, 468, 75, 300])), | |
| "induction": 497, | |
| "dev": 124, | |
| "systems": counts, | |
| "seed": 42, | |
| "induction_dev_manifest_sha256": hashlib.sha256( | |
| json.dumps([induction, dev]).encode() | |
| ).hexdigest(), | |
| "system_strata_source": "compiler case IDs and OpenRCA v2 public manifest system metadata", | |
| "evolution_and_training_vault_mounts": 0, | |
| "evolution_and_training_test_snapshot_mounts": 0, | |
| }, | |
| ) | |
| data = base / "coop" / "data" | |
| data.mkdir(parents=True, exist_ok=True) | |
| shutil.copyfile(prior / "data/train.parquet", data / "train.parquet") | |
| pq.write_table( | |
| pa.Table.from_pylist([parquet_row(d, c, "train") for d, c in dev]), | |
| data / "val.parquet", | |
| ) | |
| shutil.copyfile(views / "train/allowlists.json", data / "allowlists.json") | |
| print( | |
| json.dumps( | |
| { | |
| "train": len(allowed), | |
| "induction": len(induction), | |
| "dev": len(dev), | |
| "systems": counts, | |
| } | |
| ), | |
| flush=True, | |
| ) | |
| if __name__ == "__main__": | |
| parser = argparse.ArgumentParser(description=__doc__) | |
| for option in ("base", "prior", "work", "history", "windows"): | |
| parser.add_argument("--" + option, type=Path, required=True) | |
| args = parser.parse_args() | |
| main(args.base, args.prior, args.work, args.history, args.windows) | |