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_re.py 9.8 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
  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. """ Finetuning the library models for sequence classification on GLUE (Bert, XLM, XLNet, RoBERTa, Albert, XLM-RoBERTa)."""
  17. import dataclasses
  18. import logging
  19. import os
  20. import sys
  21. from dataclasses import dataclass, field
  22. from typing import Callable, Dict, Optional
  23. import numpy as np
  24. from transformers import AutoConfig, AutoModelForSequenceClassification, AutoTokenizer, EvalPrediction, GlueDataset
  25. from transformers import GlueDataTrainingArguments as DataTrainingArguments
  26. from transformers import (
  27. HfArgumentParser,
  28. Trainer,
  29. TrainingArguments,
  30. #glue_compute_metrics,
  31. glue_output_modes,
  32. glue_tasks_num_labels,
  33. set_seed,
  34. )
  35. from metrics import glue_compute_metrics
  36. logger = logging.getLogger(__name__)
  37. @dataclass
  38. class ModelArguments:
  39. """
  40. Arguments pertaining to which model/config/tokenizer we are going to fine-tune from.
  41. """
  42. model_name_or_path: str = field(
  43. metadata={"help": "Path to pretrained model or model identifier from huggingface.co/models"}
  44. )
  45. config_name: Optional[str] = field(
  46. default=None, metadata={"help": "Pretrained config name or path if not the same as model_name"}
  47. )
  48. tokenizer_name: Optional[str] = field(
  49. default=None, metadata={"help": "Pretrained tokenizer name or path if not the same as model_name"}
  50. )
  51. cache_dir: Optional[str] = field(
  52. default=None, metadata={"help": "Where do you want to store the pretrained models downloaded from s3"}
  53. )
  54. warmup_proportion: Optional[float] = field(
  55. default=0.1, metadata={"help": "Proportion of training to perform linear learning rate warmup for. E.g., 0.1 = 10% of training."}
  56. )
  57. def main():
  58. # See all possible arguments in src/transformers/training_args.py
  59. # or by passing the --help flag to this script.
  60. # We now keep distinct sets of args, for a cleaner separation of concerns.
  61. parser = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments))
  62. if len(sys.argv) == 2 and sys.argv[1].endswith(".json"):
  63. # If we pass only one argument to the script and it's the path to a json file,
  64. # let's parse it to get our arguments.
  65. model_args, data_args, training_args = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1]))
  66. else:
  67. model_args, data_args, training_args = parser.parse_args_into_dataclasses()
  68. if (
  69. os.path.exists(training_args.output_dir)
  70. and os.listdir(training_args.output_dir)
  71. and training_args.do_train
  72. and not training_args.overwrite_output_dir
  73. ):
  74. raise ValueError(
  75. f"Output directory ({training_args.output_dir}) already exists and is not empty. Use --overwrite_output_dir to overcome."
  76. )
  77. # Setup logging
  78. logging.basicConfig(
  79. format="%(asctime)s - %(levelname)s - %(name)s - %(message)s",
  80. datefmt="%m/%d/%Y %H:%M:%S",
  81. level=logging.INFO if training_args.local_rank in [-1, 0] else logging.WARN,
  82. )
  83. logger.warning(
  84. "Process rank: %s, device: %s, n_gpu: %s, distributed training: %s, 16-bits training: %s",
  85. training_args.local_rank,
  86. training_args.device,
  87. training_args.n_gpu,
  88. bool(training_args.local_rank != -1),
  89. training_args.fp16,
  90. )
  91. # Set seed
  92. set_seed(training_args.seed)
  93. try:
  94. num_labels = glue_tasks_num_labels[data_args.task_name]
  95. output_mode = glue_output_modes[data_args.task_name]
  96. except KeyError:
  97. raise ValueError("Task not found: %s" % (data_args.task_name))
  98. # Load tokenizer
  99. tokenizer = AutoTokenizer.from_pretrained(
  100. model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path,
  101. cache_dir=model_args.cache_dir,
  102. )
  103. # Get datasets
  104. train_dataset = (
  105. GlueDataset(data_args, tokenizer=tokenizer, cache_dir=model_args.cache_dir) if training_args.do_train else None
  106. )
  107. eval_dataset = (
  108. GlueDataset(data_args, tokenizer=tokenizer, mode="dev", cache_dir=model_args.cache_dir)
  109. if training_args.do_eval
  110. else None
  111. )
  112. test_dataset = (
  113. GlueDataset(data_args, tokenizer=tokenizer, mode="test", cache_dir=model_args.cache_dir)
  114. if training_args.do_predict
  115. else None
  116. )
  117. # Load pretrained model
  118. # Distributed training:
  119. # The .from_pretrained methods guarantee that only one local process can concurrently
  120. # download model & vocab.
  121. # Currently, this code do not support distributed training.
  122. training_args.warmup_steps = int(model_args.warmup_proportion * (len(train_dataset) / training_args.per_device_train_batch_size) * training_args.num_train_epochs)
  123. training_args_weight_decay = 0.01
  124. logger.info("Training/evaluation parameters %s", training_args)
  125. config = AutoConfig.from_pretrained(
  126. model_args.config_name if model_args.config_name else model_args.model_name_or_path,
  127. num_labels=num_labels,
  128. finetuning_task=data_args.task_name,
  129. cache_dir=model_args.cache_dir,
  130. )
  131. model = AutoModelForSequenceClassification.from_pretrained(
  132. model_args.model_name_or_path,
  133. from_tf=bool(".ckpt" in model_args.model_name_or_path),
  134. config=config,
  135. cache_dir=model_args.cache_dir,
  136. )
  137. def build_compute_metrics_fn(task_name: str) -> Callable[[EvalPrediction], Dict]:
  138. def compute_metrics_fn(p: EvalPrediction):
  139. if output_mode == "classification":
  140. preds = np.argmax(p.predictions, axis=1)
  141. elif output_mode == "regression":
  142. preds = np.squeeze(p.predictions)
  143. return glue_compute_metrics(task_name, preds, p.label_ids)
  144. return compute_metrics_fn
  145. # Initialize our Trainer
  146. trainer = Trainer(
  147. model=model,
  148. args=training_args,
  149. train_dataset=train_dataset,
  150. eval_dataset=eval_dataset,
  151. compute_metrics=build_compute_metrics_fn(data_args.task_name),
  152. )
  153. # Training
  154. if training_args.do_train:
  155. trainer.train(
  156. model_path=model_args.model_name_or_path if os.path.isdir(model_args.model_name_or_path) else None
  157. )
  158. trainer.save_model()
  159. # For convenience, we also re-save the tokenizer to the same directory,
  160. # so that you can share your model easily on huggingface.co/models =)
  161. if trainer.is_world_master():
  162. tokenizer.save_pretrained(training_args.output_dir)
  163. # Evaluation
  164. eval_results = {}
  165. if training_args.do_eval:
  166. logger.info("*** Evaluate ***")
  167. # Loop to handle MNLI double evaluation (matched, mis-matched)
  168. eval_datasets = [eval_dataset]
  169. if data_args.task_name == "mnli":
  170. mnli_mm_data_args = dataclasses.replace(data_args, task_name="mnli-mm")
  171. eval_datasets.append(
  172. GlueDataset(mnli_mm_data_args, tokenizer=tokenizer, mode="dev", cache_dir=model_args.cache_dir)
  173. )
  174. for eval_dataset in eval_datasets:
  175. trainer.compute_metrics = build_compute_metrics_fn(eval_dataset.args.task_name)
  176. eval_result = trainer.evaluate(eval_dataset=eval_dataset)
  177. output_eval_file = os.path.join(
  178. training_args.output_dir, f"eval_results_{eval_dataset.args.task_name}.txt"
  179. )
  180. if trainer.is_world_master():
  181. with open(output_eval_file, "w") as writer:
  182. logger.info("***** Eval results {} *****".format(eval_dataset.args.task_name))
  183. for key, value in eval_result.items():
  184. logger.info(" %s = %s", key, value)
  185. writer.write("%s = %s\n" % (key, value))
  186. eval_results.update(eval_result)
  187. if training_args.do_predict:
  188. logging.info("*** Test ***")
  189. test_datasets = [test_dataset]
  190. if data_args.task_name == "mnli":
  191. mnli_mm_data_args = dataclasses.replace(data_args, task_name="mnli-mm")
  192. test_datasets.append(
  193. GlueDataset(mnli_mm_data_args, tokenizer=tokenizer, mode="test", cache_dir=model_args.cache_dir)
  194. )
  195. for test_dataset in test_datasets:
  196. predictions = trainer.predict(test_dataset=test_dataset).predictions
  197. if output_mode == "classification":
  198. predictions = np.argmax(predictions, axis=1)
  199. output_test_file = os.path.join(
  200. training_args.output_dir,
  201. f"test_results.txt"
  202. #f"test_results_{test_dataset.args.task_name}.txt"
  203. )
  204. if trainer.is_world_master():
  205. with open(output_test_file, "w") as writer:
  206. logger.info("***** Test results {} *****".format(test_dataset.args.task_name))
  207. writer.write("index\tprediction\n")
  208. for index, item in enumerate(predictions):
  209. if output_mode == "regression":
  210. writer.write("%d\t%3.3f\n" % (index, item))
  211. else:
  212. item = test_dataset.get_labels()[item]
  213. writer.write("%d\t%s\n" % (index, item))
  214. return eval_results
  215. def _mp_fn(index):
  216. # For xla_spawn (TPUs)
  217. main()
  218. if __name__ == "__main__":
  219. main()
Tip!

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

Comments

Loading...