Perform a training step on a batch of inputs. Subclass and override to inject custom behavior. Args: model (`nn.Module`): The model to train. inputs (`Dict[str, Union[torch.Tensor, Any]]`): The inputs and targets of t
(self, model: nn.Module, inputs: Dict[str, Union[torch.Tensor, Any]], num_items_in_batch=None)
| 172 | return (loss, logits, labels) |
| 173 | |
| 174 | def training_step(self, model: nn.Module, inputs: Dict[str, Union[torch.Tensor, Any]], num_items_in_batch=None) -> torch.Tensor: |
| 175 | """ |
| 176 | Perform a training step on a batch of inputs. |
| 177 | |
| 178 | Subclass and override to inject custom behavior. |
| 179 | |
| 180 | Args: |
| 181 | model (`nn.Module`): |
| 182 | The model to train. |
| 183 | inputs (`Dict[str, Union[torch.Tensor, Any]]`): |
| 184 | The inputs and targets of the model. |
| 185 | |
| 186 | The dictionary will be unpacked before being fed to the model. Most models expect the targets under the |
| 187 | argument `labels`. Check your model's documentation for all accepted arguments. |
| 188 | |
| 189 | Return: |
| 190 | `torch.Tensor`: The tensor with training loss on this batch. |
| 191 | """ |
| 192 | model.train() |
| 193 | inputs = self._prepare_inputs(inputs) |
| 194 | |
| 195 | if is_sagemaker_mp_enabled(): |
| 196 | loss_mb = smp_forward_backward(model, inputs, self.args.gradient_accumulation_steps) |
| 197 | return loss_mb.reduce_mean().detach().to(self.args.device) |
| 198 | |
| 199 | with self.compute_loss_context_manager(): |
| 200 | loss = self.compute_loss(model, inputs) |
| 201 | |
| 202 | del inputs |
| 203 | torch.cuda.empty_cache() |
| 204 | |
| 205 | if self.args.n_gpu > 1: |
| 206 | loss = loss.mean() # mean() to average on multi-gpu parallel training |
| 207 | |
| 208 | if self.use_apex: |
| 209 | with amp.scale_loss(loss, self.optimizer) as scaled_loss: |
| 210 | scaled_loss.backward() |
| 211 | else: |
| 212 | self.accelerator.backward(loss) |
| 213 | |
| 214 | return loss.detach() / self.args.gradient_accumulation_steps |
| 215 | |
| 216 | def _save(self, output_dir: Optional[str] = None, state_dict=None): |
| 217 | # If we are executing this function, we are the process zero, so we don't check for that. |
nothing calls this directly
no test coverage detected