class_docstr: TrainLoop contains the core training loop logic.
class_docstr_tok: ["TrainLoop","contains","the","core","training","loop","logic","."]
docstr: Core training loop.
  
  Yields a metrics dict with each log.
docstr_tok: ["Core","training","loop",".","Yields","a","metrics","dict","with","each","log","."]
code: def train_steps(self):
      """
      Core training loop.
  
      Yields a metrics dict with each log.
      """
      logging.info("training...")
      opt = self.opt
      world = self.world
      with world:
          while True:
              # do one example / batch of examples
              try:
                  world.parley()
              except StopTrainException as e:
                  logging.info(f"Stopping from {e}")
                  break
  
              self.parleys += 1
              self._train_steps = self.parleys // self.update_freq
              self._last_log_steps += 1 / self.update_freq
  
              # the following additionally updates self._total_epochs
              (
                  train_time,
                  log_time,
                  validate_time,
                  save_time,
              ) = self._get_time(world)
              # get the total training examples done, compute epochs
              exs_per_epoch = world.num_examples()
              self._total_exs = int(
                  np.round(self._total_epochs * exs_per_epoch)
              )
  
              # check counters and timers
              if self._total_epochs >= self.max_num_epochs:
                  yield self.log()
                  logging.info(
                      f"num_epochs completed:{self.max_num_epochs} time elapsed:{train_time}s"
                  )
                  break
              if train_time > self.max_train_time:
                  logging.info(f"max_train_time elapsed:{train_time}s")
                  break
              if self._train_steps >= self.max_train_steps:
                  logging.info(
                      f"max_train_steps elapsed:{self._train_steps} "
                      f"time elapsed:{train_time}s"
                  )
                  break
              if (
                  log_time > self.log_every_n_secs
                  or self._last_log_steps >= self.log_every_n_steps
              ):
                  yield self.log()
              if (
                  validate_time > self.val_every_n_secs
                  or self._total_epochs - self.last_valid_epoch
                  >= self.val_every_n_epochs
                  or self._train_steps - self._last_valid_steps
                  >= self.val_every_n_steps
              ):
                  try:
                      # log before we validate
                      if self._last_log_steps:
                          yield self.log()
                      world.reset_metrics()
                      stop_training = self.validate()
                  except StopTrainException:
                      break
                  # reset the log time because we logged right before validating
                  self.log_time.reset()
                  self.last_valid_epoch = self._total_epochs
                  self._last_valid_steps = self._train_steps
                  if stop_training:
                      break
                  # make sure metrics are clean before we log
                  world.reset_metrics()
              if save_time > self.save_every_n_secs and opt.get(
                  "model_file"
              ):
                  logging.info(
                      f"saving model checkpoint: {opt['model_file']}.checkpoint"
                  )
                  if opt["tensorboard_log"] and is_primary_worker():
                      self.tb_logger.flush()
                  self.save_model(".checkpoint")
                  self.save_time.reset()
  
      if not sync_object(self.saved):
          # save agent
          self.save_model()
  
      # there's a rare edge case where the we never saved the model, and we try
      # # to reload it. This sync_object ensures all workers wait for the primary
      # worker to finish flushing before loading from disk.
      sync_object(None)
      if opt.get("model_file"):
          # clean up all our memory, just to make sure we don't OOM on GPU when
          # reloading the world
          del world
          del self.world
          del self.agent
          del self.valid_worlds
          # reload best validation model
          self.agent = create_agent(opt)
  
imports: import copy
  import random
  import torch
  import json
  import os
  import signal
  from typing import Tuple
  import numpy
  import parlai.utils.logging
  from parlai.core.agents import create_agent, create_agent_from_shared
  from parlai.core.exceptions import StopTrainException
  from parlai.core.logs import TensorboardLogger, WandbLogger, ClearMLLogger
  from parlai.core.metrics import Metric
  from parlai.core.metrics import aggregate_named_reports, aggregate_unnamed_reports, dict_report
  from parlai.core.opt import Opt
  from parlai.core.params import ParlaiParser, print_announcements
  from parlai.core.script import ParlaiScript, register_script
  from parlai.core.worlds import create_task, World
  from parlai.scripts.build_dict import build_dict, setup_args
  from parlai.scripts.eval_model import get_task_world_logs
  from parlai.utils.distributed import sync_object, is_primary_worker, all_gather_list, is_distributed, get_rank, num_workers
  from parlai.utils.io import PathManager
  from parlai.utils.misc import Timer, nice_report
  from parlai.utils.world_logging import WorldLogger
label_desc: Use image node_id 12 for calling the TrainLoop obj's underlying member method code with example usage: obj.train_steps() without return types