class_docstr: Test that the transform is differentiable
class_docstr_tok: ["Test","that","the","transform","is","differentiable"]
docstr: Tests that the output of the SPSA gradient transform
  can be differentiated using Torch, yielding second derivatives.
docstr_tok: ["Tests","that","the","output","of","the","SPSA","gradient","transform","can","be","differentiated","using","Torch",",","yielding","second","derivatives","."]
code: def test_torch(self, dev_name, approx_order, strategy):
      """Tests that the output of the SPSA gradient transform
      can be differentiated using Torch, yielding second derivatives."""
      import torch
  
      dev = qml.device(dev_name, wires=2, shots=many_shots_shot_vector)
      execute_fn = (
          dev.execute
          if dev_name == "default.qubit"
          else dev.batch_execute
      )
      params = torch.tensor(
          [0.543, -0.654], dtype=torch.float64, requires_grad=True
      )
      rng = np.random.default_rng(42)
  
      def cost_fn(params):
          with qml.queuing.AnnotatedQueue() as q:
              qml.RX(params[0], wires=[0])
              qml.RY(params[1], wires=[1])
              qml.CNOT(wires=[0, 1])
              qml.expval(qml.PauliZ(0) @ qml.PauliX(1))
  
          tape = qml.tape.QuantumScript.from_queue(
              q, shots=many_shots_shot_vector
          )
          tapes, fn = spsa_grad(
              tape,
              n=1,
              approx_order=approx_order,
              strategy=strategy,
              h=h_val,
              sampler_rng=rng,
          )
          jac = fn(execute_fn(tapes))
          return jac
  
      hess = torch.autograd.functional.jacobian(cost_fn, params)
  
      x, y = params.detach().numpy()
  
      expected = np.array(
          [
              [-np.cos(x) * np.sin(y), -np.cos(y) * np.sin(x)],
              [-np.cos(y) * np.sin(x), -np.cos(x) * np.sin(y)],
          ]
      )
  
      assert np.allclose(
          hess[0].detach().numpy(),
          expected[0],
          atol=spsa_shot_vec_tol,
          rtol=0,
      )
      assert np.allclose(
          hess[1].detach().numpy(),
          expected[1],
          atol=spsa_shot_vec_tol,
          rtol=0,
      )
  
imports: import numpy
  import pytest
  from pennylane import numpy
  import pennylane
  from pennylane.gradients import spsa_grad
  from pennylane.devices import DefaultQubitLegacy
  from pennylane.measurements import Shots
  from pennylane.operation import Observable, AnyWires
label_desc: Use image node_id 5 for calling the TestSpsaGradientDifferentiation obj's underlying member method code with example usage: obj.test_torch(dev_name, approx_order, strategy) and returns: jac