code: def rgb_to_grayscale(
      img: Tensor, num_output_channels: int = 1
  ) -> Tensor:
      if img.ndim < 3:
          raise TypeError(
              f"Input image tensor should have at least 3 dimensions, but found {img.ndim}"
          )
      _assert_channels(img, [1, 3])
  
      if num_output_channels not in (1, 3):
          raise ValueError(
              "num_output_channels should be either 1 or 3"
          )
  
      if img.shape[-3] == 3:
          r, g, b = img.unbind(dim=-3)
          # This implementation closely follows the TF one:
          # https://github.com/tensorflow/tensorflow/blob/v2.3.0/tensorflow/python/ops/image_ops_impl.py#L2105-L2138
          l_img = (0.2989 * r + 0.587 * g + 0.114 * b).to(img.dtype)
          l_img = l_img.unsqueeze(dim=-3)
      else:
          l_img = img.clone()
  
      if num_output_channels == 3:
          return l_img.expand(img.shape)
  
      return l_img
  
imports: import warnings
  from typing import List, Optional, Tuple, Union
  import torch
  from torch import Tensor
  from torch.nn.functional import conv2d, grid_sample, interpolate, pad
label_desc: Use image node_id 12 for calling a global function with example usage: rgb_to_grayscale(img, num_output_channels) and returns: l_img, l_img