Download scripts/reference-packer/pack_trajectory_dataset.py from LingweiGu/v17_astra: direct link, hf CLI and curl.
- Browser
- Download file 11.5 kB
-
https://huggingface.co/datasets/LingweiGu/v17_astra/resolve/main/scripts/reference-packer/pack_trajectory_dataset.py
- Command line
-
hf download hf://datasets/LingweiGu/v17_astra/scripts/reference-packer/pack_trajectory_dataset.py
-
curl -L -o pack_trajectory_dataset.py https://huggingface.co/datasets/LingweiGu/v17_astra/resolve/main/scripts/reference-packer/pack_trajectory_dataset.py
11.5 kB
| """Pack pre-tokenized trajectories (input_ids + labels per row, Parquet) into our training layout. | |
| Input: a curated export such as openswe-success-sft (train/*.parquet, validation/*.parquet) | |
| whose rows already hold MiniCPM token ids and assistant-only labels (-100 elsewhere). | |
| Nothing is re-tokenized or re-templated. Output: a `datasets` save_to_disk directory with | |
| `train` and `validation` splits in the same packed schema as stage 1 (input_ids, labels, | |
| attention_mask = per-sample segment ids, position_ids restarting at 0 per sample), plus | |
| `pack-costs.npz` for the balanced sampler and a receipt with every count. | |
| - Rows are validated (lengths, label/input agreement, first label masked, supervised count). | |
| - Rows are shuffled deterministically inside each source file, then packed greedily into | |
| ~pack_target tokens within that file (files run in parallel); a row longer than | |
| pack_target is its own pack. No row is split, truncated or dropped (except by the | |
| optional per-task attempt cap). | |
| - `validation` holds a small deterministic subset for periodic eval; the full validation | |
| split is written separately under `validation-full/`. | |
| - The nanocode data-mix layout (v1-v3: `id`, `repeat`, `num_tokens`, `num_loss_tokens`) is also | |
| accepted. Its rows are already globally shuffled by the builder, so they are streamed in file | |
| order (bounded memory); the key `id#repeat` keeps repeated records distinct. | |
| """ | |
| import argparse | |
| import hashlib | |
| import json | |
| import sys | |
| import time | |
| from collections import Counter | |
| from concurrent.futures import ProcessPoolExecutor | |
| from pathlib import Path | |
| import numpy as np | |
| import pyarrow.parquet as pq | |
| from datasets import DatasetInfo, load_from_disk | |
| from datasets.arrow_writer import ArrowWriter | |
| sys.path.insert(0, str(Path(__file__).resolve().parent)) | |
| from data_codec import IGNORE, pack_items # noqa: E402 | |
| from prepare_dataset import FEATURES # noqa: E402 | |
| COLUMNS = ["trajectory_id", "instance_id", "token_count", "supervised_tokens", "input_ids", "labels"] | |
| def h64(text, seed): | |
| return int(hashlib.sha256(f"{seed}:{text}".encode()).hexdigest()[:16], 16) | |
| MIX_COLUMNS = ["id", "repeat", "num_tokens", "num_loss_tokens", "input_ids", "labels"] | |
| def is_mix(path): | |
| return "trajectory_id" not in pq.read_schema(path).names | |
| def from_mix(r): | |
| return {"trajectory_id": f"{r['id']}#{r['repeat']}", "instance_id": None, "token_count": r["num_tokens"], | |
| "supervised_tokens": r["num_loss_tokens"], "input_ids": r["input_ids"], "labels": r["labels"]} | |
| def iter_rows(path, seed): | |
| """Curated exports: whole file, deterministic shuffle. Mix shards: already shuffled, streamed.""" | |
| if is_mix(path): | |
| for batch in pq.ParquetFile(path).iter_batches(batch_size=256, columns=MIX_COLUMNS): | |
| yield from map(from_mix, batch.to_pylist()) | |
| return | |
| table = pq.read_table(path, columns=COLUMNS).to_pylist() | |
| table.sort(key=lambda r: h64(r["trajectory_id"], seed)) | |
| yield from table | |
| def trajectory_ids(path): | |
| if is_mix(path): | |
| t = pq.read_table(path, columns=["id", "repeat"]).to_pylist() | |
| return [{"trajectory_id": f"{r['id']}#{r['repeat']}"} for r in t] | |
| return pq.read_table(path, columns=["trajectory_id"]).to_pylist() | |
| def check(row, max_len): | |
| ids, labels = row["input_ids"], row["labels"] | |
| n = len(ids) | |
| if n != len(labels) or n != row["token_count"] or n > max_len: | |
| raise ValueError(f"{row['trajectory_id']}: bad length {n}/{len(labels)}/{row['token_count']}") | |
| lab = np.asarray(labels, dtype=np.int64) | |
| arr = np.asarray(ids, dtype=np.int64) | |
| sup = lab != IGNORE | |
| if int(sup.sum()) != row["supervised_tokens"] or int(sup.sum()) == 0: | |
| raise ValueError(f"{row['trajectory_id']}: supervised count mismatch") | |
| if not np.array_equal(lab[sup], arr[sup]) or lab[0] != IGNORE: | |
| raise ValueError(f"{row['trajectory_id']}: labels disagree with input_ids or first label unmasked") | |
| def pack_file(job): | |
| """Validate, shuffle and pack one source file into its own Arrow part.""" | |
| path, part, seed, keep, max_len, pack_target = job | |
| stats = {"rows": 0, "packs": 0, "tokens": 0, "supervised": 0, "dropped_by_attempt_cap": 0} | |
| tokens, sum_sq, segments = [], [], [] | |
| writer = ArrowWriter(path=str(part), features=FEATURES, writer_batch_size=8) | |
| buffer, buffer_tokens = [], 0 | |
| def emit(items): | |
| for pack in pack_items(items, target=pack_target): | |
| writer.write(pack) | |
| seg = np.bincount(np.asarray(pack["attention_mask"]))[1:] | |
| tokens.append(len(pack["input_ids"])) | |
| sum_sq.append(int((seg.astype(np.int64) ** 2).sum())) | |
| segments.append(int((seg > 0).sum())) | |
| stats["packs"] += 1 | |
| for row in iter_rows(path, seed): | |
| if keep is not None and row["trajectory_id"] not in keep: | |
| stats["dropped_by_attempt_cap"] += 1 | |
| continue | |
| check(row, max_len) | |
| item = {"input_ids": row["input_ids"], "labels": row["labels"]} | |
| n = len(item["input_ids"]) | |
| stats["rows"] += 1 | |
| stats["tokens"] += n | |
| stats["supervised"] += row["supervised_tokens"] | |
| if buffer and buffer_tokens + n > pack_target: | |
| emit(buffer) | |
| buffer, buffer_tokens = [], 0 | |
| buffer.append(item) | |
| buffer_tokens += n | |
| if buffer_tokens >= pack_target: | |
| emit(buffer) | |
| buffer, buffer_tokens = [], 0 | |
| if buffer: | |
| emit(buffer) | |
| writer.finalize() | |
| return str(part), stats, np.asarray(tokens, np.int64), np.asarray(sum_sq, np.int64), np.asarray(segments, np.int64) | |
| def write_split(files, out_dir, seed, keep, max_len, pack_target, workers): | |
| """Pack files in parallel and lay the parts out exactly as DatasetDict.save_to_disk would.""" | |
| out_dir.mkdir(parents=True) | |
| jobs = [(f, out_dir / f"part-{i:05d}.arrow", seed, keep, max_len, pack_target) for i, f in enumerate(files)] | |
| with ProcessPoolExecutor(workers) as pool: | |
| results = list(pool.map(pack_file, jobs)) # in file order | |
| stats = {k: sum(r[1][k] for r in results) for k in results[0][1]} | |
| kept = [r for r in results if r[1]["packs"] > 0] | |
| for r in results: | |
| if r[1]["packs"] == 0: | |
| Path(r[0]).unlink() | |
| files_out = [] | |
| for i, r in enumerate(kept): | |
| final = out_dir / f"data-{i:05d}-of-{len(kept):05d}.arrow" | |
| Path(r[0]).rename(final) | |
| files_out.append({"filename": final.name}) | |
| DatasetInfo(features=FEATURES).write_to_directory(str(out_dir)) | |
| state = {"_data_files": files_out, "_fingerprint": hashlib.sha256(json.dumps([out_dir.name, stats]).encode()).hexdigest()[:16], | |
| "_format_columns": ["attention_mask", "input_ids", "labels", "position_ids"], "_format_kwargs": {}, | |
| "_format_type": None, "_output_all_columns": False, "_split": None} | |
| (out_dir / "state.json").write_text(json.dumps(state, indent=2) + "\n") | |
| return (stats, np.concatenate([r[2] for r in kept]), np.concatenate([r[3] for r in kept]), | |
| np.concatenate([r[4] for r in kept])) | |
| def main(): | |
| ap = argparse.ArgumentParser() | |
| ap.add_argument("--src", type=Path, required=True, help="curated export with train/ and validation/ Parquet") | |
| ap.add_argument("--out", type=Path, required=True) | |
| ap.add_argument("--pack-target", type=int, default=32768) | |
| ap.add_argument("--max-len", type=int, default=131072) | |
| ap.add_argument("--seed", type=int, default=20260926) | |
| ap.add_argument("--max-attempts-per-task", type=int, default=0, help="0 = keep every trajectory") | |
| ap.add_argument("--periodic-validation", type=int, default=64, help="trajectories in the periodic-eval subset") | |
| ap.add_argument("--workers", type=int, default=16) | |
| args = ap.parse_args() | |
| if args.out.exists(): | |
| raise RuntimeError(f"{args.out} exists; never overwrite a training input") | |
| staging = args.out.with_name(args.out.name + ".partial") | |
| if staging.exists(): | |
| raise RuntimeError(f"{staging} exists from an interrupted run; inspect and remove it first") | |
| t0 = time.time() | |
| train_files = sorted((args.src / "train").glob("*.parquet")) | |
| val_files = sorted((args.src / "validation").glob("*.parquet")) | |
| keep = None | |
| if args.max_attempts_per_task: | |
| meta = [r for f in train_files for r in pq.read_table(f, columns=["trajectory_id", "instance_id"]).to_pylist()] | |
| meta.sort(key=lambda r: h64(r["trajectory_id"], args.seed)) | |
| seen, keep = Counter(), set() | |
| for r in meta: | |
| if seen[r["instance_id"]] < args.max_attempts_per_task: | |
| seen[r["instance_id"]] += 1 | |
| keep.add(r["trajectory_id"]) | |
| train_stats, tok, sq, seg = write_split(train_files, staging / "train", args.seed, keep, args.max_len, | |
| args.pack_target, args.workers) | |
| # Periodic eval: deterministic subset of the (repository-disjoint) validation split. | |
| val_meta = [r for f in val_files for r in trajectory_ids(f)] | |
| val_meta.sort(key=lambda r: h64(r["trajectory_id"], args.seed)) | |
| subset = {r["trajectory_id"] for r in val_meta[:args.periodic_validation]} | |
| val_stats, *_ = write_split(val_files, staging / "validation", args.seed, subset, args.max_len, | |
| args.pack_target, args.workers) | |
| full_stats, *_ = write_split(val_files, staging / "validation-full" / "validation", args.seed, None, args.max_len, | |
| args.pack_target, args.workers) | |
| (staging / "dataset_dict.json").write_text(json.dumps({"splits": ["train", "validation"]}) + "\n") | |
| (staging / "validation-full" / "dataset_dict.json").write_text(json.dumps({"splits": ["validation"]}) + "\n") | |
| np.savez(staging / "pack-costs.npz", tokens=tok, sum_sq=sq, segments=seg) | |
| # Verify through the loader the trainer uses; pack i of the dataset must be cost row i. | |
| dd = load_from_disk(str(staging)) | |
| assert len(dd["train"]) == train_stats["packs"] == tok.size and len(dd["validation"]) == val_stats["packs"] | |
| for i in [0, tok.size // 2, tok.size - 1]: | |
| row = dd["train"][int(i)] | |
| assert len(row["input_ids"]) == tok[i] and row["position_ids"][0] == 0 | |
| receipt = {"source": str(args.src.resolve()), | |
| "source_manifest_sha256": hashlib.sha256((args.src / "manifest.json").read_bytes()).hexdigest() | |
| if (args.src / "manifest.json").exists() else None, | |
| "packer_sha256": hashlib.sha256(Path(__file__).read_bytes()).hexdigest(), | |
| "pack_target": args.pack_target, "max_len": args.max_len, "seed": args.seed, | |
| "max_attempts_per_task": args.max_attempts_per_task or None, | |
| "dropped_by_attempt_cap": train_stats["dropped_by_attempt_cap"], | |
| "train": train_stats, "validation_periodic": val_stats, "validation_full": full_stats, | |
| "train_pack_tokens": {"mean": float(tok.mean()), "p50": int(np.percentile(tok, 50)), "p90": int(np.percentile(tok, 90)), | |
| "max": int(tok.max()), "over_65536": int((tok > 65536).sum()), "single_segment": int((seg == 1).sum())}, | |
| "pack_costs_sha256": hashlib.sha256((staging / "pack-costs.npz").read_bytes()).hexdigest(), | |
| "elapsed_s": round(time.time() - t0, 1)} | |
| (staging / "receipt.json").write_text(json.dumps(receipt, indent=2) + "\n") | |
| staging.rename(args.out) | |
| print(json.dumps(receipt), flush=True) | |
| if __name__ == "__main__": | |
| main() | |