xuan-luo's picture
download
raw
10.2 kB
#!/usr/bin/env python3
"""Build non-overlapping views into the existing tokenized FineWeb-Edu .bin.
CPU only. No source tokens are copied. The GPTDataset sample/shuffle indices
from the *entire planned* 2K run determine which physical token intervals are
excluded. Every generated .idx points at disjoint, unvisited intervals in the
original .bin; each companion .bin is only a symlink.
"""
import hashlib
import json
import math
import os
import struct
from pathlib import Path
import numpy as np
ROOT = Path(__file__).resolve().parents[3]
HERE = Path(__file__).resolve().parent
DATA = HERE / "data"
SOURCE = ROOT / "dataset/megatron/fineweb_edu_100b_train"
VALID = ROOT / "dataset/megatron/fineweb_edu_100b_valid"
CACHE = ROOT / "dataset/cache/a79ad58419d4cc6b8f4550b21354332f-GPTDataset-train"
TRAIN_2K_SAMPLES = 19074 * 256
SEQ_2K = 2048
STAGES = [
("smoke_8k_from_2k", 3 * 64 * 8192 + 1_000_000),
("smoke_32k_from_2k", 3 * 16 * 32768 + 1_000_000),
("smoke_32k_from_8k", 3 * 16 * 32768 + 1_000_000),
("train_8k", 1908 * 64 * 8192 + 10_000_000),
("train_32k", 1908 * 16 * 32768 + 10_000_000),
]
def sha256(path: Path) -> str:
digest = hashlib.sha256()
with path.open("rb") as stream:
while chunk := stream.read(1 << 20):
digest.update(chunk)
return digest.hexdigest()
def source_index():
path = SOURCE.with_suffix(".idx")
with path.open("rb") as stream:
assert stream.read(9) == b"MMIDIDX\x00\x00"
assert struct.unpack("<Q", stream.read(8))[0] == 1
dtype_code = struct.unpack("<B", stream.read(1))[0]
count = struct.unpack("<Q", stream.read(8))[0]
document_count = struct.unpack("<Q", stream.read(8))[0]
itemsize = {8: 2, 4: 4}[dtype_code]
lengths = np.memmap(path, mode="r", dtype=np.int32, offset=34, shape=(count,))
pointers = np.memmap(path, mode="r", dtype=np.int64, offset=34 + 4 * count, shape=(count,))
document_indices = np.memmap(
path, mode="r", dtype=np.int64, offset=34 + 12 * count, shape=(document_count,)
)
assert document_count == count + 1
assert np.array_equal(document_indices, np.arange(document_count))
assert int(pointers[-1]) + int(lengths[-1]) * itemsize == SOURCE.with_suffix(".bin").stat().st_size
return dtype_code, itemsize, lengths, pointers
def write_view(name: str, segments: list[dict], dtype_code: int) -> dict:
prefix = DATA / name
idx = prefix.with_suffix(".idx")
bin_link = prefix.with_suffix(".bin")
lengths = np.asarray([s["length_tokens"] for s in segments], dtype=np.int32)
pointers = np.asarray([s["source_byte_offset"] for s in segments], dtype=np.int64)
documents = np.arange(len(segments) + 1, dtype=np.int64)
tmp = idx.with_suffix(".idx.tmp")
with tmp.open("wb") as out:
out.write(b"MMIDIDX\x00\x00")
out.write(struct.pack("<Q", 1))
out.write(struct.pack("<B", dtype_code))
out.write(struct.pack("<QQ", len(segments), len(documents)))
out.write(lengths.tobytes())
out.write(pointers.tobytes())
out.write(documents.tobytes())
os.replace(tmp, idx)
if bin_link.is_symlink():
assert bin_link.resolve() == SOURCE.with_suffix(".bin").resolve()
elif not bin_link.exists():
bin_link.symlink_to(SOURCE.with_suffix(".bin").resolve())
else:
raise RuntimeError(f"Refusing to overwrite existing {bin_link}")
segment_path = DATA / f"{name}.segments.jsonl"
with segment_path.open("w") as out:
for segment in segments:
out.write(json.dumps(segment, sort_keys=True) + "\n")
return {
"prefix": str(prefix.relative_to(ROOT)),
"index_sha256": sha256(idx),
"segments_file": str(segment_path.relative_to(ROOT)),
"segments_sha256": sha256(segment_path),
"segment_count": len(segments),
"allocated_source_tokens": int(lengths.astype(np.int64).sum()),
"first_sample_slot": segments[0]["sample_slot_start"],
"last_sample_slot_exclusive": segments[-1]["sample_slot_end_exclusive"],
}
def main() -> None:
DATA.mkdir(parents=True, exist_ok=True)
description_path = Path(str(CACHE) + "-description.txt")
description = json.loads(description_path.read_text())
assert Path(description["dataset_path"]).resolve() == SOURCE.resolve()
assert description["num_samples"] == TRAIN_2K_SAMPLES
assert description["sequence_length"] == SEQ_2K
assert description["random_seed"] == 5000
assert description["index_split"] == "train"
assert not os.path.samefile(SOURCE.with_suffix(".bin"), VALID.with_suffix(".bin"))
dtype_code, itemsize, source_lengths, source_pointers = source_index()
document_index = np.load(str(CACHE) + "-document_index.npy", mmap_mode="r")
sample_index = np.load(str(CACHE) + "-sample_index.npy", mmap_mode="r")
shuffle_index = np.load(str(CACHE) + "-shuffle_index.npy", mmap_mode="r")
assert len(document_index) == len(source_lengths)
assert len(np.unique(document_index)) == len(document_index), "source documents repeat"
assert len(shuffle_index) == len(sample_index) - 1
assert len(shuffle_index) > TRAIN_2K_SAMPLES
# The single dataloader consumes logical indices [0, TRAIN_2K_SAMPLES),
# mapped through shuffle_index. A sample reads 2048+1 source tokens; its
# immediate neighbors can overlap that extra label token, so exclude both.
used = np.asarray(shuffle_index[:TRAIN_2K_SAMPLES], dtype=np.int64).copy()
used.sort()
assert np.all(used[1:] > used[:-1]), "shuffle prefix contains duplicates"
used_hash = hashlib.sha256(used.tobytes()).hexdigest()
starts = np.maximum(np.concatenate((np.array([-2]), used)) + 2, 0)
ends = np.minimum(np.concatenate((used, np.array([len(shuffle_index) + 1]))) - 1, len(shuffle_index))
stage_segments: dict[str, list[dict]] = {name: [] for name, _ in STAGES}
stage_tokens = {name: 0 for name, _ in STAGES}
stage_idx = 0
for start, end in zip(starts, ends):
if stage_idx == len(STAGES):
break
if end - start < 18: # each view segment is longer than 32K+label
continue
start, end = int(start), int(end)
first_doc_pos, start_offset = map(int, sample_index[start])
end_doc_pos, end_offset = map(int, sample_index[end])
if first_doc_pos != end_doc_pos:
continue
source_doc = int(document_index[first_doc_pos])
length = end_offset - start_offset + 1
if length != (end - start) * SEQ_2K + 1:
continue
if end_offset + 1 > int(source_lengths[source_doc]):
continue
segment = {
"source_document_id": source_doc,
"source_token_offset": start_offset,
"length_tokens": length,
"source_byte_offset": int(source_pointers[source_doc]) + start_offset * itemsize,
"sample_slot_start": start,
"sample_slot_end_exclusive": end,
}
name, target = STAGES[stage_idx]
stage_segments[name].append(segment)
stage_tokens[name] += length
if stage_tokens[name] >= target:
stage_idx += 1
assert stage_idx == len(STAGES), f"not enough unvisited source tokens: {stage_tokens}"
# A second, physical-coordinate audit protects against mistakes in the
# source document permutation and enforces stage-to-stage disjointness.
all_intervals = []
for name, segments in stage_segments.items():
for s in segments:
all_intervals.append((s["source_document_id"], s["source_token_offset"], s["source_token_offset"] + s["length_tokens"], name))
all_intervals.sort()
for previous, current in zip(all_intervals, all_intervals[1:]):
if previous[0] == current[0]:
assert previous[2] < current[1], f"overlapping or touching stage intervals: {previous} {current}"
stages = {}
for name, target in STAGES:
stages[name] = write_view(name, stage_segments[name], dtype_code)
stages[name]["minimum_allocated_source_tokens"] = target
manifest = {
"schema": 1,
"source_bin": str(SOURCE.with_suffix(".bin")),
"source_bin_bytes": SOURCE.with_suffix(".bin").stat().st_size,
"source_idx": str(SOURCE.with_suffix(".idx")),
"source_idx_sha256": sha256(SOURCE.with_suffix(".idx")),
"valid_bin": str(VALID.with_suffix(".bin")),
"validation_source_is_separate_file": True,
"original_2k_config": "training/kvpath/train_10b_lr_1e-3/config.toml",
"original_2k_train_iters": 19074,
"original_2k_global_batch": 256,
"original_2k_sequence_length": 2048,
"original_2k_planned_samples": TRAIN_2K_SAMPLES,
"original_2k_planned_tokens": TRAIN_2K_SAMPLES * SEQ_2K,
"original_2k_extra_label_token_per_sample": True,
"original_2k_dataset_description": str(description_path),
"original_2k_dataset_description_sha256": sha256(description_path),
"original_2k_used_sample_slots_sorted_sha256": used_hash,
"original_2k_shuffle_index_elements": len(shuffle_index),
"original_2k_sampling": "single dataloader logical samples [0, 4882944) mapped through shuffle_index; sample_index gives document and offset",
"exclusion": "all planned 2K sample slots and both neighboring slots, including next-token label overlap; selected only same-document unvisited gaps",
"allocation_rule": "sort planned 2K shuffle prefix, scan eligible sample-slot gaps in ascending slot order, assign whole gaps to three smoke views then 8K and 32K formal views",
"source_interval_overlap_check": "PASS: all selected physical intervals are disjoint with a token gap; selected gaps exclude the 2K plan and its label-neighbor slots",
"stages": stages,
}
manifest_path = HERE / "data_manifest.json"
manifest_path.write_text(json.dumps(manifest, ensure_ascii=False, indent=2) + "\n")
print(json.dumps({name: {"tokens": s["allocated_source_tokens"], "segments": s["segment_count"]} for name, s in stages.items()}, indent=2))
if __name__ == "__main__":
main()

Xet Storage Details

Size:
10.2 kB
·
Xet hash:
330d4e2d216371e324b18e1845f145431ae486393bd8f3957ea08abd8f9c0ac0

Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.