code: def mean_ap(
      distance_matrix: torch.Tensor,
      labels: torch.Tensor,
  ) -> float:
      """Compute Mean Average Precision.
  
      Args:
          distance_matrix: pairwise distance matrix between embeddings of gallery and query sets, shape = (m,m)
          labels: labels for the query data (assuming the same as gallery), shape = (m,)
  
      Returns: mean average precision (float)
  
      """
      m, n = distance_matrix.shape
      assert m == n
  
      # Sort and find correct matches
      distance_matrix, gallery_matched_indices = torch.sort(
          distance_matrix, dim=1
      )
      truth_mask = labels[gallery_matched_indices] == labels[:, None]
  
      distance_matrix = distance_matrix.cpu().numpy()
      gallery_matched_indices = gallery_matched_indices.cpu().numpy()
      truth_mask = truth_mask.cpu().numpy()
  
      # Compute average precision for each query
      average_precisions = list()
      for query_index in range(n):
          valid_sorted_match_indices = (
              gallery_matched_indices[query_index, :] != query_index
          )
          y_true = truth_mask[query_index, valid_sorted_match_indices]
          y_score = -distance_matrix[query_index][
              valid_sorted_match_indices
          ]
          if not np.any(y_true):
              continue  # if a query does not have any match, we exclude it from mAP calculation.
          average_precisions.append(
              average_precision_score(y_true, y_score)
          )
      return np.mean(average_precisions)
  
imports: import argparse
  import copy
  from typing import Dict, Tuple
  import numpy
  import torch
  from sklearn.metrics import average_precision_score
  from torch.nn import functional
  from metrics import METRICS_REGISTRY
  from metrics.metric_base import EpochMetric
  from utils import logger
  from utils.ddp_utils import is_master
  from utils.registry import Registry
label_desc: Use image node_id 4 for calling a global function with example usage: mean_ap(distance_matrix, labels) and returns: np