docstr: Trains one epoch and returns metrics.
docstr_tok: ["Trains","one","epoch","and","returns","metrics","."]
code: def _train_epoch(self, epoch):
      """
      Trains one epoch and returns metrics.
      """
      logger.info("Epoch %d/%d", epoch, self._num_epochs - 1)
      logger.info("Peak CPU memory usage MB: {peak_memory_mb()}")
      for gpu, memory in list(gpu_memory_mb().items()):
          logger.info("GPU {gpu} memory usage MB: {memory}")
  
      train_loss = 0.0
      # Set the model to "train" mode.
      self._model.train()
  
      # Get tqdm for the training batches
      train_generator = self._iterator(
          self._train_data,
          num_epochs=1,
          shuffle=self._shuffle,
          cuda_device=self._iterator_device,
      )
      num_training_batches = self._iterator.get_num_batches(
          self._train_data
      )
      self._last_log = time.time()
      last_save_time = time.time()
  
      batches_this_epoch = 0
      if self._batch_num_total is None:
          self._batch_num_total = 0
  
      if self._histogram_interval is not None:
          histogram_parameters = set(
              self._model.get_parameters_for_histogram_tensorboard_logging()
          )
  
      logger.info("Training")
      train_generator_tqdm = Tqdm.tqdm(
          train_generator, total=num_training_batches
      )
      for batch in train_generator_tqdm:
          batches_this_epoch += 1
          self._batch_num_total += 1
          batch_num_total = self._batch_num_total
  
          self._log_histograms_this_batch = (
              self._histogram_interval is not None
              and (batch_num_total % self._histogram_interval == 0)
          )
  
          self._optimizer.zero_grad()
  
          loss = self._batch_loss(batch, for_training=True)
          loss.backward()
  
          train_loss += loss.item()
  
          batch_grad_norm = self._rescale_gradients()
  
          # This does nothing if batch_num_total is None or you are using an
          # LRScheduler which doesn't update per batch.
          if self._learning_rate_scheduler:
              self._learning_rate_scheduler.step_batch(batch_num_total)
  
          if self._log_histograms_this_batch:
              # get the magnitude of parameter updates for logging
              # We need a copy of current parameters to compute magnitude of updates,
              # and copy them to CPU so large models won't go OOM on the GPU.
              param_updates = dict(
                  (name, param.detach().cpu().clone())
                  for name, param in self._model.named_parameters()
              )
              self._optimizer.step()
              for name, param in self._model.named_parameters():
                  param_updates[name].sub_(param.detach().cpu())
                  update_norm = torch.norm(
                      param_updates[name].view(
                          -1,
                      )
                  )
                  param_norm = torch.norm(
                      param.view(
                          -1,
                      )
                  ).cpu()
                  self._tensorboard.add_train_scalar(
                      "gradient_update/" + name,
                      update_norm / (param_norm + 1e-7),
                      batch_num_total,
                  )
          else:
              self._optimizer.step()
  
          # Update the description with the latest metrics
          metrics = self._get_metrics(train_loss, batches_this_epoch)
          description = self._description_from_metrics(metrics)
  
          train_generator_tqdm.set_description(
              description, refresh=False
          )
  
          # Log parameter values to Tensorboard
          if batch_num_total % self._summary_interval == 0:
              self._parameter_and_gradient_statistics_to_tensorboard(
                  batch_num_total, batch_grad_norm
              )
              self._tensorboard.add_train_scalar(
                  "loss/loss_train", metrics["loss"], batch_num_total
              )
              self._metrics_to_tensorboard(
                  batch_num_total,
                  dict(
                      ("epoch_metrics/" + k, v)
                      for k, v in list(metrics.items())
                  ),
              )
  
          if self._log_histograms_this_batch:
              self._histograms_to_tensorboard(
                  batch_num_total, histogram_parameters
              )
  
          # Save model if needed.
          if self._model_save_interval is not None and (
              time.time() - last_save_time > self._model_save_interval
          ):
              last_save_time = time.time()
              self._save_checkpoint(
                  "{0}.{1}".format(
                      epoch, time_to_str(int(last_save_time))
                  ),
                  [],
                  is_best=False,
              )
  
      return self._get_metrics(
          train_loss, batches_this_epoch, reset=True
      )
  
imports: from __future__ import with_statement
  from __future__ import division
  from __future__ import absolute_import
  import logging
  import os
  import shutil
  import time
  import re
  import datetime
  import traceback
  import torch
  import torch.optim.lr_scheduler
  from torch.nn.parallel import replicate, parallel_apply
  from torch.nn.parallel.scatter_gather import scatter_kwargs, gather
  from allennlp.common import Params
  from allennlp.common.checks import ConfigurationError
  from allennlp.common.util import peak_memory_mb, gpu_memory_mb
  from allennlp.common.tqdm import Tqdm
  from allennlp.data.instance import Instance
  from allennlp.data.iterators.data_iterator import DataIterator
  from allennlp.models.model import Model
  from allennlp.nn import util
  from allennlp.training.learning_rate_schedulers import LearningRateScheduler
  from allennlp.training.optimizers import Optimizer
label_desc: Use image node_id 8 for calling the Trainer obj's underlying member method code with example usage: obj._train_epoch(epoch) and returns: self