code: def get_metric(
      metric_name: str,
      num_classes: Optional[int] = None,
      is_matching: Optional[bool] = False,
      problem_type: Optional[str] = None,
  ):
      """
      Obtain a torchmerics.Metric from its name.
      Define a customized metric function in case that torchmetrics doesn't support some metric.
  
      Parameters
      ----------
      metric_name
          Name of metric.
      num_classes
          Number of classes.
      is_matching
          Whether is matching.
      problem_type
          Type of problem, e.g., binary and multiclass.
  
      Returns
      -------
      torchmetrics.Metric
          A torchmetrics.Metric object.
      custom_metric_func
          A customized metric function.
      """
      metric_name = metric_name.lower()
      if metric_name in [ACC, ACCURACY, OVERALL_ACCURACY]:
          # use MULTICLASS since the head output dim is 2 for the binary problem type.
          return (
              torchmetrics.Accuracy(
                  task=MULTICLASS, num_classes=num_classes
              ),
              None,
          )
      elif metric_name == NER_TOKEN_F1:
          return (
              torchmetrics.F1Score(
                  task=MULTICLASS,
                  num_classes=num_classes,
                  ignore_index=1,
              ),
              None,
          )
      elif metric_name in [RMSE, ROOT_MEAN_SQUARED_ERROR]:
          return torchmetrics.MeanSquaredError(squared=False), None
      elif metric_name == R2:
          return torchmetrics.R2Score(), None
      elif metric_name == QUADRATIC_KAPPA:
          return (
              torchmetrics.CohenKappa(
                  task=problem_type,
                  num_classes=num_classes,
                  weights="quadratic",
              ),
              None,
          )
      elif metric_name == ROC_AUC:
          return (
              torchmetrics.AUROC(
                  task=problem_type, num_classes=num_classes
              ),
              None,
          )
      elif metric_name == AVERAGE_PRECISION:
          return torchmetrics.AveragePrecision(
              task=problem_type, num_classes=num_classes
          )
      elif metric_name in [LOG_LOSS, CROSS_ENTROPY]:
          return torchmetrics.MeanMetric(), functools.partial(
              F.cross_entropy, reduction="none"
          )
      elif metric_name == COSINE_EMBEDDING_LOSS:
          return torchmetrics.MeanMetric(), functools.partial(
              F.cosine_embedding_loss, reduction="none"
          )
      elif metric_name == PEARSONR:
          return torchmetrics.PearsonCorrCoef(), None
      elif metric_name == SPEARMANR:
          if is_matching:  # TODO: add support for matching.
              raise ValueError(
                  "spearman relation is not supported for matching yet."
              )
          else:
              return torchmetrics.SpearmanCorrCoef(), None
      elif metric_name == F1:
          return (
              torchmetrics.F1Score(
                  task=problem_type, num_classes=num_classes
              ),
              None,
          )
      elif metric_name in [F1_MACRO, F1_MICRO, F1_WEIGHTED]:
          average = metric_name.split("_")[1]
          return (
              torchmetrics.F1Score(
                  task=problem_type,
                  num_classes=num_classes,
                  average=average,
              ),
              None,
          )
      elif metric_name in DETECTION_METRICS:
          return (
              MeanAveragePrecision(
                  box_format="xyxy",
                  iou_type="bbox",
                  class_metrics=False,
              ),
              None,
          )  # TODO: remove parameter hardcodings here, and add class_metrics
      elif metric_name == DIRECT_LOSS:
          return (
              torchmetrics.MeanMetric(nan_strategy="warn"),
              None,
          )  # This only works for detection where custom_metric is not required for BaseAggregator
      elif metric_name in [RECALL, HIT_RATE]:
          if is_matching:
              return CustomHitRate(), None
          else:  # TODO: support recall for general classification tasks.
              raise ValueError("Recall is not supported yet.")
      elif metric_name == BER:
          return Balanced_Error_Rate(), None
      elif metric_name in [SM, EM, FM, MAE]:
          return COD_METRICS_NAMES[metric_name], None
      elif metric_name == IOU:
          if num_classes == 1:
              return Binary_IoU(), None
          else:
              return Multiclass_IoU(num_classes=num_classes), None
      else:
          raise ValueError(f"Unknown metric {metric_name}")
  
imports: import functools
  import logging
  import re
  import warnings
  from typing import Any, Dict, List, Optional, Tuple, Union
  import torch
  import torchmetrics
  from omegaconf import DictConfig, OmegaConf
  from packaging import version
  from pytorch_metric_learning import distances, losses, miners
  from torch import nn, optim
  from torch.nn import functional
  from torchmetrics.detection.mean_ap import MeanAveragePrecision
  from transformers import Adafactor
  from transformers.models.mask2former.modeling_mask2former import Mask2FormerConfig, Mask2FormerLoss
  from transformers.trainer_pt_utils import get_parameter_names
  from ..constants import ACC, ACCURACY, AVERAGE_PRECISION, BER, BINARY, BIT_FIT, COLUMN_FEATURES, CONTRASTIVE_LOSS, COSINE_EMBEDDING_LOSS, COSINE_SIMILARITY, CROSS_ENTROPY, DETECTION_METRICS, DIRECT_LOSS, EM, F1, F1_MACRO, F1_MICRO, F1_WEIGHTED, FEATURES, FEW_SHOT_CLASSIFICATION, FM, HIT_RATE, IA3, IA3_BIAS, IA3_LORA, IA3_LORA_BIAS, IA3_LORA_NORM, IA3_NORM, IOU, LOG_LOSS, LORA, LORA_BIAS, LORA_NORM, MAE, MULTI_NEGATIVES_SOFTMAX_LOSS, MULTICLASS, NER, NER_TOKEN_F1, NORM_FIT, OBJECT_DETECTION, OPEN_VOCABULARY_OBJECT_DETECTION, OVERALL_ACCURACY, PAIR_MARGIN_MINER, PEARSONR, PEFT_STRATEGIES, QUADRATIC_KAPPA, R2, RECALL, REGRESSION, RMSE, ROC_AUC, ROOT_MEAN_SQUARED_ERROR, SEMANTIC_SEGMENTATION, SM, SPEARMANR
  from .losses import BBCEWithLogitLoss, FocalLoss, MultiNegativesSoftmaxLoss, SoftTargetCrossEntropy, StructureLoss
  from .lr_scheduler import get_cosine_schedule_with_warmup, get_linear_schedule_with_warmup, get_polynomial_decay_schedule_with_warmup
  from .semantic_seg_metrics import COD_METRICS_NAMES, Balanced_Error_Rate, Binary_IoU, Multiclass_IoU
label_desc: Use image node_id 3 for calling a global function with example usage: get_metric(metric_name, num_classes, is_matching, problem_type) and returns: torchmetrics,  None, torchmetrics,  None, torchmetrics,  None, torchmetrics,  None, torchmetrics,  None, torchmetrics,  None, torchmetrics, torchmetrics,  functools, torchmetrics,  functools, torchmetrics,  None, torchmetrics,  None, torchmetrics,  None, torchmetrics,  None, MeanAveragePrecision,  None, torchmetrics,  None, CustomHitRate,  None, Balanced_Error_Rate,  None, COD_METRICS_NAMES,  None, Binary_IoU,  None, Multiclass_IoU,  None