File size: 4,508 Bytes
e14cd69
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
"""Shared, right-padded batches for sentence-level inference."""
from __future__ import annotations

from dataclasses import dataclass
from typing import Iterator, List, Dict

import torch
from torch.nn.utils.rnn import pad_sequence
from tqdm import tqdm

from src.data.conllu import Sentence, Token
from src.models.base import BorgBaseModel


@dataclass
class SentenceBatch:
    indices: List[int]
    tokens: List[List[Token]]
    input_ids: torch.Tensor
    attention_mask: torch.Tensor
    word_ids: List[List[int | None]]
    word_positions: List[Dict[int, int]]
    input_char_ids: torch.Tensor | None = None


def sentence_batches(
    model: BorgBaseModel,
    sentences: List[Sentence],
    *,
    show_progress: bool = False,
) -> Iterator[SentenceBatch]:
    batch_size = model.config.eval_batch_size
    if batch_size < 1:
        raise ValueError("eval_batch_size must be positive")

    token_getter = (
        Sentence.surface_tokens
        if model.component == "mwt"
        else Sentence.regular_tokens
    )
    examples = [
        (index, token_getter(sentence))
        for index, sentence in enumerate(sentences)
    ]
    examples = sorted(
        (example for example in examples if example[1]),
        key=lambda example: sum(len(token.form) for token in example[1]),
    )
    for start in tqdm(
        range(0, len(examples), batch_size),
        desc=f"[{type(model).__name__}] Predict",
        unit="batch",
        disable=not show_progress or not examples,
    ):
        chunk = examples[start:start + batch_size]
        encoding = model.hf_tokenizer(
            [[token.form for token in tokens] for _, tokens in chunk],
            is_split_into_words=True,
            max_length=model.config.max_seq_length,
            truncation=True,
            padding=False,
        )
        word_ids = [
            encoding.word_ids(batch_index=index)
            for index in range(len(chunk))
        ]
        word_positions = []
        for ids in word_ids:
            positions: Dict[int, int] = {}
            for position, word_id in enumerate(ids):
                if word_id is not None:
                    positions.setdefault(word_id, position)
            word_positions.append(positions)

        input_char_ids = None
        if model.component in ("lemmatizer", "mwt"):
            vocab = model.input_vocab
            pad_id = vocab["<PAD>"]
            char_sequences = []
            max_char_length = max(
                len(token.form) + 2
                for _, tokens in chunk
                for token in tokens
            )
            for (_, tokens), ids in zip(chunk, word_ids):
                seen_words = set()
                char_rows = []
                for word_id in ids:
                    if word_id is None:
                        continue
                    if word_id not in seen_words:
                        token = tokens[word_id]
                        char_ids = [vocab["<SOS>"]]
                        char_ids.extend(
                            vocab.get(char, vocab["<UNK>"])
                            for char in token.form
                        )
                        char_ids.append(vocab["<EOS>"])
                        seen_words.add(word_id)
                    else:
                        char_ids = [pad_id]
                    char_rows.append(
                        char_ids + [pad_id] * (max_char_length - len(char_ids))
                    )
                char_sequences.append(torch.tensor(char_rows, dtype=torch.long))
            input_char_ids = pad_sequence(
                char_sequences,
                batch_first=True,
                padding_value=pad_id,
            )

        # ROOT is position zero in the parser, irrespective of tokenizer padding_side.
        yield SentenceBatch(
            indices=[index for index, _ in chunk],
            tokens=[tokens for _, tokens in chunk],
            input_ids=pad_sequence(
                [torch.tensor(ids, dtype=torch.long) for ids in encoding["input_ids"]],
                batch_first=True,
                padding_value=model.hf_tokenizer.pad_token_id,
            ),
            attention_mask=pad_sequence(
                [torch.tensor(mask, dtype=torch.long) for mask in encoding["attention_mask"]],
                batch_first=True,
                padding_value=0,
            ),
            word_ids=word_ids,
            word_positions=word_positions,
            input_char_ids=input_char_ids,
        )