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

run_ner.py 12 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
  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. """ Fine-tuning the library models for named entity recognition on CoNLL-2003. """
  17. import logging
  18. import os
  19. import sys
  20. import pdb
  21. import yaml
  22. import dagshub
  23. import subprocess
  24. from dataclasses import dataclass, field
  25. from typing import Dict, List, Optional, Tuple
  26. import numpy as np
  27. from seqeval.metrics import f1_score, precision_score, recall_score
  28. from torch import nn
  29. from transformers import (
  30. AutoConfig,
  31. AutoModelForTokenClassification,
  32. AutoModel,
  33. AutoTokenizer,
  34. EvalPrediction,
  35. HfArgumentParser,
  36. Trainer,
  37. TrainerCallback,
  38. TrainingArguments,
  39. set_seed,
  40. )
  41. from utils_ner import NerDataset, Split, get_labels
  42. logger = logging.getLogger(__name__)
  43. @dataclass
  44. class ModelArguments:
  45. """
  46. Arguments pertaining to which model/config/tokenizer we are going to fine-tune from.
  47. """
  48. model_name_or_path: str = field(
  49. metadata={"help": "Path to pretrained model or model identifier from huggingface.co/models"}
  50. )
  51. config_name: Optional[str] = field(
  52. default=None, metadata={"help": "Pretrained config name or path if not the same as model_name"}
  53. )
  54. tokenizer_name: Optional[str] = field(
  55. default=None, metadata={"help": "Pretrained tokenizer name or path if not the same as model_name"}
  56. )
  57. use_fast: bool = field(default=False, metadata={"help": "Set this flag to use fast tokenization."})
  58. # If you want to tweak more attributes on your tokenizer, you should do it in a distinct script,
  59. # or just modify its tokenizer_config.json.
  60. cache_dir: Optional[str] = field(
  61. default=None, metadata={"help": "Where do you want to store the pretrained models downloaded from s3"}
  62. )
  63. @dataclass
  64. class DataTrainingArguments:
  65. """
  66. Arguments pertaining to what data we are going to input our model for training and eval.
  67. """
  68. data_dir: str = field(
  69. metadata={"help": "The input data dir. Should contain the .txt files for a CoNLL-2003-formatted task."}
  70. )
  71. labels: Optional[str] = field(
  72. default=None,
  73. metadata={"help": "Path to a file containing all labels. If not specified, CoNLL-2003 labels are used."},
  74. )
  75. max_seq_length: int = field(
  76. default=128,
  77. metadata={
  78. "help": "The maximum total input sequence length after tokenization. Sequences longer "
  79. "than this will be truncated, sequences shorter will be padded."
  80. },
  81. )
  82. overwrite_cache: bool = field(
  83. default=False, metadata={"help": "Overwrite the cached training and evaluation sets"}
  84. )
  85. class DAGsHubCallback(TrainerCallback):
  86. def __init__(self, logger):
  87. super(TrainerCallback, self).__init__()
  88. self.logger = logger
  89. def on_log(self, args, state, control, logs, model=None, **kwargs):
  90. if state.is_world_process_zero:
  91. self.logger.log_metrics({k:v for k,v in logs.items() if isinstance(v, (int, float))}, step_num=state.global_step)
  92. def main():
  93. # See all possible arguments in src/transformers/training_args.py
  94. # or by passing the --help flag to this script.
  95. # We now keep distinct sets of args, for a cleaner separation of concerns.
  96. parser = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments))
  97. if len(sys.argv) == 2 and sys.argv[1].endswith(".yaml"):
  98. # If we pass only one argument to the script and it's the path to a json file,
  99. # let's parse it to get our arguments.
  100. with open(os.path.abspath(sys.argv[1]), "r") as params_file:
  101. params = yaml.load(params_file)
  102. model_args, data_args, training_args = parser.parse_dict(params)
  103. else:
  104. model_args, data_args, training_args = parser.parse_args_into_dataclasses()
  105. if (
  106. os.path.exists(training_args.output_dir)
  107. and os.listdir(training_args.output_dir)
  108. and training_args.do_train
  109. and not training_args.overwrite_output_dir
  110. ):
  111. raise ValueError(
  112. f"Output directory ({training_args.output_dir}) already exists and is not empty. Use --overwrite_output_dir to overcome."
  113. )
  114. # Setup logging
  115. logging.basicConfig(
  116. format="%(asctime)s - %(levelname)s - %(name)s - %(message)s",
  117. datefmt="%m/%d/%Y %H:%M:%S",
  118. level=logging.INFO if training_args.local_rank in [-1, 0] else logging.WARN,
  119. )
  120. logger.warning(
  121. "Process rank: %s, device: %s, n_gpu: %s, distributed training: %s, 16-bits training: %s",
  122. training_args.local_rank,
  123. training_args.device,
  124. training_args.n_gpu,
  125. bool(training_args.local_rank != -1),
  126. training_args.fp16,
  127. )
  128. logger.info("Training/evaluation parameters %s", training_args)
  129. # Set seed
  130. set_seed(training_args.seed)
  131. # Prepare CONLL-2003 task
  132. labels = get_labels(data_args.labels)
  133. label_map: Dict[int, str] = {i: label for i, label in enumerate(labels)}
  134. num_labels = len(labels)
  135. # Load pretrained model and tokenizer
  136. #
  137. # Distributed training:
  138. # The .from_pretrained methods guarantee that only one local process can concurrently
  139. # download model & vocab.
  140. config = AutoConfig.from_pretrained(
  141. model_args.config_name if model_args.config_name else model_args.model_name_or_path,
  142. num_labels=num_labels,
  143. id2label=label_map,
  144. label2id={label: i for i, label in enumerate(labels)},
  145. cache_dir=model_args.cache_dir,
  146. )
  147. tokenizer = AutoTokenizer.from_pretrained(
  148. model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path,
  149. cache_dir=model_args.cache_dir,
  150. use_fast=model_args.use_fast,
  151. )
  152. model = AutoModelForTokenClassification.from_pretrained(
  153. model_args.model_name_or_path,
  154. from_tf=bool(".ckpt" in model_args.model_name_or_path),
  155. config=config,
  156. cache_dir=model_args.cache_dir,
  157. )
  158. '''
  159. model_to_save = AutoModel.from_pretrained(
  160. model_args.model_name_or_path,
  161. from_tf=bool(".ckpt" in model_args.model_name_or_path),
  162. config=config,
  163. cache_dir=model_args.cache_dir,
  164. )
  165. model_to_save.save_pretrained(training_args.output_dir)
  166. tokenizer.save_pretrained(training_args.output_dir)
  167. import pdb; pdb.set_trace()
  168. '''
  169. # Get datasets
  170. train_dataset = (
  171. NerDataset(
  172. data_dir=data_args.data_dir,
  173. tokenizer=tokenizer,
  174. labels=labels,
  175. model_type=config.model_type,
  176. max_seq_length=data_args.max_seq_length,
  177. overwrite_cache=data_args.overwrite_cache,
  178. mode=Split.train,
  179. )
  180. if training_args.do_train
  181. else None
  182. )
  183. eval_dataset = (
  184. NerDataset(
  185. data_dir=data_args.data_dir,
  186. tokenizer=tokenizer,
  187. labels=labels,
  188. model_type=config.model_type,
  189. max_seq_length=data_args.max_seq_length,
  190. overwrite_cache=data_args.overwrite_cache,
  191. mode=Split.dev,
  192. )
  193. if training_args.do_eval
  194. else None
  195. )
  196. def align_predictions(predictions: np.ndarray, label_ids: np.ndarray) -> Tuple[List[int], List[int]]:
  197. preds = np.argmax(predictions, axis=2)
  198. batch_size, seq_len = preds.shape
  199. out_label_list = [[] for _ in range(batch_size)]
  200. preds_list = [[] for _ in range(batch_size)]
  201. for i in range(batch_size):
  202. for j in range(seq_len):
  203. if label_ids[i, j] != nn.CrossEntropyLoss().ignore_index:
  204. out_label_list[i].append(label_map[label_ids[i][j]])
  205. preds_list[i].append(label_map[preds[i][j]])
  206. return preds_list, out_label_list
  207. def compute_metrics(p: EvalPrediction) -> Dict:
  208. preds_list, out_label_list = align_predictions(p.predictions, p.label_ids)
  209. return {
  210. "precision": precision_score(out_label_list, preds_list),
  211. "recall": recall_score(out_label_list, preds_list),
  212. "f1": f1_score(out_label_list, preds_list),
  213. }
  214. # Prevent runs directory from being created https://huggingface.co/transformers/v3.5.1/main_classes/trainer.html#transformers.TFTrainingArguments
  215. training_args.logging_dir = None
  216. # Initialize our Trainer
  217. trainer = Trainer(
  218. model=model,
  219. args=training_args,
  220. train_dataset=train_dataset,
  221. eval_dataset=eval_dataset,
  222. compute_metrics=compute_metrics,
  223. )
  224. dags_logger = dagshub.DAGsHubLogger(should_log_hparams=False)
  225. trainer.add_callback(DAGsHubCallback(dags_logger))
  226. # Training
  227. if training_args.do_train:
  228. trainer.train(
  229. model_path=model_args.model_name_or_path if os.path.isdir(model_args.model_name_or_path) else None
  230. )
  231. trainer.save_model()
  232. # For convenience, we also re-save the tokenizer to the same directory,
  233. # so that you can share your model easily on huggingface.co/models =)
  234. if trainer.is_world_master():
  235. tokenizer.save_pretrained(training_args.output_dir)
  236. # Evaluation
  237. results = {}
  238. if training_args.do_eval:
  239. logger.info("*** Evaluate ***")
  240. result = trainer.evaluate()
  241. output_eval_file = os.path.join(training_args.output_dir, "metrics.yaml")
  242. if trainer.is_world_master():
  243. results.update(result)
  244. # Predict
  245. if training_args.do_predict:
  246. test_dataset = NerDataset(
  247. data_dir=data_args.data_dir,
  248. tokenizer=tokenizer,
  249. labels=labels,
  250. model_type=config.model_type,
  251. max_seq_length=data_args.max_seq_length,
  252. overwrite_cache=data_args.overwrite_cache,
  253. mode=Split.test,
  254. )
  255. predictions, label_ids, metrics = trainer.predict(test_dataset)
  256. preds_list, _ = align_predictions(predictions, label_ids)
  257. # Save predictions
  258. output_test_results_file = os.path.join(training_args.output_dir, "test_results.txt")
  259. if trainer.is_world_master():
  260. with open(output_test_results_file, "w") as writer:
  261. logger.info("***** Test results *****")
  262. for key, value in metrics.items():
  263. logger.info(" %s = %s", key, value)
  264. writer.write("%s = %s\n" % (key, value))
  265. output_test_predictions_file = os.path.join(training_args.output_dir, "test_predictions.txt")
  266. if trainer.is_world_master():
  267. with open(output_test_predictions_file, "w") as writer:
  268. with open(os.path.join(data_args.data_dir, "test.txt"), "r") as f:
  269. example_id = 0
  270. for line in f:
  271. if line.startswith("-DOCSTART-") or line == "" or line == "\n":
  272. writer.write(line)
  273. if not preds_list[example_id]:
  274. example_id += 1
  275. elif preds_list[example_id]:
  276. entity_label = preds_list[example_id].pop(0)
  277. if entity_label == 'O':
  278. output_line = line.split()[0] + " " + entity_label + "\n"
  279. else:
  280. output_line = line.split()[0] + " " + entity_label[0] + "\n"
  281. # output_line = line.split()[0] + " " + preds_list[example_id].pop(0) + "\n"
  282. writer.write(output_line)
  283. else:
  284. logger.warning(
  285. "Maximum sequence length exceeded: No prediction for '%s'.", line.split()[0]
  286. )
  287. dags_logger.save()
  288. dags_logger.close()
  289. return results
  290. def _mp_fn(index):
  291. # For xla_spawn (TPUs)
  292. main()
  293. if __name__ == "__main__":
  294. main()
Tip!

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

Comments

Loading...