code: def testOpCallbackWorksWithGradientTape(self):
      instrument = _NumpyFunctionCallback()
      op_callbacks.add_op_callback(instrument.callback)
  
      v = variables.Variable(3.0, dtype=dtypes.float32)
      if not context.executing_eagerly():
          self.evaluate(v.initializer)
  
      @def_function.function
      def get_gradients():
          with backprop.GradientTape() as tape:
              loss = math_ops.sin(math_ops.square(v))
              gradients = tape.gradient(loss, v)
          return gradients
  
      gradients = get_gradients()
      # Applying the chain rule.
      self.assertAllClose(gradients, np.cos(3.0 * 3.0) * 3.0 * 2.0)
      self.assertIn(_SQUARE_OP, instrument.graph_op_types)
      self.assertIn(_SIN_OP, instrument.graph_op_types)
      # The mul and cos ops are created for backprop.
      self.assertIn(_MUL_OP, instrument.graph_op_types)
      self.assertIn(_COS_OP, instrument.graph_op_types)
  
      # Check the ndarrays from runtime.
      cos_op_outputs = instrument.graph_internal_ndarrays[
          b"gradient_tape/" + _COS_OP
      ]
      self.assertEqual(len(cos_op_outputs), 1)
      self.assertAllClose(cos_op_outputs[0], np.cos(3.0 * 3.0))
  
imports: import threading
  import numpy
  from tensorflow.python.data.ops import dataset_ops
  from tensorflow.python.eager import backprop
  from tensorflow.python.eager import context
  from tensorflow.python.eager import def_function
  from tensorflow.python.eager import test
  from tensorflow.python.framework import constant_op
  from tensorflow.python.framework import dtypes
  from tensorflow.python.framework import op_callbacks
  from tensorflow.python.framework import ops
  from tensorflow.python.framework import sparse_tensor
  from tensorflow.python.framework import test_util
  from tensorflow.python.ops import array_ops
  from tensorflow.python.ops import control_flow_ops
  from tensorflow.python.ops import math_ops
  from tensorflow.python.ops import script_ops
  from tensorflow.python.ops import sparse_ops
  from tensorflow.python.ops import variables
  from tensorflow.python.util import compat
label_desc: Use image node_id 23 for calling the OpCallbacksTest obj's underlying member method code with example usage: obj.testOpCallbackWorksWithGradientTape() and returns: gradients