Download code/prepare.py from Redhanuman/pocket-storyteller: direct link, hf CLI and curl.
- Browser
- Download file 2.43 kB
-
https://huggingface.co/Redhanuman/pocket-storyteller/resolve/main/code/prepare.py
- Command line
-
hf download hf://Redhanuman/pocket-storyteller/code/prepare.py
-
curl -L -o prepare.py https://huggingface.co/Redhanuman/pocket-storyteller/resolve/main/code/prepare.py
2.43 kB
| """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)") | |