code: def clip_gradients(
      gradients_dict: "ParamDict",
      *,
      grad_clip: Optional[float] = None,
      grad_clip_by: str,
  ) -> Optional[float]:
      """Performs gradient clipping on a grad-dict based on a clip value and clip mode.
  
      Changes the provided gradient dict in place.
  
      Args:
          gradients_dict: The gradients dict, mapping str to gradient tensors.
          grad_clip: The value to clip with. The way gradients are clipped is defined
              by the `grad_clip_by` arg (see below).
          grad_clip_by: One of 'value', 'norm', or 'global_norm'.
  
      Returns:
          If `grad_clip_by`="global_norm" and `grad_clip` is not None, returns the global
          norm of all tensors, otherwise returns None.
      """
      # No clipping, return.
      if grad_clip is None:
          return
  
      # Clip by value (each gradient individually).
      if grad_clip_by == "value":
          for k, v in gradients_dict.copy().items():
              gradients_dict[k] = tf.clip_by_value(
                  v, -grad_clip, grad_clip
              )
  
      # Clip by L2-norm (per gradient tensor).
      elif grad_clip_by == "norm":
          for k, v in gradients_dict.copy().items():
              gradients_dict[k] = tf.clip_by_norm(v, grad_clip)
  
      # Clip by global L2-norm (across all gradient tensors).
      else:
          assert grad_clip_by == "global_norm"
  
          clipped_grads, global_norm = tf.clip_by_global_norm(
              list(gradients_dict.values()), grad_clip
          )
          for k, v in zip(gradients_dict.copy().keys(), clipped_grads):
              gradients_dict[k] = v
  
          # Return the computed global norm scalar.
          return global_norm
  
imports: import logging
  from typing import Any, Callable, List, Optional, Type, TYPE_CHECKING, Union
  import gymnasium
  import numpy
  import tree
  from gymnasium.spaces import Discrete, MultiDiscrete
  from ray.rllib.utils.annotations import PublicAPI, DeveloperAPI
  from ray.rllib.utils.framework import try_import_tf
  from ray.rllib.utils.spaces.space_utils import get_base_struct_from_space
  from ray.rllib.utils.typing import LocalOptimizer, ModelGradients, PartialAlgorithmConfigDict, SpaceStruct, TensorStructType, TensorType
label_desc: Use image node_id 1 for calling a global function with example usage: clip_gradients(gradients_dict) and returns: global_norm