code: def train_step(
      train_state: train_utils.TrainState,
      batch: Batch,
      use_ncr: bool,
      *,
      use_bootstrap: bool,
      flax_model: nn.Module,
      loss_fn: LossFn,
      metrics_fn: MetricFn,
      config: ml_collections.ConfigDict,
      debug: Optional[bool] = False,
  ) -> Tuple[train_utils.TrainState, Dict[str, Tuple[float, int]]]:
      """Runs a single step of training.
  
      Given the state of the training and a batch of data, computes
      the loss and updates the parameters of the model.
  
      Note that in this code, the buffers of the first (train_state) and second
      (batch) arguments are donated to the computation.
  
      Args:
        train_state: The state of training including the current
          global_step, model_state, rng, and optimizer. The buffer of this argument
          can be donated to the computation.
        batch: A single batch of data. The buffer of this argument can be donated to
          the computation.
        use_ncr: Whether the NCR loss is used or not.
        use_bootstrap: Whether the bootstrap loss is used or not.
        flax_model: A Flax model.
        loss_fn: A loss function that given logits, a batch, and parameters of the
          model calculates the loss.
        metrics_fn: A metrics function that given logits and batch of data,
          calculates the metrics as well as the loss.
        config: Configurations of the experiment.
        debug: Whether the debug mode is enabled during training. `debug=True`
          enables model specific logging/storing some values using
          jax.host_callback.
  
      Returns:
        Updated state of training, computed metrics, and learning rate for logging.
      """
      new_rng, rng = jax.random.split(train_state.rng)
  
      if config.get("mixup") and config.mixup.alpha:
          rng, mixup_rng = jax.random.split(rng, 2)
          mixup_rng = train_utils.bind_rng_to_host_device(
              mixup_rng,
              axis_name="batch",
              bind_to=config.mixup.get("bind_to", "device"),
          )
          batch = utils.mixup(
              batch,
              config.mixup.alpha,
              config.mixup.get("image_format", "NHWC"),
              rng=mixup_rng,
          )
  
      # Bind the rng to the host/device we are on.
      dropout_rng = train_utils.bind_rng_to_host_device(
          rng, axis_name="batch", bind_to="device"
      )
  
      def training_loss_fn(params):
          variables = {"params": params, **train_state.model_state}
          model_outputs, new_model_state = flax_model.apply(
              variables,
              batch["inputs"],
              mutable=["batch_stats"],
              train=True,
              rngs={"dropout": dropout_rng},
              debug=debug,
          )
  
          logits = model_outputs["logits"]
  
          # For NCR models.
          if use_ncr:
              ncr_loss_weight = config.ncr.loss_weight
              features = model_outputs[config.ncr.ncr_feature]
              logits_all, features_all = utils.all_gather(
                  (logits, features)
              )
              logging.info(
                  "logits.shape: %s. logits_all.shape %s",
                  logits.shape,
                  logits_all.shape,
              )
  
              loss, loss_metrics = loss_fn(
                  logits,
                  batch,
                  use_ncr,
                  use_bootstrap,
                  features,
                  logits_all,
                  features_all,
                  ncr_loss_weight,
                  variables["params"],
              )
          else:
              # For classification baseline model.
              bootstrap_loss_weight = config.get(
                  "bootstrap_weight", 0.0
              )
  
              loss, loss_metrics = loss_fn(
                  logits=logits,
                  batch=batch,
                  use_ncr=use_ncr,
                  use_bootstrap=use_bootstrap,
                  loss_weight=bootstrap_loss_weight,
                  model_params=variables["params"],
              )
  
          return loss, (new_model_state, logits, loss_metrics)
  
      compute_gradient_fn = jax.value_and_grad(
          training_loss_fn, has_aux=True
      )
      step = train_state.global_step
  
      (
          train_cost,
          (new_model_state, logits, loss_metrics),
      ), grad = compute_gradient_fn(train_state.params)
  
      del train_cost
      # Re-use same axis_name as in the call to `pmap(...train_step...)` below.
      grad = jax.lax.pmean(grad, axis_name="batch")
  
      if config.get("max_grad_norm", None) is not None:
          grad = clip_grads(grad, config.max_grad_norm)
  
      updates, new_opt_state = train_state.tx.update(
          grad, train_state.opt_state, train_state.params
      )
  
      new_params = optax.apply_updates(train_state.params, updates)
  
      metrics = metrics_fn(logits, batch)
      for metric_name, metric_value in loss_metrics.items():
          metrics[metric_name] = (
              metric_value,
              1,
          )  # Normalizer here is 1.
  
      new_train_state = (
          train_state.replace(  # pytype: disable=attribute-error
              global_step=step + 1,
              opt_state=new_opt_state,
              model_state=new_model_state,
              params=new_params,
              rng=new_rng,
          )
      )
      return new_train_state, metrics
  
imports: import functools
  import math
  import pdb
  from typing import Any, Callable, Dict, Optional, Tuple, Type
  from absl import logging
  from clu import metric_writers
  from clu import periodic_actions
  from clu import platform
  from flax import jax_utils
  import flax.linen
  import jax
  from jax.example_libraries.optimizers import clip_grads
  import jax.numpy
  import jax.profiler
  import ml_collections
  import numpy
  import optax
  from scenic.dataset_lib import dataset_utils
  from scenic.model_lib.base_models import base_model
  from scenic.projects.ncr import utils
  from scenic.train_lib import train_utils
label_desc: Use image node_id 1 for calling a global function with example usage: train_step(train_state, batch, use_ncr) and returns: new_train_state,  metrics, loss,  new_model_state,  logits,  loss_metrics