File size: 5,897 Bytes
bbf3a52 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 | #!/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()
|