class_docstr: Estimator implementation for SSD.
  
  Parameters
  ----------
  config : dict
      Config in nested dict.
  logger : logging.Logger, default is None
      Optional logger for this estimator, can be `None` when default setting is used.
  reporter : callable, default is None
      If set, use reporter callback to report the metrics of the current estimator.
  
  Attributes
  ----------
  _logger : logging.Logger
      The customized/default logger for this estimator.
  _logdir : str
      The temporary dir for logs.
  _cfg : autocfg.dataclass
      The configurations.
class_docstr_tok: ["Estimator","implementation","for","SSD",".","Parameters","--","--","--","--","--","config",":","dict","Config","in","nested","dict",".","logger",":","logging.Logger",",","default","is","None","Optional","logger","for","this","estimator",",","can","be","`","None","`","when","default","setting","is","used",".","reporter",":","callable",",","default","is","None","If","set",",","use","reporter","callback","to","report","the","metrics","of","the","current","estimator",".","Attributes","--","--","--","--","--","_logger",":","logging.Logger","The","customized\/default","logger","for","this","estimator",".","_logdir",":","str","The","temporary","dir","for","logs",".","_cfg",":","autocfg.dataclass","The","configurations","."]
code: def _train_loop(
      self, train_data, val_data, train_eval_data, time_limit=math.inf
  ):
      start_tic = time.time()
      # fix seed for mxnet, numpy and python builtin random generator.
      gutils.random.seed(self._cfg.train.seed)
      # loss and metric
      mbox_loss = SSDMultiBoxLoss()
      ce_metric = mx.metric.Loss("CrossEntropy")
      smoothl1_metric = mx.metric.Loss("SmoothL1")
  
      # lr decay policy
      lr_decay = float(self._cfg.train.lr_decay)
      lr_steps = sorted(
          [float(ls) for ls in self._cfg.train.lr_decay_epoch]
      )
  
      self._logger.info(
          "Start training from [Epoch %d]",
          max(self._cfg.train.start_epoch, self.epoch),
      )
  
      self.net.collect_params().reset_ctx(self.ctx)
      early_stopper = EarlyStopperOnPlateau(
          patience=self._cfg.train.early_stop_patience,
          min_delta=self._cfg.train.early_stop_min_delta,
          baseline_value=self._cfg.train.early_stop_baseline,
          max_value=self._cfg.train.early_stop_max_value,
      )
      mean_ap = [-1]
      cp_name = ""
      self._time_elapsed += time.time() - start_tic
      for self.epoch in range(
          max(self._cfg.train.start_epoch, self.epoch),
          self._cfg.train.epochs,
      ):
          epoch = self.epoch
          tic = time.time()
          last_tic = time.time()
          if self._best_map >= 1.0:
              self._logger.info(
                  "[Epoch {}] Early stopping as mAP is reaching 1.0".format(
                      epoch
                  )
              )
              break
          (
              should_stop,
              stop_message,
          ) = early_stopper.get_early_stop_advice()
          if should_stop:
              self._logger.info(
                  "[Epoch {}] ".format(epoch) + stop_message
              )
              break
          while lr_steps and epoch >= lr_steps[0]:
              new_lr = self.trainer.learning_rate * lr_decay
              lr_steps.pop(0)
              self.trainer.set_learning_rate(new_lr)
              self._logger.info(
                  "[Epoch {}] Set learning rate to {}".format(
                      epoch, new_lr
                  )
              )
          ce_metric.reset()
          smoothl1_metric.reset()
          self.net.hybridize(static_alloc=True, static_shape=True)
  
          for i, batch in enumerate(train_data):
              btic = time.time()
              if self._time_elapsed > time_limit:
                  self._logger.warning(
                      f"`time_limit={time_limit}` reached, exit early..."
                  )
                  return {
                      "train_map": float(mean_ap[-1]),
                      "valid_map": self._best_map,
                      "time": self._time_elapsed,
                      "checkpoint": cp_name,
                  }
              if self._cfg.train.dali:
                  # dali iterator returns a mxnet.io.DataBatch
                  data = [d.data[0] for d in batch]
                  box_targets = [d.label[0] for d in batch]
                  cls_targets = [
                      nd.cast(d.label[1], dtype="float32")
                      for d in batch
                  ]
              else:
                  data = gluon.utils.split_and_load(
                      batch[0],
                      ctx_list=self.ctx,
                      batch_axis=0,
                      even_split=False,
                  )
                  cls_targets = gluon.utils.split_and_load(
                      batch[1],
                      ctx_list=self.ctx,
                      batch_axis=0,
                      even_split=False,
                  )
                  box_targets = gluon.utils.split_and_load(
                      batch[2],
                      ctx_list=self.ctx,
                      batch_axis=0,
                      even_split=False,
                  )
  
              with autograd.record():
                  cls_preds = []
                  box_preds = []
                  for x in data:
                      cls_pred, box_pred, _ = self.net(x)
                      cls_preds.append(cls_pred)
                      box_preds.append(box_pred)
                  sum_loss, cls_loss, box_loss = mbox_loss(
                      cls_preds, box_preds, cls_targets, box_targets
                  )
                  if self._cfg.ssd.amp:
                      with amp.scale_loss(
                          sum_loss, self.trainer
                      ) as scaled_loss:
                          autograd.backward(scaled_loss)
                  else:
                      autograd.backward(sum_loss)
              # since we have already normalized the loss, we don't want to normalize
              # by batch-size anymore
              self.trainer.step(1)
  
              if not self._cfg.horovod or hvd.rank() == 0:
                  local_batch_size = int(
                      self._cfg.train.batch_size
                      // (hvd.size() if self._cfg.horovod else 1)
                  )
                  ce_metric.update(
                      0, [l * local_batch_size for l in cls_loss]
                  )
                  smoothl1_metric.update(
                      0, [l * local_batch_size for l in box_loss]
                  )
                  if (
                      self._cfg.train.log_interval
                      and not (i + 1) % self._cfg.train.log_interval
                  ):
                      name1, loss1 = ce_metric.get()
                      name2, loss2 = smoothl1_metric.get()
                      self._logger.info(
                          "[Epoch %d][Batch %d], Speed: %f samples/sec, %s=%f, %s=%f",
                          epoch,
                          i,
                          self._cfg.train.batch_size
                          / (time.time() - last_tic),
                          name1,
                          loss1,
                          name2,
                          loss2,
                      )
                      last_tic = time.time()
              self._time_elapsed += time.time() - btic
  
          post_tic = time.time()
          if not self._cfg.horovod or hvd.rank() == 0:
              name1, loss1 = ce_metric.get()
              name2, loss2 = smoothl1_metric.get()
              self._logger.info(
                  "[Epoch %d] Training cost: %f, %s=%f, %s=%f",
                  epoch,
                  (time.time() - tic),
                  name1,
                  loss1,
                  name2,
                  loss2,
              )
              if (epoch % self._cfg.valid.val_interval == 0) or (
                  self._cfg.save_interval
                  and epoch % self._cfg.save_interval == 0
              ):
                  # consider reduce the frequency of validation to save time
                  map_name, mean_ap = self._evaluate(val_data)
                  val_msg = "\n".join(
                      [
                          "{}={}".format(k, v)
                          for k, v in zip(map_name, mean_ap)
                      ]
                  )
                  self._logger.info(
                      "[Epoch %d] Validation: \n%s", epoch, str(val_msg)
                  )
                  current_map = float(mean_ap[-1])
                  if current_map > self._best_map:
                      cp_name = os.path.join(
                          self._logdir, _BEST_CHECKPOINT_FILE
                      )
                      self._logger.info(
                          "[Epoch %d] Current best map: %f vs previous %f, saved to %s",
                          self.epoch,
                          current_map,
                          self._best_map,
                          cp_name,
                      )
                      self.save(cp_name)
                      self._best_map = current_map
                  if self._reporter:
                      self._reporter(
                          epoch=epoch, map_reward=current_map
                      )
                  early_stopper.update(current_map, epoch=epoch)
          self._time_elapsed += time.time() - post_tic
      # map on train data
      tic = time.time()
      map_name, mean_ap = self._evaluate(train_eval_data)
      self._time_elapsed += time.time() - tic
      return {
          "train_map": float(mean_ap[-1]),
          "valid_map": self._best_map,
          "time": self._time_elapsed,
          "checkpoint": cp_name,
      }
  
imports: import os
  import math
  import time
  import warnings
  from PIL import Image
  import pandas
  import numpy
  import mxnet
  from mxnet import nd
  from mxnet import gluon
  from mxnet import autograd
  from mxnet.contrib import amp
  from ....None import utils
  from ....data.batchify import Tuple, Stack, Pad
  from ....utils.metrics.voc_detection import VOC07MApMetric, VOCMApMetric
  from ....model_zoo import get_model
  from ....model_zoo import custom_ssd
  from ....data.transforms.presets.ssd import SSDDefaultValTransform
  from ....data.transforms.presets.ssd import load_test, transform_test
  from ....loss import SSDMultiBoxLoss
  from .utils import _get_dataloader, _get_dali_dataloader
  from ..base_estimator import BaseEstimator, set_default
  from .default import SSDCfg
  from ...data.dataset import ObjectDetectionDataset
  from ..conf import _BEST_CHECKPOINT_FILE
  from ..utils import EarlyStopperOnPlateau
label_desc: Use image node_id 4 for calling the SSDEstimator obj's underlying member method code with example usage: obj._train_loop(train_data, val_data, train_eval_data, time_limit) and returns: dict, dict