code: def mmd2_from_kernel_matrix(
      kernel_mat: torch.Tensor,
      m: int,
      permute: bool = False,
      zero_diag: bool = True,
  ) -> torch.Tensor:
      """
      Compute maximum mean discrepancy (MMD^2) between 2 samples x and y from the
      full kernel matrix between the samples.
  
      Parameters
      ----------
      kernel_mat
          Kernel matrix between samples x and y.
      m
          Number of instances in y.
      permute
          Whether to permute the row indices. Used for permutation tests.
      zero_diag
          Whether to zero out the diagonal of the kernel matrix.
  
      Returns
      -------
      MMD^2 between the samples from the kernel matrix.
      """
      n = kernel_mat.shape[0] - m
      if zero_diag:
          kernel_mat = kernel_mat - torch.diag(kernel_mat.diag())
      if permute:
          idx = torch.randperm(kernel_mat.shape[0])
          kernel_mat = kernel_mat[idx][:, idx]
      k_xx, k_yy, k_xy = (
          kernel_mat[:-m, :-m],
          kernel_mat[-m:, -m:],
          kernel_mat[-m:, :-m],
      )
      c_xx, c_yy = 1 / (n * (n - 1)), 1 / (m * (m - 1))
      mmd2 = c_xx * k_xx.sum() + c_yy * k_yy.sum() - 2.0 * k_xy.mean()
      return mmd2
  
file_path: alibi-detect/alibi_detect/utils/pytorch/distance.py
imports: import logging
  import torch
  from torch import nn
  import numpy
  from typing import Callable, List, Tuple, Optional, Union
label_desc: Use image node_id 3 for calling a global function with example usage: mmd2_from_kernel_matrix(kernel_mat, m, permute, zero_diag) and returns: mmd2