File size: 1,663 Bytes
681909f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
47
48
49
50
51
52
53
import json
from pathlib import Path

import torch
from torch.utils.data import Dataset

from .formatting import format_example


class DialogueDataset(Dataset):
    def __init__(self, path: str, tokenizer, max_seq_len: int):
        self.path = Path(path)
        self.tokenizer = tokenizer
        self.max_seq_len = max_seq_len
        self.assistant_id = tokenizer.piece_to_id("<assistant>")
        self.examples = []

        with self.path.open("r", encoding="utf-8") as f:
            for line in f:
                line = line.strip()
                if not line:
                    continue
                self.examples.append(json.loads(line))

        if not self.examples:
            raise ValueError(f"No examples found in {self.path}")

    def __len__(self):
        return len(self.examples)

    def __getitem__(self, index: int):
        text = format_example(self.examples[index])
        ids = self.tokenizer.encode(text, out_type=int)
        ids = ids[: self.max_seq_len]
        input_ids = torch.tensor(ids[:-1], dtype=torch.long)
        labels = torch.tensor(ids[1:], dtype=torch.long)
        if self.assistant_id in ids:
            assistant_pos = ids.index(self.assistant_id)
            labels[:assistant_pos] = -100
        return input_ids, labels


def collate_batch(batch, pad_id: int):
    max_len = max(x[0].numel() for x in batch)
    input_ids = torch.full((len(batch), max_len), pad_id, dtype=torch.long)
    labels = torch.full((len(batch), max_len), -100, dtype=torch.long)

    for i, (x, y) in enumerate(batch):
        input_ids[i, : x.numel()] = x
        labels[i, : y.numel()] = y

    return input_ids, labels