code: def _grad_func(y, xs, retain_grads):
      """Gradient calculation function."""
      # Creating a zero gradient nest for the case where no gradients are computed
      grads_ = ivy.nested_map(
          lambda x: ivy.to_native(ivy.zeros_like(x)),
          xs,
          include_derived=True,
          shallow=False,
      )
  
      # Gradient calculation
      if isinstance(xs, ivy.NativeArray):
          grads = torch.autograd.grad(
              y,
              xs,
              retain_graph=True,
              create_graph=retain_grads,
              allow_unused=True,
          )[0]
          grads = grads_ if grads is None else grads
      elif isinstance(xs, ivy.Container):
          grads = xs.cont_from_flat_list(
              list(
                  torch.autograd.grad(
                      [y],
                      [v for k, v in xs.cont_to_iterator()],
                      retain_graph=True,
                      create_graph=retain_grads,
                      allow_unused=True,
                  )
              )
          )
          # Returning zeros if no gradients are computed for consistent results
          if isinstance(grads, ivy.Container):
              grads = ivy.nested_map(
                  lambda x: 0 if x is None else x,
                  grads,
                  include_derived=True,
              )
              grads += grads_
          else:
              grads = grads_ if grads is None else grads
      else:
  
          def grad_(x):
              grad = torch.autograd.grad(
                  y,
                  x,
                  retain_graph=True,
                  create_graph=retain_grads,
                  allow_unused=True,
              )[0]
              return grad if grad is not None else 0
  
          grads = ivy.nested_map(
              grad_, xs, include_derived=True, shallow=False
          )
          grads = ivy.nested_multi_map(
              lambda x, _: (x[0] + x[1]), [grads, grads_]
          )
      return grads
  
file_path: ivy/ivy/functional/backends/torch/gradients.py
imports: import torch
  from typing import Optional, Callable, Sequence, Union
  import ivy
  from ivy.func_wrapper import outputs_to_ivy_arrays, inputs_to_native_arrays
  from ivy.functional.ivy.gradients import _get_required_float_variables, _get_y_and_ret_idxs, _get_native_y, _set_duplicates, _process_func_ret_and_grads
label_desc: Use image node_id 4 for calling a global function with example usage: _grad_func(y, xs, retain_grads) and returns: grads, unknown