code: def remap_instance_id(
      pred: torch.Tensor, by_size: bool = False
  ) -> torch.Tensor:
      """
      This function is used to rename all instance id of `pred`, so that the id is
      contiguous.
      For example: all ids of the input can be [0, 1, 2] rather than [0, 2, 5].
      This function is helpful for calculating metrics like Panoptic Quality (PQ).
      The implementation refers to:
  
      https://github.com/vqdang/hover_net
  
      Args:
          pred: segmentation predictions in the form of torch tensor. Each
              value of the tensor should be an integer, and represents the prediction of its corresponding instance id.
          by_size: if True, largest instance will be assigned a smaller id.
  
      """
      pred_id: Iterable[Any] = list(pred.unique())
      # the original implementation has the limitation that if there is no 0 in pred, error will happen
      pred_id = [i for i in pred_id if i != 0]
  
      if not pred_id:
          return pred
      if by_size:
          instance_size = [
              (pred == instance_id).sum() for instance_id in pred_id
          ]
          pair_data = zip(pred_id, instance_size)
          pair_list = sorted(
              pair_data, key=lambda x: x[1], reverse=True
          )
          pred_id, _ = zip(*pair_list)
  
      new_pred = torch.zeros_like(pred, dtype=torch.int)
      for idx, instance_id in enumerate(pred_id):
          new_pred[pred == instance_id] = idx + 1
      return new_pred
  
imports: from __future__ import annotations
  import warnings
  from functools import lru_cache, partial
  from types import ModuleType
  from typing import Any, Iterable, Sequence
  import numpy
  import torch
  from monai.config import NdarrayOrTensor, NdarrayTensor
  from monai.transforms.croppad.dictionary import CropForegroundD
  from monai.transforms.utils import distance_transform_edt
  from monai.utils import MetricReduction, convert_to_cupy, convert_to_dst_type, convert_to_numpy, convert_to_tensor, deprecated_arg, deprecated_arg_default, ensure_tuple_rep, look_up_option, optional_import
label_desc: Use image node_id 7 for calling a global function with example usage: remap_instance_id(pred, by_size) and returns: new_pred, pred