Skip to content

Commit

Permalink
Remove global seeds from tests (PennyLaneAI#5990)
Browse files Browse the repository at this point in the history
**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:**
  • Loading branch information
mudit2812 committed Jul 12, 2024
1 parent f1b5e31 commit bca15cc
Show file tree
Hide file tree
Showing 50 changed files with 97 additions and 199 deletions.
1 change: 0 additions & 1 deletion pennylane/devices/tests/test_gates.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,6 @@

pytestmark = pytest.mark.skip_unsupported

np.random.seed(42)

# ==========================================================
# Some useful global variables
Expand Down
2 changes: 0 additions & 2 deletions pennylane/devices/tests/test_gates_with_expval.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,8 +28,6 @@

pytestmark = pytest.mark.skip_unsupported

np.random.seed(42)


# ===============================================================

Expand Down
3 changes: 0 additions & 3 deletions tests/devices/default_qubit/test_default_qubit.py
Original file line number Diff line number Diff line change
Expand Up @@ -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),
Expand Down
2 changes: 1 addition & 1 deletion tests/devices/default_tensor/test_default_tensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -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))
Expand Down
2 changes: 0 additions & 2 deletions tests/devices/default_tensor/test_scalability.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand All @@ -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)

Expand Down
12 changes: 0 additions & 12 deletions tests/devices/qubit/test_apply_operation.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)))
Expand All @@ -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,)
Expand All @@ -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)
Expand All @@ -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))
Expand Down Expand Up @@ -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))
Expand Down Expand Up @@ -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))
Expand Down Expand Up @@ -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))
Expand Down Expand Up @@ -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")]
Expand All @@ -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)
Expand All @@ -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)
Expand All @@ -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)
Expand All @@ -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)
Expand Down
3 changes: 2 additions & 1 deletion tests/devices/qubit/test_sampling.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand Down
4 changes: 2 additions & 2 deletions tests/devices/test_default_mixed.py
Original file line number Diff line number Diff line change
Expand Up @@ -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))
Expand Down Expand Up @@ -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)
Expand Down
5 changes: 0 additions & 5 deletions tests/devices/test_default_qubit_tf.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,9 +56,6 @@
DefaultQubitTF,
)

np.random.seed(42)


#####################################################
# Test matrices
#####################################################
Expand Down Expand Up @@ -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
Expand All @@ -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]

Expand Down
2 changes: 0 additions & 2 deletions tests/devices/test_default_qubit_torch.py
Original file line number Diff line number Diff line change
Expand Up @@ -75,8 +75,6 @@
torch_devices.append("cuda")


np.random.seed(42)

#####################################################
# Test matrices
#####################################################
Expand Down
2 changes: 0 additions & 2 deletions tests/devices/test_default_qutrit_mixed.py
Original file line number Diff line number Diff line change
Expand Up @@ -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."""
Expand Down
1 change: 0 additions & 1 deletion tests/devices/test_lightning_qubit.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
)
Expand Down
2 changes: 0 additions & 2 deletions tests/devices/test_null_qubit.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,8 +27,6 @@
StateMeasurement,
)

np.random.seed(0)


def test_name():
"""Tests the name of NullQubit."""
Expand Down
3 changes: 0 additions & 3 deletions tests/gradients/core/test_gradient_transform.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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)
Expand Down
12 changes: 0 additions & 12 deletions tests/gradients/core/test_pulse_gradient.py
Original file line number Diff line number Diff line change
Expand Up @@ -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))
Expand Down Expand Up @@ -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))
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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

Expand Down Expand Up @@ -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

Expand Down
2 changes: 0 additions & 2 deletions tests/gradients/finite_diff/test_spsa_gradient_shot_vec.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand Down Expand Up @@ -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)

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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)
Expand Down
2 changes: 0 additions & 2 deletions tests/interfaces/test_autograd_qnode_shot_vector.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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)
Expand Down
Loading

0 comments on commit bca15cc

Please sign in to comment.