"""Exactly-once, resumable token stream over GPT-2 .bin shards (modded-nanogpt format). Row r is the window [r*T, r*T + T] of the concatenated shards: T inputs plus the next token as the last target. So every token is an input exactly once; rows run across shard boundaries without dropping or repeating tokens; and the stream never wraps around. When the data runs out, next_row() returns None and training must end (Experiment-1-A's loader wrapped back to the first shard with `% len(files)` and dropped each shard's tail). state() is the position after the last row handed out. Restoring it (on this VM or any other with the same shard files) continues with the very next token. File names, token counts and the dataset revision are checked, so a different shard set cannot silently change the order. Changing the row length requires explicit opt-in and preserves the absolute token position. Together with a checkpoint taken at an optimizer-step boundary, the model never trains twice on the same tokens: rows read after the last checkpoint belong to updates that are lost along with the stopped run. """ from pathlib import Path import numpy as np import torch HEADER_BYTES = 256 * 4 # 256 int32 words MAGIC = 20240520 # modded-nanogpt header: [magic, version, n_tokens, ...] def shard_tokens(path) -> int: """Number of uint16 tokens in a shard, checked against its header when it has one.""" path = Path(path) size = path.stat().st_size if size < HEADER_BYTES or (size - HEADER_BYTES) % 2: raise ValueError(f"{path.name}: not a uint16 token shard ({size} bytes)") count = (size - HEADER_BYTES) // 2 header = np.fromfile(path, dtype=np.int32, count=3) if header[0] == MAGIC and int(header[2]) != count: raise ValueError(f"{path.name}: header says {int(header[2])} tokens, file holds {count}") return count def write_shard(path, tokens: np.ndarray): """A shard in the same format (used by tests and data preparation).""" header = np.zeros(256, dtype=np.int32) header[:3] = MAGIC, 1, len(tokens) with open(path, "wb") as f: f.write(header.tobytes()) f.write(np.asarray(tokens, dtype=np.uint16).tobytes()) class TokenStream: def __init__(self, files, row_tokens: int, state: dict | None = None, revision: str | None = None, *, allow_row_resize: bool = False): self.files = [Path(f) for f in files] if not self.files: raise ValueError("no shard files") self.row_tokens = row_tokens self.revision = revision self.sizes = [shard_tokens(f) for f in self.files] self._maps = {} self.shard = self.offset = self.rows = 0 if state is not None: self.load_state(state, allow_row_resize=allow_row_resize) @property def total_tokens(self) -> int: return sum(self.sizes) @property def consumed_tokens(self) -> int: return sum(self.sizes[:self.shard]) + self.offset def state(self) -> dict: return {"files": [f.name for f in self.files], "sizes": list(self.sizes), "revision": self.revision, "row_tokens": self.row_tokens, "shard": self.shard, "offset": self.offset, "rows": self.rows} def load_state(self, state: dict, *, allow_row_resize: bool = False): """The checkpoint's shards must be the first shards here, unchanged; more may follow (a run extended to more tokens appends shards, keeping the order of everything read).""" mine = self.state() n = len(state["files"]) if state["revision"] != self.revision: raise ValueError(f"data stream revision differs from the checkpoint's: {state['revision']!r} vs {self.revision!r}") if not allow_row_resize and state["row_tokens"] != self.row_tokens: raise ValueError(f"data stream row length differs from the checkpoint's: {state['row_tokens']} vs {self.row_tokens}") for key in ("files", "sizes"): if state[key] != mine[key][:n]: raise ValueError(f"data stream {key} differ from the checkpoint's: {state[key]!r} vs {mine[key][:n]!r}") self.shard, self.offset, self.rows = int(state["shard"]), int(state["offset"]), int(state["rows"]) def _read(self, shard: int, start: int, count: int) -> np.ndarray: if shard not in self._maps: self._maps[shard] = np.memmap(self.files[shard], dtype=np.uint16, mode="r", offset=HEADER_BYTES, shape=(self.sizes[shard],)) return self._maps[shard][start:start + count] def next_row(self) -> torch.Tensor | None: """The next row_tokens + 1 tokens (int64; inputs row[:-1], targets row[1:]), or None once fewer remain. Only a returned row advances the position.""" need, shard, offset, pieces = self.row_tokens + 1, self.shard, self.offset, [] while need: if shard == len(self.files): return None take = min(self.sizes[shard] - offset, need) if take: pieces.append(self._read(shard, offset, take)) need -= take offset += take if need: shard, offset = shard + 1, 0 self._advance(self.row_tokens) # the extra token is the next row's first input self.rows += 1 return torch.from_numpy(np.concatenate(pieces).astype(np.int64)) def _advance(self, count: int): while count: left = self.sizes[self.shard] - self.offset if count < left: self.offset += count return count -= left self.shard, self.offset = self.shard + 1, 0