Repository navigation
Expand file tree
/
Copy pathload.py
More file actions
239 lines (205 loc) · 6.57 KB
/
Copy pathload.py
File metadata and controls
239 lines (205 loc) · 6.57 KB
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
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
import logging
from pathlib import Path
import torch
import torch.utils.data
import transformers
from sklearn.preprocessing import LabelEncoder
from tqdm import tqdm
logger = logging.getLogger("bert.load")
def flush_tokens(
list_all_tokens,
list_all_labels,
list_all_masks,
list_all_crf_masks,
list_labels,
list_tokens,
cls_token_id,
sep_token_id,
pad_label,
null_label,
):
# add the tokens to a collective list, append [CLS]
# token to beginning an the [SEP] token to the end
list_all_tokens.append(torch.tensor([cls_token_id, *list_tokens] + [sep_token_id]))
# add the labels to a collective list, append <pad> to
# the beginning and the end
list_all_labels.append([pad_label, *list_labels] + [pad_label])
# create the mask - ignore all tokens from [SEP] token onwards
list_all_masks.append(torch.tensor([1] * (len(list_tokens) + 2)))
list_all_crf_masks.append(
torch.tensor(
[1 if label != null_label else 0 for label in list_all_labels[-1]],
dtype=torch.bool,
)
)
list_tokens.clear()
list_labels.clear()
def load_data_from_file(
path: Path,
batch_size,
tokens_column,
predict_column,
lang_model,
max_len,
separator,
pad_label,
null_label,
device,
label_encoder=None,
shuffle=True,
):
# create the tokenizer for subtokens
logger.info("Loading Tokenizer")
tokenizer = transformers.AutoTokenizer.from_pretrained(lang_model, use_fast=True)
logger.info("Tokenizer loaded")
cls_token_id = tokenizer.cls_token_id
sep_token_id = tokenizer.sep_token_id
list_all_tokens = []
list_all_labels = []
list_all_masks = []
list_all_crf_masks = []
logger.info("Loading data file: %s", path)
with path.open() as file:
list_tokens = []
list_labels = []
for line in tqdm(file):
if line.startswith("#"):
continue
if line != "\n":
tokens = line.split(separator)
token = tokens[tokens_column]
label = tokens[predict_column].replace("\n", "")
# subtokenize each token
subtokens = tokenizer.encode(token, add_special_tokens=False)
# add the subtokens to the list of tokens
list_tokens += subtokens
# only the first subtoken retains the token value, the rest
# are marked with the null label - <X>
list_labels += [label] + [null_label] * (len(subtokens) - 1)
continue
assert len(list_tokens) == len(list_labels)
if len(list_tokens) == 0:
continue
list_tokens = list_tokens[:max_len]
list_labels = list_labels[:max_len]
flush_tokens(
list_all_tokens,
list_all_labels,
list_all_masks,
list_all_crf_masks,
list_labels,
list_tokens,
cls_token_id,
sep_token_id,
pad_label,
null_label,
)
if list_tokens:
flush_tokens(
list_all_tokens,
list_all_labels,
list_all_masks,
list_all_crf_masks,
list_labels,
list_tokens,
cls_token_id,
sep_token_id,
pad_label,
null_label,
)
logger.info("File loading done")
assert len(list_all_tokens) == len(list_all_labels) == len(list_all_masks)
# fit the label encoder
logger.info("Fitting the label encoder")
if label_encoder is None:
label_encoder = LabelEncoder()
label_encoder.fit(sum(list_all_labels, []))
# encode the labels -> transform strings in integers that represent the classes
list_all_encoded_labels = [
torch.tensor(label_encoder.transform(list_labels))
for list_labels in list_all_labels
]
# pad the tokens, the labels and the masks
X = torch.nn.utils.rnn.pad_sequence( # noqa: N806
list_all_tokens,
batch_first=True,
padding_value=int(tokenizer.pad_token_id or 0),
).to(device)
y = torch.nn.utils.rnn.pad_sequence(
list_all_encoded_labels,
batch_first=True,
padding_value=label_encoder.transform([pad_label])[0], # type: ignore
).to(device)
masks = torch.nn.utils.rnn.pad_sequence(
list_all_masks,
batch_first=True,
padding_value=0,
).to(device)
crf_mask = torch.nn.utils.rnn.pad_sequence(
list_all_crf_masks,
batch_first=True,
padding_value=0,
).to(device)
# create the loader
dataset = torch.utils.data.TensorDataset(X, y, masks, crf_mask)
loader = torch.utils.data.DataLoader(
dataset, batch_size=batch_size, shuffle=shuffle
)
return loader, label_encoder
def load_data(
train_path,
dev_path,
batch_size,
tokens_column,
predict_column,
lang_model,
max_len,
separator,
pad_label,
null_label,
device,
):
"""
Function that loads the training and the development data.
:param train_path: Path to the training data.
:param dev_path: Path to the development data.
:param batch_size: The batch size.
:param tokens_column: The column of the tokens in the data file.
:param predict_column: The column that must be predicted.
:param lang_model: The name of the language model that will be used. See
HuggingFace's available models.
:param max_len: The maximum length of the sequences.
:param separator: The separator of the data files.
:param pad_label: The padding label that will be used. Defaults to <pad>.
:param null_label: The null label that will be used to mask the second to
last subtokens's label. Defaults to <X>.
:param device: The device used for training.
:return: Two pytorch loaders for train and dev, and the label encoder (from
scikit) used to encode the labels.
"""
train_loader, label_encoder = load_data_from_file(
Path(train_path),
batch_size,
tokens_column,
predict_column,
lang_model,
max_len,
separator,
pad_label,
null_label,
device,
)
dev_loader, _ = load_data_from_file(
Path(dev_path),
batch_size,
tokens_column,
predict_column,
lang_model,
max_len,
separator,
pad_label,
null_label,
device,
label_encoder,
)
return train_loader, dev_loader, label_encoder