dist_methods / code /prepare_fineweb_text.py
Ilikemechuri's picture
Add distributed training experiment code and results
bbf3a52 verified
Raw History Blame Contribute Delete
5.9 kB
#!/usr/bin/env python3
"""Cache a small raw-text FineWeb sample with document-level held-out splits."""
from __future__ import annotations
import hashlib
import json
import shutil
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"
TARGET_BYTES = {
"train": 392_000_000,
"val": 4_000_000,
"test": 4_000_000,
}
OUTPUT_DIR = Path("/workspace/data/fineweb_text")
STAGING_DIR = OUTPUT_DIR.with_name(OUTPUT_DIR.name + ".partial")
def normalized_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_DIR.exists():
raise SystemExit(f"Refusing to overwrite existing cache: {OUTPUT_DIR}")
if STAGING_DIR.exists():
raise SystemExit(f"Partial cache already exists; inspect or remove it: {STAGING_DIR}")
STAGING_DIR.parent.mkdir(parents=True, exist_ok=True)
STAGING_DIR.mkdir()
written = {split: 0 for split in TARGET_BYTES}
documents = {split: 0 for split in TARGET_BYTES}
selected_hashes: set[bytes] = set()
source_rows = 0
source_text_bytes = 0
next_progress = 50_000_000
handles = {
split: (STAGING_DIR / f"{split}.txt").open("wb")
for split in TARGET_BYTES
}
try:
dataset = load_dataset(
DATASET_ID,
name=DATASET_CONFIG,
split="train",
streaming=True,
revision=DATASET_REVISION,
)
for row in dataset:
source_rows += 1
text = row.get("text") or ""
if not text.strip():
continue
encoded = text.encode("utf-8") + b"\n\n"
source_text_bytes += len(encoded)
content_hash = normalized_content_hash(text)
if content_hash in selected_hashes:
continue
bucket = int.from_bytes(content_hash[:8], "big") % 100
split = "val" if bucket == 0 else "test" if bucket == 1 else "train"
if written[split] >= TARGET_BYTES[split]:
continue
handles[split].write(encoded)
written[split] += len(encoded)
documents[split] += 1
selected_hashes.add(content_hash)
total_written = sum(written.values())
if total_written >= next_progress:
print(
f"cached={total_written:,} bytes; "
f"train={written['train']:,}, val={written['val']:,}, "
f"test={written['test']:,}; source_rows={source_rows:,}",
flush=True,
)
next_progress += 50_000_000
if all(written[split] >= TARGET_BYTES[split] for split in TARGET_BYTES):
break
finally:
for handle in handles.values():
handle.flush()
handle.close()
incomplete = {
split: TARGET_BYTES[split] - written[split]
for split in TARGET_BYTES
if written[split] < TARGET_BYTES[split]
}
if incomplete:
raise RuntimeError(
f"Dataset stream ended before byte targets were met: {incomplete}; "
f"partial output is at {STAGING_DIR}"
)
files = {}
for split in TARGET_BYTES:
path = STAGING_DIR / f"{split}.txt"
files[path.name] = {
"bytes": path.stat().st_size,
"documents": documents[split],
"sha256": sha256_file(path),
}
manifest = {
"created_utc": datetime.now(timezone.utc).isoformat(),
"dataset": DATASET_ID,
"config": DATASET_CONFIG,
"source_split": "train",
"revision": DATASET_REVISION,
"license": "ODC-BY",
"tokenizer_used": False,
"sizing_basis": "UTF-8 output bytes; FineWeb token_count was not used",
"split_method": (
"SHA-256 of NFKC-normalized, whitespace-collapsed document text; "
"hash mod 100: 0=val, 1=test, 2-99=train; exact normalized duplicates skipped"
),
"format": "UTF-8 plain text; source document text followed by two newline bytes",
"target_bytes": TARGET_BYTES,
"actual_files": files,
"source_rows_scanned": source_rows,
"source_text_bytes_scanned": source_text_bytes,
"total_output_bytes": sum(item["bytes"] for item in files.values()),
}
(STAGING_DIR / "manifest.json").write_text(
json.dumps(manifest, indent=2, ensure_ascii=False) + "\n",
encoding="utf-8",
)
(STAGING_DIR / "README.md").write_text(
"# FineWeb raw-text cache\n\n"
"Source: [HuggingFaceFW/fineweb](https://huggingface.co/datasets/HuggingFaceFW/fineweb), "
"`sample-10BT` configuration, pinned to the revision in `manifest.json`. "
"FineWeb is published under ODC-BY.\n\n"
"No tokenizer was used. `train.txt`, `val.txt`, and `test.txt` contain raw "
"UTF-8 text, with source documents separated by blank lines. Splits use a "
"stable content hash so identical normalized documents cannot cross splits. "
"The byte targets are approximate because whole documents are retained.\n",
encoding="utf-8",
)
STAGING_DIR.rename(OUTPUT_DIR)
print(json.dumps(manifest, indent=2, ensure_ascii=False), flush=True)
print(f"cache_ready={OUTPUT_DIR}", flush=True)
if __name__ == "__main__":
main()