dist_methods / code /prepare_fineweb_ext_val.py
Ilikemechuri's picture
Add distributed training experiment code and results
bbf3a52 verified
Raw History Blame Contribute Delete
6.93 kB
#!/usr/bin/env python3
"""Append about 100 MB of non-overlapping FineWeb text as an extended val set."""
from __future__ import annotations
import hashlib
import json
import unicodedata
from datetime import datetime, timezone
from pathlib import Path
from datasets import load_dataset
DATASET_ID = "HuggingFaceFW/fineweb"
DATASET_CONFIG = "sample-10BT"
DATASET_REVISION = "9bb295ddab0e05d785b879661af7260fed5140fc"
DATA_DIR = Path("/workspace/data/fineweb_text")
MAIN_MANIFEST = DATA_DIR / "manifest.json"
OUTPUT_PATH = DATA_DIR / "ext_val.txt"
PARTIAL_PATH = DATA_DIR / "ext_val.txt.partial"
TARGET_BYTES = 100_000_000
OLD_TARGETS = {"train": 392_000_000, "val": 4_000_000, "test": 4_000_000}
def content_hash(text: str) -> bytes:
canonical = " ".join(unicodedata.normalize("NFKC", text).split())
return hashlib.sha256(canonical.encode("utf-8")).digest()
def sha256_file(path: Path) -> str:
digest = hashlib.sha256()
with path.open("rb") as handle:
for chunk in iter(lambda: handle.read(8 * 1024 * 1024), b""):
digest.update(chunk)
return digest.hexdigest()
def main() -> None:
if OUTPUT_PATH.exists() or PARTIAL_PATH.exists():
raise SystemExit(f"ext_val output already exists: {OUTPUT_PATH} or {PARTIAL_PATH}")
previous = json.loads(MAIN_MANIFEST.read_text(encoding="utf-8"))
cutoff_rows = int(previous["source_rows_scanned"])
expected = previous["actual_files"]
dataset = load_dataset(
DATASET_ID,
name=DATASET_CONFIG,
split="train",
streaming=True,
revision=DATASET_REVISION,
)
old_written = {split: 0 for split in OLD_TARGETS}
old_documents = {split: 0 for split in OLD_TARGETS}
old_hashes: set[bytes] = set()
source_rows = 0
ext_written = 0
ext_documents = 0
progress_mark = 10_000_000
replay_checked = False
with PARTIAL_PATH.open("wb") as output:
for row in dataset:
source_rows += 1
text = row.get("text") or ""
if source_rows <= cutoff_rows:
if not text.strip():
continue
encoded = text.encode("utf-8") + b"\n\n"
digest = content_hash(text)
if digest in old_hashes:
continue
bucket = int.from_bytes(digest[:8], "big") % 100
split = "val" if bucket == 0 else "test" if bucket == 1 else "train"
if old_written[split] >= OLD_TARGETS[split]:
continue
old_written[split] += len(encoded)
old_documents[split] += 1
old_hashes.add(digest)
if source_rows == cutoff_rows:
for split_name in OLD_TARGETS:
recorded = expected[f"{split_name}.txt"]
if (
old_written[split_name] != recorded["bytes"]
or old_documents[split_name] != recorded["documents"]
):
raise RuntimeError(
"Could not reproduce the existing cached split selection; "
f"mismatch in {split_name}: "
f"bytes={old_written[split_name]} vs {recorded['bytes']}, "
f"docs={old_documents[split_name]} vs {recorded['documents']}"
)
replay_checked = True
print(
f"reproduced existing selection: rows={cutoff_rows:,}, "
f"documents={sum(old_documents.values()):,}; continuing stream",
flush=True,
)
continue
if not replay_checked:
raise RuntimeError("Existing FineWeb selection replay was not verified")
if not text.strip():
continue
digest = content_hash(text)
if digest in old_hashes:
continue
encoded = text.encode("utf-8") + b"\n\n"
output.write(encoded)
ext_written += len(encoded)
ext_documents += 1
old_hashes.add(digest)
if ext_written >= progress_mark:
print(
f"ext_val={ext_written:,} bytes, documents={ext_documents:,}, "
f"source_rows={source_rows:,}",
flush=True,
)
progress_mark += 10_000_000
if ext_written >= TARGET_BYTES:
break
output.flush()
if not replay_checked:
raise RuntimeError("FineWeb stream ended before the existing cache was reproduced")
if ext_written < TARGET_BYTES:
raise RuntimeError(
f"FineWeb stream ended at {ext_written:,} bytes; partial file remains at {PARTIAL_PATH}"
)
PARTIAL_PATH.rename(OUTPUT_PATH)
extension = {
"created_utc": datetime.now(timezone.utc).isoformat(),
"dataset": DATASET_ID,
"config": DATASET_CONFIG,
"revision": DATASET_REVISION,
"source_split": "train",
"license": "ODC-BY",
"tokenizer_used": False,
"target_bytes": TARGET_BYTES,
"file": OUTPUT_PATH.name,
"bytes": OUTPUT_PATH.stat().st_size,
"documents": ext_documents,
"sha256": sha256_file(OUTPUT_PATH),
"overlap_policy": (
"Replayed and verified the original train/val/test selection from the pinned "
"stream, then excluded identical NFKC-normalized, whitespace-collapsed text"
),
"source_rows_replayed": cutoff_rows,
"source_rows_scanned_through": source_rows,
"format": "UTF-8 plain text; source documents separated by blank lines",
}
(DATA_DIR / "ext_val_manifest.json").write_text(
json.dumps(extension, indent=2, ensure_ascii=False) + "\n",
encoding="utf-8",
)
previous["extended_validation"] = extension
previous["total_output_bytes_including_ext_val"] = (
previous["total_output_bytes"] + extension["bytes"]
)
MAIN_MANIFEST.write_text(
json.dumps(previous, indent=2, ensure_ascii=False) + "\n",
encoding="utf-8",
)
readme = DATA_DIR / "README.md"
with readme.open("a", encoding="utf-8") as handle:
handle.write(
"\n`ext_val.txt` is an additional ~100 MB held-out text set. It was "
"collected from later rows of the same pinned FineWeb sample, with "
"normalized exact-text overlap against the original splits excluded. "
"See `ext_val_manifest.json` for its checksum and byte count.\n"
)
print(json.dumps(extension, indent=2, ensure_ascii=False), flush=True)
print(f"ext_val_ready={OUTPUT_PATH}", flush=True)
if __name__ == "__main__":
main()