From bca15cce85a58aa633d98e8c2d46bf9019f45cdd Mon Sep 17 00:00:00 2001 From: Mudit Pandey Date: Fri, 12 Jul 2024 15:24:03 -0400 Subject: [PATCH] Remove global seeds from tests (#5990) **Context:** A while back we added an autouse fixture to our test suite that sets a global seed before each test. Thus there is no need to be setting global seeds inside tests unless they're explicitly testing behaviour related to seeding. **Description of the Change:** * Remove all references to `np.random.seed` from the tests, unless the test cases are specifically for seeding related functionality. * Replace the global seeds with local seeds where appropriate. **Benefits:** * Better practices with setting seeds in stochastic tests. Less random CI failures. **Possible Drawbacks:** **Related GitHub Issues:** --- pennylane/devices/tests/test_gates.py | 1 - .../devices/tests/test_gates_with_expval.py | 2 - .../default_qubit/test_default_qubit.py | 3 - .../default_tensor/test_default_tensor.py | 2 +- .../default_tensor/test_scalability.py | 2 - tests/devices/qubit/test_apply_operation.py | 12 ---- tests/devices/qubit/test_sampling.py | 3 +- tests/devices/test_default_mixed.py | 4 +- tests/devices/test_default_qubit_tf.py | 5 -- tests/devices/test_default_qubit_torch.py | 2 - tests/devices/test_default_qutrit_mixed.py | 2 - tests/devices/test_lightning_qubit.py | 1 - tests/devices/test_null_qubit.py | 2 - .../gradients/core/test_gradient_transform.py | 3 - tests/gradients/core/test_pulse_gradient.py | 12 ---- .../test_spsa_gradient_shot_vec.py | 2 - .../test_parameter_shift_shot_vec.py | 2 - ...graph_qnode_shot_vector_default_qubit_2.py | 2 - ...rflow_qnode_shot_vector_default_qubit_2.py | 2 - .../test_autograd_qnode_shot_vector.py | 2 - .../interfaces/test_jax_qnode_shot_vector.py | 2 - ..._tensorflow_autograph_qnode_shot_vector.py | 1 - .../test_tensorflow_qnode_shot_vector.py | 2 - tests/interfaces/test_torch_qnode.py | 2 - .../legacy/test_classical_shadow_legacy.py | 1 - .../measurements/legacy/test_expval_legacy.py | 3 - .../measurements/legacy/test_probs_legacy.py | 6 -- tests/measurements/legacy/test_var_legacy.py | 2 - tests/measurements/test_classical_shadow.py | 1 - tests/measurements/test_counts.py | 24 ++++--- tests/measurements/test_expval.py | 9 ++- tests/measurements/test_probs.py | 6 +- tests/measurements/test_var.py | 3 +- .../op_math/test_controlled_decompositions.py | 4 +- tests/ops/qubit/test_matrix_ops.py | 16 ++--- tests/ops/qubit/test_special_unitary.py | 24 +++---- tests/optimize/test_optimize_shot_adaptive.py | 4 +- tests/qinfo/test_fisher.py | 5 +- tests/shadow/test_shadow_class.py | 2 - tests/shadow/test_shadow_entropies.py | 2 - tests/shadow/test_shadow_transforms.py | 3 +- .../test_layers/test_cv_neural_net.py | 1 - tests/test_classical_gradients.py | 2 - tests/test_debugging.py | 20 +++--- tests/test_hermitian_edge_cases.py | 3 - tests/test_tensor_measurements.py | 2 - tests/test_vqe.py | 68 ++++++++----------- tests/transforms/test_batch_input.py | 1 - tests/transforms/test_defer_measurements.py | 5 +- tests/transforms/test_mitigate.py | 6 -- 50 files changed, 97 insertions(+), 199 deletions(-) diff --git a/pennylane/devices/tests/test_gates.py b/pennylane/devices/tests/test_gates.py index 49a985dc63b..622f6a4bdb9 100644 --- a/pennylane/devices/tests/test_gates.py +++ b/pennylane/devices/tests/test_gates.py @@ -31,7 +31,6 @@ pytestmark = pytest.mark.skip_unsupported -np.random.seed(42) # ========================================================== # Some useful global variables diff --git a/pennylane/devices/tests/test_gates_with_expval.py b/pennylane/devices/tests/test_gates_with_expval.py index d43da1870a4..7239ab2bcd3 100755 --- a/pennylane/devices/tests/test_gates_with_expval.py +++ b/pennylane/devices/tests/test_gates_with_expval.py @@ -28,8 +28,6 @@ pytestmark = pytest.mark.skip_unsupported -np.random.seed(42) - # =============================================================== diff --git a/tests/devices/default_qubit/test_default_qubit.py b/tests/devices/default_qubit/test_default_qubit.py index 4ee14716f77..6fcd69a3062 100644 --- a/tests/devices/default_qubit/test_default_qubit.py +++ b/tests/devices/default_qubit/test_default_qubit.py @@ -22,9 +22,6 @@ import pennylane as qml from pennylane.devices import DefaultQubit, ExecutionConfig -np.random.seed(0) - - max_workers_list = [ None, pytest.param(1, marks=pytest.mark.slow), diff --git a/tests/devices/default_tensor/test_default_tensor.py b/tests/devices/default_tensor/test_default_tensor.py index 0e9e9d1d9f6..9fb622e3174 100644 --- a/tests/devices/default_tensor/test_default_tensor.py +++ b/tests/devices/default_tensor/test_default_tensor.py @@ -297,7 +297,7 @@ def test_supported_gates_yield_correct_state(self, operation, method): nwires = 4 dq = qml.device("default.qubit", wires=nwires) dev = qml.device("default.tensor", wires=nwires, method=method) - np.random.seed(0) + state = np.random.rand(2**nwires) + 1j * np.random.rand(2**nwires) state /= np.linalg.norm(state) wires = qml.wires.Wires(range(nwires)) diff --git a/tests/devices/default_tensor/test_scalability.py b/tests/devices/default_tensor/test_scalability.py index 010ccba776f..af6ec5b6fc4 100644 --- a/tests/devices/default_tensor/test_scalability.py +++ b/tests/devices/default_tensor/test_scalability.py @@ -35,7 +35,6 @@ def test_multirz(self, method): wires = 16 dev = qml.device("default.tensor", wires=wires, method=method) - np.random.seed(0) state = np.random.rand(2**wires) + 1j * np.random.rand(2**wires) state /= np.linalg.norm(state) @@ -51,7 +50,6 @@ def test_paulirot(self, method): wires = 16 dev = qml.device("default.tensor", wires=wires, method=method) - np.random.seed(0) state = np.random.rand(2**wires) + 1j * np.random.rand(2**wires) state /= np.linalg.norm(state) diff --git a/tests/devices/qubit/test_apply_operation.py b/tests/devices/qubit/test_apply_operation.py index fe52935b670..bf385ace81d 100644 --- a/tests/devices/qubit/test_apply_operation.py +++ b/tests/devices/qubit/test_apply_operation.py @@ -948,7 +948,6 @@ def grover_kernel_partial_wires(self, state, op_wires, batched): def test_dispatching(self, op_wires, state_wires, einsum_called, tensordot_called, mocker): """Test that apply_operation dispatches to einsum, tensordot and the kernel correctly.""" # pylint: disable=too-many-arguments - np.random.seed(752) state = np.random.random([2] * state_wires) + 1j * np.random.random([2] * state_wires) op = qml.GroverOperator(list(range(op_wires))) @@ -963,7 +962,6 @@ def test_dispatching(self, op_wires, state_wires, einsum_called, tensordot_calle def test_correctness_full_wires(self, op_wires, state_wires, batch_dim): """Test that apply_operation is correct for GroverOperator for all dispatch branches when applying it to all wires of a state.""" - np.random.seed(752) batched = batch_dim is not None shape = [batch_dim] + [2] * state_wires if batched else [2] * state_wires flat_shape = (batch_dim, 2**state_wires) if batched else (2**state_wires,) @@ -983,7 +981,6 @@ def test_correctness_partial_wires(self, op_wires, state_wires, batch_dim): """Test that apply_operation is correct for GroverOperator for all dispatch branches but einsum (because Grover can't act on a single wire) when applying it only to some of the wires of a state.""" - np.random.seed(752) batched = batch_dim is not None shape = [batch_dim] + [2] * state_wires if batched else [2] * state_wires state = np.random.random(shape) + 1j * np.random.random(shape) @@ -1006,7 +1003,6 @@ def test_correctness_autograd(self, op_wires, state_wires, batch_dim): batched = batch_dim is not None shape = [batch_dim] + [2] * state_wires if batched else [2] * state_wires # Input state - np.random.seed(752) state = np.random.random(shape) + 1j * np.random.random(shape) wires = list(range(op_wires)) @@ -1035,7 +1031,6 @@ def test_correctness_tf(self, op_wires, state_wires, batch_dim): batched = batch_dim is not None shape = [batch_dim] + [2] * state_wires if batched else [2] * state_wires # Input state - np.random.seed(752) state = np.random.random(shape) + 1j * np.random.random(shape) wires = list(range(op_wires)) @@ -1066,7 +1061,6 @@ def test_correctness_jax(self, op_wires, state_wires, batch_dim): batched = batch_dim is not None shape = [batch_dim] + [2] * state_wires if batched else [2] * state_wires # Input state - np.random.seed(752) state = np.random.random(shape) + 1j * np.random.random(shape) wires = list(range(op_wires)) @@ -1095,7 +1089,6 @@ def test_correctness_torch(self, op_wires, state_wires, batch_dim): batched = batch_dim is not None shape = [batch_dim] + [2] * state_wires if batched else [2] * state_wires # Input state - np.random.seed(752) state = np.random.random(shape) + 1j * np.random.random(shape) wires = list(range(op_wires)) @@ -1140,7 +1133,6 @@ def test_multicontrolledx_dispatching( self, num_op_wires, num_state_wires, einsum_called, tdot_called, mocker ): """Test that apply_multicontrolledx dispatches to the right method and is correct.""" - np.random.seed(2751) op = qml.MultiControlledX(wires=list(range(num_op_wires))) state = np.random.random([2] * num_state_wires).astype(complex) spies = [mocker.spy(qml.math, "einsum"), mocker.spy(qml.math, "tensordot")] @@ -1159,7 +1151,6 @@ def test_with_jax(self, batch_dim): """Test that the custom kernel works with JAX.""" from jax import numpy as jnp - np.random.seed(2751) op = qml.MultiControlledX(wires=[0, 4, 3, 1]) state_shape = ([batch_dim] if batch_dim is not None else []) + [2] * 5 state = np.random.random(state_shape).astype(complex) @@ -1176,7 +1167,6 @@ def test_with_tf(self, batch_dim): """Test that the custom kernel works with Tensorflow.""" import tensorflow as tf - np.random.seed(2751) op = qml.MultiControlledX(wires=[0, 4, 3, 1]) state_shape = ([batch_dim] if batch_dim is not None else []) + [2] * 5 state = np.random.random(state_shape).astype(complex) @@ -1191,7 +1181,6 @@ def test_with_tf(self, batch_dim): @pytest.mark.parametrize("batch_dim", [None, 1, 3]) def test_with_autograd(self, batch_dim): """Test that the custom kernel works with Autograd.""" - np.random.seed(2751) op = qml.MultiControlledX(wires=[0, 4, 3, 1]) state_shape = ([batch_dim] if batch_dim is not None else []) + [2] * 5 state = np.random.random(state_shape).astype(complex) @@ -1208,7 +1197,6 @@ def test_with_torch(self, batch_dim): """Test that the custom kernel works with Torch.""" import torch - np.random.seed(2751) op = qml.MultiControlledX(wires=[0, 4, 3, 1]) state_shape = ([batch_dim] if batch_dim is not None else []) + [2] * 5 state = np.random.random(state_shape).astype(complex) diff --git a/tests/devices/qubit/test_sampling.py b/tests/devices/qubit/test_sampling.py index cb493841418..26a86a12592 100644 --- a/tests/devices/qubit/test_sampling.py +++ b/tests/devices/qubit/test_sampling.py @@ -34,7 +34,8 @@ def fixture_init_state(): def _init_state(n): """random initial state""" - state = np.random.random([1 << n]) + np.random.random([1 << n]) * 1j + rng = np.random.default_rng(123) + state = rng.random([1 << n]) + rng.random([1 << n]) * 1j state /= np.linalg.norm(state) return state.reshape((2,) * n) diff --git a/tests/devices/test_default_mixed.py b/tests/devices/test_default_mixed.py index 51a27f20d86..78d7e92e000 100644 --- a/tests/devices/test_default_mixed.py +++ b/tests/devices/test_default_mixed.py @@ -511,7 +511,7 @@ def test_channel_against_matmul(self, num_dev_wires, op, apply_method, tol): """Test the application of a channel againt matrix multiplication.""" if num_dev_wires < max(op.wires) + 1: pytest.skip("Need at least as many wires in the device as in the operation.") - np.random.seed(52) + dev = qml.device("default.mixed", wires=num_dev_wires) init_state = random_state(num_dev_wires) dev._state = qml.math.reshape(init_state, [2] * (2 * num_dev_wires)) @@ -1110,7 +1110,7 @@ def test_apply_qubitunitary(self, tol): @pytest.mark.parametrize("num_wires", [1, 2, 3]) def test_apply_specialunitary(self, tol, num_wires): """Tests that a special unitary is correctly applied""" - np.random.seed(2514) + theta = np.random.random(4**num_wires - 1) dev = qml.device("default.mixed", wires=num_wires) diff --git a/tests/devices/test_default_qubit_tf.py b/tests/devices/test_default_qubit_tf.py index 5135d5fdd44..6c4ef169e23 100644 --- a/tests/devices/test_default_qubit_tf.py +++ b/tests/devices/test_default_qubit_tf.py @@ -56,9 +56,6 @@ DefaultQubitTF, ) -np.random.seed(42) - - ##################################################### # Test matrices ##################################################### @@ -117,7 +114,6 @@ def init_state_fixture(scope="session"): def _init_state(n): """random initial state""" - np.random.seed(4214152) state = np.random.random([2**n]) + np.random.random([2**n]) * 1j state /= np.linalg.norm(state) return state @@ -132,7 +128,6 @@ def broadcasted_init_state_fixture(scope="session"): def _broadcasted_init_state(n, batch_size): """random initial state""" - np.random.seed(4214152) state = np.random.random([batch_size, 2**n]) + np.random.random([batch_size, 2**n]) * 1j return state / np.linalg.norm(state, axis=1)[:, np.newaxis] diff --git a/tests/devices/test_default_qubit_torch.py b/tests/devices/test_default_qubit_torch.py index afc7ea7854e..3a132070038 100644 --- a/tests/devices/test_default_qubit_torch.py +++ b/tests/devices/test_default_qubit_torch.py @@ -75,8 +75,6 @@ torch_devices.append("cuda") -np.random.seed(42) - ##################################################### # Test matrices ##################################################### diff --git a/tests/devices/test_default_qutrit_mixed.py b/tests/devices/test_default_qutrit_mixed.py index 7cc94324742..1203363b319 100644 --- a/tests/devices/test_default_qutrit_mixed.py +++ b/tests/devices/test_default_qutrit_mixed.py @@ -22,8 +22,6 @@ from pennylane import math from pennylane.devices import DefaultQutritMixed, ExecutionConfig -np.random.seed(0) - class TestDeviceProperties: """Tests for general device properties.""" diff --git a/tests/devices/test_lightning_qubit.py b/tests/devices/test_lightning_qubit.py index fe97c9c8b07..6fe2cac85b5 100644 --- a/tests/devices/test_lightning_qubit.py +++ b/tests/devices/test_lightning_qubit.py @@ -32,7 +32,6 @@ def circuit(weights): qml.templates.StronglyEntanglingLayers(weights, wires=range(wires)) return qml.expval(qml.PauliZ(0)) - np.random.seed(1967) weights = np.random.random( qml.templates.StronglyEntanglingLayers.shape(layers, wires), requires_grad=True ) diff --git a/tests/devices/test_null_qubit.py b/tests/devices/test_null_qubit.py index 0044b377cc8..e206dae2948 100644 --- a/tests/devices/test_null_qubit.py +++ b/tests/devices/test_null_qubit.py @@ -27,8 +27,6 @@ StateMeasurement, ) -np.random.seed(0) - def test_name(): """Tests the name of NullQubit.""" diff --git a/tests/gradients/core/test_gradient_transform.py b/tests/gradients/core/test_gradient_transform.py index 681920f777e..61cd765f85a 100644 --- a/tests/gradients/core/test_gradient_transform.py +++ b/tests/gradients/core/test_gradient_transform.py @@ -223,7 +223,6 @@ class TestGradientTransformIntegration: @pytest.mark.parametrize("prefactor", [1.0, 2.0]) def test_acting_on_qnodes_single_param(self, shots, slicing, prefactor, atol): """Test that a gradient transform acts on QNodes with a single parameter correctly""" - np.random.seed(412) dev = qml.device("default.qubit", wires=2, shots=shots) @qml.qnode(dev) @@ -252,7 +251,6 @@ def circuit(weights): @pytest.mark.parametrize("prefactor", [1.0, 2.0]) def test_acting_on_qnodes_multi_param(self, shots, prefactor, atol): """Test that a gradient transform acts on QNodes with multiple parameters correctly""" - np.random.seed(412) dev = qml.device("default.qubit", wires=2, shots=shots) @qml.qnode(dev) @@ -288,7 +286,6 @@ def circuit(weights): def test_acting_on_qnodes_multi_param_multi_arg(self, shots, atol): """Test that a gradient transform acts on QNodes with multiple parameters in both the tape and the QNode correctly""" - np.random.seed(234) dev = qml.device("default.qubit", wires=2, shots=shots) @qml.qnode(dev) diff --git a/tests/gradients/core/test_pulse_gradient.py b/tests/gradients/core/test_pulse_gradient.py index 5c99c1a3b3c..28dfa294673 100644 --- a/tests/gradients/core/test_pulse_gradient.py +++ b/tests/gradients/core/test_pulse_gradient.py @@ -295,8 +295,6 @@ def test_single_measure_single_shots( """ from jax import numpy as jnp - np.random.seed(3751) - cjac_shape = (num_split_times,) + par_shape if multi_term > 1: cjacs = tuple(np.random.random(cjac_shape) for _ in range(multi_term)) @@ -354,8 +352,6 @@ def test_single_measure_single_shots_broadcast( """ from jax import numpy as jnp - np.random.seed(3751) - cjac_shape = (num_split_times,) + par_shape if multi_term > 1: cjacs = tuple(np.random.random(cjac_shape) for _ in range(multi_term)) @@ -418,8 +414,6 @@ def test_multi_measure_or_multi_shots( """ from jax import numpy as jnp - np.random.seed(3751) - num_meas_or_shots = 5 cjac_shape = (num_split_times,) + par_shape @@ -492,8 +486,6 @@ def test_multi_measure_or_multi_shots_broadcast( """ from jax import numpy as jnp - np.random.seed(3751) - num_meas_or_shots = 5 cjac_shape = (num_split_times,) + par_shape @@ -568,8 +560,6 @@ def test_multi_measure_multi_shots( """ from jax import numpy as jnp - np.random.seed(3751) - num_shots = 3 num_meas = 5 @@ -644,8 +634,6 @@ def test_multi_measure_multi_shots_broadcast( """ from jax import numpy as jnp - np.random.seed(3751) - num_shots = 3 num_meas = 5 diff --git a/tests/gradients/finite_diff/test_spsa_gradient_shot_vec.py b/tests/gradients/finite_diff/test_spsa_gradient_shot_vec.py index 3df01afb383..e2c57bfd714 100644 --- a/tests/gradients/finite_diff/test_spsa_gradient_shot_vec.py +++ b/tests/gradients/finite_diff/test_spsa_gradient_shot_vec.py @@ -24,8 +24,6 @@ from pennylane.measurements import Shots from pennylane.operation import AnyWires, Observable -np.random.seed(0) - h_val = 0.1 spsa_shot_vec_tol = 0.31 diff --git a/tests/gradients/parameter_shift/test_parameter_shift_shot_vec.py b/tests/gradients/parameter_shift/test_parameter_shift_shot_vec.py index 90b37dd451e..2281fa735e6 100644 --- a/tests/gradients/parameter_shift/test_parameter_shift_shot_vec.py +++ b/tests/gradients/parameter_shift/test_parameter_shift_shot_vec.py @@ -512,7 +512,6 @@ def test_pauli_rotation_gradient(self, mocker, G, theta, shift, broadcast): """Tests that the automatic gradients of Pauli rotations are correct.""" # pylint: disable=too-many-arguments - np.random.seed(824) spy = mocker.spy(qml.gradients.parameter_shift, "_get_operation_recipe") shot_vec = many_shots_shot_vector dev = qml.device("default.qubit", wires=1, shots=shot_vec) @@ -2060,7 +2059,6 @@ def test_not_expval_error(self, broadcast): def test_no_trainable_coeffs(self, mocker, broadcast, tol): """Test no trainable Hamiltonian coefficients""" - np.random.seed(3751) shot_vec = many_shots_shot_vector dev = qml.device("default.qubit", wires=2, shots=shot_vec) spy = mocker.spy(qml.gradients, "hamiltonian_grad") diff --git a/tests/interfaces/default_qubit_2_integration/test_tensorflow_autograph_qnode_shot_vector_default_qubit_2.py b/tests/interfaces/default_qubit_2_integration/test_tensorflow_autograph_qnode_shot_vector_default_qubit_2.py index b24f223f248..c831fce26cc 100644 --- a/tests/interfaces/default_qubit_2_integration/test_tensorflow_autograph_qnode_shot_vector_default_qubit_2.py +++ b/tests/interfaces/default_qubit_2_integration/test_tensorflow_autograph_qnode_shot_vector_default_qubit_2.py @@ -391,7 +391,6 @@ def test_single_expectation_value( ): """Tests correct output shape and evaluation for a tape with a single expval output""" - np.random.seed(215) x = tf.Variable(0.543, dtype=tf.float64) y = tf.Variable(-0.654, dtype=tf.float64) @@ -425,7 +424,6 @@ def test_prob_expectation_values( ): """Tests correct output shape and evaluation for a tape with prob and expval outputs""" - np.random.seed(214) x = tf.Variable(0.543, dtype=tf.float64) y = tf.Variable(-0.654, dtype=tf.float64) diff --git a/tests/interfaces/default_qubit_2_integration/test_tensorflow_qnode_shot_vector_default_qubit_2.py b/tests/interfaces/default_qubit_2_integration/test_tensorflow_qnode_shot_vector_default_qubit_2.py index d4290493958..a3a5606fc78 100644 --- a/tests/interfaces/default_qubit_2_integration/test_tensorflow_qnode_shot_vector_default_qubit_2.py +++ b/tests/interfaces/default_qubit_2_integration/test_tensorflow_qnode_shot_vector_default_qubit_2.py @@ -453,7 +453,6 @@ def test_single_expectation_value( ): """Tests correct output shape and evaluation for a tape with a single expval output""" - np.random.seed(215) x = tf.Variable(0.543) y = tf.Variable(-0.654) @@ -487,7 +486,6 @@ def test_prob_expectation_values( ): """Tests correct output shape and evaluation for a tape with prob and expval outputs""" - np.random.seed(214) x = tf.Variable(0.543) y = tf.Variable(-0.654) diff --git a/tests/interfaces/test_autograd_qnode_shot_vector.py b/tests/interfaces/test_autograd_qnode_shot_vector.py index fb0ba04eaf0..6aee767d01e 100644 --- a/tests/interfaces/test_autograd_qnode_shot_vector.py +++ b/tests/interfaces/test_autograd_qnode_shot_vector.py @@ -567,7 +567,6 @@ def test_single_expectation_value( ): """Tests correct output shape and evaluation for a tape with a single expval output""" - np.random.seed(42) dev = qml.device(dev_name, wires=2, shots=shots) x = np.array(0.543) y = np.array(-0.654) @@ -601,7 +600,6 @@ def test_prob_expectation_values( ): """Tests correct output shape and evaluation for a tape with prob and expval outputs""" - np.random.seed(42) dev = qml.device(dev_name, wires=2, shots=shots) x = np.array(0.543) y = np.array(-0.654) diff --git a/tests/interfaces/test_jax_qnode_shot_vector.py b/tests/interfaces/test_jax_qnode_shot_vector.py index 6530d3a05e1..0ef5c8291de 100644 --- a/tests/interfaces/test_jax_qnode_shot_vector.py +++ b/tests/interfaces/test_jax_qnode_shot_vector.py @@ -838,7 +838,6 @@ def test_single_expectation_value( ): """Tests correct output shape and evaluation for a tape with a single expval output""" - np.random.seed(42) dev = qml.device(dev_name, wires=2, shots=shots) x = jax.numpy.array(0.543) y = jax.numpy.array(-0.654) @@ -874,7 +873,6 @@ def test_prob_expectation_values( ): """Tests correct output shape and evaluation for a tape with prob and expval outputs""" - np.random.seed(42) dev = qml.device(dev_name, wires=2, shots=shots) x = jax.numpy.array(0.543) y = jax.numpy.array(-0.654) diff --git a/tests/interfaces/test_tensorflow_autograph_qnode_shot_vector.py b/tests/interfaces/test_tensorflow_autograph_qnode_shot_vector.py index fb143315bf5..ab3147dfc95 100644 --- a/tests/interfaces/test_tensorflow_autograph_qnode_shot_vector.py +++ b/tests/interfaces/test_tensorflow_autograph_qnode_shot_vector.py @@ -435,7 +435,6 @@ def test_prob_expectation_values( ): """Tests correct output shape and evaluation for a tape with prob and expval outputs""" - np.random.seed(214) dev = qml.device(dev_name, wires=2, shots=shots) x = tf.Variable(0.543, dtype=tf.float64) y = tf.Variable(-0.654, dtype=tf.float64) diff --git a/tests/interfaces/test_tensorflow_qnode_shot_vector.py b/tests/interfaces/test_tensorflow_qnode_shot_vector.py index 113e4f04412..614c71ee7d4 100644 --- a/tests/interfaces/test_tensorflow_qnode_shot_vector.py +++ b/tests/interfaces/test_tensorflow_qnode_shot_vector.py @@ -468,7 +468,6 @@ def test_single_expectation_value( ): """Tests correct output shape and evaluation for a tape with a single expval output""" - np.random.seed(215) dev = qml.device(dev_name, wires=2, shots=shots) x = tf.Variable(0.543) y = tf.Variable(-0.654) @@ -502,7 +501,6 @@ def test_prob_expectation_values( ): """Tests correct output shape and evaluation for a tape with prob and expval outputs""" - np.random.seed(214) dev = qml.device(dev_name, wires=2, shots=shots) x = tf.Variable(0.543) y = tf.Variable(-0.654) diff --git a/tests/interfaces/test_torch_qnode.py b/tests/interfaces/test_torch_qnode.py index ebbf2beee8a..3965255a4a4 100644 --- a/tests/interfaces/test_torch_qnode.py +++ b/tests/interfaces/test_torch_qnode.py @@ -1490,8 +1490,6 @@ def test_hamiltonian_expansion_finite_shots( elif diff_method == "hadamard": pytest.skip("The hadamard method does not yet support Hamiltonians") - np.random.seed(1235) - dev = qml.device(dev_name, wires=3, shots=50000) spy = mocker.spy(qml.transforms, "split_non_commuting") obs = [qml.PauliX(0), qml.PauliX(0) @ qml.PauliZ(1), qml.PauliZ(0) @ qml.PauliZ(1)] diff --git a/tests/measurements/legacy/test_classical_shadow_legacy.py b/tests/measurements/legacy/test_classical_shadow_legacy.py index 691570506e5..e049247e717 100644 --- a/tests/measurements/legacy/test_classical_shadow_legacy.py +++ b/tests/measurements/legacy/test_classical_shadow_legacy.py @@ -192,7 +192,6 @@ def test_return_distribution(self, wires, interface, device, circuit_fn, basis_r """Test that the distribution of the bits and recipes are correct for a circuit that prepares all qubits in a Pauli basis""" # high number of shots to prevent true negatives - np.random.seed(42) shots = 1000 circuit = circuit_fn(wires, shots=shots, interface=interface, device=device) diff --git a/tests/measurements/legacy/test_expval_legacy.py b/tests/measurements/legacy/test_expval_legacy.py index 141247b40d3..da59c0aaca8 100644 --- a/tests/measurements/legacy/test_expval_legacy.py +++ b/tests/measurements/legacy/test_expval_legacy.py @@ -105,7 +105,6 @@ def test_observable_is_measurement_value( ): # pylint: disable=too-many-arguments """Test that expectation values for mid-circuit measurement values are correct for a single measurement value.""" - np.random.seed(42) dev = qml.device(device_name, wires=2, shots=shots) @qml.qnode(dev) @@ -133,7 +132,6 @@ def test_observable_is_composite_measurement_value( ): # pylint: disable=too-many-arguments """Test that expectation values for mid-circuit measurement values are correct for a composite measurement value.""" - np.random.seed(42) dev = qml.device(device_name, wires=6, shots=shots) @qml.qnode(dev) @@ -201,7 +199,6 @@ def test_projector_expval(self, state, shots, mocker): """Tests that the expectation of a ``Projector`` object is computed correctly for both of its subclasses.""" dev = qml.device("default.qubit.legacy", wires=3, shots=shots) - np.random.seed(42) @qml.qnode(dev) def circuit(): diff --git a/tests/measurements/legacy/test_probs_legacy.py b/tests/measurements/legacy/test_probs_legacy.py index 40e4e0a05bd..2fe3243bab8 100644 --- a/tests/measurements/legacy/test_probs_legacy.py +++ b/tests/measurements/legacy/test_probs_legacy.py @@ -49,10 +49,6 @@ def custom_measurement_process(device, spy): assert qml.math.allequal(old_res, new_res) -# make the test deterministic -np.random.seed(42) - - @pytest.fixture(name="init_state") def fixture_init_state(): """Fixture that creates an initial state""" @@ -181,7 +177,6 @@ def test_observable_is_measurement_value( ): # pylint: disable=too-many-arguments """Test that probs for mid-circuit measurement values are correct for a single measurement value.""" - np.random.seed(42) dev = qml.device(device_name, wires=2, shots=shots) @qml.qnode(dev) @@ -215,7 +210,6 @@ def test_observable_is_measurement_value_list( ): # pylint: disable=too-many-arguments """Test that probs for mid-circuit measurement values are correct for a list of measurement value.""" - np.random.seed(42) dev = qml.device(device_name, wires=6, shots=shots) @qml.qnode(dev) diff --git a/tests/measurements/legacy/test_var_legacy.py b/tests/measurements/legacy/test_var_legacy.py index 69c36115732..4472d01dc22 100644 --- a/tests/measurements/legacy/test_var_legacy.py +++ b/tests/measurements/legacy/test_var_legacy.py @@ -100,7 +100,6 @@ def test_observable_is_measurement_value( ): # pylint: disable=too-many-arguments """Test that variances for mid-circuit measurement values are correct for a single measurement value.""" - np.random.seed(42) dev = qml.device(device_name, wires=2, shots=shots) @qml.qnode(dev) @@ -129,7 +128,6 @@ def test_observable_is_composite_measurement_value( ): # pylint: disable=too-many-arguments """Test that variances for mid-circuit measurement values are correct for a composite measurement value.""" - np.random.seed(42) dev = qml.device(device_name, wires=6, shots=shots) @qml.qnode(dev) diff --git a/tests/measurements/test_classical_shadow.py b/tests/measurements/test_classical_shadow.py index d20d41bd7a3..04d9f8e80af 100644 --- a/tests/measurements/test_classical_shadow.py +++ b/tests/measurements/test_classical_shadow.py @@ -318,7 +318,6 @@ def test_return_distribution(self, wires, interface, circuit_fn, basis_recipe): """Test that the distribution of the bits and recipes are correct for a circuit that prepares all qubits in a Pauli basis""" # high number of shots to prevent true negatives - np.random.seed(42) shots = 1000 circuit = circuit_fn(wires, shots=shots, interface=interface) diff --git a/tests/measurements/test_counts.py b/tests/measurements/test_counts.py index 7ac4fddc95f..efc8a552765 100644 --- a/tests/measurements/test_counts.py +++ b/tests/measurements/test_counts.py @@ -94,7 +94,8 @@ class TestProcessSamples: def test_counts_shape_single_wires(self): """Test that the counts output is correct for single wires""" shots = 1000 - samples = np.random.choice([0, 1], size=(shots, 2)).astype(np.int64) + rng = np.random.default_rng(123) + samples = rng.choice([0, 1], size=(shots, 2)).astype(np.int64) result = qml.counts(wires=0).process_samples(samples, wire_order=[0]) @@ -107,7 +108,8 @@ def test_counts_shape_multi_wires(self): """Test that the counts function outputs counts of the right size for multiple wires""" shots = 1000 - samples = np.random.choice([0, 1], size=(shots, 2)).astype(np.int64) + rng = np.random.default_rng(123) + samples = rng.choice([0, 1], size=(shots, 2)).astype(np.int64) result = qml.counts(wires=[0, 1]).process_samples(samples, wire_order=[0, 1]) @@ -130,7 +132,8 @@ def test_counts_with_nan_samples(self): """Test that the counts function disregards failed measurements (samples including NaN values) when totalling counts""" shots = 1000 - samples = np.random.choice([0, 1], size=(shots, 2)).astype(np.float64) + rng = np.random.default_rng(123) + samples = rng.choice([0, 1], size=(shots, 2)).astype(np.float64) samples[0][0] = np.NaN samples[17][1] = np.NaN @@ -173,7 +176,8 @@ def test_counts_multi_wires_no_overflow(self, n_wires, all_outcomes, batch_size) def test_counts_obs(self): """Test that the counts function outputs counts of the right size for observables""" shots = 1000 - samples = np.random.choice([0, 1], size=(shots, 2)).astype(np.int64) + rng = np.random.default_rng(123) + samples = rng.choice([0, 1], size=(shots, 2)).astype(np.int64) result = qml.counts(qml.PauliZ(0)).process_samples(samples, wire_order=[0]) @@ -186,7 +190,8 @@ def test_count_eigvals(self): """Tests that eigvals are used instead of obs for counts""" shots = 100 - samples = np.random.choice([0, 1], size=(shots, 2)).astype(np.int64) + rng = np.random.default_rng(123) + samples = rng.choice([0, 1], size=(shots, 2)).astype(np.int64) result = CountsMP(eigvals=[1, -1], wires=0).process_samples(samples, wire_order=[0]) assert len(result) == 2 assert set(result.keys()) == {1, -1} @@ -197,7 +202,8 @@ def test_counts_shape_single_measurement_value(self): """Test that the counts output is correct for single mid-circuit measurement values.""" shots = 1000 - samples = np.random.choice([0, 1], size=(shots, 2)).astype(np.int64) + rng = np.random.default_rng(123) + samples = rng.choice([0, 1], size=(shots, 2)).astype(np.int64) mv = qml.measure(0) result = qml.counts(mv).process_samples(samples, wire_order=[0]) @@ -211,7 +217,8 @@ def test_counts_shape_composite_measurement_value(self): """Test that the counts output is correct for composite mid-circuit measurement values.""" shots = 1000 - samples = np.random.choice([0, 1], size=(shots, 2)).astype(np.int64) + rng = np.random.default_rng(123) + samples = rng.choice([0, 1], size=(shots, 2)).astype(np.int64) m0 = qml.measure(0) m1 = qml.measure(1) @@ -227,7 +234,8 @@ def test_counts_shape_measurement_value_list(self): """Test that the counts output is correct for list mid-circuit measurement values.""" shots = 1000 - samples = np.random.choice([0, 1], size=(shots, 2)).astype(np.int64) + rng = np.random.default_rng(123) + samples = rng.choice([0, 1], size=(shots, 2)).astype(np.int64) m0 = qml.measure(0) m1 = qml.measure(1) diff --git a/tests/measurements/test_expval.py b/tests/measurements/test_expval.py index 42df19caf4f..14dcbb4ba83 100644 --- a/tests/measurements/test_expval.py +++ b/tests/measurements/test_expval.py @@ -113,8 +113,7 @@ def test_observable_is_composite_measurement_value( ): # pylint: disable=too-many-arguments """Test that expectation values for mid-circuit measurement values are correct for a composite measurement value.""" - np.random.seed(0) - dev = qml.device("default.qubit") + dev = qml.device("default.qubit", seed=123) @qml.qnode(dev) def circuit(phi): @@ -149,7 +148,8 @@ def test_eigvals_instead_of_observable(self): """Tests process samples with eigvals instead of observables""" shots = 100 - samples = np.random.choice([0, 1], size=(shots, 2)).astype(np.int64) + rng = np.random.default_rng(123) + samples = rng.choice([0, 1], size=(shots, 2)).astype(np.int64) expected = qml.expval(qml.PauliZ(0)).process_samples(samples, [0, 1]) assert ( ExpectationMP(eigvals=[1, -1], wires=[0]).process_samples(samples, [0, 1]) == expected @@ -203,8 +203,7 @@ def test_shape_shot_vector(self, obs): def test_projector_expval(self, state, shots): """Tests that the expectation of a ``Projector`` object is computed correctly for both of its subclasses.""" - dev = qml.device("default.qubit", wires=3, shots=shots) - np.random.seed(42) + dev = qml.device("default.qubit", wires=3, shots=shots, seed=123) @qml.qnode(dev) def circuit(): diff --git a/tests/measurements/test_probs.py b/tests/measurements/test_probs.py index ea6b6784a9e..18a44eeb4a4 100644 --- a/tests/measurements/test_probs.py +++ b/tests/measurements/test_probs.py @@ -22,9 +22,6 @@ from pennylane.measurements import MeasurementProcess, Probability, ProbabilityMP, Shots from pennylane.queuing import AnnotatedQueue -# make the test deterministic -np.random.seed(42) - @pytest.fixture(name="init_state") def fixture_init_state(): @@ -32,7 +29,8 @@ def fixture_init_state(): def _init_state(n): """An initial state over n wires""" - state = np.random.random([2**n]) + np.random.random([2**n]) * 1j + rng = np.random.default_rng(42) + state = rng.random([2**n]) + rng.random([2**n]) * 1j state /= np.linalg.norm(state) return state diff --git a/tests/measurements/test_var.py b/tests/measurements/test_var.py index 1882b50c63f..8d0619a213f 100644 --- a/tests/measurements/test_var.py +++ b/tests/measurements/test_var.py @@ -126,7 +126,8 @@ def test_eigvals_instead_of_observable(self): """Tests process samples with eigvals instead of observables""" shots = 100 - samples = np.random.choice([0, 1], size=(shots, 2)).astype(np.int64) + rng = np.random.default_rng(123) + samples = rng.choice([0, 1], size=(shots, 2)).astype(np.int64) expected = qml.var(qml.PauliZ(0)).process_samples(samples, [0, 1]) assert VarianceMP(eigvals=[1, -1], wires=[0]).process_samples(samples, [0, 1]) == expected diff --git a/tests/ops/op_math/test_controlled_decompositions.py b/tests/ops/op_math/test_controlled_decompositions.py index e4aa1f2a293..810d2a9c233 100644 --- a/tests/ops/op_math/test_controlled_decompositions.py +++ b/tests/ops/op_math/test_controlled_decompositions.py @@ -148,10 +148,10 @@ def test_decomposition_circuit_gradient(self, control_wires, tol): """Tests that the controlled decomposition of a single-qubit operation behaves as expected in a quantum circuit""" n_qubits = 4 - np.random.seed(1337) + rng = np.random.default_rng(1337) dev = qml.device("default.qubit", wires=n_qubits) - init_state = np.random.rand(2**n_qubits) + 1.0j * np.random.rand(2**n_qubits) + init_state = rng.random(2**n_qubits) + 1.0j * rng.random(2**n_qubits) init_state /= np.sqrt(np.dot(np.conj(init_state), init_state)) init_state = np.array(init_state) target_wires = [0] diff --git a/tests/ops/qubit/test_matrix_ops.py b/tests/ops/qubit/test_matrix_ops.py index 39d6b4f157e..54e56e1d3c5 100644 --- a/tests/ops/qubit/test_matrix_ops.py +++ b/tests/ops/qubit/test_matrix_ops.py @@ -387,8 +387,8 @@ def test_compare_analytic_results(self, inp, exp): @pytest.mark.parametrize("provide_n", [True, False]) def test_compare_matrix_mult(self, n, provide_n): """Test against matrix multiplication for a few random inputs.""" - np.random.seed(382) - inp = np.random.random(2**n) + rng = np.random.default_rng(382) + inp = rng.random(2**n) output = _walsh_hadamard_transform(inp, n=n if provide_n else None) h = np.array([[0.5, 0.5], [0.5, -0.5]]) h = reduce(np.kron, [h] * n) @@ -406,8 +406,8 @@ def test_compare_analytic_results_broadcasted(self): @pytest.mark.parametrize("provide_n", [True, False]) def test_compare_matrix_mult_broadcasted(self, n, provide_n): """Test against matrix multiplication for a few random inputs.""" - np.random.seed(382) - inp = np.random.random((5, 2**n)) + rng = np.random.default_rng(382) + inp = rng.random((5, 2**n)) output = _walsh_hadamard_transform(inp, n=n if provide_n else None) h = np.array([[0.5, 0.5], [0.5, -0.5]]) h = reduce(np.kron, [h] * n) @@ -531,8 +531,8 @@ def test_decomposition_three_qubits_broadcasted(self): @pytest.mark.parametrize("n", [1, 2, 3]) def test_decomposition_matrix_match(self, n): """Test that the matrix of the decomposition matches the original matrix.""" - np.random.seed(7241) - D = np.exp(1j * np.random.random(2**n)) + rng = np.random.default_rng(382) + D = np.exp(1j * rng.random(2**n)) wires = list(range(n)) decomp = qml.DiagonalQubitUnitary.compute_decomposition(D, wires) decomp2 = qml.DiagonalQubitUnitary(D, wires=wires).decomposition() @@ -546,8 +546,8 @@ def test_decomposition_matrix_match(self, n): @pytest.mark.parametrize("n", [1, 2, 3]) def test_decomposition_matrix_match_broadcasted(self, n): """Test that the broadcasted matrix of the decomposition matches the original matrix.""" - np.random.seed(7241) - D = np.exp(1j * np.random.random((5, 2**n))) + rng = np.random.default_rng(382) + D = np.exp(1j * rng.random((5, 2**n))) wires = list(range(n)) decomp = qml.DiagonalQubitUnitary.compute_decomposition(D, wires) decomp2 = qml.DiagonalQubitUnitary(D, wires=wires).decomposition() diff --git a/tests/ops/qubit/test_special_unitary.py b/tests/ops/qubit/test_special_unitary.py index 83461988297..e7f3d4f9ae7 100644 --- a/tests/ops/qubit/test_special_unitary.py +++ b/tests/ops/qubit/test_special_unitary.py @@ -120,9 +120,9 @@ def test_jax(self, n, use_jit): jax.config.update("jax_enable_x64", True) from jax import numpy as jnp - np.random.seed(14521) + rng = np.random.default_rng(14521) d = 4**n - 1 - theta = jnp.array(np.random.random(d)) + theta = jnp.array(rng.random(d)) fn = ( jax.jit(self.get_one_parameter_generators, static_argnums=[1, 2]) if use_jit @@ -161,7 +161,6 @@ def test_tf(self, n): """Test that generators are computed correctly in Tensorflow.""" import tensorflow as tf - np.random.seed(14521) d = 4**n - 1 theta = tf.Variable(np.random.random(d)) Omegas = self.get_one_parameter_generators(theta, n, "tf") @@ -189,7 +188,6 @@ def test_torch(self, n): """Test that generators are computed correctly in Torch.""" import torch - np.random.seed(14521) d = 4**n - 1 theta = torch.tensor(np.random.random(d), requires_grad=True) Omegas = self.get_one_parameter_generators(theta, n, "torch") @@ -254,7 +252,6 @@ def test_jacobian_jax(self, n, use_jit): jax.config.update("jax_enable_x64", True) from jax import numpy as jnp - np.random.seed(14521) d = 4**n - 1 theta = jnp.array(np.random.random(d), dtype=jnp.complex128) fn = ( @@ -271,7 +268,6 @@ def test_jacobian_tf(self, n): """Test that generators are differentiable in Tensorflow.""" import tensorflow as tf - np.random.seed(14521) d = 4**n - 1 theta = tf.Variable(np.random.random(d)) with tf.GradientTape() as t: @@ -285,7 +281,6 @@ def test_jacobian_torch(self, n): """Test that generators are differentiable in Torch.""" import torch - np.random.seed(14521) d = 4**n - 1 theta = torch.tensor(np.random.random(d), requires_grad=True) @@ -315,7 +310,6 @@ def test_jax(self, n): jax.config.update("jax_enable_x64", True) from jax import numpy as jnp - np.random.seed(14521) d = 4**n - 1 theta = jnp.array(np.random.random(d)) op = qml.SpecialUnitary(theta, list(range(n))) @@ -334,7 +328,6 @@ def test_tf(self, n): """Test that the coefficients of the generators are computed correctly in Tensorflow.""" import tensorflow as tf - np.random.seed(14521) d = 4**n - 1 theta = tf.Variable(np.random.random(d)) op = qml.SpecialUnitary(theta, list(range(n))) @@ -353,7 +346,6 @@ def test_torch(self, n): """Test that the coefficients of the generators are computed correctly in Torch.""" import torch - np.random.seed(14521) d = 4**n - 1 theta = torch.tensor(np.random.random(d), requires_grad=True) op = qml.SpecialUnitary(theta, list(range(n))) @@ -418,9 +410,9 @@ def interface_array(x, interface): def test_compute_matrix_random(self, n, seed, interface): """Test that ``compute_matrix`` returns a correctly-shaped unitary matrix for random input parameters.""" - np.random.seed(seed) + rng = np.random.default_rng(seed) d = 4**n - 1 - theta = np.random.random(d) + theta = rng.random(d) theta = self.interface_array(theta, interface) matrices = [ qml.SpecialUnitary(theta, list(range(n))).matrix(), @@ -438,10 +430,10 @@ def test_compute_matrix_random(self, n, seed, interface): def test_compute_matrix_random_many_wires(self, seed, interface): """Test that ``compute_matrix`` returns a correctly-shaped unitary matrix for random input parameters and more than 5 wires.""" - np.random.seed(seed) + rng = np.random.default_rng(seed) n = 6 d = 4**n - 1 - theta = np.random.random(d) + theta = rng.random(d) theta = self.interface_array(theta, interface) matrices = [ qml.SpecialUnitary(theta, list(range(n))).matrix(), @@ -460,9 +452,9 @@ def test_compute_matrix_random_many_wires(self, seed, interface): def test_compute_matrix_random_broadcasted(self, n, seed, interface): """Test that ``compute_matrix`` returns a correctly-shaped unitary matrix for broadcasted random input parameters.""" - np.random.seed(seed) + rng = np.random.default_rng(seed) d = 4**n - 1 - theta = np.random.random((2, d)) + theta = rng.random((2, d)) separate_matrices = [qml.SpecialUnitary.compute_matrix(t, n) for t in theta] theta = self.interface_array(theta, interface) matrices = [ diff --git a/tests/optimize/test_optimize_shot_adaptive.py b/tests/optimize/test_optimize_shot_adaptive.py index c4c7f58293b..b8643143cbb 100644 --- a/tests/optimize/test_optimize_shot_adaptive.py +++ b/tests/optimize/test_optimize_shot_adaptive.py @@ -649,7 +649,8 @@ def cost(params): ansatz(params) return qml.expval(H) - params = np.random.random((4, 3), requires_grad=True) + rng = np.random.default_rng(123) + params = rng.random((4, 3), requires_grad=True) initial_loss = cost(params) min_shots = 10 @@ -674,7 +675,6 @@ class TestStepAndCost: def test_qnode_cost(self, tol): """Test that the cost is correctly returned when using a QNode as the cost function""" - np.random.seed(0) dev = qml.device("default.qubit", wires=1, shots=10) diff --git a/tests/qinfo/test_fisher.py b/tests/qinfo/test_fisher.py index 0a13125c17b..7db6526cde4 100644 --- a/tests/qinfo/test_fisher.py +++ b/tests/qinfo/test_fisher.py @@ -157,7 +157,8 @@ def test_quantum_fisher_info(self, dev): n_wires = 2 - dev_hard = qml.device("default.qubit", wires=n_wires + 1, shots=1000) + rng = pnp.random.default_rng(200) + dev_hard = qml.device("default.qubit", wires=n_wires + 1, shots=1000, seed=rng) def qfunc(params): qml.RX(params[0], wires=0) @@ -165,7 +166,7 @@ def qfunc(params): qml.CNOT(wires=(0, 1)) return qml.probs(wires=[0, 1]) - params = pnp.random.random(2) + params = rng.random(2, requires_grad=True) circ_hard = qml.QNode(qfunc, dev_hard) QFIM_hard = quantum_fisher(circ_hard)(params) diff --git a/tests/shadow/test_shadow_class.py b/tests/shadow/test_shadow_class.py index ee3b4055ea7..aabec6012a0 100644 --- a/tests/shadow/test_shadow_class.py +++ b/tests/shadow/test_shadow_class.py @@ -22,8 +22,6 @@ import pennylane.numpy as np from pennylane.shadows import ClassicalShadow, median_of_means, pauli_expval -np.random.seed(777) - wires = range(3) shots = 10000 dev = qml.device("default.qubit", wires=wires, shots=shots) diff --git a/tests/shadow/test_shadow_entropies.py b/tests/shadow/test_shadow_entropies.py index b6ac84b4332..009607bdf0b 100644 --- a/tests/shadow/test_shadow_entropies.py +++ b/tests/shadow/test_shadow_entropies.py @@ -22,8 +22,6 @@ from pennylane.shadows import ClassicalShadow from pennylane.shadows.classical_shadow import _project_density_matrix_spectrum -np.random.seed(777) - def max_entangled_circuit(wires, shots=10000, interface="autograd"): """maximally entangled state preparation circuit""" diff --git a/tests/shadow/test_shadow_transforms.py b/tests/shadow/test_shadow_transforms.py index 626721aea9e..0bce7c2876c 100644 --- a/tests/shadow/test_shadow_transforms.py +++ b/tests/shadow/test_shadow_transforms.py @@ -364,7 +364,8 @@ def test_basic_entangler_backward(self): shadow_circuit = qml.shadows.shadow_expval(shadow_circuit, obs) exact_circuit = basic_entangler_circuit_exact_expval(3, "autograd") - x = np.random.uniform(0.8, 2, size=qml.BasicEntanglerLayers.shape(n_layers=1, n_wires=3)) + rng = np.random.default_rng(123) + x = rng.uniform(0.8, 2, size=qml.BasicEntanglerLayers.shape(n_layers=1, n_wires=3)) def shadow_cost(x): res = shadow_circuit(x) diff --git a/tests/templates/test_layers/test_cv_neural_net.py b/tests/templates/test_layers/test_cv_neural_net.py index e3f57f1b071..ddb4c35a2c2 100644 --- a/tests/templates/test_layers/test_cv_neural_net.py +++ b/tests/templates/test_layers/test_cv_neural_net.py @@ -209,7 +209,6 @@ def circuit_decomposed(*weights): def test_adjoint(): """Test that the adjoint method works""" dev = DummyDevice(wires=2) - np.random.seed(42) shapes = qml.CVNeuralNetLayers.shape(n_layers=1, n_wires=2) weights = [np.random.random(shape) for shape in shapes] diff --git a/tests/test_classical_gradients.py b/tests/test_classical_gradients.py index 9184382dd82..07d53f15266 100644 --- a/tests/test_classical_gradients.py +++ b/tests/test_classical_gradients.py @@ -20,8 +20,6 @@ import pennylane as qml from pennylane import numpy as np -np.random.seed(42) - def test_grad_no_ints(): """Test that grad raises a `ValueError` if the trainable parameter is an int.""" diff --git a/tests/test_debugging.py b/tests/test_debugging.py index 4a2d06e62f7..207b97bca04 100644 --- a/tests/test_debugging.py +++ b/tests/test_debugging.py @@ -671,9 +671,8 @@ def circuit(): @pytest.mark.parametrize("method", [None, "parameter-shift"]) def test_default_qutrit(self, method): """Test that multiple snapshots are returned correctly on the pure qutrit simulator.""" - np.random.seed(7) - dev = qml.device("default.qutrit", wires=2, shots=100) + dev = qml.device("default.qutrit", wires=2) assert not qml.debugging.snapshot._is_snapshot_compatible(dev) @@ -682,18 +681,18 @@ def circuit(): qml.THadamard(wires=0) qml.Snapshot(measurement=qml.probs()) qml.TSWAP(wires=[0, 1]) - return qml.counts() + return qml.probs() with pytest.warns(UserWarning, match="Snapshots are not supported for the given device"): circuit = qml.snapshots(circuit) result = circuit() expected = { - 0: np.array([0.27, 0.0, 0.0, 0.38, 0.0, 0.0, 0.35, 0.0, 0.0]), - "execution_results": {"00": 39, "01": 31, "02": 30}, + 0: np.array([1 / 3, 0.0, 0.0, 1 / 3, 0.0, 0.0, 1 / 3, 0.0, 0.0]), + "execution_results": np.array([1 / 3, 1 / 3, 1 / 3, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]), } - assert result["execution_results"] == expected["execution_results"] + assert np.allclose(result["execution_results"], expected["execution_results"]) del result["execution_results"] del expected["execution_results"] @@ -701,8 +700,13 @@ def circuit(): _compare_numpy_dicts(result, expected) # Make sure shots are overriden correctly - result = circuit(shots=50) - assert np.allclose(result[0], np.array([0.3, 0.0, 0.0, 0.32, 0.0, 0.0, 0.38, 0.0, 0.0])) + result = circuit(shots=200) + assert np.allclose( + result[0], + np.array([1 / 3, 0.0, 0.0, 1 / 3, 0.0, 0.0, 1 / 3, 0.0, 0.0]), + atol=0.1, + rtol=0, + ) # pylint: disable=protected-access diff --git a/tests/test_hermitian_edge_cases.py b/tests/test_hermitian_edge_cases.py index a71a89b6b4f..41224a00b7c 100644 --- a/tests/test_hermitian_edge_cases.py +++ b/tests/test_hermitian_edge_cases.py @@ -21,9 +21,6 @@ import pennylane as qml -np.random.seed(0) - - THETA = np.linspace(0.11, 1, 3) PHI = np.linspace(0.32, 1, 3) diff --git a/tests/test_tensor_measurements.py b/tests/test_tensor_measurements.py index 7880dd5ef67..543eba1618b 100644 --- a/tests/test_tensor_measurements.py +++ b/tests/test_tensor_measurements.py @@ -22,8 +22,6 @@ import pennylane as qml from pennylane import expval, sample, var -np.random.seed(0) - Z = np.array([[1, 0], [0, -1]]) THETA = np.linspace(0.11, 3, 5) PHI = np.linspace(0.32, 3, 5) diff --git a/tests/test_vqe.py b/tests/test_vqe.py index 9c8d63ce1b9..e8edc6c84cf 100644 --- a/tests/test_vqe.py +++ b/tests/test_vqe.py @@ -23,12 +23,6 @@ from pennylane import numpy as pnp -@pytest.fixture(scope="function") -def seed(): - """Resets the random seed with every test""" - np.random.seed(0) - - def generate_cost_fn(ansatz, hamiltonian, device, **kwargs): """Generates a QNode and computes the expectation value of a cost Hamiltonian with respect to the parameters provided to an ansatz""" @@ -123,16 +117,16 @@ def res(params): np.array( [ [ - [6.52084595e-18, -2.11464420e-02, -1.16576858e-02], - [-8.22589330e-18, -5.20597922e-02, -1.85365365e-02], - [-2.73850768e-17, 1.14202988e-01, -5.45041403e-03], - [-1.27514307e-17, -1.10465531e-01, 5.19489457e-02], + [3.46944695e-17, 2.19990188e-01, -2.30793349e-02], + [3.28242208e-17, -2.40632771e-02, -3.24974295e-04], + [3.81639165e-17, 5.36985274e-02, 5.09078210e-02], + [4.16333634e-17, -1.65286612e-01, 1.00566407e-01], ], [ - [-2.45428288e-02, 8.38921555e-02, -2.00641818e-17], - [-2.21085973e-02, 7.39332741e-04, -1.25580654e-17], - [9.62058625e-03, -1.51398765e-01, 2.02129847e-03], - [1.10020832e-03, -3.49066271e-01, 2.13669117e-03], + [-1.30075605e-02, 7.64413731e-02, -1.73472348e-17], + [-3.93930424e-02, -1.41264311e-02, -3.03576608e-18], + [1.27502468e-02, 2.53562554e-02, -1.93489132e-02], + [-3.78744735e-02, 1.04547989e-02, 1.86649332e-02], ], ] ), @@ -342,9 +336,9 @@ def test_optimize_torch(self, dev_name, shots): diff_method="parameter-shift", ) - np.random.seed(1967) shape = qml.templates.StronglyEntanglingLayers.shape(n_layers=2, n_wires=4) - w = np.random.random(shape) + _rng = np.random.default_rng(1234) + w = _rng.random(shape) with qml.Tracker(dev) as tracker: c1 = cost(w) @@ -394,9 +388,9 @@ def test_optimize_tf(self, shots, dev_name): diff_method="parameter-shift", ) - np.random.seed(1967) shape = qml.templates.StronglyEntanglingLayers.shape(n_layers=2, n_wires=4) - w = np.random.random(shape) + _rng = np.random.default_rng(1234) + w = _rng.random(shape) with qml.Tracker(dev) as tracker: c1 = cost(w) @@ -444,9 +438,9 @@ def test_optimize_autograd(self, shots, dev_name): diff_method="parameter-shift", ) - np.random.seed(1967) shape = qml.templates.StronglyEntanglingLayers.shape(n_layers=2, n_wires=4) - w = np.random.random(shape) + _rng = np.random.default_rng(1234) + w = _rng.random(shape) with qml.Tracker(dev) as tracker: c1 = cost(w) @@ -500,9 +494,9 @@ def test_optimize_multiple_terms_autograd(self): diff_method="parameter-shift", ) - np.random.seed(1967) shape = qml.templates.StronglyEntanglingLayers.shape(n_layers=2, n_wires=5) - w = np.random.random(shape) + _rng = np.random.default_rng(1234) + w = _rng.random(shape) with qml.Tracker(dev) as tracker: c1 = cost(w) @@ -556,9 +550,9 @@ def test_optimize_multiple_terms_torch(self): diff_method="parameter-shift", ) - np.random.seed(1967) shape = qml.templates.StronglyEntanglingLayers.shape(n_layers=2, n_wires=5) - w = np.random.random(shape) + _rng = np.random.default_rng(1234) + w = _rng.random(shape) with qml.Tracker(dev) as tracker: c1 = cost(w) @@ -612,9 +606,9 @@ def test_optimize_multiple_terms_tf(self): diff_method="parameter-shift", ) - np.random.seed(1967) shape = qml.templates.StronglyEntanglingLayers.shape(n_layers=2, n_wires=5) - w = np.random.random(shape) + _rng = np.random.default_rng(1234) + w = _rng.random(shape) with qml.Tracker(dev) as tracker: c1 = cost(w) @@ -654,9 +648,9 @@ def test_optimize_grad(self): diff_method="parameter-shift", ) - np.random.seed(1967) shape = qml.templates.StronglyEntanglingLayers.shape(n_layers=2, n_wires=4) - w = pnp.random.uniform(low=0, high=2 * np.pi, size=shape, requires_grad=True) + _rng = pnp.random.default_rng(1967) + w = _rng.uniform(low=0, high=2 * np.pi, size=shape, requires_grad=True) with qml.Tracker(dev) as tracker: dc = qml.grad(cost)(w) @@ -688,7 +682,6 @@ def test_grad_zero_hamiltonian(self, opt): diff_method="parameter-shift", ) - np.random.seed(1967) shape = qml.templates.StronglyEntanglingLayers.shape(n_layers=2, n_wires=4) w = pnp.random.random(shape, requires_grad=True) @@ -714,9 +707,9 @@ def test_optimize_grad_torch(self): interface="torch", ) - np.random.seed(1967) shape = qml.templates.StronglyEntanglingLayers.shape(n_layers=2, n_wires=4) - w = np.random.uniform(low=0, high=2 * np.pi, size=shape) + _rng = np.random.default_rng(1967) + w = _rng.uniform(low=0, high=2 * np.pi, size=shape) w = torch.tensor(w, requires_grad=True) res = cost(w) @@ -741,9 +734,9 @@ def test_optimize_grad_tf(self): qml.templates.StronglyEntanglingLayers, hamiltonian, dev, interface="tf" ) - np.random.seed(1967) shape = qml.templates.StronglyEntanglingLayers.shape(n_layers=2, n_wires=4) - w = np.random.uniform(low=0, high=2 * np.pi, size=shape) + _rng = np.random.default_rng(1967) + w = _rng.uniform(low=0, high=2 * np.pi, size=shape) w = tf.Variable(w) with tf.GradientTape() as tape: @@ -755,9 +748,9 @@ def test_optimize_grad_tf(self): # Test data -np.random.seed(1967) +rng = np.random.default_rng(1967) _shape = qml.templates.StronglyEntanglingLayers.shape(2, 4) -PARAMS = np.random.uniform(low=0, high=2 * np.pi, size=_shape) +PARAMS = rng.uniform(low=0, high=2 * np.pi, size=_shape) class TestNewVQE: @@ -802,7 +795,7 @@ def test_acting_on_subcircuit(self, tol): """Tests a VQE circuit where the observable does not act on all wires.""" dev = qml.device("default.qubit", wires=3) coeffs = [1.0, 1.0, 1.0] - np.random.seed(1967) + w = np.random.random(qml.templates.StronglyEntanglingLayers.shape(n_layers=1, n_wires=2)) observables1 = [qml.PauliZ(0), qml.PauliY(0), qml.PauliZ(1)] @@ -1038,7 +1031,7 @@ def test_grad_jax(self, tol): dev = qml.device("default.qubit", wires=4) H = big_hamiltonian - np.random.seed(1967) + w = jnp.array(PARAMS) @qml.qnode(dev) @@ -1219,7 +1212,6 @@ def test_all_interfaces_gradient_agree(self, tol): H = qml.Hamiltonian(coeffs, observables) - np.random.seed(1) shape = qml.templates.StronglyEntanglingLayers.shape(3, 2) params = np.random.uniform(low=0, high=2 * np.pi, size=shape) diff --git a/tests/transforms/test_batch_input.py b/tests/transforms/test_batch_input.py index c642cf15ac9..3d97e981ed2 100644 --- a/tests/transforms/test_batch_input.py +++ b/tests/transforms/test_batch_input.py @@ -128,7 +128,6 @@ def circuit(input1, input2, weights): qml.RY(weights[1], wires=1) return qml.expval(qml.PauliZ(1)) - np.random.seed(42) batch_size = 5 input1 = np.random.uniform(0, np.pi, (batch_size, 2), requires_grad=False) input2 = np.random.uniform(0, np.pi, (4, 1), requires_grad=False) diff --git a/tests/transforms/test_defer_measurements.py b/tests/transforms/test_defer_measurements.py index d93d542b2c4..3d5e98791ea 100644 --- a/tests/transforms/test_defer_measurements.py +++ b/tests/transforms/test_defer_measurements.py @@ -371,8 +371,7 @@ def circ1(phi): def test_some_postselection_qnode(self, phi, shots, reduce_postselected, tol, tol_stochastic): """Test that a qnode with some mid-circuit measurements with postselection is transformed correctly by defer_measurements""" - np.random.seed(822) - dev = DefaultQubit() + dev = DefaultQubit(seed=822) dm_transform = qml.defer_measurements if reduce_postselected is not None: @@ -421,8 +420,6 @@ def test_all_postselection_qnode( is transformed correctly by defer_measurements""" dev = DefaultQubit() - np.random.seed(None) - # Initializing mid circuit measurements here so that id can be controlled (affects # wire ordering for qml.cond) mp0 = MidMeasureMP(wires=0, postselect=0, id=0) diff --git a/tests/transforms/test_mitigate.py b/tests/transforms/test_mitigate.py index 0e41c2c29ee..7cf6dd17915 100644 --- a/tests/transforms/test_mitigate.py +++ b/tests/transforms/test_mitigate.py @@ -120,7 +120,6 @@ def test_multi_returns(self): n_layers = 2 shapes = qml.SimplifiedTwoDesign.shape(n_layers, n_wires) - np.random.seed(0) w1, w2 = [np.random.random(s) for s in shapes] @partial( @@ -242,7 +241,6 @@ def test_multiple_returns(self): n_layers = 2 shapes = qml.SimplifiedTwoDesign.shape(n_layers, n_wires) - np.random.seed(0) w1, w2 = [np.random.random(s) for s in shapes] @partial( @@ -292,7 +290,6 @@ def test_single_return(self): n_layers = 2 shapes = qml.SimplifiedTwoDesign.shape(n_layers, n_wires) - np.random.seed(0) w1, w2 = [np.random.random(s) for s in shapes] @partial( @@ -332,7 +329,6 @@ def test_with_reps_per_factor(self): n_layers = 2 shapes = qml.SimplifiedTwoDesign.shape(n_layers, n_wires) - np.random.seed(0) w1, w2 = [np.random.random(s) for s in shapes] @partial( @@ -372,7 +368,6 @@ def test_integration(self): n_layers = 2 shapes = qml.SimplifiedTwoDesign.shape(n_layers, n_wires) - np.random.seed(0) w1, w2 = [np.random.random(s) for s in shapes] def circuit(w1, w2): @@ -430,7 +425,6 @@ def test_grad(self): n_layers = 2 shapes = qml.SimplifiedTwoDesign.shape(n_layers, n_wires) - np.random.seed(0) w1, w2 = [np.random.random(s, requires_grad=True) for s in shapes] @partial(