class_docstr: Test for caching behaviour
class_docstr_tok: ["Test","for","caching","behaviour"]
docstr: Test that, when using parameter-shift transform,
  caching produces the optimum number of evaluations.
docstr_tok: ["Test","that",",","when","using","parameter-shift","transform",",","caching","produces","the","optimum","number","of","evaluations","."]
code: def test_caching_param_shift(self, tol):
      """Test that, when using parameter-shift transform,
      caching produces the optimum number of evaluations."""
      dev = qml.device("default.qubit.legacy", wires=1)
  
      def cost(a, cache):
          with qml.queuing.AnnotatedQueue() as q:
              qml.RY(a[0], wires=0)
              qml.RX(a[1], wires=0)
              qml.expval(qml.PauliZ(0))
  
          tape = qml.tape.QuantumScript.from_queue(q)
          return execute(
              [tape],
              dev,
              gradient_fn=param_shift,
              cache=cache,
          )[0]
  
      # Without caching, 5 evaluations are required to compute
      # the Jacobian: 1 (forward pass) + 2 (backward pass) * (2 shifts * 2 params)
      params = jax.numpy.array([0.1, 0.2])
      jax.grad(cost)(params, cache=None)
      assert dev.num_executions == 5
  
      # With caching, 5 evaluations are required to compute
      # the Jacobian: 1 (forward pass) + (2 shifts * 2 params)
      dev._num_executions = 0
      jac_fn = jax.grad(cost)
      grad1 = jac_fn(params, cache=True)
      assert dev.num_executions == 5
  
      # Check that calling the cost function again
      # continues to evaluate the device (that is, the cache
      # is emptied between calls)
      grad2 = jac_fn(params, cache=True)
      assert dev.num_executions == 10
      assert np.allclose(grad1, grad2, atol=tol, rtol=0)
  
      # Check that calling the cost function again
      # with different parameters produces a different Jacobian
      grad2 = jac_fn(2 * params, cache=True)
      assert dev.num_executions == 15
      assert not np.allclose(grad1, grad2, atol=tol, rtol=0)
  
imports: import pytest
  import numpy
  import pennylane
  from pennylane.gradients import param_shift
  from pennylane import execute
label_desc: Use image node_id 4 for calling the TestCaching obj's underlying member method code with example usage: obj.test_caching_param_shift(tol) and returns: execute