File size: 7,754 Bytes
7f1e014
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Data pipeline: download, tokenize, memmap, batch sampling.

Two-stage design:
  1. tokenize_dataset(): raw .txt β†’ tokenized np.uint16 memmap .bin
  2. TinyStoriesDataset: PyTorch Dataset backed by the memmap file
  3. get_batch(): random-offset batch sampling (nanoGPT-style)
"""

import os
import urllib.request
from pathlib import Path

import numpy as np
import torch
from torch.utils.data import Dataset
from tqdm import tqdm

from .tokenizer import Tokenizer

# ── HuggingFace raw URLs for TinyStories ──────────────────────────────
# These are the raw text exports hosted on HuggingFace datasets.
TINYSTORIES_URLS = {
    "train": "https://huggingface.co/datasets/roneneldan/TinyStories/resolve/main/TinyStories-train.txt",
    "valid": "https://huggingface.co/datasets/roneneldan/TinyStories/resolve/main/TinyStories-valid.txt",
}

# Fallback: if HuggingFace is slow, use the Hugging Face Hub mirror via CDN
TINYSTORIES_URLS_CDN = {
    "train": "https://huggingface.co/datasets/roneneldan/TinyStories/resolve/main/TinyStories-train.txt?download=true",
    "valid": "https://huggingface.co/datasets/roneneldan/TinyStories/resolve/main/TinyStories-valid.txt?download=true",
}


def _download_with_progress(url: str, dest: Path) -> None:
    """Download a file with a tqdm progress bar."""

    def _report(block_num: int, block_size: int, total_size: int):
        if pbar.total is None and total_size > 0:
            pbar.total = total_size
        pbar.update(block_size)

    pbar = tqdm(
        unit="B", unit_scale=True, unit_divisor=1024, desc=f"Downloading {dest.name}"
    )
    urllib.request.urlretrieve(url, str(dest), reporthook=_report)
    pbar.close()


def download_tinystories(
    data_dir: str | Path = "data/tinystories", force: bool = False
) -> dict[str, Path]:
    """Download TinyStories raw text files from HuggingFace.

    Args:
        data_dir: directory to store the files.
        force: re-download even if files already exist.

    Returns:
        dict with keys 'train' and 'valid' mapping to file paths.
    """
    data_dir = Path(data_dir)
    data_dir.mkdir(parents=True, exist_ok=True)

    paths: dict[str, Path] = {}
    for split, url in TINYSTORIES_URLS.items():
        dest = data_dir / f"TinyStories-{split}.txt"
        if dest.exists() and not force:
            print(f"  {dest.name} already exists ({dest.stat().st_size / 1e6:.1f} MB)")
        else:
            _download_with_progress(url, dest)
            print(f"  Downloaded {dest.name} ({dest.stat().st_size / 1e6:.1f} MB)")
        paths[split] = dest

    return paths


def tokenize_dataset(
    text_path: str | Path,
    output_bin_path: str | Path,
    tokenizer: Tokenizer | None = None,
) -> int:
    """Tokenize a raw text file and write as np.uint16 memmap.

    Args:
        text_path: path to the raw .txt file.
        output_bin_path: path where the .bin file will be written.
        tokenizer: optional pre-created Tokenizer; creates one if None.

    Returns:
        Total number of tokens written.
    """
    if tokenizer is None:
        tokenizer = Tokenizer()

    text_path = Path(text_path)
    output_bin_path = Path(output_bin_path)
    output_bin_path.parent.mkdir(parents=True, exist_ok=True)

    print(f"Tokenizing {text_path.name}...")
    with open(text_path, "r", encoding="utf-8") as f:
        raw_text = f.read()

    tokens = tokenizer.encode(raw_text)
    token_count = len(tokens)

    # Use uint16 β€” 65535 > 50257 vocab, so it fits and saves space vs int32
    dtype = np.uint16
    arr = np.array(tokens, dtype=dtype)
    arr.tofile(str(output_bin_path))

    print(
        f"  Saved {output_bin_path.name}: {token_count:,} tokens "
        f"({output_bin_path.stat().st_size / 1e6:.1f} MB)"
    )
    return token_count


class TinyStoriesDataset(Dataset):
    """Memory-mapped dataset for TinyStories tokenized data.

    Backed by a raw .bin file of np.uint16 token IDs.
    Uses random-offset sampling for efficient shuffling.
    """

    def __init__(self, bin_path: str | Path, seq_len: int = 1024):
        self.seq_len = seq_len
        self.bin_path = Path(bin_path)

        # Open as memmap for zero-copy reads
        self._data = np.memmap(str(bin_path), dtype=np.uint16, mode="r")
        # Usable length: need seq_len input tokens + 1 target token
        self._len = len(self._data) - seq_len - 1

        if self._len <= 0:
            raise ValueError(
                f"Tokenized data ({len(self._data)} tokens) is too short "
                f"for seq_len={seq_len}"
            )

    def __len__(self) -> int:
        return self._len

    def __getitem__(self, idx: int) -> tuple[torch.Tensor, torch.Tensor]:
        """Return (input, target) pair, where target is input shifted by 1."""
        x = torch.from_numpy(
            self._data[idx : idx + self.seq_len].astype(np.int64)
        )
        y = torch.from_numpy(
            self._data[idx + 1 : idx + self.seq_len + 1].astype(np.int64)
        )
        return x, y

    @property
    def num_tokens(self) -> int:
        return len(self._data)


def get_batch(
    split_data: np.memmap,
    batch_size: int,
    seq_len: int,
    device: torch.device,
) -> tuple[torch.Tensor, torch.Tensor]:
    """Sample a random batch using nanoGPT-style random-offset sampling.

    This avoids DataLoader shuffling overhead β€” we just pick random start
    indices into the memmap. Equivalent to uniform sampling with replacement.

    Args:
        split_data: np.memmap of uint16 token IDs.
        batch_size: number of sequences per batch.
        seq_len: length of each sequence.
        device: target torch device.

    Returns:
        (x, y) tuple of shape (batch_size, seq_len) each.
    """
    max_start = len(split_data) - seq_len - 1
    # Pick random starting indices
    ix = torch.randint(0, max_start, (batch_size,))

    x = torch.stack(
        [
            torch.from_numpy(split_data[i : i + seq_len].astype(np.int64))
            for i in ix.tolist()
        ]
    )
    y = torch.stack(
        [
            torch.from_numpy(
                split_data[i + 1 : i + seq_len + 1].astype(np.int64)
            )
            for i in ix.tolist()
        ]
    )
    return x.to(device, non_blocking=True), y.to(device, non_blocking=True)


def load_data(config) -> tuple[np.memmap, np.memmap, int, int]:
    """Load (or download+tokenize) TinyStories data.

    Args:
        config: Config object with data_dir and training params.

    Returns:
        (train_data, val_data, train_tokens, val_tokens)
    """
    data_dir = Path(config.data_dir)

    # Step 1: Download raw text if needed
    txt_paths = {
        "train": data_dir / "TinyStories-train.txt",
        "valid": data_dir / "TinyStories-valid.txt",
    }
    missing = [p for p in txt_paths.values() if not p.exists()]
    if missing:
        print("Downloading TinyStories dataset...")
        download_tinystories(data_dir)

    # Step 2: Tokenize to .bin if needed
    bin_paths = {
        "train": data_dir / "train.bin",
        "valid": data_dir / "val.bin",
    }
    tokenizer = Tokenizer()

    for split, bin_path in bin_paths.items():
        if not bin_path.exists():
            tokenize_dataset(txt_paths[split], bin_path, tokenizer)

    # Step 3: Load as memmap
    train_data = np.memmap(str(bin_paths["train"]), dtype=np.uint16, mode="r")
    val_data = np.memmap(str(bin_paths["valid"]), dtype=np.uint16, mode="r")

    print(
        f"Train tokens: {len(train_data):,} | "
        f"Val tokens: {len(val_data):,} | "
        f"Seq len: {config.training.seq_len}"
    )

    return train_data, val_data, len(train_data), len(val_data)