Datasets:
Download scripts/build_dataset.py from shanec7825/zh-cs-algorithm-traces: direct link, hf CLI and curl.
- Browser
- Download file 7.2 kB
-
https://huggingface.co/datasets/shanec7825/zh-cs-algorithm-traces/resolve/main/scripts/build_dataset.py
- Command line
-
hf download hf://datasets/shanec7825/zh-cs-algorithm-traces/scripts/build_dataset.py
-
curl -L -o build_dataset.py https://huggingface.co/datasets/shanec7825/zh-cs-algorithm-traces/resolve/main/scripts/build_dataset.py
7.2 kB
| """Build and independently replay the Chinese CS trace corpus. Use Python 3.12.""" | |
| import argparse | |
| import hashlib | |
| import json | |
| from collections import Counter, defaultdict | |
| from pathlib import Path | |
| import pyarrow as pa | |
| import pyarrow.parquet as pq | |
| import cache_replacement | |
| import graph_shortest_paths | |
| ROOT = Path(__file__).resolve().parents[1] | |
| SPLITS = ("train", "validation", "test") | |
| # Base groups, not rows: a cache workload has three variants and a graph has two. | |
| CONFIGS = { | |
| "cache_replacement": (cache_replacement, (960, 120, 120), 3), | |
| "graph_shortest_paths": (graph_shortest_paths, (1200, 150, 150), 2), | |
| } | |
| SCHEMA = pa.schema([ | |
| ("id", pa.string()), ("group_id", pa.string()), ("source_seed", pa.int64()), | |
| ("task", pa.string()), ("family", pa.string()), ("variant", pa.string()), | |
| ("question", pa.string()), ("instance_json", pa.string()), ("answer_json", pa.string()), | |
| ("trace_json", pa.string()), ("n_steps", pa.int32()), | |
| ]) | |
| def encode(value): | |
| return json.dumps(value, ensure_ascii=False, separators=(",", ":"), sort_keys=True, allow_nan=False) | |
| def require(condition, message): | |
| if not condition: | |
| raise ValueError(message) | |
| def identity(config, key): | |
| digest = hashlib.sha256((config + "|" + key).encode()).hexdigest() | |
| bucket = int(digest[:8], 16) % 10 | |
| split = "train" if bucket < 8 else ("validation" if bucket == 8 else "test") | |
| return digest, split | |
| def pack(raw, config, digest, seed, index): | |
| group_id = config + "-" + digest[:24] | |
| return { | |
| "id": f"{group_id}-{index}", "group_id": group_id, "source_seed": seed, | |
| "task": raw["task"], "family": raw["family"], "variant": raw["variant"], | |
| "question": raw["question"], "instance_json": encode(raw["instance"]), | |
| "answer_json": encode(raw["answer"]), "trace_json": encode(raw["trace"]), | |
| "n_steps": len(raw["trace"]), | |
| } | |
| def build_config(root, config): | |
| module, counts, size = CONFIGS[config] | |
| remaining = dict(zip(SPLITS, counts, strict=True)) | |
| rows = {split: [] for split in SPLITS} | |
| seen = set() | |
| seed = 0 | |
| while any(remaining.values()): | |
| seed += 1 | |
| require(seed < 200_000, f"Insufficient unique {config} inputs") | |
| key, examples = module.make_group(seed, "train") | |
| digest, split = identity(config, key) | |
| if not remaining[split] or digest in seen: | |
| continue | |
| if split != "train": | |
| selected_key, examples = module.make_group(seed, split) | |
| require(key == selected_key, f"Split-dependent input for seed {seed}") | |
| require(len(examples) == size, f"Unexpected group size at seed {seed}") | |
| seen.add(digest) | |
| remaining[split] -= 1 | |
| for index, example in enumerate(examples): | |
| rows[split].append(pack(example, config, digest, seed, index)) | |
| directory = root / "data" / config | |
| directory.mkdir(parents=True, exist_ok=True) | |
| for split, examples in rows.items(): | |
| table = pa.Table.from_pylist(examples, schema=SCHEMA) | |
| pq.write_table(table, directory / f"{split}.parquet", compression="zstd", row_group_size=256) | |
| def verify_config(root, config): | |
| module, counts, size = CONFIGS[config] | |
| module.self_test() | |
| group_splits = {} | |
| questions = set() | |
| row_ids = set() | |
| report = {} | |
| family_sets, task_sets = [], [] | |
| for split, expected_groups in zip(SPLITS, counts, strict=True): | |
| path = root / "data" / config / f"{split}.parquet" | |
| table = pq.read_table(path) | |
| require(table.schema.equals(SCHEMA), f"Unexpected schema in {path}") | |
| groups = defaultdict(list) | |
| task_counts, family_counts, variants = Counter(), Counter(), Counter() | |
| step_counts = [] | |
| content = hashlib.sha256() | |
| for row in table.to_pylist(): | |
| require(None not in row.values(), f"Null field in {row['id']}") | |
| require(row["question"] not in questions, f"Duplicate question: {row['id']}") | |
| require(row["id"] not in row_ids, f"Duplicate row ID: {row['id']}") | |
| questions.add(row["question"]) | |
| row_ids.add(row["id"]) | |
| groups[row["group_id"]].append(row) | |
| raw = {k: row[k] for k in ("question", "variant", "task", "family")} | |
| for k in ("instance", "answer", "trace"): | |
| raw[k] = json.loads(row[k + "_json"]) | |
| module.verify(raw) | |
| require(len(raw["trace"]) == row["n_steps"] > 0, f"Bad trace length: {row['id']}") | |
| task_counts[row["task"]] += 1 | |
| family_counts[row["family"]] += 1 | |
| variants[row["variant"]] += 1 | |
| step_counts.append(row["n_steps"]) | |
| content.update((encode(row) + "\n").encode()) | |
| require(len(groups) == expected_groups, f"Group count mismatch in {path}") | |
| for group_id, members in groups.items(): | |
| require(len(members) == size, f"Incomplete group {group_id}") | |
| require(group_id not in group_splits, f"Shared group across splits: {group_id}") | |
| group_splits[group_id] = split | |
| seed = members[0]["source_seed"] | |
| key, originals = module.make_group(seed, split) | |
| digest, assigned = identity(config, key) | |
| require(assigned == split, f"Misassigned seed {seed}") | |
| expected = [pack(raw, config, digest, seed, i) for i, raw in enumerate(originals)] | |
| require(expected == members, f"Seed replay differs in {group_id}") | |
| family_sets.append(set(family_counts)) | |
| task_sets.append(set(task_counts)) | |
| report[split] = { | |
| "rows": len(step_counts), "groups": len(groups), "trace_steps": sum(step_counts), | |
| "min_steps": min(step_counts), "max_steps": max(step_counts), | |
| "families_by_row": dict(sorted(family_counts.items())), | |
| "tasks": dict(sorted(task_counts.items())), "variants": dict(sorted(variants.items())), | |
| "rows_sha256": content.hexdigest(), | |
| "parquet_sha256": hashlib.sha256(path.read_bytes()).hexdigest(), | |
| } | |
| require(family_sets[0] == family_sets[1] == family_sets[2], f"Missing family in {config}") | |
| require(task_sets[0] == task_sets[1] == task_sets[2], f"Missing task in {config}") | |
| return report | |
| def main(): | |
| parser = argparse.ArgumentParser(description=__doc__) | |
| parser.add_argument("action", choices=("build", "verify")) | |
| parser.add_argument("--root", type=Path, default=ROOT, help="Dataset repository or new output directory") | |
| args = parser.parse_args() | |
| root = args.root.resolve() | |
| report = {} | |
| for config in CONFIGS: | |
| if args.action == "build": | |
| build_config(root, config) | |
| report[config] = verify_config(root, config) | |
| manifest = root / "validation_report.json" | |
| if args.action == "build": | |
| manifest.write_text(json.dumps(report, indent=2, ensure_ascii=False) + "\n", encoding="utf-8") | |
| else: | |
| require(json.loads(manifest.read_text(encoding="utf-8")) == report, "Validation manifest differs") | |
| for config, result in report.items(): | |
| print(config, ", ".join(f"{split}={summary['rows']}" for split, summary in result.items())) | |
| if __name__ == "__main__": | |
| main() | |