mlvar's picture
Upload model weights, training code, and model card
7f1e014 verified
Raw History Blame Contribute Delete
7.75 kB
"""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)