code: def train_and_evaluate(
      *,
      rng: jnp.ndarray,
      config: ml_collections.ConfigDict,
      model_cls: Any,
      dataset: dataset_utils.Dataset,
      workdir: str,
      writer: metric_writers.MetricWriter,
  ) -> Tuple[train_utils.TrainState, Dict[str, Any], Dict[str, Any]]:
      """Main training loop lives in this function.
  
      Given the model class and dataset, it prepares the items needed to run the
      training, including the TrainState.
  
      Args:
        rng: JAX PRNGKey.
        config: Configurations of the experiment.
        model_cls: Model class; A model has a flax_module, a loss_fn, and a
          metrics_fn associated with it.
        dataset: The dataset that has train_iter, eval_iter, meta_data, and
          optionally, test_iter.
        workdir: Directory for checkpointing.
        writer: CLU metrics writer instance.
  
      Returns:
        train_sate that has the state of training (including current
          global_step, model_state, rng, and the optimizer), train_summary
          and eval_summary which are dict of metrics. These outputs are used for
          regression testing.
      """
      lead_host = jax.process_index() == 0
  
      # The pool is used to perform misc operations such as logging in async way.
      pool = futures.ThreadPoolExecutor(max_workers=2)
  
      input_spec = [
          (
              dataset.meta_data["input_shape"],
              dataset.meta_data.get("input_dtype", jnp.float32),
          )
      ]
      (
          model,
          tx,
          train_state,
          num_trainable_params,
          gflops,
          start_step,
      ) = get_model_and_tx_and_train_state(
          rng,
          dataset,
          config,
          model_cls,
          workdir,
          input_spec=input_spec,
      )
  
      # Calculate the total number of training steps.
      total_steps, steps_per_epoch = train_utils.get_num_training_steps(
          config, dataset.meta_data
      )
  
      update_batch_stats = not config.get(
          "freeze_backbone_batch_stats", False
      )
      if not update_batch_stats:
          if not config.load_pretrained_backbone:
              raise ValueError(
                  "Freezing the batch statistics of the resnet backbone "
                  "is only possible when loading a pretrained resnet "
                  "backbone is enabled."
              )
  
      train_step = get_train_step(
          apply_fn=model.flax_model.apply,
          loss_and_metrics_fn=model.loss_and_metrics_function,
          tx=tx,
          update_batch_stats=update_batch_stats,
          debug=config.debug_train,
      )
  
      train_step_pmapped = jax.pmap(
          train_step, axis_name="batch", donate_argnums=(0,)
      )
  
      ############### EVALUATION CODE #################
      eval_step = ddetr_eval.get_eval_step(
          flax_model=model.flax_model,
          loss_and_metrics_fn=model.loss_and_metrics_function,
          logits_to_probs_fn=model.logits_to_probs,
          debug=config.debug_eval,
      )
      eval_step_pmapped = jax.pmap(eval_step, axis_name="batch")
  
      # Ceil rounding such that we include the last incomplete batch.
      eval_batch_size = config.get("eval_batch_size", config.batch_size)
      total_eval_steps = int(
          np.ceil(
              dataset.meta_data["num_eval_examples"] / eval_batch_size
          )
      )
      steps_per_eval = config.get("steps_per_eval") or total_eval_steps
  
      metrics_normalizer_fn = functools.partial(
          detr_train_utils.normalize_metrics_summary,
          object_detection_loss_keys=model.loss_terms_weights.keys(),
      )
  
      global_metrics_evaluator = (
          None  # Only run eval on the lead_host node.
      )
      if lead_host:
          global_metrics_evaluator = (
              coco_eval.DeformableDetrGlobalEvaluator(
                  config.dataset_name
              )
          )
  
      ###################################################
  
      log_eval_steps = config.get("log_eval_steps") or steps_per_epoch
      if not log_eval_steps:
          raise ValueError(
              "'log_eval_steps' should be specified in the config."
          )
      log_summary_steps = config.get("log_summary_steps", 25)
      log_large_summary_steps = config.get("log_large_summary_steps", 0)
      checkpoint_steps = (
          config.get("checkpoint_steps") or log_eval_steps
      )
  
      train_metrics, extra_training_logs = [], []
      train_summary, eval_summary = None, None
  
      logging.info("Starting training loop at step %d.", start_step + 1)
      report_progress = periodic_actions.ReportProgress(
          num_train_steps=total_steps,
          writer=writer,
          every_secs=None,
          every_steps=config.get(
              "report_progress_step", log_summary_steps
          ),
      )
      hooks = []
      if lead_host:
          hooks.append(report_progress)
      if config.get("xprof", True) and lead_host:
          hooks.append(
              periodic_actions.Profile(
                  num_profile_steps=5, logdir=workdir
              )
          )
  
      if start_step == 0:
          step0_log = {"num_trainable_params": num_trainable_params}
          if gflops:
              step0_log["gflops"] = gflops
          writer.write_scalars(1, step0_log)
  
      (last_eval_step, last_eval_metrics), last_eval_future = (
          None,
          None,
      ), None
  
      # Do eval before first train step.
      if config.get("do_eval_first", False):
          # Sync model state across replicas (in case of having model state, e.g.
          # batch statistic when using batch norm).
          start_time = time.time()
          with report_progress.timed("eval"):
              train_state = (
                  train_utils.sync_model_state_across_replicas(
                      train_state
                  )
              )
              (
                  last_eval_step,
                  last_eval_metrics,
              ), last_eval_future = ddetr_eval.run_eval(
                  global_metrics_evaluator,
                  dataset,
                  train_state,
                  eval_step_pmapped,
                  pool,
                  0,
                  steps_per_eval,
              )
          duration = time.time() - start_time
          logging.info(
              "Done with async evaluation: %.4f sec.", duration
          )
          writer.flush()
  
      for step in range(start_step + 1, total_steps + 1):
          with jax.profiler.StepTraceAnnotation("train", step_num=step):
              train_batch = next(dataset.train_iter)
              (
                  train_state,
                  t_metrics,
                  train_predictions,
              ) = train_step_pmapped(train_state, train_batch)
              # This will accumulate metrics in TPU memory up to the point that we log
              # them. This is no problem for small metrics but may be a problem for
              # large (e.g. segmentation) metrics. An alternative is to set
              # `log_summary_steps` to a small number, or to use
              # `train_utils.unreplicate_and_get` here instead of right before writing
              # summaries, but that means in each step, we have data transfer between
              # tpu and host, which might slow down the training.
              train_metrics.append(
                  train_utils.unreplicate_and_get(t_metrics)
              )
  
          for h in hooks:
              h(step)
  
          if (
              log_large_summary_steps
              and step % log_large_summary_steps == 0
              and lead_host
          ):
              ############### LOG EXPENSIVE TRAIN SUMMARY ###############
              # Visualizes detections using side-by-side gt-pred images.
              # TODO(mjlm): Investigate this error when including `batch_mask`:
              # RuntimeError: Invalid argument: from_python argument must be an array.
              to_cpu = lambda x: jax.device_get(
                  dataset_utils.unshard(x)
              )
              del train_batch["batch_mask"]
              train_pred_cpu = to_cpu(train_predictions)
              train_batch_cpu = to_cpu(train_batch)
              viz = detr_train_utils.draw_boxes_side_by_side(
                  train_pred_cpu,
                  train_batch_cpu,
                  label_map=dataset.meta_data["label_to_name"],
              )
              viz_detections = {
                  f"sidebyside_{i}/detection": viz_[None, ...]
                  for i, viz_ in enumerate(viz)
              }
              writer.write_images(step, viz_detections)
  
          del train_predictions
  
          if (step % log_summary_steps == 0) or (step == total_steps):
              ############### LOG TRAIN SUMMARY ###############
  
              # Write summary:
              train_summary = train_utils.log_train_summary(
                  step=step,
                  train_metrics=train_metrics,
                  extra_training_logs=jax.tree_util.tree_map(
                      train_utils.unreplicate_and_get,
                      extra_training_logs,
                  ),
                  writer=writer,
                  metrics_normalizer_fn=metrics_normalizer_fn,
              )
              # Reset metric accumulation for next evaluation cycle.
              train_metrics, extra_training_logs = [], []
              #################################################
  
          if (step % log_eval_steps == 0) or (step == total_steps):
              # First wait for the previous eval to finish & write summary.
              if last_eval_future is not None:
                  eval_summary = train_utils.log_eval_summary(
                      step=last_eval_step,
                      eval_metrics=last_eval_metrics,
                      extra_eval_summary=last_eval_future.result(),
                      writer=writer,
                      metrics_normalizer_fn=metrics_normalizer_fn,
                  )
                  last_eval_future = None
  
              # Sync model state across replicas (in case of having model state, e.g.
              # batch statistic when using batch norm).
              start_time = time.time()
              with report_progress.timed("eval"):
                  train_state = (
                      train_utils.sync_model_state_across_replicas(
                          train_state
                      )
                  )
                  (
                      last_eval_step,
                      last_eval_metrics,
                  ), last_eval_future = ddetr_eval.run_eval(
                      global_metrics_evaluator,
                      dataset,
                      train_state,
                      eval_step_pmapped,
                      pool,
                      step,
                      steps_per_eval,
                  )
              duration = time.time() - start_time
              logging.info(
                  "Done with async evaluation: %.4f sec.", duration
              )
              writer.flush()
  
          ##################### CHECKPOINTING ############################
          if (
              (step % checkpoint_steps == 0 and step > 0)
              or (step == total_steps)
          ) and config.checkpoint:
              with report_progress.timed("checkpoint"):
                  # Sync model state across replicas.
                  train_state = (
                      train_utils.sync_model_state_across_replicas(
                          train_state
                      )
                  )
                  if lead_host:
                      train_utils.save_checkpoint(
                          workdir, jax_utils.unreplicate(train_state)
                      )
  
      # Wait until computations are done before exiting.
      pool.shutdown()
      if last_eval_future is not None:
          eval_summary = train_utils.log_eval_summary(
              step=last_eval_step,
              eval_metrics=last_eval_metrics,
              extra_eval_summary=last_eval_future.result(),
              writer=writer,
              metrics_normalizer_fn=metrics_normalizer_fn,
          )
      train_utils.barrier()
      return train_state, train_summary, eval_summary
  
imports: from collections.abc import Mapping
  from concurrent import futures
  import functools
  import time
  from typing import Any, Callable, Dict, Sequence, Tuple, Type, Union
  from absl import logging
  from clu import metric_writers
  from clu import periodic_actions
  import flax
  from flax import jax_utils
  from flax.training.checkpoints import restore_checkpoint
  import jax
  import jax.numpy
  import jax.profiler
  import ml_collections
  import numpy
  import optax
  from scenic.dataset_lib import dataset_utils
  from scenic.projects.baselines.deformable_detr import coco_eval
  from scenic.projects.baselines.deformable_detr import evaluate
  from scenic.projects.baselines.deformable_detr.model import DeformableDETRModel
  from scenic.projects.baselines.detr import train_utils
  from scenic.train_lib import pretrain_utils
  from scenic.train_lib import train_utils
  from scenic.train_lib.train_utils import PyTree
  from scenic.train_lib.train_utils import TrainState
label_desc: Use image node_id 5 for calling a global function with example usage: train_and_evaluate() and returns: train_state,  train_summary,  eval_summary