""" Storage optimizer for Neo. Job 1 - shrink the token files (default): Every token id is < 50,000, so int32 storage wastes 2 bytes/token. This rewrites data/training.bin (9.5 GB -> ~4.7 GB) and the data/sft_*_tokens.npy files as uint16, in place and losslessly. No re-tokenising and no retraining are needed; every writer/reader (build_tokens.py, prepare_sft.py, dataset.py) now agrees on the ".meta.json" sidecar dtype. Job 2 - reclaim big redundant files (--reclaim, needs --yes to delete): data/processed/* and data/training.txt are fully redundant once training.bin exists, and checkpoints/neo_282m_latest.pt is an incompatible legacy model. Regenerable / obsolete -> safe to drop. Job 3 - compress the raw corpus (--compress-raw, needs --yes to run): data/raw/*.txt (~12 GB) is the source of truth but is never re-read once training.bin exists. gzip-ing it to *.txt.gz frees several GB with no information loss; prepare.py and build_corpus.py read *.gz transparently. Opt-in because a *.gz cannot be appended to, so a later build_corpus.py run for that source would start it over. Run: run.bat data\\optimize_storage.py run.bat data\\optimize_storage.py --reclaim run.bat data\\optimize_storage.py --reclaim --yes run.bat data\\optimize_storage.py --compress-raw run.bat data\\optimize_storage.py --compress-raw --yes """ import argparse import gzip import json import os import shutil import sys import time from pathlib import Path import numpy as np # Prevent the broken Windows Store Python alias hang. if ( "WindowsApps" in sys.executable or ".venv" not in sys.prefix ): print( "ERROR: run with the project venv " "(run.bat data\\optimize_storage.py)." ) sys.exit(1) if hasattr(sys.stdout, "reconfigure"): sys.stdout.reconfigure(encoding="utf-8", errors="replace") TOKEN_FILES = [ Path("data/training.bin"), Path("data/sft_train_tokens.npy"), Path("data/sft_val_tokens.npy"), ] CHUNK_TOKENS = 128_000_000 # 512 MB of int32 per read # Redundant or obsolete - safe to drop when --yes is given. DECOMMISSION = [ Path("data/processed"), Path("data/training.txt"), Path("checkpoints/neo_282m_latest.pt"), ] # Kept unless the user really wants them gone (listed only). OPTIONAL = [ Path("checkpoints/neo_500m_sft_final_backup.pt"), Path("checkpoints/neo_500m_sft_latest.pt"), Path("data/raw"), ] # Raw corpus text lives in data/raw/*.txt. It is the source of truth (the # only thing expensive to re-download) and is never re-read once # data/training.bin exists, so it compresses well. This is opt-in because a # *compressed* raw file cannot be appended to, so re-running # data/build_corpus.py after compression would start that source over from # scratch (prepare.py and build_corpus.py are gzip-aware, so the tokens are # still rebuildable). RAW_DIR = Path("data/raw") RAW_GZIP_LEVEL = 6 def human(n): n = float(n) for unit in ("B", "KB", "MB", "GB", "TB"): if abs(n) < 1024: return f"{n:.2f} {unit}" n /= 1024 return f"{n:.2f} PB" def dir_size(path): if path.is_file(): return path.stat().st_size total = 0 for root, _, files in os.walk(path): for name in files: try: total += os.path.getsize(os.path.join(root, name)) except OSError: pass return total def meta_dtype(path): meta = Path(str(path) + ".meta.json") if meta.exists(): try: return np.dtype( json.loads(meta.read_text(encoding="utf-8"))["dtype"] ) except (ValueError, KeyError): pass return None def write_meta(path, dtype, tokens): Path(str(path) + ".meta.json").write_text( json.dumps( {"dtype": np.dtype(dtype).name, "tokens": int(tokens)}, indent=2, ), encoding="utf-8", ) def shrink_bin(path): """Streaming int32 -> uint16 rewrite of a raw token file.""" if meta_dtype(path) == np.dtype(np.uint16): print(f" [skip] {path}: already uint16 " f"({human(path.stat().st_size)})") return 0 before = path.stat().st_size tmp = Path(str(path) + ".tmp") chunk_bytes = CHUNK_TOKENS * 4 print(f" [conv] {path}: int32 -> uint16 ({human(before)})") written = 0 start = time.perf_counter() with open(path, "rb") as src, open(tmp, "wb") as dst: while True: buf = src.read(chunk_bytes) if not buf: break # A truncated tail (interrupted write) is dropped, not # silently mis-cast. usable = len(buf) - (len(buf) % 4) arr = np.frombuffer(buf[:usable], dtype=np.int32) dst.write(arr.astype(np.uint16).tobytes()) written += len(arr) print(f" {written:,} tokens", end="\r", flush=True) os.replace(tmp, path) write_meta(path, np.uint16, written) after = path.stat().st_size print(f" {written:,} tokens, {human(before)} -> " f"{human(after)} in {time.perf_counter() - start:.1f}s") return before - after def shrink_npy(path): # Fully load (not memmap): on Windows a still-open memory map # blocks os.replace() below. The SFT arrays are only a few # hundred MB, so holding them in RAM is fine. arr = np.load(path) if arr.dtype == np.uint16: print(f" [skip] {path}: already uint16") return 0 before = path.stat().st_size tmp = Path(str(path) + ".tmp.npy") np.save(tmp, arr.astype(np.uint16, copy=False)) os.replace(tmp, path) write_meta(path, np.uint16, arr.shape[0]) after = path.stat().st_size print(f" [conv] {path}: {arr.dtype} -> uint16, " f"{human(before)} -> {human(after)}") return before - after def shrink_tokens(): print("=== shrinking token files ===") freed = 0 for path in TOKEN_FILES: if not path.exists(): print(f" [skip] {path}: missing") continue if path.suffix == ".bin": freed += shrink_bin(path) else: freed += shrink_npy(path) print(f"freed this run: {human(freed)}") def reclaim(delete): print() print("=== reclaimable storage ===") freed = 0 for path in DECOMMISSION: if not path.exists(): continue size = dir_size(path) freed += size if delete: if path.is_dir(): shutil.rmtree(path) else: path.unlink() print(f" [deleted] {path} ({human(size)})") else: print(f" [candidate] {path} ({human(size)})") print() print("optional (kept - listed only):") for path in OPTIONAL: if path.exists(): print(f" [optional] {path} ({human(dir_size(path))})") print() if delete: print(f"freed: {human(freed)}") else: print(f"would free: {human(freed)} " "(re-run with --yes to delete)") def compress_raw(delete): """gzip data/raw/*.txt -> *.txt.gz (opt-in; ~3x smaller for text).""" print() print("=== raw corpus compression (data/raw/*.txt) ===") if not RAW_DIR.exists(): print(" [skip] data/raw missing") return before_total = after_total = 0 for path in sorted(RAW_DIR.glob("*.txt")): before = path.stat().st_size gz_path = Path(str(path) + ".gz") if gz_path.exists(): print(f" [skip] {gz_path.name} already exists") continue if not delete: print(f" [candidate] {path.name} ({human(before)}) -> .gz") before_total += before continue start = time.perf_counter() # Stream-compress: the files are multi-GB, so never load one whole. with open(path, "rb") as src, gzip.open( gz_path, "wb", compresslevel=RAW_GZIP_LEVEL ) as dst: shutil.copyfileobj(src, dst, length=8 * 1024 * 1024) after = gz_path.stat().st_size # Only drop the original once the gz is safely on disk. if after > 0: path.unlink() before_total += before after_total += after saved = 100 * (1 - after / before) if before else 0 print(f" [zip] {path.name}: {human(before)} -> {human(after)} " f"({saved:.0f}% smaller, {time.perf_counter() - start:.0f}s)") print() if not delete: print(f"would free: {human(before_total)} " "(re-run with --yes to compress)") else: print(f"raw: {human(before_total)} -> {human(after_total)} " f"(freed {human(before_total - after_total)})") def main(): parser = argparse.ArgumentParser( description="Neo storage optimizer" ) parser.add_argument( "--reclaim", action="store_true", help="also report/delete redundant large files", ) parser.add_argument( "--compress-raw", action="store_true", help="gzip data/raw/*.txt (opt-in; source of truth, ~3x smaller)", ) parser.add_argument( "--yes", action="store_true", help="actually delete/compress the candidates", ) args = parser.parse_args() shrink_tokens() if args.reclaim: reclaim(args.yes) if args.compress_raw: compress_raw(args.yes) if __name__ == "__main__": main()