File size: 9,912 Bytes
6ae136b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
"""

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

    "<file>.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()