def test_multi_thread(self, enable_tape_mode): """Test that multi-threaded queuing in tape mode works correctly""" n_qubits = 4 n_batches = 5 dev = qml.device("default.qubit", wires=n_qubits) def circuit(inputs, weights): for index, input in enumerate(inputs): qml.RY(input, wires=index) for index in range(n_qubits - 1): qml.CNOT(wires=(index, index + 1)) for index, weight in enumerate(weights): qml.RX(weight, wires=index) return [qml.expval(qml.PauliZ(wires=i)) for i in range(n_qubits)] weight_shapes = {"weights": (n_qubits)} try: qnode = QNodeCollection([QNode(circuit, dev) for _ in range(n_batches)]) except Exception as e: pytest.fail("QNodeCollection cannot be instantiated") x = np.random.rand(n_qubits).astype(np.float64) p = np.random.rand(weight_shapes["weights"]).astype(np.float64) try: for _ in range(10): qnode(x, p, parallel=True) except: pytest.fail("Multi-threading on QuantumTape failed")
def test_gradient_torch(self, mocker): """Test that caching works when calculating the gradient method using the Torch interface""" import torch qnode = get_qnode(caching=10, interface="torch") args0 = torch.tensor(0.1, requires_grad=True) args1 = torch.tensor(0.2) res = qnode(args0, args1) res.backward() assert args0.grad is not None spy = mocker.spy(DefaultQubitAutograd, "execute") res = qnode(args0, args1) res.backward() spy.assert_not_called()
def test_caching(self, mocker): """Test that multiple device executions with different params are cached and accessed on subsequent executions""" qnode = get_qnode(caching=10) args = np.arange(10) for arg in args: qnode(arg, 0.2) assert qnode.qtape.caching == 10 spy = mocker.spy(DefaultQubitAutograd, "execute") for arg in args: qnode(arg, 0.2) spy.assert_not_called()
def test_gradient_tf(self, mocker): """Test that caching works when calculating the gradient method using the TF interface""" import tensorflow as tf qnode = get_qnode(caching=10, interface="tf") args0 = tf.Variable(0.1) args1 = tf.Variable(0.2) with tf.GradientTape() as tape: res = qnode(args0, args1) grad = tape.gradient(res, args0) assert grad is not None spy = mocker.spy(DefaultQubitAutograd, "execute") with tf.GradientTape() as tape: res = qnode(args0, args1) tape.gradient(res, args0) spy.assert_not_called()