File size: 3,554 Bytes
6b665d1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Extend train_v32768.bin with the REST of TinyStories, without touching val.

prepare.py tokenized the first 300MiB of TinyStories-train.txt and carved val
from the LAST 0.5% of that token stream. Re-running it on more data would move
the carve point and leak today's val tokens into train, invalidating every
number in the ablation series. Instead: keep val_v32768.bin frozen, tokenize
only text strictly PAST the original 300MiB slice with the existing tokenizer,
and append it to a copy of the existing train bin.

Skip boundary: the recorded slice file is exactly 300MiB (314,572,800 bytes),
and prepare.py additionally cut it back to its last complete <|endoftext|>.
Starting at the first <|endoftext|> past 300MiB therefore drops only the one
story straddling the boundary and can never overlap the original stream.
"""

import argparse
import os

import numpy as np
import requests
from tokenizers import Tokenizer

HERE = os.path.dirname(os.path.abspath(__file__))
URL = "https://huggingface.co/datasets/roneneldan/TinyStories/resolve/main/TinyStories-train.txt"
FULL = os.path.join(HERE, "tinystories_full.txt")
SKIP = 300 * 1024 * 1024  # == the recorded slice size, verified 314,572,800
EOT = "<|endoftext|>"

ap = argparse.ArgumentParser()
ap.add_argument("--vocab", type=int, default=32768)
args = ap.parse_args()
OUT = os.path.join(HERE, f"train_full_v{args.vocab}.bin")
TRAIN = os.path.join(HERE, f"train_v{args.vocab}.bin")


def download():
    if os.path.exists(FULL) and os.path.getsize(FULL) > 1_500_000_000:
        print(f"already have {FULL} ({os.path.getsize(FULL) / 1e9:.2f}GB)")
        return
    print("downloading full TinyStories-train.txt...")
    got = 0
    with requests.get(URL, stream=True, timeout=60) as r:
        r.raise_for_status()
        with open(FULL, "wb") as f:
            for chunk in r.iter_content(chunk_size=1 << 20):
                f.write(chunk)
                got += len(chunk)
                if got % (200 << 20) < (1 << 20):
                    print(f"  {got / 1e9:.2f}GB", flush=True)
    print(f"done, {got / 1e9:.2f}GB")


def main():
    if os.path.exists(OUT) and os.path.getsize(OUT) > os.path.getsize(TRAIN):
        print(f"already have {OUT}")
        return

    download()
    with open(FULL, "rb") as f:
        f.seek(SKIP)
        text = f.read().decode("utf-8", errors="ignore")
    # First complete story past the boundary; last complete story in the file.
    text = text[text.find(EOT) + len(EOT):]
    text = text[: text.rfind(EOT) + len(EOT)]
    print(f"new text past slice: {len(text) / 1e9:.2f}GB")

    tok = Tokenizer.from_file(os.path.join(HERE, f"bpe{args.vocab}.json"))
    eot = tok.token_to_id(EOT)

    old = np.fromfile(TRAIN, dtype=np.uint16)
    n_new = 0
    with open(OUT, "wb") as out:
        old.tofile(out)
        docs = text.split(EOT)
        for i in range(0, len(docs), 20000):
            batch = [d for d in docs[i : i + 20000] if d.strip()]
            ids = []
            for enc in tok.encode_batch(batch):
                ids.extend(enc.ids)
                ids.append(eot)
            arr = np.array(ids, dtype=np.uint16)
            assert arr.max() < args.vocab
            arr.tofile(out)
            n_new += len(arr)
            print(f"  {i + len(batch)}/{len(docs)} docs, +{n_new / 1e6:.1f}M tokens", flush=True)

    total = len(old) + n_new
    print(f"train_full: {len(old):,} original + {n_new:,} new = {total:,} tokens")
    print(f"one epoch at bs16 sl256 = {total // 4096:,} steps")


if __name__ == "__main__":
    main()