class_docstr: Members:
      eval_only: If True, only run evaluation using the test dataloader.
      max_epochs: Train for this many epochs. Note that if the model was
          loaded from a checkpoint, we will restart training at the appropriate
          epoch and run for (max_epochs - checkpoint_epoch) epochs.
      store_checkpoints: If True, store model and optimizer state checkpoints.
      store_checkpoints_purge: If >= 0, remove any checkpoints older or equal
          to this many epochs.
      test_interval: Evaluate on a test dataloader each `test_interval` epochs.
      test_when_finished: If True, evaluate on a test dataloader when training
          completes.
      validation_interval: Validate each `validation_interval` epochs.
      clip_grad: Optionally clip the gradient norms.
          If set to a value <=0.0, no clipping
      metric_print_interval: The batch interval at which the stats should be
          logged.
      visualize_interval: The batch interval at which the visualizations
          should be plotted
      visdom_env: The name of the Visdom environment to use for plotting.
      visdom_port: The Visdom port.
      visdom_server: Address of the Visdom server.
docstr: This is the main loop for training and evaluation including:
  model forward pass, loss computation, backward pass and visualization.
  
  Args:
      epoch: The index of the current epoch
      loader: The dataloader to use for the loop
      model: The model module optionally loaded from checkpoint
      optimizer: The optimizer module optionally loaded from checkpoint
      stats: The stats struct, also optionally loaded from checkpoint
      validation: If true, run the loop with the model in eval mode
          and skip the backward pass
      accelerator: An optional Accelerator instance.
      bp_var: The name of the key in the model output `preds` dict which
          should be used as the loss for the backward pass.
      device: The device on which to run the model.
docstr_tok: ["This","is","the","main","loop","for","training","and","evaluation","including",":","model","forward","pass",",","loss","computation",",","backward","pass","and","visualization",".","Args",":","epoch",":","The","index","of","the","current","epoch","loader",":","The","dataloader","to","use","for","the","loop","model",":","The","model","module","optionally","loaded","from","checkpoint","optimizer",":","The","optimizer","module","optionally","loaded","from","checkpoint","stats",":","The","stats","struct",",","also","optionally","loaded","from","checkpoint","validation",":","If","true",",","run","the","loop","with","the","model","in","eval","mode","and","skip","the","backward","pass","accelerator",":","An","optional","Accelerator","instance",".","bp_var",":","The","name","of","the","key","in","the","model","output","`","preds","`","dict","which","should","be","used","as","the","loss","for","the","backward","pass",".","device",":","The","device","on","which","to","run","the","model","."]
code: def _training_or_validation_epoch(
      self,
      epoch: int,
      loader: DataLoader,
      model: ImplicitronModelBase,
      optimizer: torch.optim.Optimizer,
      stats: Stats,
      validation: bool,
      *,
      accelerator: Optional[Accelerator],
      bp_var: str = "objective",
      device: torch.device,
      **kwargs,
  ) -> None:
      """
      This is the main loop for training and evaluation including:
      model forward pass, loss computation, backward pass and visualization.
  
      Args:
          epoch: The index of the current epoch
          loader: The dataloader to use for the loop
          model: The model module optionally loaded from checkpoint
          optimizer: The optimizer module optionally loaded from checkpoint
          stats: The stats struct, also optionally loaded from checkpoint
          validation: If true, run the loop with the model in eval mode
              and skip the backward pass
          accelerator: An optional Accelerator instance.
          bp_var: The name of the key in the model output `preds` dict which
              should be used as the loss for the backward pass.
          device: The device on which to run the model.
      """
  
      if validation:
          model.eval()
          trainmode = "val"
      else:
          model.train()
          trainmode = "train"
  
      t_start = time.time()
  
      # get the visdom env name
      visdom_env_imgs = stats.visdom_env + "_images_" + trainmode
      viz = vis_utils.get_visdom_connection(
          server=stats.visdom_server,
          port=stats.visdom_port,
      )
  
      # Iterate through the batches
      n_batches = len(loader)
      for it, net_input in enumerate(loader):
          last_iter = it == n_batches - 1
  
          # move to gpu where possible (in place)
          net_input = net_input.to(device)
  
          # run the forward pass
          if not validation:
              optimizer.zero_grad()
              preds = model(
                  **{
                      **net_input,
                      "evaluation_mode": EvaluationMode.TRAINING,
                  }
              )
          else:
              with torch.no_grad():
                  preds = model(
                      **{
                          **net_input,
                          "evaluation_mode": EvaluationMode.EVALUATION,
                      }
                  )
  
          # make sure we dont overwrite something
          assert all(k not in preds for k in net_input.keys())
          # merge everything into one big dict
          preds.update(net_input)
  
          # update the stats logger
          stats.update(preds, time_start=t_start, stat_set=trainmode)
          # pyre-ignore [16]
          assert (
              stats.it[trainmode] == it
          ), "inconsistent stat iteration number!"
  
          # print textual status update
          if it % self.metric_print_interval == 0 or last_iter:
              std_out = stats.get_status_string(
                  stat_set=trainmode, max_it=n_batches
              )
              logger.info(std_out)
  
          # visualize results
          if (
              (accelerator is None or accelerator.is_local_main_process)
              and self.visualize_interval > 0
              and it % self.visualize_interval == 0
          ):
              prefix = f"e{stats.epoch}_it{stats.it[trainmode]}"
              if hasattr(model, "visualize"):
                  model.visualize(
                      viz,
                      visdom_env_imgs,
                      preds,
                      prefix,
                  )
  
          # optimizer step
          if not validation:
              loss = preds[bp_var]
              assert torch.isfinite(loss).all(), "Non-finite loss!"
              # backprop
              if accelerator is None:
                  loss.backward()
              else:
                  accelerator.backward(loss)
              if self.clip_grad > 0.0:
                  # Optionally clip the gradient norms.
                  total_norm = torch.nn.utils.clip_grad_norm(
                      model.parameters(), self.clip_grad
                  )
                  if total_norm > self.clip_grad:
                      logger.debug(
                          f"Clipping gradient: {total_norm}"
                          + f" with coef {self.clip_grad / float(total_norm)}."
                      )
  
              optimizer.step()
  
imports: import logging
  import os
  import time
  from typing import Any, List, Optional
  import torch
  from accelerate import Accelerator
  from pytorch3d.implicitron.evaluation.evaluator import EvaluatorBase
  from pytorch3d.implicitron.models.base_model import ImplicitronModelBase
  from pytorch3d.implicitron.models.generic_model import EvaluationMode
  from pytorch3d.implicitron.tools import model_io, vis_utils
  from pytorch3d.implicitron.tools.config import registry, ReplaceableBase, run_auto_creation
  from pytorch3d.implicitron.tools.stats import Stats
  from torch.utils.data import DataLoader, Dataset
  from .utils import seed_all_random_engines
label_desc: Use image node_id 4 for calling the ImplicitronTrainingLoop obj's underlying member method code with example usage: obj._training_or_validation_epoch(epoch, loader, model, optimizer, stats, validation) without return types