from pathlib import Path import torch def load_text(path: str) -> str: p = Path(path) if not p.exists(): raise FileNotFoundError(f"Text file not found: {p}") return p.read_text(encoding="utf-8", errors="replace") def split_text(text: str, val_ratio=0.05, test_ratio=0.05): if not (0 < val_ratio < 0.5 and 0 < test_ratio < 0.5 and val_ratio + test_ratio < 0.5): raise ValueError("invalid split ratios") # Prefer paragraph boundaries. This is deterministic and avoids arbitrary # character cuts while remaining compatible with a single corpus.txt file. paragraphs = [p.strip() for p in text.split("\n\n") if p.strip()] if len(paragraphs) < 20: n = len(text) a = int(n * (1 - val_ratio - test_ratio)) b = int(n * (1 - test_ratio)) return text[:a], text[a:b], text[b:] n = len(paragraphs) train_n = max(1, int(n * (1 - val_ratio - test_ratio))) val_n = max(1, int(n * val_ratio)) train = "\n\n".join(paragraphs[:train_n]) val = "\n\n".join(paragraphs[train_n:train_n + val_n]) test = "\n\n".join(paragraphs[train_n + val_n:]) return train, val, test class RandomTokenDataset: def __init__(self, ids, seq_len: int, seed: int = 42): self.ids = torch.tensor(ids, dtype=torch.long) self.seq_len = seq_len self.gen = torch.Generator() self.gen.manual_seed(seed) if len(self.ids) <= seq_len + 1: raise ValueError("dataset is shorter than seq_len + 1") def batch(self, batch_size: int): starts = torch.randint( 0, len(self.ids) - self.seq_len - 1, (batch_size,), generator=self.gen, ) x = torch.stack([self.ids[s:s + self.seq_len] for s in starts]) return x