transformers
163 строки · 7.0 Кб
1# coding=utf-8
2# Copyright 2021 The HuggingFace Team All rights reserved.
3#
4# Licensed under the Apache License, Version 2.0 (the "License");
5# you may not use this file except in compliance with the License.
6# You may obtain a copy of the License at
7#
8# http://www.apache.org/licenses/LICENSE-2.0
9#
10# Unless required by applicable law or agreed to in writing, software
11# distributed under the License is distributed on an "AS IS" BASIS,
12# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13# See the License for the specific language governing permissions and
14# limitations under the License.
15"""
16A subclass of `Trainer` specific to Question-Answering tasks
17"""
18import math
19import time
20from typing import Dict, List, Optional
21
22from torch.utils.data import Dataset
23
24from transformers import Seq2SeqTrainer, is_torch_tpu_available
25from transformers.trainer_utils import PredictionOutput, speed_metrics
26
27
28if is_torch_tpu_available(check_device=False):
29import torch_xla.core.xla_model as xm
30import torch_xla.debug.metrics as met
31
32
33class QuestionAnsweringSeq2SeqTrainer(Seq2SeqTrainer):
34def __init__(self, *args, eval_examples=None, post_process_function=None, **kwargs):
35super().__init__(*args, **kwargs)
36self.eval_examples = eval_examples
37self.post_process_function = post_process_function
38
39# def evaluate(self, eval_dataset=None, eval_examples=None, ignore_keys=None, metric_key_prefix: str = "eval"):
40def evaluate(
41self,
42eval_dataset: Optional[Dataset] = None,
43eval_examples=None,
44ignore_keys: Optional[List[str]] = None,
45metric_key_prefix: str = "eval",
46**gen_kwargs,
47) -> Dict[str, float]:
48gen_kwargs = gen_kwargs.copy()
49
50# Use legacy argument setting if a) the option is not explicitly passed; and b) the argument is set in the
51# training args
52if gen_kwargs.get("max_length") is None and self.args.generation_max_length is not None:
53gen_kwargs["max_length"] = self.args.generation_max_length
54if gen_kwargs.get("num_beams") is None and self.args.generation_num_beams is not None:
55gen_kwargs["num_beams"] = self.args.generation_num_beams
56self._gen_kwargs = gen_kwargs
57
58eval_dataset = self.eval_dataset if eval_dataset is None else eval_dataset
59eval_dataloader = self.get_eval_dataloader(eval_dataset)
60eval_examples = self.eval_examples if eval_examples is None else eval_examples
61
62# Temporarily disable metric computation, we will do it in the loop here.
63compute_metrics = self.compute_metrics
64self.compute_metrics = None
65start_time = time.time()
66eval_loop = self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop
67try:
68output = eval_loop(
69eval_dataloader,
70description="Evaluation",
71# No point gathering the predictions if there are no metrics, otherwise we defer to
72# self.args.prediction_loss_only
73prediction_loss_only=True if compute_metrics is None else None,
74ignore_keys=ignore_keys,
75metric_key_prefix=metric_key_prefix,
76)
77finally:
78self.compute_metrics = compute_metrics
79total_batch_size = self.args.eval_batch_size * self.args.world_size
80if f"{metric_key_prefix}_jit_compilation_time" in output.metrics:
81start_time += output.metrics[f"{metric_key_prefix}_jit_compilation_time"]
82output.metrics.update(
83speed_metrics(
84metric_key_prefix,
85start_time,
86num_samples=output.num_samples,
87num_steps=math.ceil(output.num_samples / total_batch_size),
88)
89)
90
91if self.post_process_function is not None and self.compute_metrics is not None and self.args.should_save:
92# Only the main node write the results by default
93eval_preds = self.post_process_function(eval_examples, eval_dataset, output)
94metrics = self.compute_metrics(eval_preds)
95
96# Prefix all keys with metric_key_prefix + '_'
97for key in list(metrics.keys()):
98if not key.startswith(f"{metric_key_prefix}_"):
99metrics[f"{metric_key_prefix}_{key}"] = metrics.pop(key)
100
101metrics.update(output.metrics)
102else:
103metrics = output.metrics
104
105if self.args.should_log:
106# Only the main node log the results by default
107self.log(metrics)
108
109if self.args.tpu_metrics_debug or self.args.debug:
110# tpu-comment: Logging debug metrics for PyTorch/XLA (compile, execute times, ops, etc.)
111xm.master_print(met.metrics_report())
112
113self.control = self.callback_handler.on_evaluate(self.args, self.state, self.control, metrics)
114return metrics
115
116def predict(
117self, predict_dataset, predict_examples, ignore_keys=None, metric_key_prefix: str = "test", **gen_kwargs
118):
119self._gen_kwargs = gen_kwargs.copy()
120
121predict_dataloader = self.get_test_dataloader(predict_dataset)
122
123# Temporarily disable metric computation, we will do it in the loop here.
124compute_metrics = self.compute_metrics
125self.compute_metrics = None
126start_time = time.time()
127eval_loop = self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop
128try:
129output = eval_loop(
130predict_dataloader,
131description="Prediction",
132# No point gathering the predictions if there are no metrics, otherwise we defer to
133# self.args.prediction_loss_only
134prediction_loss_only=True if compute_metrics is None else None,
135ignore_keys=ignore_keys,
136metric_key_prefix=metric_key_prefix,
137)
138finally:
139self.compute_metrics = compute_metrics
140
141total_batch_size = self.args.eval_batch_size * self.args.world_size
142if f"{metric_key_prefix}_jit_compilation_time" in output.metrics:
143start_time += output.metrics[f"{metric_key_prefix}_jit_compilation_time"]
144output.metrics.update(
145speed_metrics(
146metric_key_prefix,
147start_time,
148num_samples=output.num_samples,
149num_steps=math.ceil(output.num_samples / total_batch_size),
150)
151)
152if self.post_process_function is None or self.compute_metrics is None:
153return output
154
155predictions = self.post_process_function(predict_examples, predict_dataset, output, "predict")
156metrics = self.compute_metrics(predictions)
157
158# Prefix all keys with metric_key_prefix + '_'
159for key in list(metrics.keys()):
160if not key.startswith(f"{metric_key_prefix}_"):
161metrics[f"{metric_key_prefix}_{key}"] = metrics.pop(key)
162metrics.update(output.metrics)
163return PredictionOutput(predictions=predictions.predictions, label_ids=predictions.label_ids, metrics=metrics)
164