|
3 | 3 | """ |
4 | 4 | import gc |
5 | 5 | from collections import deque |
6 | | -from typing import Iterator, Optional |
| 6 | +from typing import Iterator, Optional, List, Tuple, Iterable |
7 | 7 | import torch |
8 | 8 | from torch.utils.data import Dataset, IterableDataset |
9 | 9 | from pathlib import Path |
10 | 10 | from collections import Counter |
11 | | -from typing import List, Tuple, Iterable |
| 11 | +import numpy as np |
12 | 12 |
|
13 | 13 | from .tokenizer import Tokenizer |
14 | 14 |
|
@@ -45,6 +45,132 @@ def encode(self, tokens: List[str]) -> List[int]: |
45 | 45 | return [self.stoi.get(t, self.stoi['<unk>']) for t in tokens] |
46 | 46 |
|
47 | 47 |
|
| 48 | +class PretokenizedDataset(IterableDataset): |
| 49 | + """ |
| 50 | + Dataset that streams tokens from pre-tokenized binary files. |
| 51 | + """ |
| 52 | + def __init__(self, data_dir: str, seq_len: int = 1024, split: str = "train", |
| 53 | + vocab_size: int = 50257): |
| 54 | + self.data_dir = Path(data_dir) |
| 55 | + self.seq_len = seq_len |
| 56 | + self.vocab_size = vocab_size |
| 57 | + |
| 58 | + # Check vocab size safety |
| 59 | + if self.vocab_size > 65535: |
| 60 | + raise ValueError(f"Vocab size {self.vocab_size} too large for uint16 storage used by PretokenizedDataset") |
| 61 | + |
| 62 | + # Find all bin files matching the split |
| 63 | + self.files = sorted(list(self.data_dir.glob(f"*{split}*.bin"))) |
| 64 | + if not self.files: |
| 65 | + raise FileNotFoundError(f"No bin files found in {data_dir} for split '{split}'. Did you run prepare_dataset.py?") |
| 66 | + |
| 67 | + print(f"Found {len(self.files)} bin files in {data_dir} for split {split}") |
| 68 | + |
| 69 | + def __iter__(self): |
| 70 | + worker_info = torch.utils.data.get_worker_info() |
| 71 | + if worker_info: |
| 72 | + # Shard files across workers |
| 73 | + # Simple interleaving |
| 74 | + files = self.files[worker_info.id::worker_info.num_workers] |
| 75 | + else: |
| 76 | + files = self.files |
| 77 | + |
| 78 | + # Buffer to hold tokens from multiple files to ensure continuity |
| 79 | + buffer = np.array([], dtype=np.uint16) |
| 80 | + chunk_len = self.seq_len + 1 |
| 81 | + |
| 82 | + for path in files: |
| 83 | + # Read file as numpy array |
| 84 | + try: |
| 85 | + # Use memmap for efficiency |
| 86 | + new_data = np.memmap(path, dtype=np.uint16, mode='r') |
| 87 | + |
| 88 | + # Append to buffer (we have to copy here, but buffer is small) |
| 89 | + # Actually, appending memmap to numpy array forces a read. |
| 90 | + # To be efficient, we should process the buffer as much as possible first. |
| 91 | + |
| 92 | + # However, for continuity, we need to stitch the end of the previous file |
| 93 | + # with the start of the new file. |
| 94 | + |
| 95 | + # Since we are iterating, we can yield chunks from `new_data` |
| 96 | + # but we need to handle the "leftover" from previous file. |
| 97 | + |
| 98 | + # If buffer is not empty (from previous iteration), prepend it |
| 99 | + if len(buffer) > 0: |
| 100 | + # This forces a read of the whole file if we use np.concatenate |
| 101 | + # Ideally we only read the beginning. |
| 102 | + |
| 103 | + # Optimization: Only concat the leftovers with the start of new file? |
| 104 | + # No, memmap is array-like. |
| 105 | + |
| 106 | + # Let's just process the memmap directly and keep the tail in buffer. |
| 107 | + pass |
| 108 | + |
| 109 | + # We can't easily concatenate memmap without reading it. |
| 110 | + # Strategy: |
| 111 | + # 1. Take leftovers from buffer. |
| 112 | + # 2. Iterate through memmap. |
| 113 | + # 3. If we have enough for a chunk using leftovers + start of memmap, yield it. |
| 114 | + # 4. Then yield chunks from memmap. |
| 115 | + # 5. Save tail of memmap to buffer. |
| 116 | + |
| 117 | + current_idx = 0 |
| 118 | + total_len = len(new_data) |
| 119 | + |
| 120 | + # Handle leftovers |
| 121 | + if len(buffer) > 0: |
| 122 | + needed = chunk_len - len(buffer) |
| 123 | + if total_len >= needed: |
| 124 | + # Take 'needed' from new_data |
| 125 | + part = new_data[:needed] # This reads from disk |
| 126 | + full_chunk = np.concatenate([buffer, part]) |
| 127 | + |
| 128 | + x = torch.from_numpy(full_chunk[:-1].astype(np.int64)) |
| 129 | + y = torch.from_numpy(full_chunk[1:].astype(np.int64)) |
| 130 | + yield x, y |
| 131 | + |
| 132 | + current_idx = needed |
| 133 | + buffer = np.array([], dtype=np.uint16) |
| 134 | + else: |
| 135 | + # File is too small to complete the buffer |
| 136 | + # Append all of it to buffer and continue to next file |
| 137 | + part = new_data[:] |
| 138 | + buffer = np.concatenate([buffer, part]) |
| 139 | + continue |
| 140 | + |
| 141 | + # Process main body of file |
| 142 | + # We can compute how many chunks fit |
| 143 | + remaining = total_len - current_idx |
| 144 | + num_chunks = remaining // chunk_len |
| 145 | + |
| 146 | + if num_chunks > 0: |
| 147 | + # Create a view or slice |
| 148 | + # Note: slicing memmap returns memmap, which is good. |
| 149 | + # We can iterate over the slices. |
| 150 | + |
| 151 | + # But constructing individual tensors from memmap slices is fine. |
| 152 | + for i in range(num_chunks): |
| 153 | + start = current_idx + i * chunk_len |
| 154 | + end = start + chunk_len |
| 155 | + chunk = new_data[start:end] |
| 156 | + |
| 157 | + # Copy to memory and convert |
| 158 | + chunk_arr = np.array(chunk, dtype=np.int64) |
| 159 | + x = torch.from_numpy(chunk_arr[:-1]) |
| 160 | + y = torch.from_numpy(chunk_arr[1:]) |
| 161 | + yield x, y |
| 162 | + |
| 163 | + current_idx += num_chunks * chunk_len |
| 164 | + |
| 165 | + # Save leftovers |
| 166 | + if current_idx < total_len: |
| 167 | + buffer = np.array(new_data[current_idx:], dtype=np.uint16) |
| 168 | + |
| 169 | + except Exception as e: |
| 170 | + print(f"Error reading {path}: {e}") |
| 171 | + continue |
| 172 | + |
| 173 | + |
48 | 174 | class RealTextDataset(Dataset): |
49 | 175 | """Loads text files from a directory, builds a simple token-level vocab, |
50 | 176 | and yields sequences for next-token prediction. |
|
0 commit comments