Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

utils_ner.py 16 KB

You have to be logged in to leave a comment. Sign In
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
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
  1. # coding=utf-8
  2. # Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team.
  3. # Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
  4. #
  5. # Licensed under the Apache License, Version 2.0 (the "License");
  6. # you may not use this file except in compliance with the License.
  7. # You may obtain a copy of the License at
  8. #
  9. # http://www.apache.org/licenses/LICENSE-2.0
  10. #
  11. # Unless required by applicable law or agreed to in writing, software
  12. # distributed under the License is distributed on an "AS IS" BASIS,
  13. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. # See the License for the specific language governing permissions and
  15. # limitations under the License.
  16. """ Named entity recognition fine-tuning: utilities to work with CoNLL-2003 task. """
  17. import logging
  18. import os
  19. import pdb
  20. from dataclasses import dataclass
  21. from enum import Enum
  22. from typing import List, Optional, Union
  23. from filelock import FileLock
  24. from transformers import PreTrainedTokenizer, is_tf_available, is_torch_available
  25. logger = logging.getLogger(__name__)
  26. @dataclass
  27. class InputExample:
  28. """
  29. A single training/test example for token classification.
  30. Args:
  31. guid: Unique id for the example.
  32. words: list. The words of the sequence.
  33. labels: (Optional) list. The labels for each word of the sequence. This should be
  34. specified for train and dev examples, but not for test examples.
  35. """
  36. guid: str
  37. words: List[str]
  38. labels: Optional[List[str]]
  39. @dataclass
  40. class InputFeatures:
  41. """
  42. A single set of features of data.
  43. Property names are the same names as the corresponding inputs to a model.
  44. """
  45. input_ids: List[int]
  46. attention_mask: List[int]
  47. token_type_ids: Optional[List[int]] = None
  48. label_ids: Optional[List[int]] = None
  49. class Split(Enum):
  50. train = "train_dev"
  51. dev = "devel"
  52. test = "test"
  53. if is_torch_available():
  54. import torch
  55. from torch import nn
  56. from torch.utils.data.dataset import Dataset
  57. class NerDataset(Dataset):
  58. """
  59. This will be superseded by a framework-agnostic approach
  60. soon.
  61. """
  62. features: List[InputFeatures]
  63. pad_token_label_id: int = nn.CrossEntropyLoss().ignore_index
  64. # Use cross entropy ignore_index as padding label id so that only
  65. # real label ids contribute to the loss later.
  66. def __init__(
  67. self,
  68. data_dir: str,
  69. tokenizer: PreTrainedTokenizer,
  70. labels: List[str],
  71. model_type: str,
  72. max_seq_length: Optional[int] = None,
  73. overwrite_cache=False,
  74. mode: Split = Split.train,
  75. ):
  76. # Load data features from cache or dataset file
  77. cached_features_file = os.path.join(
  78. data_dir, "cached_{}_{}_{}".format(mode.value, tokenizer.__class__.__name__, str(max_seq_length)),
  79. )
  80. # Make sure only the first process in distributed training processes the dataset,
  81. # and the others will use the cache.
  82. lock_path = cached_features_file + ".lock"
  83. with FileLock(lock_path):
  84. if os.path.exists(cached_features_file) and not overwrite_cache:
  85. logger.info(f"Loading features from cached file {cached_features_file}")
  86. self.features = torch.load(cached_features_file)
  87. else:
  88. logger.info(f"Creating features from dataset file at {data_dir}")
  89. examples = read_examples_from_file(data_dir, mode)
  90. # TODO clean up all this to leverage built-in features of tokenizers
  91. self.features = convert_examples_to_features(
  92. examples,
  93. labels,
  94. max_seq_length,
  95. tokenizer,
  96. cls_token_at_end=bool(model_type in ["xlnet"]),
  97. # xlnet has a cls token at the end
  98. cls_token=tokenizer.cls_token,
  99. cls_token_segment_id=2 if model_type in ["xlnet"] else 0,
  100. sep_token=tokenizer.sep_token,
  101. sep_token_extra=False,
  102. # roberta uses an extra separator b/w pairs of sentences, cf. github.com/pytorch/fairseq/commit/1684e166e3da03f5b600dbb7855cb98ddfcd0805
  103. pad_on_left=bool(tokenizer.padding_side == "left"),
  104. pad_token=tokenizer.pad_token_id,
  105. pad_token_segment_id=tokenizer.pad_token_type_id,
  106. pad_token_label_id=self.pad_token_label_id,
  107. )
  108. logger.info(f"Saving features into cached file {cached_features_file}")
  109. torch.save(self.features, cached_features_file)
  110. def __len__(self):
  111. return len(self.features)
  112. def __getitem__(self, i) -> InputFeatures:
  113. return self.features[i]
  114. if is_tf_available():
  115. import tensorflow as tf
  116. class TFNerDataset:
  117. """
  118. This will be superseded by a framework-agnostic approach
  119. soon.
  120. """
  121. features: List[InputFeatures]
  122. pad_token_label_id: int = -1
  123. # Use cross entropy ignore_index as padding label id so that only
  124. # real label ids contribute to the loss later.
  125. def __init__(
  126. self,
  127. data_dir: str,
  128. tokenizer: PreTrainedTokenizer,
  129. labels: List[str],
  130. model_type: str,
  131. max_seq_length: Optional[int] = None,
  132. overwrite_cache=False,
  133. mode: Split = Split.train,
  134. ):
  135. examples = read_examples_from_file(data_dir, mode)
  136. # TODO clean up all this to leverage built-in features of tokenizers
  137. self.features = convert_examples_to_features(
  138. examples,
  139. labels,
  140. max_seq_length,
  141. tokenizer,
  142. cls_token_at_end=bool(model_type in ["xlnet"]),
  143. # xlnet has a cls token at the end
  144. cls_token=tokenizer.cls_token,
  145. cls_token_segment_id=2 if model_type in ["xlnet"] else 0,
  146. sep_token=tokenizer.sep_token,
  147. sep_token_extra=False,
  148. # roberta uses an extra separator b/w pairs of sentences, cf. github.com/pytorch/fairseq/commit/1684e166e3da03f5b600dbb7855cb98ddfcd0805
  149. pad_on_left=bool(tokenizer.padding_side == "left"),
  150. pad_token=tokenizer.pad_token_id,
  151. pad_token_segment_id=tokenizer.pad_token_type_id,
  152. pad_token_label_id=self.pad_token_label_id,
  153. )
  154. def gen():
  155. for ex in self.features:
  156. if ex.token_type_ids is None:
  157. yield (
  158. {"input_ids": ex.input_ids, "attention_mask": ex.attention_mask},
  159. ex.label_ids,
  160. )
  161. else:
  162. yield (
  163. {
  164. "input_ids": ex.input_ids,
  165. "attention_mask": ex.attention_mask,
  166. "token_type_ids": ex.token_type_ids,
  167. },
  168. ex.label_ids,
  169. )
  170. if "token_type_ids" not in tokenizer.model_input_names:
  171. self.dataset = tf.data.Dataset.from_generator(
  172. gen,
  173. ({"input_ids": tf.int32, "attention_mask": tf.int32}, tf.int64),
  174. (
  175. {"input_ids": tf.TensorShape([None]), "attention_mask": tf.TensorShape([None])},
  176. tf.TensorShape([None]),
  177. ),
  178. )
  179. else:
  180. self.dataset = tf.data.Dataset.from_generator(
  181. gen,
  182. ({"input_ids": tf.int32, "attention_mask": tf.int32, "token_type_ids": tf.int32}, tf.int64),
  183. (
  184. {
  185. "input_ids": tf.TensorShape([None]),
  186. "attention_mask": tf.TensorShape([None]),
  187. "token_type_ids": tf.TensorShape([None]),
  188. },
  189. tf.TensorShape([None]),
  190. ),
  191. )
  192. def get_dataset(self):
  193. return self.dataset
  194. def __len__(self):
  195. return len(self.features)
  196. def __getitem__(self, i) -> InputFeatures:
  197. return self.features[i]
  198. def read_examples_from_file(data_dir, mode: Union[Split, str]) -> List[InputExample]:
  199. if isinstance(mode, Split):
  200. mode = mode.value
  201. file_path = os.path.join(data_dir, f"{mode}.txt")
  202. guid_index = 1
  203. examples = []
  204. with open(file_path, encoding="utf-8") as f:
  205. words = []
  206. labels = []
  207. for line in f:
  208. if line.startswith("-DOCSTART-") or line == "" or line == "\n":
  209. if words:
  210. examples.append(InputExample(guid=f"{mode}-{guid_index}", words=words, labels=labels))
  211. guid_index += 1
  212. words = []
  213. labels = []
  214. else:
  215. splits = line.split(" ")
  216. words.append(splits[0])
  217. if len(splits) > 1:
  218. splits_replace = splits[-1].replace("\n", "")
  219. if splits_replace == 'O':
  220. labels.append(splits_replace)
  221. else:
  222. labels.append(splits_replace + "-bio")
  223. else:
  224. # Examples could have no label for mode = "test"
  225. labels.append("O")
  226. if words:
  227. examples.append(InputExample(guid=f"{mode}-{guid_index}", words=words, labels=labels))
  228. return examples
  229. def convert_examples_to_features(
  230. examples: List[InputExample],
  231. label_list: List[str],
  232. max_seq_length: int,
  233. tokenizer: PreTrainedTokenizer,
  234. cls_token_at_end=False,
  235. cls_token="[CLS]",
  236. cls_token_segment_id=1,
  237. sep_token="[SEP]",
  238. sep_token_extra=False,
  239. pad_on_left=False,
  240. pad_token=0,
  241. pad_token_segment_id=0,
  242. pad_token_label_id=-100,
  243. sequence_a_segment_id=0,
  244. mask_padding_with_zero=True,
  245. ) -> List[InputFeatures]:
  246. """ Loads a data file into a list of `InputFeatures`
  247. `cls_token_at_end` define the location of the CLS token:
  248. - False (Default, BERT/XLM pattern): [CLS] + A + [SEP] + B + [SEP]
  249. - True (XLNet/GPT pattern): A + [SEP] + B + [SEP] + [CLS]
  250. `cls_token_segment_id` define the segment id associated to the CLS token (0 for BERT, 2 for XLNet)
  251. """
  252. # TODO clean up all this to leverage built-in features of tokenizers
  253. label_map = {label: i for i, label in enumerate(label_list)}
  254. features = []
  255. for (ex_index, example) in enumerate(examples):
  256. if ex_index % 10_000 == 0:
  257. logger.info("Writing example %d of %d", ex_index, len(examples))
  258. tokens = []
  259. label_ids = []
  260. for word, label in zip(example.words, example.labels):
  261. word_tokens = tokenizer.tokenize(word)
  262. # bert-base-multilingual-cased sometimes output "nothing ([]) when calling tokenize with just a space.
  263. if len(word_tokens) > 0:
  264. tokens.extend(word_tokens)
  265. # Use the real label id for the first token of the word, and padding ids for the remaining tokens
  266. label_ids.extend([label_map[label]] + [pad_token_label_id] * (len(word_tokens) - 1))
  267. # Account for [CLS] and [SEP] with "- 2" and with "- 3" for RoBERTa.
  268. special_tokens_count = tokenizer.num_special_tokens_to_add()
  269. if len(tokens) > max_seq_length - special_tokens_count:
  270. tokens = tokens[: (max_seq_length - special_tokens_count)]
  271. label_ids = label_ids[: (max_seq_length - special_tokens_count)]
  272. # The convention in BERT is:
  273. # (a) For sequence pairs:
  274. # tokens: [CLS] is this jack ##son ##ville ? [SEP] no it is not . [SEP]
  275. # type_ids: 0 0 0 0 0 0 0 0 1 1 1 1 1 1
  276. # (b) For single sequences:
  277. # tokens: [CLS] the dog is hairy . [SEP]
  278. # type_ids: 0 0 0 0 0 0 0
  279. #
  280. # Where "type_ids" are used to indicate whether this is the first
  281. # sequence or the second sequence. The embedding vectors for `type=0` and
  282. # `type=1` were learned during pre-training and are added to the wordpiece
  283. # embedding vector (and position vector). This is not *strictly* necessary
  284. # since the [SEP] token unambiguously separates the sequences, but it makes
  285. # it easier for the model to learn the concept of sequences.
  286. #
  287. # For classification tasks, the first vector (corresponding to [CLS]) is
  288. # used as as the "sentence vector". Note that this only makes sense because
  289. # the entire model is fine-tuned.
  290. tokens += [sep_token]
  291. label_ids += [pad_token_label_id]
  292. if sep_token_extra:
  293. # roberta uses an extra separator b/w pairs of sentences
  294. tokens += [sep_token]
  295. label_ids += [pad_token_label_id]
  296. segment_ids = [sequence_a_segment_id] * len(tokens)
  297. if cls_token_at_end:
  298. tokens += [cls_token]
  299. label_ids += [pad_token_label_id]
  300. segment_ids += [cls_token_segment_id]
  301. else:
  302. tokens = [cls_token] + tokens
  303. label_ids = [pad_token_label_id] + label_ids
  304. segment_ids = [cls_token_segment_id] + segment_ids
  305. input_ids = tokenizer.convert_tokens_to_ids(tokens)
  306. # The mask has 1 for real tokens and 0 for padding tokens. Only real
  307. # tokens are attended to.
  308. input_mask = [1 if mask_padding_with_zero else 0] * len(input_ids)
  309. # Zero-pad up to the sequence length.
  310. padding_length = max_seq_length - len(input_ids)
  311. if pad_on_left:
  312. input_ids = ([pad_token] * padding_length) + input_ids
  313. input_mask = ([0 if mask_padding_with_zero else 1] * padding_length) + input_mask
  314. segment_ids = ([pad_token_segment_id] * padding_length) + segment_ids
  315. label_ids = ([pad_token_label_id] * padding_length) + label_ids
  316. else:
  317. input_ids += [pad_token] * padding_length
  318. input_mask += [0 if mask_padding_with_zero else 1] * padding_length
  319. segment_ids += [pad_token_segment_id] * padding_length
  320. label_ids += [pad_token_label_id] * padding_length
  321. assert len(input_ids) == max_seq_length
  322. assert len(input_mask) == max_seq_length
  323. assert len(segment_ids) == max_seq_length
  324. assert len(label_ids) == max_seq_length
  325. if ex_index < 5:
  326. logger.info("*** Example ***")
  327. logger.info("guid: %s", example.guid)
  328. logger.info("tokens: %s", " ".join([str(x) for x in tokens]))
  329. logger.info("input_ids: %s", " ".join([str(x) for x in input_ids]))
  330. logger.info("input_mask: %s", " ".join([str(x) for x in input_mask]))
  331. logger.info("segment_ids: %s", " ".join([str(x) for x in segment_ids]))
  332. logger.info("label_ids: %s", " ".join([str(x) for x in label_ids]))
  333. if "token_type_ids" not in tokenizer.model_input_names:
  334. segment_ids = None
  335. features.append(
  336. InputFeatures(
  337. input_ids=input_ids, attention_mask=input_mask, token_type_ids=segment_ids, label_ids=label_ids
  338. )
  339. )
  340. return features
  341. def get_labels(path: str) -> List[str]:
  342. if path:
  343. with open(path, "r") as f:
  344. labels = f.read().splitlines()
  345. labels = [i+'-bio' if i != 'O' else 'O' for i in labels]
  346. if "O" not in labels:
  347. labels = ["O"] + labels
  348. return labels
  349. else:
  350. # return ["O", "B-MISC", "I-MISC", "B-PER", "I-PER", "B-ORG", "I-ORG", "B-LOC", "I-LOC"]
  351. return ["O", "B-bio", "I-bio"]
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...