code: def terminate_if_not_finite(state, value=None, gradient=None):
      """Terminates optimization if the objective or gradient values are not finite.
  
      Specifically,
  
      - If the objective is -inf, stop with success, since this position is a global
        minimum.
  
      - Otherwise, if the objective or any component of the gradient is not finite,
        stop with failure.
  
      Why fail?
  
      - If the objective is nan, it could be a global minimum, but we can't know.
  
      - If the objective is +inf, we can't trust the gradient, so we can't know
        where to go next.  This should only ever happen on the first iteration,
        because the line search avoids returning points whose objective values are
        +inf.
  
      - If the gradient has any nonfinite values, we can't use it to move a finite
        amount.
  
      Args:
        state: A BfgsOptimizerResults or LbfgsOptimizerResults representing the
          current position and information about it.
        value: A Tensor giving the value of the objective function.
          `state.objective_value` if not supplied.
        gradient: A Tensor giving the gradient of the objective function.
          `state.objective_gradient` if not supplied.
  
      Returns:
        state: A namedputple of the same type with possibly updated `converged` and
          `failed` fields.
      """
      if value is None:
          value = state.objective_value
      if gradient is None:
          gradient = state.objective_gradient
  
      minus_inf_mask = _is_negative_inf(value)
      state = state._replace(converged=state.converged | minus_inf_mask)
  
      non_finite_mask = ~tf.math.is_finite(value) | tf.reduce_any(
          ~tf.math.is_finite(gradient), axis=-1
      )
      state = state._replace(
          failed=state.failed | (~state.converged & non_finite_mask)
      )
  
      return state
  
file_path: probability/tensorflow_probability/python/optimizer/bfgs_utils.py
imports: import collections
  import numpy
  import tensorflow.compat.v2
  from tensorflow_probability.python.internal import dtype_util
  from tensorflow_probability.python.internal import prefer_static
  from tensorflow_probability.python.optimizer.linesearch.hager_zhang import hager_zhang
label_desc: Use image node_id 4 for calling a global function with example usage: terminate_if_not_finite(state, value, gradient) and returns: state