update model card README.md
Browse files- .run.sh.swp +0 -0
- README.md +57 -0
- run_qa.py +674 -0
.run.sh.swp
ADDED
Binary file (4.1 kB). View file
|
|
README.md
ADDED
@@ -0,0 +1,57 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
---
|
2 |
+
license: mit
|
3 |
+
tags:
|
4 |
+
- generated_from_trainer
|
5 |
+
model-index:
|
6 |
+
- name: rob-base-gc1
|
7 |
+
results: []
|
8 |
+
---
|
9 |
+
|
10 |
+
<!-- This model card has been generated automatically according to the information the Trainer had access to. You
|
11 |
+
should probably proofread and complete it, then remove this comment. -->
|
12 |
+
|
13 |
+
# rob-base-gc1
|
14 |
+
|
15 |
+
This model is a fine-tuned version of [roberta-base](https://huggingface.co/roberta-base) on the None dataset.
|
16 |
+
|
17 |
+
## Model description
|
18 |
+
|
19 |
+
More information needed
|
20 |
+
|
21 |
+
## Intended uses & limitations
|
22 |
+
|
23 |
+
More information needed
|
24 |
+
|
25 |
+
## Training and evaluation data
|
26 |
+
|
27 |
+
More information needed
|
28 |
+
|
29 |
+
## Training procedure
|
30 |
+
|
31 |
+
### Training hyperparameters
|
32 |
+
|
33 |
+
The following hyperparameters were used during training:
|
34 |
+
- learning_rate: 0.0001
|
35 |
+
- train_batch_size: 4
|
36 |
+
- eval_batch_size: 4
|
37 |
+
- seed: 42
|
38 |
+
- distributed_type: IPU
|
39 |
+
- gradient_accumulation_steps: 64
|
40 |
+
- total_train_batch_size: 256
|
41 |
+
- total_eval_batch_size: 20
|
42 |
+
- optimizer: Adam with betas=(0.9,0.999) and epsilon=1e-08
|
43 |
+
- lr_scheduler_type: linear
|
44 |
+
- lr_scheduler_warmup_ratio: 0.1
|
45 |
+
- num_epochs: 2.0
|
46 |
+
- training precision: Mixed Precision
|
47 |
+
|
48 |
+
### Training results
|
49 |
+
|
50 |
+
|
51 |
+
|
52 |
+
### Framework versions
|
53 |
+
|
54 |
+
- Transformers 4.20.0
|
55 |
+
- Pytorch 1.10.0+cpu
|
56 |
+
- Datasets 2.4.0
|
57 |
+
- Tokenizers 0.12.1
|
run_qa.py
ADDED
@@ -0,0 +1,674 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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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 |
+
"""
|
17 |
+
Fine-tuning the library models for question answering using a slightly adapted version of the 馃 Trainer.
|
18 |
+
"""
|
19 |
+
# You can also adapt this script on your own question answering task. Pointers for this are left as comments.
|
20 |
+
|
21 |
+
import logging
|
22 |
+
import os
|
23 |
+
import sys
|
24 |
+
from dataclasses import dataclass, field
|
25 |
+
from typing import Optional
|
26 |
+
|
27 |
+
import datasets
|
28 |
+
from datasets import load_dataset, load_metric
|
29 |
+
|
30 |
+
import transformers
|
31 |
+
from optimum.graphcore import IPUConfig
|
32 |
+
from optimum.graphcore import IPUTrainingArguments as TrainingArguments
|
33 |
+
from optimum.graphcore.data import pad_on_batch_axis
|
34 |
+
from optimum.graphcore.utils import check_min_version
|
35 |
+
from trainer_qa import QuestionAnsweringTrainer
|
36 |
+
from transformers import (
|
37 |
+
AutoConfig,
|
38 |
+
AutoModelForQuestionAnswering,
|
39 |
+
AutoTokenizer,
|
40 |
+
DataCollatorWithPadding,
|
41 |
+
EvalPrediction,
|
42 |
+
HfArgumentParser,
|
43 |
+
PreTrainedTokenizerFast,
|
44 |
+
default_data_collator,
|
45 |
+
set_seed,
|
46 |
+
)
|
47 |
+
from transformers.trainer_utils import get_last_checkpoint
|
48 |
+
from transformers.utils import check_min_version as tf_check_min_version
|
49 |
+
from transformers.utils import send_example_telemetry
|
50 |
+
from transformers.utils.versions import require_version
|
51 |
+
from utils_qa import postprocess_qa_predictions
|
52 |
+
|
53 |
+
|
54 |
+
# Will error if the minimal version of Transformers is not installed. Remove at your own risks.
|
55 |
+
tf_check_min_version("4.20.0")
|
56 |
+
|
57 |
+
# Will error if the minimal version of Optimum Graphcore is not installed. Remove at your own risks.
|
58 |
+
check_min_version("0.2.4.dev0")
|
59 |
+
|
60 |
+
require_version("datasets>=1.8.0", "To fix: pip install -r examples/pytorch/question-answering/requirements.txt")
|
61 |
+
|
62 |
+
logger = logging.getLogger(__name__)
|
63 |
+
|
64 |
+
|
65 |
+
@dataclass
|
66 |
+
class ModelArguments:
|
67 |
+
"""
|
68 |
+
Arguments pertaining to which model/config/tokenizer we are going to fine-tune from.
|
69 |
+
"""
|
70 |
+
|
71 |
+
model_name_or_path: str = field(
|
72 |
+
metadata={"help": "Path to pretrained model or model identifier from huggingface.co/models"}
|
73 |
+
)
|
74 |
+
config_name: Optional[str] = field(
|
75 |
+
default=None, metadata={"help": "Pretrained config name or path if not the same as model_name"}
|
76 |
+
)
|
77 |
+
tokenizer_name: Optional[str] = field(
|
78 |
+
default=None, metadata={"help": "Pretrained tokenizer name or path if not the same as model_name"}
|
79 |
+
)
|
80 |
+
cache_dir: Optional[str] = field(
|
81 |
+
default=None,
|
82 |
+
metadata={"help": "Path to directory to store the pretrained models downloaded from huggingface.co"},
|
83 |
+
)
|
84 |
+
model_revision: str = field(
|
85 |
+
default="main",
|
86 |
+
metadata={"help": "The specific model version to use (can be a branch name, tag name or commit id)."},
|
87 |
+
)
|
88 |
+
use_auth_token: bool = field(
|
89 |
+
default=False,
|
90 |
+
metadata={
|
91 |
+
"help": (
|
92 |
+
"Will use the token generated when running `transformers-cli login` (necessary to use this script "
|
93 |
+
"with private models)."
|
94 |
+
)
|
95 |
+
},
|
96 |
+
)
|
97 |
+
|
98 |
+
|
99 |
+
@dataclass
|
100 |
+
class DataTrainingArguments:
|
101 |
+
"""
|
102 |
+
Arguments pertaining to what data we are going to input our model for training and eval.
|
103 |
+
"""
|
104 |
+
dataset_path: Optional[str] = field(default=None, metadata={"help": "Path to dataset saved with `save_to_disk`"})
|
105 |
+
dataset_name: Optional[str] = field(
|
106 |
+
default=None, metadata={"help": "The name of the dataset to use (via the datasets library)."}
|
107 |
+
)
|
108 |
+
dataset_config_name: Optional[str] = field(
|
109 |
+
default=None, metadata={"help": "The configuration name of the dataset to use (via the datasets library)."}
|
110 |
+
)
|
111 |
+
train_file: Optional[str] = field(default=None, metadata={"help": "The input training data file (a text file)."})
|
112 |
+
validation_file: Optional[str] = field(
|
113 |
+
default=None,
|
114 |
+
metadata={"help": "An optional input evaluation data file to evaluate the perplexity on (a text file)."},
|
115 |
+
)
|
116 |
+
test_file: Optional[str] = field(
|
117 |
+
default=None,
|
118 |
+
metadata={"help": "An optional input test data file to evaluate the perplexity on (a text file)."},
|
119 |
+
)
|
120 |
+
overwrite_cache: bool = field(
|
121 |
+
default=False, metadata={"help": "Overwrite the cached training and evaluation sets"}
|
122 |
+
)
|
123 |
+
preprocessing_num_workers: Optional[int] = field(
|
124 |
+
default=None,
|
125 |
+
metadata={"help": "The number of processes to use for the preprocessing."},
|
126 |
+
)
|
127 |
+
max_seq_length: int = field(
|
128 |
+
default=384,
|
129 |
+
metadata={
|
130 |
+
"help": (
|
131 |
+
"The maximum total input sequence length after tokenization. Sequences longer "
|
132 |
+
"than this will be truncated, sequences shorter will be padded."
|
133 |
+
)
|
134 |
+
},
|
135 |
+
)
|
136 |
+
pad_to_max_length: bool = field(
|
137 |
+
default=True,
|
138 |
+
metadata={
|
139 |
+
"help": (
|
140 |
+
"Whether to pad all samples to `max_seq_length`. If False, will pad the samples dynamically when"
|
141 |
+
" batching to the maximum length in the batch (which can be faster on GPU but will be slower on TPU)."
|
142 |
+
)
|
143 |
+
},
|
144 |
+
)
|
145 |
+
max_train_samples: Optional[int] = field(
|
146 |
+
default=None,
|
147 |
+
metadata={
|
148 |
+
"help": (
|
149 |
+
"For debugging purposes or quicker training, truncate the number of training examples to this "
|
150 |
+
"value if set."
|
151 |
+
)
|
152 |
+
},
|
153 |
+
)
|
154 |
+
max_eval_samples: Optional[int] = field(
|
155 |
+
default=None,
|
156 |
+
metadata={
|
157 |
+
"help": (
|
158 |
+
"For debugging purposes or quicker training, truncate the number of evaluation examples to this "
|
159 |
+
"value if set."
|
160 |
+
)
|
161 |
+
},
|
162 |
+
)
|
163 |
+
max_predict_samples: Optional[int] = field(
|
164 |
+
default=None,
|
165 |
+
metadata={
|
166 |
+
"help": (
|
167 |
+
"For debugging purposes or quicker training, truncate the number of prediction examples to this "
|
168 |
+
"value if set."
|
169 |
+
)
|
170 |
+
},
|
171 |
+
)
|
172 |
+
version_2_with_negative: bool = field(
|
173 |
+
default=False, metadata={"help": "If true, some of the examples do not have an answer."}
|
174 |
+
)
|
175 |
+
null_score_diff_threshold: float = field(
|
176 |
+
default=0.0,
|
177 |
+
metadata={
|
178 |
+
"help": (
|
179 |
+
"The threshold used to select the null answer: if the best answer has a score that is less than "
|
180 |
+
"the score of the null answer minus this threshold, the null answer is selected for this example. "
|
181 |
+
"Only useful when `version_2_with_negative=True`."
|
182 |
+
)
|
183 |
+
},
|
184 |
+
)
|
185 |
+
doc_stride: int = field(
|
186 |
+
default=128,
|
187 |
+
metadata={"help": "When splitting up a long document into chunks, how much stride to take between chunks."},
|
188 |
+
)
|
189 |
+
n_best_size: int = field(
|
190 |
+
default=20,
|
191 |
+
metadata={"help": "The total number of n-best predictions to generate when looking for an answer."},
|
192 |
+
)
|
193 |
+
max_answer_length: int = field(
|
194 |
+
default=30,
|
195 |
+
metadata={
|
196 |
+
"help": (
|
197 |
+
"The maximum length of an answer that can be generated. This is needed because the start "
|
198 |
+
"and end predictions are not conditioned on one another."
|
199 |
+
)
|
200 |
+
},
|
201 |
+
)
|
202 |
+
|
203 |
+
|
204 |
+
|
205 |
+
def main():
|
206 |
+
# See all possible arguments in src/transformers/training_args.py
|
207 |
+
# or by passing the --help flag to this script.
|
208 |
+
# We now keep distinct sets of args, for a cleaner separation of concerns.
|
209 |
+
|
210 |
+
parser = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments))
|
211 |
+
if len(sys.argv) == 2 and sys.argv[1].endswith(".json"):
|
212 |
+
# If we pass only one argument to the script and it's the path to a json file,
|
213 |
+
# let's parse it to get our arguments.
|
214 |
+
model_args, data_args, training_args = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1]))
|
215 |
+
else:
|
216 |
+
model_args, data_args, training_args = parser.parse_args_into_dataclasses()
|
217 |
+
|
218 |
+
# Sending telemetry. Tracking the example usage helps us better allocate resources to maintain them. The
|
219 |
+
# information sent is the one passed as arguments along with your Python/PyTorch versions.
|
220 |
+
send_example_telemetry("run_qa", model_args, data_args)
|
221 |
+
|
222 |
+
# Setup logging
|
223 |
+
logging.basicConfig(
|
224 |
+
format="%(asctime)s - %(levelname)s - %(name)s - %(message)s",
|
225 |
+
datefmt="%m/%d/%Y %H:%M:%S",
|
226 |
+
handlers=[logging.StreamHandler(sys.stdout)],
|
227 |
+
)
|
228 |
+
|
229 |
+
log_level = training_args.get_process_log_level()
|
230 |
+
logger.setLevel(log_level)
|
231 |
+
datasets.utils.logging.set_verbosity(log_level)
|
232 |
+
transformers.utils.logging.set_verbosity(log_level)
|
233 |
+
transformers.utils.logging.enable_default_handler()
|
234 |
+
transformers.utils.logging.enable_explicit_format()
|
235 |
+
|
236 |
+
logger.info(f"Training/evaluation parameters {training_args}")
|
237 |
+
|
238 |
+
# Detecting last checkpoint.
|
239 |
+
last_checkpoint = None
|
240 |
+
if os.path.isdir(training_args.output_dir) and training_args.do_train and not training_args.overwrite_output_dir:
|
241 |
+
last_checkpoint = get_last_checkpoint(training_args.output_dir)
|
242 |
+
if last_checkpoint is None and len(os.listdir(training_args.output_dir)) > 0:
|
243 |
+
raise ValueError(
|
244 |
+
f"Output directory ({training_args.output_dir}) already exists and is not empty. "
|
245 |
+
"Use --overwrite_output_dir to overcome."
|
246 |
+
)
|
247 |
+
elif last_checkpoint is not None and training_args.resume_from_checkpoint is None:
|
248 |
+
logger.info(
|
249 |
+
f"Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change "
|
250 |
+
"the `--output_dir` or add `--overwrite_output_dir` to train from scratch."
|
251 |
+
)
|
252 |
+
|
253 |
+
# Set seed before initializing model.
|
254 |
+
set_seed(training_args.seed)
|
255 |
+
|
256 |
+
# Get the datasets: you can either provide your own CSV/JSON/TXT training and evaluation files (see below)
|
257 |
+
# or just provide the name of one of the public datasets available on the hub at https://huggingface.co/datasets/
|
258 |
+
# (the dataset will be downloaded automatically from the datasets Hub).
|
259 |
+
#
|
260 |
+
# For CSV/JSON files, this script will use the column called 'text' or the first column if no column called
|
261 |
+
# 'text' is found. You can easily tweak this behavior (see below).
|
262 |
+
#
|
263 |
+
# In distributed training, the load_dataset function guarantee that only one local process can concurrently
|
264 |
+
# download the dataset.
|
265 |
+
if data_args.dataset_path is not None:
|
266 |
+
raw_datasets = datasets.load_from_disk(data_args.dataset_path)
|
267 |
+
elif data_args.dataset_name is not None:
|
268 |
+
# Downloading and loading a dataset from the hub.
|
269 |
+
raw_datasets = load_dataset(
|
270 |
+
data_args.dataset_name,
|
271 |
+
data_args.dataset_config_name,
|
272 |
+
cache_dir=model_args.cache_dir,
|
273 |
+
use_auth_token=True if model_args.use_auth_token else None,
|
274 |
+
)
|
275 |
+
else:
|
276 |
+
data_files = {}
|
277 |
+
if data_args.train_file is not None:
|
278 |
+
data_files["train"] = data_args.train_file
|
279 |
+
extension = data_args.train_file.split(".")[-1]
|
280 |
+
|
281 |
+
if data_args.validation_file is not None:
|
282 |
+
data_files["validation"] = data_args.validation_file
|
283 |
+
extension = data_args.validation_file.split(".")[-1]
|
284 |
+
if data_args.test_file is not None:
|
285 |
+
data_files["test"] = data_args.test_file
|
286 |
+
extension = data_args.test_file.split(".")[-1]
|
287 |
+
raw_datasets = load_dataset(
|
288 |
+
extension,
|
289 |
+
data_files=data_files,
|
290 |
+
field="data",
|
291 |
+
cache_dir=model_args.cache_dir,
|
292 |
+
use_auth_token=True if model_args.use_auth_token else None,
|
293 |
+
)
|
294 |
+
# See more about loading any type of standard or custom dataset (from files, python dict, pandas DataFrame, etc) at
|
295 |
+
# https://huggingface.co/docs/datasets/loading_datasets.html.
|
296 |
+
|
297 |
+
# Load pretrained model and tokenizer
|
298 |
+
#
|
299 |
+
# Distributed training:
|
300 |
+
# The .from_pretrained methods guarantee that only one local process can concurrently
|
301 |
+
# download model & vocab.
|
302 |
+
config = AutoConfig.from_pretrained(
|
303 |
+
model_args.config_name if model_args.config_name else model_args.model_name_or_path,
|
304 |
+
cache_dir=model_args.cache_dir,
|
305 |
+
revision=model_args.model_revision,
|
306 |
+
use_auth_token=True if model_args.use_auth_token else None,
|
307 |
+
)
|
308 |
+
ipu_config = IPUConfig.from_pretrained(
|
309 |
+
training_args.ipu_config_name if training_args.ipu_config_name else model_args.model_name_or_path,
|
310 |
+
cache_dir=model_args.cache_dir,
|
311 |
+
revision=model_args.model_revision,
|
312 |
+
use_auth_token=True if model_args.use_auth_token else None,
|
313 |
+
)
|
314 |
+
|
315 |
+
tokenizer = AutoTokenizer.from_pretrained(
|
316 |
+
model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path,
|
317 |
+
cache_dir=model_args.cache_dir,
|
318 |
+
use_fast=True,
|
319 |
+
revision=model_args.model_revision,
|
320 |
+
use_auth_token=True if model_args.use_auth_token else None,
|
321 |
+
)
|
322 |
+
model = AutoModelForQuestionAnswering.from_pretrained(
|
323 |
+
model_args.model_name_or_path,
|
324 |
+
from_tf=bool(".ckpt" in model_args.model_name_or_path),
|
325 |
+
config=config,
|
326 |
+
cache_dir=model_args.cache_dir,
|
327 |
+
revision=model_args.model_revision,
|
328 |
+
use_auth_token=True if model_args.use_auth_token else None,
|
329 |
+
)
|
330 |
+
|
331 |
+
# Tokenizer check: this script requires a fast tokenizer.
|
332 |
+
if not isinstance(tokenizer, PreTrainedTokenizerFast):
|
333 |
+
raise ValueError(
|
334 |
+
"This example script only works for models that have a fast tokenizer. Checkout the big table of models at"
|
335 |
+
" https://huggingface.co/transformers/index.html#supported-frameworks to find the model types that meet"
|
336 |
+
" this requirement"
|
337 |
+
)
|
338 |
+
|
339 |
+
# Preprocessing the datasets.
|
340 |
+
# Preprocessing is slighlty different for training and evaluation.
|
341 |
+
if training_args.do_train:
|
342 |
+
column_names = raw_datasets["train"].column_names
|
343 |
+
elif training_args.do_eval:
|
344 |
+
column_names = raw_datasets["validation"].column_names
|
345 |
+
else:
|
346 |
+
column_names = raw_datasets["test"].column_names
|
347 |
+
question_column_name = "question" if "question" in column_names else column_names[0]
|
348 |
+
context_column_name = "context" if "context" in column_names else column_names[1]
|
349 |
+
answer_column_name = "answers" if "answers" in column_names else column_names[2]
|
350 |
+
|
351 |
+
# Padding side determines if we do (question|context) or (context|question).
|
352 |
+
pad_on_right = tokenizer.padding_side == "right"
|
353 |
+
|
354 |
+
if data_args.max_seq_length > tokenizer.model_max_length:
|
355 |
+
logger.warning(
|
356 |
+
f"The max_seq_length passed ({data_args.max_seq_length}) is larger than the maximum length for the"
|
357 |
+
f"model ({tokenizer.model_max_length}). Using max_seq_length={tokenizer.model_max_length}."
|
358 |
+
)
|
359 |
+
max_seq_length = min(data_args.max_seq_length, tokenizer.model_max_length)
|
360 |
+
|
361 |
+
# Training preprocessing
|
362 |
+
def prepare_train_features(examples):
|
363 |
+
# Some of the questions have lots of whitespace on the left, which is not useful and will make the
|
364 |
+
# truncation of the context fail (the tokenized question will take a lots of space). So we remove that
|
365 |
+
# left whitespace
|
366 |
+
examples[question_column_name] = [q.lstrip() for q in examples[question_column_name]]
|
367 |
+
|
368 |
+
# Tokenize our examples with truncation and maybe padding, but keep the overflows using a stride. This results
|
369 |
+
# in one example possible giving several features when a context is long, each of those features having a
|
370 |
+
# context that overlaps a bit the context of the previous feature.
|
371 |
+
tokenized_examples = tokenizer(
|
372 |
+
examples[question_column_name if pad_on_right else context_column_name],
|
373 |
+
examples[context_column_name if pad_on_right else question_column_name],
|
374 |
+
truncation="only_second" if pad_on_right else "only_first",
|
375 |
+
max_length=max_seq_length,
|
376 |
+
stride=data_args.doc_stride,
|
377 |
+
return_overflowing_tokens=True,
|
378 |
+
return_offsets_mapping=True,
|
379 |
+
padding="max_length" if data_args.pad_to_max_length else False,
|
380 |
+
)
|
381 |
+
|
382 |
+
# Since one example might give us several features if it has a long context, we need a map from a feature to
|
383 |
+
# its corresponding example. This key gives us just that.
|
384 |
+
sample_mapping = tokenized_examples.pop("overflow_to_sample_mapping")
|
385 |
+
# The offset mappings will give us a map from token to character position in the original context. This will
|
386 |
+
# help us compute the start_positions and end_positions.
|
387 |
+
offset_mapping = tokenized_examples.pop("offset_mapping")
|
388 |
+
|
389 |
+
# Let's label those examples!
|
390 |
+
tokenized_examples["start_positions"] = []
|
391 |
+
tokenized_examples["end_positions"] = []
|
392 |
+
|
393 |
+
for i, offsets in enumerate(offset_mapping):
|
394 |
+
# We will label impossible answers with the index of the CLS token.
|
395 |
+
input_ids = tokenized_examples["input_ids"][i]
|
396 |
+
cls_index = input_ids.index(tokenizer.cls_token_id)
|
397 |
+
|
398 |
+
# Grab the sequence corresponding to that example (to know what is the context and what is the question).
|
399 |
+
sequence_ids = tokenized_examples.sequence_ids(i)
|
400 |
+
|
401 |
+
# One example can give several spans, this is the index of the example containing this span of text.
|
402 |
+
sample_index = sample_mapping[i]
|
403 |
+
answers = examples[answer_column_name][sample_index]
|
404 |
+
# If no answers are given, set the cls_index as answer.
|
405 |
+
if len(answers["answer_start"]) == 0:
|
406 |
+
tokenized_examples["start_positions"].append(cls_index)
|
407 |
+
tokenized_examples["end_positions"].append(cls_index)
|
408 |
+
else:
|
409 |
+
# Start/end character index of the answer in the text.
|
410 |
+
start_char = answers["answer_start"][0]
|
411 |
+
end_char = start_char + len(answers["text"][0])
|
412 |
+
|
413 |
+
# Start token index of the current span in the text.
|
414 |
+
token_start_index = 0
|
415 |
+
while sequence_ids[token_start_index] != (1 if pad_on_right else 0):
|
416 |
+
token_start_index += 1
|
417 |
+
|
418 |
+
# End token index of the current span in the text.
|
419 |
+
token_end_index = len(input_ids) - 1
|
420 |
+
while sequence_ids[token_end_index] != (1 if pad_on_right else 0):
|
421 |
+
token_end_index -= 1
|
422 |
+
|
423 |
+
# Detect if the answer is out of the span (in which case this feature is labeled with the CLS index).
|
424 |
+
if not (offsets[token_start_index][0] <= start_char and offsets[token_end_index][1] >= end_char):
|
425 |
+
tokenized_examples["start_positions"].append(cls_index)
|
426 |
+
tokenized_examples["end_positions"].append(cls_index)
|
427 |
+
else:
|
428 |
+
# Otherwise move the token_start_index and token_end_index to the two ends of the answer.
|
429 |
+
# Note: we could go after the last offset if the answer is the last word (edge case).
|
430 |
+
while token_start_index < len(offsets) and offsets[token_start_index][0] <= start_char:
|
431 |
+
token_start_index += 1
|
432 |
+
tokenized_examples["start_positions"].append(token_start_index - 1)
|
433 |
+
while offsets[token_end_index][1] >= end_char:
|
434 |
+
token_end_index -= 1
|
435 |
+
tokenized_examples["end_positions"].append(token_end_index + 1)
|
436 |
+
|
437 |
+
return tokenized_examples
|
438 |
+
|
439 |
+
if training_args.do_train:
|
440 |
+
if "train" not in raw_datasets:
|
441 |
+
raise ValueError("--do_train requires a train dataset")
|
442 |
+
train_dataset = raw_datasets["train"]
|
443 |
+
if data_args.max_train_samples is not None:
|
444 |
+
# We will select sample from whole data if argument is specified
|
445 |
+
max_train_samples = min(len(train_dataset), data_args.max_train_samples)
|
446 |
+
train_dataset = train_dataset.select(range(max_train_samples))
|
447 |
+
# Create train feature from dataset
|
448 |
+
with training_args.main_process_first(desc="train dataset map pre-processing"):
|
449 |
+
train_dataset = train_dataset.map(
|
450 |
+
prepare_train_features,
|
451 |
+
batched=True,
|
452 |
+
num_proc=data_args.preprocessing_num_workers,
|
453 |
+
remove_columns=column_names,
|
454 |
+
load_from_cache_file=not data_args.overwrite_cache,
|
455 |
+
desc="Running tokenizer on train dataset",
|
456 |
+
)
|
457 |
+
if data_args.max_train_samples is not None:
|
458 |
+
# Number of samples might increase during Feature Creation, We select only specified max samples
|
459 |
+
max_train_samples = min(len(train_dataset), data_args.max_train_samples)
|
460 |
+
train_dataset = train_dataset.select(range(max_train_samples))
|
461 |
+
|
462 |
+
# Validation preprocessing
|
463 |
+
def prepare_validation_features(examples):
|
464 |
+
# Some of the questions have lots of whitespace on the left, which is not useful and will make the
|
465 |
+
# truncation of the context fail (the tokenized question will take a lots of space). So we remove that
|
466 |
+
# left whitespace
|
467 |
+
examples[question_column_name] = [q.lstrip() for q in examples[question_column_name]]
|
468 |
+
|
469 |
+
# Tokenize our examples with truncation and maybe padding, but keep the overflows using a stride. This results
|
470 |
+
# in one example possible giving several features when a context is long, each of those features having a
|
471 |
+
# context that overlaps a bit the context of the previous feature.
|
472 |
+
tokenized_examples = tokenizer(
|
473 |
+
examples[question_column_name if pad_on_right else context_column_name],
|
474 |
+
examples[context_column_name if pad_on_right else question_column_name],
|
475 |
+
truncation="only_second" if pad_on_right else "only_first",
|
476 |
+
max_length=max_seq_length,
|
477 |
+
stride=data_args.doc_stride,
|
478 |
+
return_overflowing_tokens=True,
|
479 |
+
return_offsets_mapping=True,
|
480 |
+
padding="max_length" if data_args.pad_to_max_length else False,
|
481 |
+
)
|
482 |
+
|
483 |
+
# Since one example might give us several features if it has a long context, we need a map from a feature to
|
484 |
+
# its corresponding example. This key gives us just that.
|
485 |
+
sample_mapping = tokenized_examples.pop("overflow_to_sample_mapping")
|
486 |
+
|
487 |
+
# For evaluation, we will need to convert our predictions to substrings of the context, so we keep the
|
488 |
+
# corresponding example_id and we will store the offset mappings.
|
489 |
+
tokenized_examples["example_id"] = []
|
490 |
+
|
491 |
+
for i in range(len(tokenized_examples["input_ids"])):
|
492 |
+
# Grab the sequence corresponding to that example (to know what is the context and what is the question).
|
493 |
+
sequence_ids = tokenized_examples.sequence_ids(i)
|
494 |
+
context_index = 1 if pad_on_right else 0
|
495 |
+
|
496 |
+
# One example can give several spans, this is the index of the example containing this span of text.
|
497 |
+
sample_index = sample_mapping[i]
|
498 |
+
tokenized_examples["example_id"].append(examples["id"][sample_index])
|
499 |
+
|
500 |
+
# Set to None the offset_mapping that are not part of the context so it's easy to determine if a token
|
501 |
+
# position is part of the context or not.
|
502 |
+
tokenized_examples["offset_mapping"][i] = [
|
503 |
+
(o if sequence_ids[k] == context_index else None)
|
504 |
+
for k, o in enumerate(tokenized_examples["offset_mapping"][i])
|
505 |
+
]
|
506 |
+
|
507 |
+
return tokenized_examples
|
508 |
+
|
509 |
+
if training_args.do_eval:
|
510 |
+
if "validation" not in raw_datasets:
|
511 |
+
raise ValueError("--do_eval requires a validation dataset")
|
512 |
+
eval_examples = raw_datasets["validation"]
|
513 |
+
if data_args.max_eval_samples is not None:
|
514 |
+
# We will select sample from whole data
|
515 |
+
max_eval_samples = min(len(eval_examples), data_args.max_eval_samples)
|
516 |
+
eval_examples = eval_examples.select(range(max_eval_samples))
|
517 |
+
# Validation Feature Creation
|
518 |
+
with training_args.main_process_first(desc="validation dataset map pre-processing"):
|
519 |
+
eval_dataset = eval_examples.map(
|
520 |
+
prepare_validation_features,
|
521 |
+
batched=True,
|
522 |
+
num_proc=data_args.preprocessing_num_workers,
|
523 |
+
remove_columns=column_names,
|
524 |
+
load_from_cache_file=not data_args.overwrite_cache,
|
525 |
+
desc="Running tokenizer on validation dataset",
|
526 |
+
)
|
527 |
+
if data_args.max_eval_samples is not None:
|
528 |
+
# During Feature creation dataset samples might increase, we will select required samples again
|
529 |
+
max_eval_samples = min(len(eval_dataset), data_args.max_eval_samples)
|
530 |
+
eval_dataset = eval_dataset.select(range(max_eval_samples))
|
531 |
+
|
532 |
+
if training_args.do_predict:
|
533 |
+
if "test" not in raw_datasets:
|
534 |
+
raise ValueError("--do_predict requires a test dataset")
|
535 |
+
predict_examples = raw_datasets["test"]
|
536 |
+
if data_args.max_predict_samples is not None:
|
537 |
+
# We will select sample from whole data
|
538 |
+
predict_examples = predict_examples.select(range(data_args.max_predict_samples))
|
539 |
+
# Predict Feature Creation
|
540 |
+
with training_args.main_process_first(desc="prediction dataset map pre-processing"):
|
541 |
+
predict_dataset = predict_examples.map(
|
542 |
+
prepare_validation_features,
|
543 |
+
batched=True,
|
544 |
+
num_proc=data_args.preprocessing_num_workers,
|
545 |
+
remove_columns=column_names,
|
546 |
+
load_from_cache_file=not data_args.overwrite_cache,
|
547 |
+
desc="Running tokenizer on prediction dataset",
|
548 |
+
)
|
549 |
+
if data_args.max_predict_samples is not None:
|
550 |
+
# During Feature creation dataset samples might increase, we will select required samples again
|
551 |
+
max_predict_samples = min(len(predict_dataset), data_args.max_predict_samples)
|
552 |
+
predict_dataset = predict_dataset.select(range(max_predict_samples))
|
553 |
+
|
554 |
+
# Data collator
|
555 |
+
# We have already padded to max length if the corresponding flag is True, otherwise we need to pad in the data
|
556 |
+
# collator.
|
557 |
+
data_collator = (
|
558 |
+
default_data_collator
|
559 |
+
if data_args.pad_to_max_length
|
560 |
+
else DataCollatorWithPadding(tokenizer, pad_to_multiple_of=8 if training_args.fp16 else None)
|
561 |
+
)
|
562 |
+
|
563 |
+
# Post-processing:
|
564 |
+
def post_processing_function(examples, features, predictions, stage="eval"):
|
565 |
+
# Post-processing: we match the start logits and end logits to answers in the original context.
|
566 |
+
predictions = postprocess_qa_predictions(
|
567 |
+
examples=examples,
|
568 |
+
features=features,
|
569 |
+
predictions=predictions,
|
570 |
+
version_2_with_negative=data_args.version_2_with_negative,
|
571 |
+
n_best_size=data_args.n_best_size,
|
572 |
+
max_answer_length=data_args.max_answer_length,
|
573 |
+
null_score_diff_threshold=data_args.null_score_diff_threshold,
|
574 |
+
output_dir=training_args.output_dir,
|
575 |
+
log_level=log_level,
|
576 |
+
prefix=stage,
|
577 |
+
)
|
578 |
+
# Format the result to the format the metric expects.
|
579 |
+
if data_args.version_2_with_negative:
|
580 |
+
formatted_predictions = [
|
581 |
+
{"id": k, "prediction_text": v, "no_answer_probability": 0.0} for k, v in predictions.items()
|
582 |
+
]
|
583 |
+
else:
|
584 |
+
formatted_predictions = [{"id": k, "prediction_text": v} for k, v in predictions.items()]
|
585 |
+
|
586 |
+
references = [{"id": ex["id"], "answers": ex[answer_column_name]} for ex in examples]
|
587 |
+
return EvalPrediction(predictions=formatted_predictions, label_ids=references)
|
588 |
+
|
589 |
+
metric = load_metric("squad_v2" if data_args.version_2_with_negative else "squad")
|
590 |
+
|
591 |
+
def compute_metrics(p: EvalPrediction):
|
592 |
+
return metric.compute(predictions=p.predictions, references=p.label_ids)
|
593 |
+
|
594 |
+
# Initialize our Trainer
|
595 |
+
trainer = QuestionAnsweringTrainer(
|
596 |
+
model=model,
|
597 |
+
ipu_config=ipu_config,
|
598 |
+
args=training_args,
|
599 |
+
train_dataset=train_dataset if training_args.do_train else None,
|
600 |
+
eval_dataset=eval_dataset if training_args.do_eval else None,
|
601 |
+
eval_examples=eval_examples if training_args.do_eval else None,
|
602 |
+
tokenizer=tokenizer,
|
603 |
+
data_collator=data_collator,
|
604 |
+
post_process_function=post_processing_function,
|
605 |
+
compute_metrics=compute_metrics,
|
606 |
+
)
|
607 |
+
|
608 |
+
# Training
|
609 |
+
if training_args.do_train:
|
610 |
+
checkpoint = None
|
611 |
+
if training_args.resume_from_checkpoint is not None:
|
612 |
+
checkpoint = training_args.resume_from_checkpoint
|
613 |
+
elif last_checkpoint is not None:
|
614 |
+
checkpoint = last_checkpoint
|
615 |
+
train_result = trainer.train(resume_from_checkpoint=checkpoint)
|
616 |
+
trainer.save_model() # Saves the tokenizer too for easy upload
|
617 |
+
|
618 |
+
metrics = train_result.metrics
|
619 |
+
max_train_samples = (
|
620 |
+
data_args.max_train_samples if data_args.max_train_samples is not None else len(train_dataset)
|
621 |
+
)
|
622 |
+
metrics["train_samples"] = min(max_train_samples, len(train_dataset))
|
623 |
+
|
624 |
+
trainer.log_metrics("train", metrics)
|
625 |
+
trainer.save_metrics("train", metrics)
|
626 |
+
trainer.save_state()
|
627 |
+
|
628 |
+
# Evaluation
|
629 |
+
if training_args.do_eval:
|
630 |
+
logger.info("*** Evaluate ***")
|
631 |
+
metrics = trainer.evaluate()
|
632 |
+
|
633 |
+
max_eval_samples = data_args.max_eval_samples if data_args.max_eval_samples is not None else len(eval_dataset)
|
634 |
+
metrics["eval_samples"] = min(max_eval_samples, len(eval_dataset))
|
635 |
+
|
636 |
+
trainer.log_metrics("eval", metrics)
|
637 |
+
trainer.save_metrics("eval", metrics)
|
638 |
+
|
639 |
+
# Prediction
|
640 |
+
if training_args.do_predict:
|
641 |
+
logger.info("*** Predict ***")
|
642 |
+
results = trainer.predict(predict_dataset, predict_examples)
|
643 |
+
metrics = results.metrics
|
644 |
+
|
645 |
+
max_predict_samples = (
|
646 |
+
data_args.max_predict_samples if data_args.max_predict_samples is not None else len(predict_dataset)
|
647 |
+
)
|
648 |
+
metrics["predict_samples"] = min(max_predict_samples, len(predict_dataset))
|
649 |
+
|
650 |
+
trainer.log_metrics("predict", metrics)
|
651 |
+
trainer.save_metrics("predict", metrics)
|
652 |
+
|
653 |
+
kwargs = {"finetuned_from": model_args.model_name_or_path, "tasks": "question-answering"}
|
654 |
+
if data_args.dataset_name is not None:
|
655 |
+
kwargs["dataset_tags"] = data_args.dataset_name
|
656 |
+
if data_args.dataset_config_name is not None:
|
657 |
+
kwargs["dataset_args"] = data_args.dataset_config_name
|
658 |
+
kwargs["dataset"] = f"{data_args.dataset_name} {data_args.dataset_config_name}"
|
659 |
+
else:
|
660 |
+
kwargs["dataset"] = data_args.dataset_name
|
661 |
+
|
662 |
+
if training_args.push_to_hub:
|
663 |
+
trainer.push_to_hub(**kwargs)
|
664 |
+
else:
|
665 |
+
trainer.create_model_card(**kwargs)
|
666 |
+
|
667 |
+
|
668 |
+
def _mp_fn(index):
|
669 |
+
# For xla_spawn (TPUs)
|
670 |
+
main()
|
671 |
+
|
672 |
+
|
673 |
+
if __name__ == "__main__":
|
674 |
+
main()
|