|
| 1 | +""" |
| 2 | +Downloads and tokenizes the TinyStories dataset. |
| 3 | +- The download is from HuggingFace datasets. |
| 4 | +- The tokenization is GPT-2 tokenizer with tiktoken |
| 5 | +
|
| 6 | +The output is written to a newly created data/ folder. |
| 7 | +The script prints: |
| 8 | +
|
| 9 | +Tokenizing val split... |
| 10 | +Saved 19043638 tokens to data/TinyStories_val.bin |
| 11 | +Tokenizing train split... |
| 12 | +Saved 925653391 tokens to data/TinyStories_train.bin |
| 13 | +
|
| 14 | +And runs in 1-2 minutes two depending on your internet |
| 15 | +connection and computer. The .bin files are raw byte |
| 16 | +streams of int32 numbers indicating the token ids. |
| 17 | +""" |
| 18 | + |
| 19 | +import os |
| 20 | +import glob |
| 21 | +import json |
| 22 | +import random |
| 23 | +import requests |
| 24 | +from tqdm import tqdm |
| 25 | +from concurrent.futures import ProcessPoolExecutor, as_completed |
| 26 | + |
| 27 | +import tiktoken |
| 28 | +import numpy as np |
| 29 | + |
| 30 | +DATA_CACHE_DIR = "data" |
| 31 | +enc = tiktoken.get_encoding("gpt2") |
| 32 | +encode = lambda s: enc.encode_ordinary(s) |
| 33 | + |
| 34 | +def download_file(url: str, fname: str, chunk_size=1024): |
| 35 | + """Helper function to download a file from a given url""" |
| 36 | + resp = requests.get(url, stream=True) |
| 37 | + total = int(resp.headers.get("content-length", 0)) |
| 38 | + with open(fname, "wb") as file, tqdm( |
| 39 | + desc=fname, |
| 40 | + total=total, |
| 41 | + unit="iB", |
| 42 | + unit_scale=True, |
| 43 | + unit_divisor=1024, |
| 44 | + ) as bar: |
| 45 | + for data in resp.iter_content(chunk_size=chunk_size): |
| 46 | + size = file.write(data) |
| 47 | + bar.update(size) |
| 48 | + |
| 49 | +def download(): |
| 50 | + """Downloads the TinyStories dataset to DATA_CACHE_DIR""" |
| 51 | + os.makedirs(DATA_CACHE_DIR, exist_ok=True) |
| 52 | + |
| 53 | + # download the TinyStories dataset, unless it's already downloaded |
| 54 | + data_url = "https://huggingface.co/datasets/roneneldan/TinyStories/resolve/main/TinyStories_all_data.tar.gz" |
| 55 | + data_filename = os.path.join(DATA_CACHE_DIR, "TinyStories_all_data.tar.gz") |
| 56 | + if not os.path.exists(data_filename): |
| 57 | + print(f"Downloading {data_url} to {data_filename}...") |
| 58 | + download_file(data_url, data_filename) |
| 59 | + else: |
| 60 | + print(f"{data_filename} already exists, skipping download...") |
| 61 | + |
| 62 | + # unpack the tar.gz file into all the data shards (json files) |
| 63 | + data_dir = os.path.join(DATA_CACHE_DIR, "TinyStories_all_data") |
| 64 | + if not os.path.exists(data_dir): |
| 65 | + os.makedirs(data_dir, exist_ok=True) |
| 66 | + print(f"Unpacking {data_filename}...") |
| 67 | + os.system(f"tar -xzf {data_filename} -C {data_dir}") |
| 68 | + else: |
| 69 | + print(f"{data_dir} already exists, skipping unpacking...") |
| 70 | + |
| 71 | + # print a single example just for debugging and such |
| 72 | + shard_filenames = sorted(glob.glob(os.path.join(data_dir, "*.json"))) |
| 73 | + with open(shard_filenames[0], "r") as f: |
| 74 | + data = json.load(f) |
| 75 | + print("Download done.") |
| 76 | + print(f"Number of shards: {len(shard_filenames)}") |
| 77 | + #print(f"Example story:\n{data[0]}") |
| 78 | + |
| 79 | +def process_shard(shard_index, shard_filename): |
| 80 | + with open(shard_filename, "r") as f: |
| 81 | + data = json.load(f) |
| 82 | + eot = enc._special_tokens['<|endoftext|>'] # end of text token |
| 83 | + rng = random.Random(1337 + shard_index) |
| 84 | + rng.shuffle(data) |
| 85 | + all_tokens = [] |
| 86 | + for example in data: |
| 87 | + text = example["story"] |
| 88 | + text = text.strip() # get rid of leading/trailing whitespace |
| 89 | + tokens = encode(text) |
| 90 | + all_tokens.append(eot) |
| 91 | + all_tokens.extend(tokens) |
| 92 | + return all_tokens |
| 93 | + |
| 94 | +def tokenize(): |
| 95 | + # shard 0 will be the val split, rest is train |
| 96 | + data_dir = os.path.join(DATA_CACHE_DIR, "TinyStories_all_data") |
| 97 | + shard_filenames = sorted(glob.glob(os.path.join(data_dir, "*.json"))) |
| 98 | + val_shards = [shard_filenames[0]] |
| 99 | + train_shards = shard_filenames[1:] |
| 100 | + for split_name, split_shards in [("val", val_shards), ("train", train_shards)]: |
| 101 | + |
| 102 | + print(f"Tokenizing {split_name} split...") |
| 103 | + all_tokens = [] |
| 104 | + with ProcessPoolExecutor() as executor: |
| 105 | + futures = [executor.submit(process_shard, shard_index, shard_filename) |
| 106 | + for shard_index, shard_filename in enumerate(split_shards)] |
| 107 | + for future in as_completed(futures): |
| 108 | + all_tokens.extend(future.result()) |
| 109 | + |
| 110 | + all_tokens_np = np.array(all_tokens, dtype=np.int32) |
| 111 | + split_filename = os.path.join(DATA_CACHE_DIR, f"TinyStories_{split_name}.bin") |
| 112 | + with open(split_filename, "wb") as f: |
| 113 | + f.write(all_tokens_np.tobytes()) |
| 114 | + print(f"Saved {len(all_tokens_np)} tokens to {split_filename}") |
| 115 | + |
| 116 | +if __name__ == "__main__": |
| 117 | + download() |
| 118 | + tokenize() |
| 119 | + |
| 120 | + # Prints: |
| 121 | + # Tokenizing val split... |
| 122 | + # Saved 19043638 tokens to data/TinyStories_val.bin |
| 123 | + # Tokenizing train split... |
| 124 | + # Saved 925653391 tokens to data/TinyStories_train.bin |
0 commit comments