Datasets:
Download prepare_data_splits.py from lylybig8/routing_analysis-finetuning-data: direct link, hf CLI and curl.
- Browser
- Download file 7.81 kB
-
https://huggingface.co/datasets/lylybig8/routing_analysis-finetuning-data/resolve/main/prepare_data_splits.py
- Command line
-
hf download hf://datasets/lylybig8/routing_analysis-finetuning-data/prepare_data_splits.py
-
curl -L -o prepare_data_splits.py https://huggingface.co/datasets/lylybig8/routing_analysis-finetuning-data/resolve/main/prepare_data_splits.py
7.81 kB
| """ | |
| Build fixed, nested training splits from local FineWeb2-HQ parquet shards. | |
| Sampling strategy (Scheme A — canonical prefix): | |
| 1. Sort parquet shards by filename (e.g. 000_00000.parquet, 000_00001.parquet, …). | |
| 2. Walk rows in that order and assign a global index 0, 1, 2, … | |
| 3. Optionally skip rows with len(text) < min_text_length. | |
| 4. Export the requested nested prefixes. For example: | |
| - {lang}_50k.jsonl = first 50,000 accepted rows | |
| - {lang}_100k.jsonl = first 100,000 accepted rows | |
| - {lang}_500k.jsonl = first 500,000 accepted rows | |
| - {lang}_1000k.jsonl = first 1,000,000 accepted rows | |
| Each JSONL line: {"id": "...", "text": "...", "language": "<lang>"} | |
| (embeddings and other heavy fields are dropped.) | |
| Usage: | |
| python prepare_data_splits.py \ | |
| --data-root /root/userdata/liangyan/routing_analysis/datasets/FineWeb2-HQ \ | |
| --languages dan_Latn \ | |
| --tiers 50000 100000 500000 1000000 \ | |
| --require-full-tiers | |
| """ | |
| from __future__ import annotations | |
| import argparse | |
| import json | |
| from pathlib import Path | |
| import pyarrow.parquet as pq | |
| from tqdm import tqdm | |
| def list_shards(lang_dir: Path) -> list[Path]: | |
| """Return parquet shards sorted by filename (canonical order).""" | |
| return sorted(lang_dir.glob("*.parquet")) | |
| def iter_rows_canonical(lang_dir: Path, min_text_length: int): | |
| """ | |
| Yield (id, text) in canonical shard order. | |
| Rows failing min_text_length are skipped and do not consume a tier slot. | |
| """ | |
| shards = list_shards(lang_dir) | |
| if not shards: | |
| raise FileNotFoundError(f"No parquet files in {lang_dir}") | |
| for shard in shards: | |
| table = pq.read_table(shard, columns=["id", "text"]) | |
| ids = table.column("id").to_pylist() | |
| texts = table.column("text").to_pylist() | |
| for doc_id, text in zip(ids, texts): | |
| if not text or len(text) < min_text_length: | |
| continue | |
| yield doc_id, text | |
| def write_nested_splits( | |
| language: str, | |
| lang_dir: Path, | |
| output_dir: Path, | |
| tiers: list[int], | |
| min_text_length: int, | |
| require_full_tiers: bool = False, | |
| ) -> dict: | |
| """ | |
| Stream canonical rows once and write all nested tier JSONL files. | |
| Returns manifest metadata for this language. | |
| """ | |
| tiers = sorted(set(tiers)) | |
| max_tier = max(tiers) | |
| tier_paths = { | |
| n: output_dir / f"{language}_{_tier_label(n)}.jsonl" for n in tiers | |
| } | |
| files = {n: open(tier_paths[n], "w", encoding="utf-8") for n in tiers} | |
| tier_counts = {n: 0 for n in tiers} | |
| try: | |
| accepted = 0 | |
| for doc_id, text in tqdm( | |
| iter_rows_canonical(lang_dir, min_text_length), | |
| desc=language, | |
| unit="rows", | |
| ): | |
| record = { | |
| "id": doc_id, | |
| "text": text, | |
| "language": language, | |
| } | |
| line = json.dumps(record, ensure_ascii=False) + "\n" | |
| for n in tiers: | |
| if accepted < n: | |
| files[n].write(line) | |
| tier_counts[n] += 1 | |
| accepted += 1 | |
| if accepted >= max_tier: | |
| break | |
| finally: | |
| for fh in files.values(): | |
| fh.close() | |
| short_tiers = { | |
| _tier_label(n): {"target": n, "actual": tier_counts[n]} | |
| for n in tiers | |
| if tier_counts[n] != n | |
| } | |
| if require_full_tiers and short_tiers: | |
| details = ", ".join( | |
| f"{name}: {counts['actual']:,}/{counts['target']:,}" | |
| for name, counts in short_tiers.items() | |
| ) | |
| raise RuntimeError( | |
| f"Insufficient accepted rows for {language}; incomplete tiers: {details}" | |
| ) | |
| manifest = { | |
| "language": language, | |
| "strategy": "canonical_prefix", | |
| "seed": None, | |
| "filters": {"min_text_length": min_text_length}, | |
| "source": str(lang_dir), | |
| "tiers": { | |
| _tier_label(n): { | |
| "target_count": n, | |
| "actual_count": tier_counts[n], | |
| "path": str(tier_paths[n]), | |
| "nested_in": [ | |
| _tier_label(m) for m in tiers if m > n | |
| ], | |
| } | |
| for n in tiers | |
| }, | |
| "accepted_rows_scanned": accepted, | |
| } | |
| manifest_path = output_dir / f"{language}_manifest.json" | |
| with open(manifest_path, "w", encoding="utf-8") as f: | |
| json.dump(manifest, f, indent=2, ensure_ascii=False) | |
| return manifest | |
| def _tier_label(n: int) -> str: | |
| if n >= 1000 and n % 1000 == 0: | |
| return f"{n // 1000}k" | |
| return str(n) | |
| def main(): | |
| parser = argparse.ArgumentParser( | |
| description="Build fixed nested JSONL splits (Scheme A: canonical prefix)." | |
| ) | |
| parser.add_argument( | |
| "--data-root", | |
| type=Path, | |
| default=Path( | |
| "/root/userdata/liangyan/routing_analysis/datasets/FineWeb2-HQ" | |
| ), | |
| help="Root directory with one subdirectory per language.", | |
| ) | |
| parser.add_argument( | |
| "--output-dir", | |
| type=Path, | |
| default=Path(__file__).resolve().parent / "splits", | |
| help="Where to write JSONL splits and per-language manifests.", | |
| ) | |
| parser.add_argument( | |
| "--languages", | |
| nargs="+", | |
| default=["dan_Latn", "fas_Arab", "swe_Latn"], | |
| help="Language subdirectory names under data-root.", | |
| ) | |
| parser.add_argument( | |
| "--tiers", | |
| type=int, | |
| nargs="+", | |
| default=[50_000, 100_000, 500_000], | |
| help=( | |
| "Nested sample counts " | |
| "(e.g. 50000 100000 500000 1000000)." | |
| ), | |
| ) | |
| parser.add_argument( | |
| "--min-text-length", | |
| type=int, | |
| default=100, | |
| help="Skip rows with fewer characters than this (default: 100).", | |
| ) | |
| parser.add_argument( | |
| "--require-full-tiers", | |
| action="store_true", | |
| help=( | |
| "Fail instead of writing manifests when any requested tier has " | |
| "fewer accepted rows than its target." | |
| ), | |
| ) | |
| args = parser.parse_args() | |
| args.output_dir.mkdir(parents=True, exist_ok=True) | |
| print("Scheme A: canonical parquet order + nested prefix splits") | |
| print(f" data root: {args.data_root}") | |
| print(f" output dir: {args.output_dir}") | |
| print(f" languages: {', '.join(args.languages)}") | |
| print(f" tiers: {args.tiers}") | |
| print(f" min text: {args.min_text_length} chars") | |
| print() | |
| all_manifests = {} | |
| for lang in args.languages: | |
| lang_dir = args.data_root / lang | |
| if not lang_dir.is_dir(): | |
| if args.require_full_tiers: | |
| raise FileNotFoundError( | |
| f"Requested language directory is missing: {lang_dir}" | |
| ) | |
| print(f"[skip] missing directory: {lang_dir}") | |
| continue | |
| manifest = write_nested_splits( | |
| language=lang, | |
| lang_dir=lang_dir, | |
| output_dir=args.output_dir, | |
| tiers=args.tiers, | |
| min_text_length=args.min_text_length, | |
| require_full_tiers=args.require_full_tiers, | |
| ) | |
| all_manifests[lang] = manifest | |
| print(f"[done] {lang}:") | |
| for tier_name, info in manifest["tiers"].items(): | |
| print(f" {tier_name}: {info['actual_count']:,} rows → {info['path']}") | |
| summary_path = args.output_dir / "splits_summary.json" | |
| with open(summary_path, "w", encoding="utf-8") as f: | |
| json.dump( | |
| { | |
| "strategy": "canonical_prefix", | |
| "languages": all_manifests, | |
| }, | |
| f, | |
| indent=2, | |
| ensure_ascii=False, | |
| ) | |
| print(f"\nSummary written to: {summary_path}") | |
| if __name__ == "__main__": | |
| main() | |