seq2seq_trainer.py 6.65 KB
Newer Older
Suraj Patil's avatar
Suraj Patil committed
1
2
3
4
5
6
7
8
import logging
from typing import Any, Dict, Optional, Tuple, Union

import torch
from torch import nn
from torch.utils.data import DistributedSampler, RandomSampler

from transformers import Trainer
9
from transformers.configuration_fsmt import FSMTConfig
Suraj Patil's avatar
Suraj Patil committed
10
from transformers.file_utils import is_torch_tpu_available
11
from transformers.optimization import Adafactor, AdamW, get_linear_schedule_with_warmup
Suraj Patil's avatar
Suraj Patil committed
12
13
14
15
16
17
18
19
20
21
22
23
24
from transformers.trainer import get_tpu_sampler


try:
    from .utils import label_smoothed_nll_loss
except ImportError:
    from utils import label_smoothed_nll_loss


logger = logging.getLogger(__name__)


class Seq2SeqTrainer(Trainer):
25
    def __init__(self, config, data_args, *args, **kwargs):
26
        super().__init__(*args, **kwargs)
27
        self.config = config
28
29
        self.data_args = data_args
        self.max_gen_length = data_args.val_max_target_length
30
        self.vocab_size = self.config.tgt_vocab_size if isinstance(self.config, FSMTConfig) else self.config.vocab_size
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
    def create_optimizer_and_scheduler(self, num_training_steps: int):
        """
        Setup the optimizer and the learning rate scheduler.

        We provide a reasonable default that works well. If you want to use something else, you can pass a tuple in the
        Trainer's init through :obj:`optimizers`, or subclass and override this method in a subclass.
        """
        if self.optimizer is None:
            no_decay = ["bias", "LayerNorm.weight"]
            optimizer_grouped_parameters = [
                {
                    "params": [p for n, p in self.model.named_parameters() if not any(nd in n for nd in no_decay)],
                    "weight_decay": self.args.weight_decay,
                },
                {
                    "params": [p for n, p in self.model.named_parameters() if any(nd in n for nd in no_decay)],
                    "weight_decay": 0.0,
                },
            ]
            if self.args.adafactor:
                self.optimizer = Adafactor(
                    optimizer_grouped_parameters,
                    lr=self.args.learning_rate,
                    scale_parameter=False,
                    relative_step=False,
                )

            else:
                self.optimizer = AdamW(
                    optimizer_grouped_parameters, lr=self.args.learning_rate, eps=self.args.adam_epsilon
                )

        if self.lr_scheduler is None:
            self.lr_scheduler = get_linear_schedule_with_warmup(
                self.optimizer, num_warmup_steps=self.args.warmup_steps, num_training_steps=num_training_steps
            )

Suraj Patil's avatar
Suraj Patil committed
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
    def _get_train_sampler(self) -> Optional[torch.utils.data.sampler.Sampler]:
        if isinstance(self.train_dataset, torch.utils.data.IterableDataset):
            return None
        elif is_torch_tpu_available():
            return get_tpu_sampler(self.train_dataset)
        else:
            if self.args.sortish_sampler:
                self.train_dataset.make_sortish_sampler(
                    self.args.per_device_train_batch_size, distributed=self.args.n_gpu > 1
                )

            return (
                RandomSampler(self.train_dataset)
                if self.args.local_rank == -1
                else DistributedSampler(self.train_dataset)
            )

    def compute_loss(self, model, inputs):
        labels = inputs.pop("labels")
        outputs = model(**inputs, use_cache=False)
        logits = outputs[0]
90
        return self._compute_loss(logits, labels)
Suraj Patil's avatar
Suraj Patil committed
91

92
    def _compute_loss(self, logits, labels):
Suraj Patil's avatar
Suraj Patil committed
93
94
        if self.args.label_smoothing == 0:
            # Same behavior as modeling_bart.py
95
            loss_fct = torch.nn.CrossEntropyLoss(ignore_index=self.config.pad_token_id)
96
            assert logits.shape[-1] == self.vocab_size
Suraj Patil's avatar
Suraj Patil committed
97
98
99
100
            loss = loss_fct(logits.view(-1, logits.shape[-1]), labels.view(-1))
        else:
            lprobs = torch.nn.functional.log_softmax(logits, dim=-1)
            loss, nll_loss = label_smoothed_nll_loss(
101
                lprobs, labels, self.args.label_smoothing, ignore_index=self.config.pad_token_id
Suraj Patil's avatar
Suraj Patil committed
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
            )
        return loss

    def prediction_step(
        self, model: nn.Module, inputs: Dict[str, Union[torch.Tensor, Any]], prediction_loss_only: bool
    ) -> Tuple[Optional[float], Optional[torch.Tensor], Optional[torch.Tensor]]:
        """
        Perform an evaluation step on :obj:`model` using obj:`inputs`.

        Subclass and override to inject custom behavior.

        Args:
            model (:obj:`nn.Module`):
                The model to evaluate.
            inputs (:obj:`Dict[str, Union[torch.Tensor, Any]]`):
                The inputs and targets of the model.

                The dictionary will be unpacked before being fed to the model. Most models expect the targets under the
                argument :obj:`labels`. Check your model's documentation for all accepted arguments.
            prediction_loss_only (:obj:`bool`):
                Whether or not to return the loss only.

        Return:
            Tuple[Optional[float], Optional[torch.Tensor], Optional[torch.Tensor]]:
            A tuple with the loss, logits and labels (each being optional).
        """
        inputs = self._prepare_inputs(inputs)

        with torch.no_grad():
            if self.args.predict_with_generate and not self.args.prediction_loss_only:
                generated_tokens = model.generate(
                    inputs["input_ids"],
                    attention_mask=inputs["attention_mask"],
                    use_cache=True,
136
137
                    num_beams=self.data_args.eval_beams,
                    max_length=self.max_gen_length,
Suraj Patil's avatar
Suraj Patil committed
138
139
                )
                # in case the batch is shorter than max length, the output should be padded
140
                generated_tokens = self._pad_tensors_to_max_len(generated_tokens, self.max_gen_length)
Suraj Patil's avatar
Suraj Patil committed
141
142

            labels_out = inputs.get("labels")
143
144
            # Call forward again to get loss # TODO: avoidable?
            outputs = model(**inputs, use_cache=False)
145
            loss = self._compute_loss(outputs[1], labels_out)
Suraj Patil's avatar
Suraj Patil committed
146
147
            loss = loss.mean().item()
            if self.args.prediction_loss_only:
148
                return (loss, None, None)
Suraj Patil's avatar
Suraj Patil committed
149

150
            logits = generated_tokens if self.args.predict_with_generate else outputs[1]
Suraj Patil's avatar
Suraj Patil committed
151
152

        labels_out = labels_out.detach()
153
        labels = self._pad_tensors_to_max_len(labels_out, self.max_gen_length)
Suraj Patil's avatar
Suraj Patil committed
154
155
        return (loss, logits.detach(), labels)

156
157
    def _pad_tensors_to_max_len(self, tensor, max_length):
        padded_tensor = self.config.pad_token_id * torch.ones(
Suraj Patil's avatar
Suraj Patil committed
158
159
160
161
            (tensor.shape[0], max_length), dtype=tensor.dtype, device=tensor.device
        )
        padded_tensor[:, : tensor.shape[-1]] = tensor
        return padded_tensor