code: def train(net, train_data, val_data, eval_metric, ctx, args):
      """Training pipeline"""
      net.collect_params().reset_ctx(ctx)
  
      if args.horovod:
          hvd.broadcast_parameters(net.collect_params(), root_rank=0)
          trainer = hvd.DistributedTrainer(
              net.collect_params(),
              "sgd",
              {
                  "learning_rate": args.lr,
                  "wd": args.wd,
                  "momentum": args.momentum,
              },
          )
      else:
          trainer = gluon.Trainer(
              net.collect_params(),
              "sgd",
              {
                  "learning_rate": args.lr,
                  "wd": args.wd,
                  "momentum": args.momentum,
              },
              update_on_kvstore=(False if args.amp else None),
          )
  
      if args.amp:
          amp.init_trainer(trainer)
  
      # lr decay policy
      lr_decay = float(args.lr_decay)
      lr_steps = sorted(
          [
              float(ls)
              for ls in args.lr_decay_epoch.split(",")
              if ls.strip()
          ]
      )
  
      mbox_loss = gcv.loss.SSDMultiBoxLoss()
      ce_metric = mx.metric.Loss("CrossEntropy")
      smoothl1_metric = mx.metric.Loss("SmoothL1")
  
      # set up logger
      logging.basicConfig()
      logger = logging.getLogger()
      logger.setLevel(logging.INFO)
      log_file_path = args.save_prefix + "_train.log"
      log_dir = os.path.dirname(log_file_path)
      if log_dir and not os.path.exists(log_dir):
          os.makedirs(log_dir)
      fh = logging.FileHandler(log_file_path)
      logger.addHandler(fh)
      logger.info(args)
      logger.info(
          "Start training from [Epoch {}]".format(args.start_epoch)
      )
      best_map = [0]
  
      for epoch in range(args.start_epoch, args.epochs):
          while lr_steps and epoch >= lr_steps[0]:
              new_lr = trainer.learning_rate * lr_decay
              lr_steps.pop(0)
              trainer.set_learning_rate(new_lr)
              logger.info(
                  "[Epoch {}] Set learning rate to {}".format(
                      epoch, new_lr
                  )
              )
          ce_metric.reset()
          smoothl1_metric.reset()
          tic = time.time()
          btic = time.time()
          net.hybridize(static_alloc=True, static_shape=True)
  
          for i, batch in enumerate(train_data):
              if args.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=ctx, batch_axis=0
                  )
                  cls_targets = gluon.utils.split_and_load(
                      batch[1], ctx_list=ctx, batch_axis=0
                  )
                  box_targets = gluon.utils.split_and_load(
                      batch[2], ctx_list=ctx, batch_axis=0
                  )
  
              with autograd.record():
                  cls_preds = []
                  box_preds = []
                  for x in data:
                      cls_pred, box_pred, _ = 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 args.amp:
                      with amp.scale_loss(
                          sum_loss, 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
              trainer.step(1)
  
              if not args.horovod or hvd.rank() == 0:
                  local_batch_size = int(
                      args.batch_size
                      // (hvd.size() if args.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 (
                      args.log_interval
                      and not (i + 1) % args.log_interval
                  ):
                      name1, loss1 = ce_metric.get()
                      name2, loss2 = smoothl1_metric.get()
                      logger.info(
                          "[Epoch {}][Batch {}], Speed: {:.3f} samples/sec, {}={:.3f}, {}={:.3f}".format(
                              epoch,
                              i,
                              args.batch_size / (time.time() - btic),
                              name1,
                              loss1,
                              name2,
                              loss2,
                          )
                      )
                  btic = time.time()
  
          if not args.horovod or hvd.rank() == 0:
              name1, loss1 = ce_metric.get()
              name2, loss2 = smoothl1_metric.get()
              logger.info(
                  "[Epoch {}] Training cost: {:.3f}, {}={:.3f}, {}={:.3f}".format(
                      epoch,
                      (time.time() - tic),
                      name1,
                      loss1,
                      name2,
                      loss2,
                  )
              )
              if (epoch % args.val_interval == 0) or (
                  args.save_interval and epoch % args.save_interval == 0
              ):
                  # consider reduce the frequency of validation to save time
                  map_name, mean_ap = validate(
                      net, val_data, ctx, eval_metric
                  )
                  val_msg = "\n".join(
                      [
                          "{}={}".format(k, v)
                          for k, v in zip(map_name, mean_ap)
                      ]
                  )
                  logger.info(
                      "[Epoch {}] Validation: \n{}".format(
                          epoch, val_msg
                      )
                  )
                  current_map = float(mean_ap[-1])
              else:
                  current_map = 0.0
              save_params(
                  net,
                  best_map,
                  current_map,
                  epoch,
                  args.save_interval,
                  args.save_prefix,
              )
  
imports: import argparse
  import os
  import logging
  import warnings
  import time
  import numpy
  import mxnet
  from mxnet import nd
  from mxnet import gluon
  from mxnet import autograd
  import gluoncv
  from gluoncv import data
  from gluoncv import utils
  from gluoncv.model_zoo import get_model
  from gluoncv.data.batchify import Tuple, Stack, Pad
  from gluoncv.data.transforms.presets.ssd import SSDDefaultTrainTransform
  from gluoncv.data.transforms.presets.ssd import SSDDefaultValTransform
  from gluoncv.data.transforms.presets.ssd import SSDDALIPipeline
  from gluoncv.utils.metrics.voc_detection import VOC07MApMetric
  from gluoncv.utils.metrics.coco_detection import COCODetectionMetric
  from gluoncv.utils.metrics.accuracy import Accuracy
  from mxnet.contrib import amp
label_desc: Use image node_id 8 for calling a global function with example usage: train(net, train_data, val_data, eval_metric, ctx, args) without return types