Download tools/mkpack_aligned.py from unparallelled/BluScriptCP-aligned-mixes: direct link, hf CLI and curl.
- Browser
- Download file 8.47 kB
-
https://huggingface.co/datasets/unparallelled/BluScriptCP-aligned-mixes/resolve/main/tools/mkpack_aligned.py
- Command line
-
hf download hf://datasets/unparallelled/BluScriptCP-aligned-mixes/tools/mkpack_aligned.py
-
curl -L -o mkpack_aligned.py https://huggingface.co/datasets/unparallelled/BluScriptCP-aligned-mixes/resolve/main/tools/mkpack_aligned.py
8.47 kB
| #!/usr/bin/env python3 | |
| """Repack an existing mix so NO document is cut by a training-window edge unless | |
| it is longer than the window -- and then only at multiples of T from its own start. | |
| WHY. DataLoaderLite reads the file from offset 0 in exact T-token steps (verified: | |
| the P2 resume fast-forwarded 16,000 batches = 524,288,000 tokens = 16,000 x 32,768), | |
| so window k is file[k*T : (k+1)*T]. A plain concatenation cuts documents wherever | |
| the stream crosses k*T; under CP_DOC_MASK a cut-off continuation cannot see its own | |
| beginning. On the P2c mix that left 11.7% of tokens with >= 24k same-document | |
| context; this layout of the SAME documents gives ~14.8%. | |
| LAYOUT (measured on P2c before choosing it): | |
| * a document LONGER than --align-min (default T) starts a window and is chunked | |
| at multiples of T from its own start. A continuation chunk ALWAYS opens a window: | |
| it has no leading EOT, so mid-window it would merge with the previous document's | |
| id under CP_DOC_MASK. | |
| * every shorter document is placed WHOLE, best-fit decreasing, into the tightest | |
| gap it fits; one that fits nowhere opens a fresh window. Whole means never cut, | |
| and inside a window its offset does not matter under the doc mask. | |
| * aligning every document >= T/2 instead was measured to leave 3.9% of window space | |
| empty (not enough short documents to fill behind them) -- that would need padding, | |
| which this trainer does not have. Aligning only > T leaves 0.006%. | |
| * the remaining small gaps are closed from a RESERVE of the shortest documents held | |
| out before packing: whole reserve documents first, then the HEAD of the shortest | |
| reserve document that covers the rest (it keeps its leading EOT, so it is still | |
| its own document); the cut tail is dropped and counted. Unused reserve documents | |
| fill final windows; the last partial window is dropped and counted. | |
| * --float-tails: the LAST, partial chunk of a split document already cannot see | |
| its own beginning (it is in another window), so it gets an inserted leading EOT | |
| and becomes an ordinary filler placed whole in any gap. No token loses context | |
| versus strict alignment; it costs one inserted EOT per tail. Needed when the mix | |
| is dominated by documents just over T with few mid-size fillers (P1b at T=16k: | |
| strict alignment left 14.3% of window space empty). | |
| Windows are shuffled (seeded). No padding token exists: every window is exactly T | |
| real tokens. One EOT is appended at the end because the loader reads T+1 tokens for | |
| the last window. Validation is copied unchanged. | |
| """ | |
| import argparse, bisect, json, os, shutil, sys | |
| import numpy as np | |
| EOT = 50256 | |
| def main(): | |
| ap = argparse.ArgumentParser() | |
| ap.add_argument("--in-mix", required=True) | |
| ap.add_argument("--out", required=True) | |
| ap.add_argument("--window", type=int, required=True) | |
| ap.add_argument("--align-min", type=int, default=0, help="anchor docs longer than this (default: window)") | |
| ap.add_argument("--reserve", type=int, default=20000, help="shortest docs held out to close gaps") | |
| ap.add_argument("--float-tails", action="store_true") | |
| ap.add_argument("--seed", type=int, default=1015) | |
| a = ap.parse_args() | |
| T = a.window | |
| A = a.align_min or T | |
| src = np.fromfile(f"{a.in_mix}/train_000000.bin", dtype=np.uint16) | |
| starts = np.flatnonzero(src == EOT) | |
| if starts.size == 0 or starts[0] != 0: | |
| sys.exit("input does not start with EOT -- not a document stream") | |
| lens = np.diff(np.append(starts, src.size)).astype(np.int64) | |
| by_len = np.argsort(lens, kind="stable") | |
| reserve = [int(i) for i in by_len[:a.reserve]] # ascending length | |
| rest = by_len[a.reserve:] | |
| anchors = [int(i) for i in rest[::-1] if lens[i] > A] | |
| fillers = [int(i) for i in rest[::-1] if lens[i] <= A] # descending length | |
| win, room = [], [] # win[w] = [(doc, off, n)], room[w] = free tokens | |
| gaps = [] # sorted (room, w) for windows with room > 0 | |
| def open_window(seg): | |
| win.append([seg]); room.append(T - seg[2] - seg[3]) | |
| if room[-1] > 0: | |
| bisect.insort(gaps, (room[-1], len(win) - 1)) | |
| def put(w, seg): | |
| win[w].append(seg); room[w] -= seg[2] + seg[3] | |
| if room[w] > 0: | |
| bisect.insort(gaps, (room[w], w)) | |
| items = [(i, 0, int(lens[i]), 0) for i in fillers] # (doc, off, n, inserted_eot) | |
| tails = 0 | |
| for i in anchors: | |
| off = 0 | |
| while off < lens[i]: | |
| n = int(min(T, lens[i] - off)) | |
| if a.float_tails and off > 0 and n < T and n + 1 <= T: | |
| items.append((i, off, n, 1)); tails += 1 # floats as a filler with its own EOT | |
| else: | |
| open_window((i, off, n, 0)) | |
| off += n | |
| items.sort(key=lambda it: -(it[2] + it[3])) | |
| for it in items: | |
| L = it[2] + it[3]; k = bisect.bisect_left(gaps, (L, -1)) | |
| if k == len(gaps): | |
| open_window(it) | |
| else: | |
| _, w = gaps.pop(k); put(w, it) | |
| gap_before = sum(r for r, _ in gaps) | |
| # close gaps from the reserve (ascending lengths) | |
| res = sorted(reserve, key=lambda i: lens[i]); res_len = [int(lens[i]) for i in res] | |
| dropped = 0 | |
| while gaps: | |
| r, w = gaps.pop() # largest gap first | |
| while True: # whole reserve docs, largest that fits | |
| k = bisect.bisect_right(res_len, r) - 1 | |
| if k < 0: | |
| break | |
| i = res.pop(k); L = res_len.pop(k); win[w].append((i, 0, L, 0)); r -= L | |
| if r == 0: | |
| break | |
| if r > 0: # head of the shortest doc covering r | |
| k = bisect.bisect_left(res_len, r) | |
| if k == len(res): | |
| sys.exit("reserve exhausted -- raise --reserve") | |
| i = res.pop(k); L = res_len.pop(k) | |
| win[w].append((i, 0, r, 0)); dropped += L - r | |
| room[w] = 0 | |
| cur, used = [], 0 # unused reserve -> final windows | |
| for i, L in zip(res, res_len): | |
| if used + L <= T: | |
| cur.append((i, 0, L, 0)); used += L | |
| else: | |
| if T - used > 0: | |
| cur.append((i, 0, T - used, 0)); dropped += L - (T - used) | |
| win.append(cur); room.append(0); cur, used = [], 0 | |
| if used == T: | |
| win.append(cur); room.append(0); cur, used = [], 0 | |
| dropped += used # last partial window discarded | |
| order = np.random.default_rng(a.seed).permutation(len(win)) | |
| os.makedirs(a.out, exist_ok=True) | |
| tot, split_docs = 0, 0 | |
| with open(f"{a.out}/train_000000.bin.tmp", "wb") as f: | |
| for wi in order: | |
| w = win[wi] | |
| assert sum(s[2] + s[3] for s in w) == T, f"window {wi} is not exactly T" | |
| for j, (doc, off, n, pre) in enumerate(w): | |
| assert off == 0 or j == 0 or pre, "un-prefixed continuation chunk not at window start" | |
| if pre: | |
| np.array([EOT], dtype=np.uint16).tofile(f); tot += 1 | |
| src[starts[doc] + off: starts[doc] + off + n].tofile(f); tot += n | |
| np.array([EOT], dtype=np.uint16).tofile(f); tot += 1 | |
| os.replace(f"{a.out}/train_000000.bin.tmp", f"{a.out}/train_000000.bin") | |
| shutil.copy(f"{a.in_mix}/val_000000.bin", f"{a.out}/val_000000.bin") | |
| rep = {"provenance": f"mkpack_aligned.py repack of {a.in_mix}: same documents, laid out so only docs > {A} " | |
| f"are split, at multiples of T={T} from their own start", | |
| "window": T, "align_min": A, "reserve": a.reserve, "seed": a.seed, "windows": len(win), | |
| "anchored_docs": len(anchors), "float_tails": bool(a.float_tails), "floated_tails": tails, | |
| "gap_before_close": int(gap_before), | |
| "train_tokens": int(tot), "written_tokens": int(tot), "input_train_tokens": int(src.size), | |
| "dropped_tokens": int(dropped), "source_report": json.load(open(f"{a.in_mix}/mix_report.json"))} | |
| json.dump(rep, open(f"{a.out}/mix_report.json", "w"), indent=2) | |
| print(json.dumps({k: rep[k] for k in ("window", "align_min", "windows", "anchored_docs", "floated_tails", "gap_before_close", | |
| "train_tokens", "input_train_tokens", "dropped_tokens")}, indent=1)) | |
| if __name__ == "__main__": | |
| main() | |