File size: 2,434 Bytes
ebf8f81
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Turn the raw stories text into a flat file of token ids (uint16).

python prepare.py data/train.txt data/tok4096.json data/train.bin

Reads the text a piece at a time, so the full 2.2 GB file needs well under 2 GB of memory.
"""
import sys, numpy as np
from multiprocessing import Pool
from tokenizer import Tokenizer, split_stories, EOS

tok = None
n_chars = 0


def init(path):
    global tok
    tok = Tokenizer.load(path)


def enc(parts):
    """Raw pieces of text between two end-of-story marks -> token ids, plus the size of the last story."""
    out, last = [], 0
    for part in parts:
        for s in split_stories(part):          # cleans it, and skips scraps under 50 characters
            ids = tok.encode(s)
            out.extend(ids); out.append(0)
            last = len(ids) + 1
    return np.array(out, dtype=np.uint16), last


def raw_parts(path, block=16_000_000, group=4000):
    """Yield lists of raw stories without ever holding the whole file."""
    global n_chars
    carry, batch = "", []
    with open(path, encoding="utf-8", errors="ignore") as f:
        while True:
            s = f.read(block)
            if not s:
                break
            n_chars += len(s)
            parts = (carry + s).split(EOS)
            carry = parts.pop()                # may be half a story, or half an end-of-story mark
            batch.extend(parts)
            while len(batch) >= group:
                yield batch[:group]; batch = batch[group:]
    yield batch + [carry]


if __name__ == "__main__":
    text_path, tok_path, out_path = sys.argv[1:4]
    drop_last = text_path.endswith("train.txt")   # with a partial download the last story is cut off
    n_tokens, n_stories, held = 1, 0, None
    with Pool(4, initializer=init, initargs=(tok_path,)) as p, open(out_path, "wb") as out:
        np.zeros(1, np.uint16).tofile(out)
        for arr, last in p.imap(enc, raw_parts(text_path)):
            if not len(arr):
                continue
            if held is not None:
                held[0].tofile(out)
            held = (arr, last)
            n_tokens += len(arr); n_stories += int((arr == 0).sum())
        if held is not None:
            arr, last = held
            if drop_last:
                arr = arr[:len(arr) - last]; n_tokens -= last; n_stories -= 1
            arr.tofile(out)
    print(f"{n_stories:,} stories -> {n_tokens:,} tokens ({n_chars/n_tokens:.2f} chars/token)")