code: def unstructured_sparsity_matrix(
      name: str, weight: _torch.Tensor, block_size: int
  ) -> _torch.Tensor:
      import matplotlib
  
      matplotlib.use("agg")
      import matplotlib.pyplot as plt
  
      rank = len(weight.shape)
  
      weight = weight.clone().detach()
  
      if block_size is not None and block_size > 1:
          C_out, C_in = weight.shape[:2]
          assert C_out % block_size == 0
          if rank > 2:
              weight = weight.flatten(2).view(
                  C_out // block_size, block_size, C_in, -1
              )
          else:
              weight = weight.view(C_out // 2, 2, C_in)
  
          sparsity_matrix = weight.sum(1).eq(0.0).float()
      else:
          sparsity_matrix = weight.eq(0.0).float()
  
      if rank > 2:
          max_kernel_support = _np.prod(sparsity_matrix.shape[2:])
          sparsity_matrix = sparsity_matrix.sum(
              dim=tuple(range(2, len(sparsity_matrix.shape)))
          )
      else:
          max_kernel_support = 1
  
      f = plt.figure()
      ax = f.gca()
      ax.imshow(
          max_kernel_support - sparsity_matrix.cpu().numpy(),
          cmap="jet",
          interpolation="nearest",
          vmin=0,
          vmax=max_kernel_support,
      )
      ax.set_xlabel("Input channels index")
      ax.set_ylabel("Output channels index")
      sparsity_type = (
          f"Block-{block_size}"
          if block_size is not None and block_size > 1
          else "Unstructured"
      )
      ax.set_title(f"{sparsity_type} Sparsity Matrix for Layer {name}")
      ax.set_xticks([])
      ax.set_yticks([])
      f.canvas.draw()
  
      im = _np.frombuffer(
          f.canvas.tostring_rgb(), dtype=_np.uint8
      ).copy()
      im = im.reshape((1,) + f.canvas.get_width_height()[::-1] + (3,))
  
      f.clear()
      plt.close(f)
      return _torch.from_numpy(im)
  
file_path: coremltools/coremltools/optimize/torch/pruning/_utils.py
imports: import logging
  from typing import List
  from typing import Optional
  from typing import Tuple
  from typing import cast
  import numpy
  import torch
label_desc: Use image node_id 8 for calling a global function with example usage: unstructured_sparsity_matrix(name, weight, block_size) and returns: _torch