File size: 1,787 Bytes
63ae7d6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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