code: def __init__(self, cfg, mode="train"):
      self.cfg = cfg.copy()
      assert mode.lower() in [
          "train",
          "eval",
          "test",
      ], "mode should be 'train', 'eval' or 'test'"
      self.mode = mode.lower()
      self.optimizer = None
      self.is_loaded_weights = False
      self.use_amp = self.cfg.get("amp", False)
      self.amp_level = self.cfg.get("amp_level", "O1")
      self.custom_white_list = self.cfg.get("custom_white_list", None)
      self.custom_black_list = self.cfg.get("custom_black_list", None)
      self.use_master_grad = self.cfg.get("master_grad", False)
      if "slim" in cfg and cfg["slim_type"] == "PTQ":
          self.cfg["TestDataset"] = create("TestDataset")()
  
      # build data loader
      capital_mode = self.mode.capitalize()
      if (
          cfg.architecture in MOT_ARCH
          and self.mode in ["eval", "test"]
          and cfg.metric not in ["COCO", "VOC"]
      ):
          self.dataset = self.cfg[
              "{}MOTDataset".format(capital_mode)
          ] = create("{}MOTDataset".format(capital_mode))()
      else:
          self.dataset = self.cfg[
              "{}Dataset".format(capital_mode)
          ] = create("{}Dataset".format(capital_mode))()
  
      if cfg.architecture == "DeepSORT" and self.mode == "train":
          logger.error(
              "DeepSORT has no need of training on mot dataset."
          )
          sys.exit(1)
  
      if cfg.architecture == "FairMOT" and self.mode == "eval":
          images = self.parse_mot_images(cfg)
          self.dataset.set_images(images)
  
      if self.mode == "train":
          self.loader = create("{}Reader".format(capital_mode))(
              self.dataset, cfg.worker_num
          )
  
      if cfg.architecture == "JDE" and self.mode == "train":
          self.cfg["JDEEmbeddingHead"][
              "num_identities"
          ] = self.dataset.num_identities_dict[0]
          # JDE only support single class MOT now.
  
      if cfg.architecture == "FairMOT" and self.mode == "train":
          self.cfg["FairMOTEmbeddingHead"][
              "num_identities_dict"
          ] = self.dataset.num_identities_dict
          # FairMOT support single class and multi-class MOT now.
  
      # build model
      if "model" not in self.cfg:
          self.model = create(cfg.architecture)
      else:
          self.model = self.cfg.model
          self.is_loaded_weights = True
  
      if cfg.architecture == "YOLOX":
          for k, m in self.model.named_sublayers():
              if isinstance(m, nn.BatchNorm2D):
                  m._epsilon = 1e-3  # for amp(fp16)
                  m._momentum = 0.97  # 0.03 in pytorch
  
      # normalize params for deploy
      if "slim" in cfg and cfg["slim_type"] == "OFA":
          self.model.model.load_meanstd(
              cfg["TestReader"]["sample_transforms"]
          )
      elif "slim" in cfg and cfg["slim_type"] == "Distill":
          self.model.student_model.load_meanstd(
              cfg["TestReader"]["sample_transforms"]
          )
      elif (
          "slim" in cfg
          and cfg["slim_type"] == "DistillPrune"
          and self.mode == "train"
      ):
          self.model.student_model.load_meanstd(
              cfg["TestReader"]["sample_transforms"]
          )
      else:
          self.model.load_meanstd(
              cfg["TestReader"]["sample_transforms"]
          )
  
      # EvalDataset build with BatchSampler to evaluate in single device
      # TODO: multi-device evaluate
      if self.mode == "eval":
          if cfg.architecture == "FairMOT":
              self.loader = create("EvalMOTReader")(self.dataset, 0)
          elif cfg.architecture == "METRO_Body":
              reader_name = "{}Reader".format(self.mode.capitalize())
              self.loader = create(reader_name)(
                  self.dataset, cfg.worker_num
              )
          else:
              self._eval_batch_sampler = paddle.io.BatchSampler(
                  self.dataset,
                  batch_size=self.cfg.EvalReader["batch_size"],
              )
              reader_name = "{}Reader".format(self.mode.capitalize())
              # If metric is VOC, need to be set collate_batch=False.
              if cfg.metric == "VOC":
                  self.cfg[reader_name]["collate_batch"] = False
              self.loader = create(reader_name)(
                  self.dataset, cfg.worker_num, self._eval_batch_sampler
              )
      # TestDataset build after user set images, skip loader creation here
  
      # get Params
      print_params = self.cfg.get("print_params", False)
      if print_params:
          params = sum(
              [
                  p.numel()
                  for n, p in self.model.named_parameters()
                  if all(
                      [
                          x not in n
                          for x in ["_mean", "_variance", "aux_"]
                      ]
                  )
              ]
          )  # exclude BatchNorm running status
          logger.info(
              "Model Params : {} M.".format((params / 1e6).numpy()[0])
          )
  
      # build optimizer in train mode
      if self.mode == "train":
          steps_per_epoch = len(self.loader)
          if steps_per_epoch < 1:
              logger.warning(
                  "Samples in dataset are less than batch_size, please set smaller batch_size in TrainReader."
              )
          self.lr = create("LearningRate")(steps_per_epoch)
          self.optimizer = create("OptimizerBuilder")(
              self.lr, self.model
          )
  
          # Unstructured pruner is only enabled in the train mode.
          if self.cfg.get("unstructured_prune"):
              self.pruner = create("UnstructuredPruner")(
                  self.model, steps_per_epoch
              )
      if self.use_amp and self.amp_level == "O2":
          paddle_version = paddle.__version__[:3]
          # paddle version >= 2.5.0 or develop
          if paddle_version in ["2.5", "0.0"]:
              self.model, self.optimizer = paddle.amp.decorate(
                  models=self.model,
                  optimizers=self.optimizer,
                  level=self.amp_level,
                  master_grad=self.use_master_grad,
              )
          else:
              self.model, self.optimizer = paddle.amp.decorate(
                  models=self.model,
                  optimizers=self.optimizer,
                  level=self.amp_level,
              )
      self.use_ema = "use_ema" in cfg and cfg["use_ema"]
      if self.use_ema:
          ema_decay = self.cfg.get("ema_decay", 0.9998)
          ema_decay_type = self.cfg.get("ema_decay_type", "threshold")
          cycle_epoch = self.cfg.get("cycle_epoch", -1)
          ema_black_list = self.cfg.get("ema_black_list", None)
          ema_filter_no_grad = self.cfg.get("ema_filter_no_grad", False)
          self.ema = ModelEMA(
              self.model,
              decay=ema_decay,
              ema_decay_type=ema_decay_type,
              cycle_epoch=cycle_epoch,
              ema_black_list=ema_black_list,
              ema_filter_no_grad=ema_filter_no_grad,
          )
  
      self._nranks = dist.get_world_size()
      self._local_rank = dist.get_rank()
  
      self.status = {}
  
      self.start_epoch = 0
      self.end_epoch = 0 if "epoch" not in cfg else cfg.epoch
  
      # initial default callbacks
      self._init_callbacks()
  
      # initial default metrics
      self._init_metrics()
      self._reset_metrics()
  
imports: from __future__ import absolute_import
  from __future__ import division
  from __future__ import print_function
  import os
  import sys
  import copy
  import time
  from tqdm import tqdm
  import numpy
  import typing
  from PIL import Image, ImageOps, ImageFile
  import paddle
  import paddle.nn
  import paddle.distributed
  from paddle.distributed import fleet
  from paddle.static import InputSpec
  from ppdet.optimizer import ModelEMA
  from ppdet.core.workspace import create
  from ppdet.utils.checkpoint import load_weight, load_pretrain_weight
  from ppdet.utils.visualizer import visualize_results, save_result
  from ppdet.metrics import get_infer_results, KeyPointTopDownCOCOEval, KeyPointTopDownCOCOWholeBadyHandEval, KeyPointTopDownMPIIEval, Pose3DEval
  from ppdet.metrics import Metric, COCOMetric, VOCMetric, WiderFaceMetric, RBoxMetric, JDEDetMetric, SNIPERCOCOMetric, CULaneMetric
  from ppdet.data.source.sniper_coco import SniperCOCODataSet
  from ppdet.data.source.category import get_categories
  import ppdet.utils.stats
  from ppdet.utils.fuse_utils import fuse_conv_bn
  from ppdet.utils import profiler
  from ppdet.modeling.post_process import multiclass_nms
  from ppdet.modeling.lane_utils import imshow_lanes
  from .callbacks import Callback, ComposeCallback, LogPrinter, Checkpointer, WiferFaceEval, VisualDLWriter, SniperProposalsGenerator, WandbCallback, SemiCheckpointer, SemiLogPrinter
  from .export_utils import _dump_infer_config, _prune_input_spec, apply_to_static
  from paddle.distributed.fleet.utils.hybrid_parallel_util import fused_allreduce_gradients
  from ppdet.utils.logger import setup_logger
label_desc: Use image node_id 1 to create a new Trainer object from inherited base classes: object with example: obj = Trainer(cfg, mode)