class_docstr: Base model for object detection with matching.
class_docstr_tok: ["Base","model","for","object","detection","with","matching","."]
docstr: Classification softmax cross entropy loss.
  
  Args:
    outputs: Model predictions. For the purpose of this loss, outputs must
      have key 'pred_logits'. outputs['pred_logits'] is a nd-array of the
      predicted pre-softmax logits of shape [batch-size, num-objects,
      num-classes].
    batch: Dict that has 'inputs', 'batch_mask' and, 'label' (ground truth).
      batch['label'] is a dict. For the purpose of this loss, label dict must
      have key 'labels', which the value is an int nd-array of labels. It may
      be one-hot if dataset_meta_data.target_is_onehot was set to True. If
      batch['batch_mask'] is provided it is used to weight the loss for
      different images in the current batch of examples.
    log: If true, return class_error as well.
  
  Returns:
    loss: Dict with keys 'loss_ce'.
    metrics: Dict with keys 'loss_ce' and 'class_error`.
docstr_tok: ["Classification","softmax","cross","entropy","loss",".","Args",":","outputs",":","Model","predictions",".","For","the","purpose","of","this","loss",",","outputs","must","have","key","'pred_logits","'",".","outputs","[","'pred_logits","'","]","is","a","nd-array","of","the","predicted","pre-softmax","logits","of","shape","[","batch-size",",","num-objects",",","num-classes","]",".","batch",":","Dict","that","has","'inputs","'",",","'batch_mask","'","and",",","'label","'","(","ground","truth",")",".","batch","[","'label","'","]","is","a","dict",".","For","the","purpose","of","this","loss",",","label","dict","must","have","key","'labels","'",",","which","the","value","is","an","int","nd-array","of","labels",".","It","may","be","one-hot","if","dataset_meta_data.target_is_onehot","was","set","to","True",".","If","batch","[","'batch_mask","'","]","is","provided","it","is","used","to","weight","the","loss","for","different","images","in","the","current","batch","of","examples",".","log",":","If","true",",","return","class_error","as","well",".","Returns",":","loss",":","Dict","with","keys","'loss_ce","'",".","metrics",":","Dict","with","keys","'loss_ce","'","and","'class_error","`","."]
code: def label_losses_and_metrics(
      self, outputs: ArrayDict, batch: ArrayDict, log: bool = True
  ) -> Tuple[Any, MetricsDict]:
      """Classification softmax cross entropy loss.
  
      Args:
        outputs: Model predictions. For the purpose of this loss, outputs must
          have key 'pred_logits'. outputs['pred_logits'] is a nd-array of the
          predicted pre-softmax logits of shape [batch-size, num-objects,
          num-classes].
        batch: Dict that has 'inputs', 'batch_mask' and, 'label' (ground truth).
          batch['label'] is a dict. For the purpose of this loss, label dict must
          have key 'labels', which the value is an int nd-array of labels. It may
          be one-hot if dataset_meta_data.target_is_onehot was set to True. If
          batch['batch_mask'] is provided it is used to weight the loss for
          different images in the current batch of examples.
        log: If true, return class_error as well.
  
      Returns:
        loss: Dict with keys 'loss_ce'.
        metrics: Dict with keys 'loss_ce' and 'class_error`.
      """
      assert "pred_logits" in outputs
      assert "label" in batch
  
      metrics = {}
      batch_weights = batch.get("batch_mask")
      targets = batch["label"]["labels"]
  
      # Shape: [batch, 101, 101]
      src_logits = jax.nn.log_softmax(outputs["pred_logits"])
  
      tgt_labels_weights = targets != 0
      tgt_labels_onehot = jax.nn.one_hot(
          targets, self.config.get("num_classes", 25)
      )
      tgt_labels_onehot *= tgt_labels_weights[..., None]
  
      # For predicted bbox that don't have a matched parent id, the weight is 0.
      # Shape: [batch, num_matched]
      weights = tgt_labels_weights
      if batch_weights is not None:
          weights *= batch_weights[..., None]
  
      label_weights = [0.0] + [1.0] * (
          self.config.get("num_classes") - 1
      )
      label_weights = jnp.array(label_weights)
  
      unnormalized_loss_ce = (
          model_utils.weighted_unnormalized_softmax_cross_entropy(
              src_logits,
              tgt_labels_onehot,
              weights=weights,
              logits_normalized=True,
              label_smoothing=self.config.label_smoothing,
          )
      )
  
      denom = tgt_labels_onehot.sum(axis=[1, 2])
      if batch_weights is not None:
          denom *= batch_weights
  
      norm_type = self.config.get("normalization", "detr")
      if norm_type == "detr":
          denom = denom.sum()
          normalized_loss_ce = unnormalized_loss_ce.sum() / jnp.maximum(
              denom, 1.0
          )
      elif norm_type == "global":
          denom = jax.lax.pmean(denom.sum(), axis_name="batch")
          normalized_loss_ce = unnormalized_loss_ce.sum() / jnp.maximum(
              denom, 1.0
          )
      elif norm_type == "per_example":
          normalized_loss_ce = unnormalized_loss_ce.sum(axis=1)
          normalized_loss_ce = (
              normalized_loss_ce / jnp.maximum(denom, 1.0)
          ).mean()
      else:
          raise ValueError(f"Unknown normalization {norm_type}.")
  
      metrics["loss_ce"] = (unnormalized_loss_ce.sum(), denom.sum())
  
      if log:
          # For normalization, we need to have number of inputs that we do
          # prediction for, which is number of predicted boxes that have a matched
          # parent id.
          batch_num_inputs = weights.sum()
          # We are not using the eos_coef for accuracy computation
          num_correct = model_utils.weighted_correctly_classified(
              src_logits, tgt_labels_onehot, weights=weights
          )
          # For the evaluation, we will globally (across replicas) normalize the
          # num_correct to get the accuracy. The caller will do the normalization,
          # so we dont normalize and simply collect the sums here.
          metrics["label_accuracy"] = (num_correct, batch_num_inputs)
  
      # Sum metrics and normalizers over all replicas.
      for k, v in metrics.items():
          metrics[k] = model_utils.psum_metric_normalizer(v)
      return normalized_loss_ce, metrics
  
file_path: scenic/scenic/projects/layout_denoise/base_model.py
imports: from typing import Any, Dict, Optional, Tuple
  from absl import logging
  import jax
  import jax.numpy
  import ml_collections
  from scenic.model_lib.base_models import base_model
  from scenic.model_lib.base_models import model_utils
label_desc: Use image node_id 2 for calling the LayoutDenoiseBaseModel obj's underlying member method code with example usage: obj.label_losses_and_metrics(outputs, batch, log) and returns: normalized_loss_ce,  metrics