Repository: PennyLaneAI/pennylane
Pull request #4920 (2023-12-05 22:45:30)

Clarify the distinction between pennylane and vanilla numpy
**Context:**
We are working toward distinguishing between pennylane-numpy (autograd) and vanilla numpy within the codebase. A first step would be to always import the one we actually intend on importing.

**Description of the Change:**
1. Replace all instances of `from pennylane import numpy as np` with `import numpy as np`
2. Find the files broken by step 1, and undo those changes, but importing it as `pnp` to clarify that it's on purpose

I also `import pennylane.numpy` at the top of `__init__.py` because if I don't, a circular dependency happens (it needs to be imported before the `kernels` module is imported now that it no longer imports pennylane-numpy, because it still imports something else that imports it).

**Benefits:**
- We are closer to making some autograd-only parts of the code compatible with all interfaces
- We don't use autograd when it isn't necessary

**Possible Drawbacks:**
I might have accidentally removed trainability from something that needs it? I don't think I have because tests are passing, but maybe that's just an issue in our test coverage. The optimizers were my main concern, but surely those tests check for trainability and correctness already.

**Note for QChem reviewers**
I changed every file in qchem/ to use vanilla numpy, and tests failed. By doing some binary-search undoing, I found that we need pennylane-numpy in `molecule.py` and that's it. I guess it creates the variables, and trainability is preserved everywhere else. Maybe this is a gap in testing, but it looks good now. If someone more familiar with that part of the code could confirm it, that would be much appreciated

github-actions[bot]: Hello. You may have forgotten to update the changelog!
Please edit [`doc/releases/changelog-dev.md`](/PennyLaneAI/pennylane/blob/master/doc/releases/changelog-dev.md) with:
* A one-to-two sentence description of the change. You may include a small working example for new features.
* A link back to this PR.
* Your name (or GitHub username) in the contributors section.
codecov[bot]: ## [Codecov](https://app.codecov.io/gh/PennyLaneAI/pennylane/pull/4920?src=pr&el=h1&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=PennyLaneAI) Report
Attention: `1 lines` in your changes are missing coverage. Please review.
> Comparison is base [(`73d2b28`)](https://app.codecov.io/gh/PennyLaneAI/pennylane/commit/73d2b2831d2e47a9ba4e5c962d754fbddc06da61?el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=PennyLaneAI) 99.66% compared to head [(`53a4873`)](https://app.codecov.io/gh/PennyLaneAI/pennylane/pull/4920?src=pr&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=PennyLaneAI) 99.66%.
> Report is 2 commits behind head on master.

| [Files](https://app.codecov.io/gh/PennyLaneAI/pennylane/pull/4920?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=PennyLaneAI) | Patch % | Lines |
|---|---|---|
| [pennylane/devices/default\_qubit\_autograd.py](https://app.codecov.io/gh/PennyLaneAI/pennylane/pull/4920?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=PennyLaneAI#diff-cGVubnlsYW5lL2RldmljZXMvZGVmYXVsdF9xdWJpdF9hdXRvZ3JhZC5weQ==) | 95.45% | [1 Missing :warning: ](https://app.codecov.io/gh/PennyLaneAI/pennylane/pull/4920?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=PennyLaneAI) |

<details><summary>Additional details and impacted files</summary>


```diff
@@           Coverage Diff           @@
##           master    #4920   +/-   ##
=======================================
  Coverage   99.66%   99.66%           
=======================================
  Files         387      387           
  Lines       35029    35044   +15     
=======================================
+ Hits        34910    34927   +17     
+ Misses        119      117    -2     
```



</details>

[:umbrella: View full report in Codecov by Sentry](https://app.codecov.io/gh/PennyLaneAI/pennylane/pull/4920?src=pr&el=continue&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=PennyLaneAI).   
:loudspeaker: Have feedback on the report? [Share it here](https://about.codecov.io/codecov-pr-comment-feedback/?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=PennyLaneAI).

albi3ro: [sc-43685]

Patch:
diff --git a/pennylane/__init__.py b/pennylane/__init__.py
index a59c70ce2..6f29d5394 100644
--- a/pennylane/__init__.py
+++ b/pennylane/__init__.py
@@ -23,6 +23,7 @@ import numpy as _np
 from semantic_version import SimpleSpec, Version
 
 from pennylane.boolean_fn import BooleanFn
+import pennylane.numpy
 from pennylane.queuing import QueuingManager, apply
 
 import pennylane.kernels
diff --git a/pennylane/devices/default_mixed.py b/pennylane/devices/default_mixed.py
index a9486e985..64b2a960e 100644
--- a/pennylane/devices/default_mixed.py
+++ b/pennylane/devices/default_mixed.py
@@ -23,6 +23,7 @@ import functools
 import itertools
 from collections import defaultdict
 from string import ascii_letters as ABC
+import numpy as np
 
 import pennylane as qml
 import pennylane.math as qnp
@@ -34,7 +35,6 @@ from pennylane import (
     StatePrep,
     Snapshot,
 )
-from pennylane import numpy as np
 from pennylane.measurements import CountsMP, MutualInfoMP, SampleMP, StateMP, VnEntropyMP, PurityMP
 from pennylane.operation import Channel
 from pennylane.ops.qubit.attributes import diagonal_in_z_basis
diff --git a/pennylane/devices/default_qubit_autograd.py b/pennylane/devices/default_qubit_autograd.py
index dcf57f0b8..f65e4a6c3 100644
--- a/pennylane/devices/default_qubit_autograd.py
+++ b/pennylane/devices/default_qubit_autograd.py
@@ -14,7 +14,7 @@
 """This module contains an autograd implementation of the :class:`~.DefaultQubitLegacy`
 reference plugin.
 """
-from pennylane import numpy as np
+from pennylane import numpy as pnp
 
 from pennylane.devices import DefaultQubitLegacy
 
@@ -79,39 +79,34 @@ class DefaultQubitAutograd(DefaultQubitLegacy):
     name = "Default qubit (Autograd) PennyLane plugin"
     short_name = "default.qubit.autograd"
 
-    _dot = staticmethod(np.dot)
-    _abs = staticmethod(np.abs)
-    _reduce_sum = staticmethod(lambda array, axes: np.sum(array, axis=tuple(axes)))
-    _reshape = staticmethod(np.reshape)
+    _dot = staticmethod(pnp.dot)
+    _abs = staticmethod(pnp.abs)
+    _reduce_sum = staticmethod(lambda array, axes: pnp.sum(array, axis=tuple(axes)))
+    _reshape = staticmethod(pnp.reshape)
     _flatten = staticmethod(lambda array: array.flatten())
-    _einsum = staticmethod(np.einsum)
-    _cast = staticmethod(np.asarray)
-    _transpose = staticmethod(np.transpose)
-    _tensordot = staticmethod(np.tensordot)
-    _conj = staticmethod(np.conj)
-    _real = staticmethod(np.real)
-    _imag = staticmethod(np.imag)
-    _roll = staticmethod(np.roll)
-    _stack = staticmethod(np.stack)
-    _size = staticmethod(np.size)
-    _ndim = staticmethod(np.ndim)
+    _einsum = staticmethod(pnp.einsum)
+    _cast = staticmethod(pnp.asarray)
+    _transpose = staticmethod(pnp.transpose)
+    _tensordot = staticmethod(pnp.tensordot)
+    _conj = staticmethod(pnp.conj)
+    _real = staticmethod(pnp.real)
+    _imag = staticmethod(pnp.imag)
+    _roll = staticmethod(pnp.roll)
+    _stack = staticmethod(pnp.stack)
+    _size = staticmethod(pnp.size)
+    _ndim = staticmethod(pnp.ndim)
 
     @staticmethod
     def _asarray(array, dtype=None):
-        res = np.asarray(array, dtype=dtype)
-
-        if res.dtype is np.dtype("O"):
-            return np.hstack(array).flatten().astype(dtype)
-
-        return res
+        return pnp.asarray(array, dtype=dtype)
 
     @staticmethod
     def _const_mul(constant, array):
         return constant * array
 
     def __init__(self, wires, *, shots=None, analytic=None):
-        r_dtype = np.float64
-        c_dtype = np.complex128
+        r_dtype = pnp.float64
+        c_dtype = pnp.complex128
         super().__init__(wires, shots=shots, r_dtype=r_dtype, c_dtype=c_dtype, analytic=analytic)
 
         # prevent using special apply methods for these gates due to slowdown in Autograd
@@ -128,6 +123,6 @@ class DefaultQubitAutograd(DefaultQubitLegacy):
 
     @staticmethod
     def _scatter(indices, array, new_dimensions):
-        new_array = np.zeros(new_dimensions, dtype=array.dtype.type)
+        new_array = pnp.zeros(new_dimensions, dtype=array.dtype.type)
         new_array[indices] = array
         return new_array
diff --git a/pennylane/devices/null_qubit.py b/pennylane/devices/null_qubit.py
index 28032a421..fcda59767 100644
--- a/pennylane/devices/null_qubit.py
+++ b/pennylane/devices/null_qubit.py
@@ -15,11 +15,11 @@ r"""
 The null.qubit device is a no-op device for benchmarking PennyLane's auxiliary functionality outside direct circuit evaluations.
 """
 from collections import defaultdict
+import numpy as np
 
 from pennylane.ops.qubit.attributes import diagonal_in_z_basis
 
 from pennylane import QubitDevice
-from pennylane import numpy as np
 from pennylane.measurements import Shots
 from pennylane.resource import Resources
 from .._version import __version__
diff --git a/pennylane/gradients/adjoint_metric_tensor.py b/pennylane/gradients/adjoint_metric_tensor.py
index 78d4d0228..847ab41cf 100644
--- a/pennylane/gradients/adjoint_metric_tensor.py
+++ b/pennylane/gradients/adjoint_metric_tensor.py
@@ -18,8 +18,8 @@ from typing import Sequence, Callable
 from itertools import chain
 from functools import partial
 
+import numpy as np
 import pennylane as qml
-from pennylane import numpy as np
 
 # pylint: disable=too-many-statements,unused-argument
 from pennylane.gradients.metric_tensor import _contract_metric_tensor_with_cjac
diff --git a/pennylane/gradients/classical_jacobian.py b/pennylane/gradients/classical_jacobian.py
index 626eb1fcb..a2ce9fe52 100644
--- a/pennylane/gradients/classical_jacobian.py
+++ b/pennylane/gradients/classical_jacobian.py
@@ -15,8 +15,8 @@
 Contains the classical Jacobian transform.
 """
 # pylint: disable=import-outside-toplevel
+import numpy as np
 import pennylane as qml
-from pennylane import numpy as np
 
 
 def classical_jacobian(qnode, argnum=None, expand_fn=None, trainable_only=True):
diff --git a/pennylane/gradients/hadamard_gradient.py b/pennylane/gradients/hadamard_gradient.py
index 851e30f24..9648d3e44 100644
--- a/pennylane/gradients/hadamard_gradient.py
+++ b/pennylane/gradients/hadamard_gradient.py
@@ -18,8 +18,8 @@ of a qubit-based quantum tape.
 # pylint: disable=unused-argument
 from typing import Sequence, Callable
 from functools import partial
+import numpy as np
 import pennylane as qml
-import pennylane.numpy as np
 from pennylane.gradients.metric_tensor import _get_aux_wire
 from pennylane import transform
 from pennylane.gradients.gradient_transform import _contract_qjac_with_cjac
diff --git a/pennylane/gradients/parameter_shift_hessian.py b/pennylane/gradients/parameter_shift_hessian.py
index 89eeaa96b..11a4c9a48 100644
--- a/pennylane/gradients/parameter_shift_hessian.py
+++ b/pennylane/gradients/parameter_shift_hessian.py
@@ -20,8 +20,8 @@ import warnings
 from functools import partial
 from typing import Sequence, Callable
 
+import numpy as np
 import pennylane as qml
-from pennylane import numpy as np
 from pennylane.measurements import ProbabilityMP, StateMP, VarianceMP
 from pennylane.transforms import transform
 
diff --git a/pennylane/kernels/cost_functions.py b/pennylane/kernels/cost_functions.py
index 64ffe4918..a7960755f 100644
--- a/pennylane/kernels/cost_functions.py
+++ b/pennylane/kernels/cost_functions.py
@@ -15,7 +15,7 @@
 This file contains functionalities for kernel related costs.
 See `here <https://www.doi.org/10.1007/s10462-012-9369-4>`_ for a review.
 """
-from pennylane import numpy as np
+import numpy as np
 from ..math import frobenius_inner_product
 from .utils import square_kernel_matrix
 
diff --git a/pennylane/kernels/postprocessing.py b/pennylane/kernels/postprocessing.py
index b93f13364..75edaa132 100644
--- a/pennylane/kernels/postprocessing.py
+++ b/pennylane/kernels/postprocessing.py
@@ -14,7 +14,7 @@
 """
 This file contains functionalities for postprocessing of kernel matrices.
 """
-from pennylane import numpy as np
+import numpy as np
 
 
 def threshold_matrix(K):
diff --git a/pennylane/measurements/mid_measure.py b/pennylane/measurements/mid_measure.py
index 1006ad40b..319a7f8b9 100644
--- a/pennylane/measurements/mid_measure.py
+++ b/pennylane/measurements/mid_measure.py
@@ -16,9 +16,9 @@ This module contains the qml.measure measurement.
 """
 import uuid
 from typing import Generic, TypeVar, Optional
+import numpy as np
 
 import pennylane as qml
-import pennylane.numpy as np
 from pennylane.wires import Wires
 
 from .measurements import MeasurementProcess, MidMeasure
diff --git a/pennylane/measurements/probs.py b/pennylane/measurements/probs.py
index 20ef2a02f..b7fe0afd5 100644
--- a/pennylane/measurements/probs.py
+++ b/pennylane/measurements/probs.py
@@ -16,8 +16,8 @@ This module contains the qml.probs measurement.
 """
 from typing import Sequence, Tuple
 
+import numpy as np
 import pennylane as qml
-from pennylane import numpy as np
 from pennylane.wires import Wires
 
 from .measurements import Probability, SampleMeasurement, StateMeasurement
diff --git a/pennylane/ops/functions/is_commuting.py b/pennylane/ops/functions/is_commuting.py
index 9db93dfde..b0f50101b 100644
--- a/pennylane/ops/functions/is_commuting.py
+++ b/pennylane/ops/functions/is_commuting.py
@@ -15,8 +15,8 @@
 Defines `is_commuting`, an function for determining if two functions commute.
 """
 
+import numpy as np
 import pennylane as qml
-from pennylane import numpy as np
 from pennylane.pauli.utils import is_pauli_word, pauli_to_binary, _wire_map_from_pauli_pair
 
 
diff --git a/pennylane/ops/qubit/hamiltonian.py b/pennylane/ops/qubit/hamiltonian.py
index f1d991536..a1a5579f6 100644
--- a/pennylane/ops/qubit/hamiltonian.py
+++ b/pennylane/ops/qubit/hamiltonian.py
@@ -22,11 +22,11 @@ from collections.abc import Iterable
 from copy import copy
 import functools
 from typing import List
+import numpy as np
 import scipy
 
 
 import pennylane as qml
-from pennylane import numpy as np
 from pennylane.operation import Observable, Tensor
 from pennylane.wires import Wires
 
diff --git a/pennylane/ops/qubit/state_preparation.py b/pennylane/ops/qubit/state_preparation.py
index e6348a1f0..df7b09667 100644
--- a/pennylane/ops/qubit/state_preparation.py
+++ b/pennylane/ops/qubit/state_preparation.py
@@ -16,7 +16,7 @@ This submodule contains the discrete-variable quantum operations concerned
 with preparing a certain state on the device.
 """
 # pylint:disable=abstract-method,arguments-differ,protected-access,no-member
-from pennylane import numpy as np
+import numpy as np
 from pennylane import math
 from pennylane.operation import AnyWires, Operation, StatePrepBase
 from pennylane.templates.state_preparations import BasisStatePreparation, MottonenStatePreparation
diff --git a/pennylane/ops/qutrit/state_preparation.py b/pennylane/ops/qutrit/state_preparation.py
index 1c2ab0b1c..67f976461 100644
--- a/pennylane/ops/qutrit/state_preparation.py
+++ b/pennylane/ops/qutrit/state_preparation.py
@@ -16,7 +16,7 @@ This submodule contains the discrete-variable quantum operations concerned
 with preparing a certain state on the qutrit device.
 """
 # pylint:disable=abstract-method,arguments-differ,protected-access,no-member
-from pennylane import numpy as np
+import numpy as np
 from pennylane import math
 from pennylane.operation import AnyWires, StatePrepBase
 from pennylane.templates.state_preparations import QutritBasisStatePreparation
diff --git a/pennylane/optimize/adagrad.py b/pennylane/optimize/adagrad.py
index 48b5de161..001ab0ae2 100644
--- a/pennylane/optimize/adagrad.py
+++ b/pennylane/optimize/adagrad.py
@@ -12,7 +12,7 @@
 # See the License for the specific language governing permissions and
 # limitations under the License.
 """Adagrad optimizer"""
-from pennylane.numpy import sqrt
+from numpy import sqrt
 from .gradient_descent import GradientDescentOptimizer
 
 
diff --git a/pennylane/optimize/adam.py b/pennylane/optimize/adam.py
index c24b61026..a064520a5 100644
--- a/pennylane/optimize/adam.py
+++ b/pennylane/optimize/adam.py
@@ -12,7 +12,7 @@
 # See the License for the specific language governing permissions and
 # limitations under the License.
 """Adam optimizer"""
-from pennylane.numpy import sqrt
+from numpy import sqrt
 from .gradient_descent import GradientDescentOptimizer
 
 
diff --git a/pennylane/optimize/adaptive.py b/pennylane/optimize/adaptive.py
index bf42b17f1..649ae0655 100644
--- a/pennylane/optimize/adaptive.py
+++ b/pennylane/optimize/adaptive.py
@@ -17,7 +17,7 @@ from typing import Sequence, Callable
 
 # pylint: disable= no-value-for-parameter, protected-access, not-callable
 import pennylane as qml
-from pennylane import numpy as np
+from pennylane import numpy as pnp
 from pennylane.tape import QuantumTape
 from pennylane import transform
 
@@ -210,17 +210,17 @@ class AdaptiveOptimizer:
                 )
             ]
 
-        params = np.array([gate.parameters[0] for gate in operator_pool], requires_grad=True)
+        params = pnp.array([gate.parameters[0] for gate in operator_pool], requires_grad=True)
         qnode.func = self._circuit
         grads = qml.grad(qnode)(params, gates=operator_pool, initial_circuit=circuit.func)
 
-        selected_gates = [operator_pool[np.argmax(abs(grads))]]
+        selected_gates = [operator_pool[pnp.argmax(abs(grads))]]
         optimizer = qml.GradientDescentOptimizer(stepsize=self.stepsize)
 
         if params_zero:
-            params = np.zeros(len(selected_gates))
+            params = pnp.zeros(len(selected_gates))
         else:
-            params = np.array([gate.parameters[0] for gate in selected_gates], requires_grad=True)
+            params = pnp.array([gate.parameters[0] for gate in selected_gates], requires_grad=True)
 
         for _ in range(self.param_steps):
             params, _ = optimizer.step_and_cost(
diff --git a/pennylane/optimize/qng.py b/pennylane/optimize/qng.py
index 918ae9f92..8ba0f02e4 100644
--- a/pennylane/optimize/qng.py
+++ b/pennylane/optimize/qng.py
@@ -14,7 +14,7 @@
 """Quantum natural gradient optimizer"""
 # pylint: disable=too-many-branches
 # pylint: disable=too-many-arguments
-from pennylane import numpy as np
+from pennylane import numpy as pnp
 
 import pennylane as qml
 from pennylane.utils import _flatten, unflatten
@@ -200,7 +200,7 @@ class QNGOptimizer(GradientDescentOptimizer):
             )
 
         g, forward = self.compute_grad(qnode, args, kwargs, grad_fn=grad_fn)
-        new_args = np.array(self.apply_grad(g, args), requires_grad=True)
+        new_args = pnp.array(self.apply_grad(g, args), requires_grad=True)
 
         if forward is None:
             forward = qnode(*args, **kwargs)
@@ -272,7 +272,7 @@ class QNGOptimizer(GradientDescentOptimizer):
         Returns:
             array: the new values :math:`x^{(t+1)}`
         """
-        grad_flat = np.array(list(_flatten(grad)))
-        x_flat = np.array(list(_flatten(args)))
-        x_new_flat = x_flat - self.stepsize * np.linalg.solve(self.metric_tensor, grad_flat)
+        grad_flat = pnp.array(list(_flatten(grad)))
+        x_flat = pnp.array(list(_flatten(args)))
+        x_new_flat = x_flat - self.stepsize * pnp.linalg.solve(self.metric_tensor, grad_flat)
         return unflatten(x_new_flat, args)
diff --git a/pennylane/optimize/qnspsa.py b/pennylane/optimize/qnspsa.py
index e1c084531..6fd8869df 100644
--- a/pennylane/optimize/qnspsa.py
+++ b/pennylane/optimize/qnspsa.py
@@ -14,8 +14,8 @@
 """Quantum natural SPSA optimizer"""
 import warnings
 from scipy.linalg import sqrtm
+import numpy as np
 import pennylane as qml
-from pennylane import numpy as np
 
 
 class QNSPSAOptimizer:
diff --git a/pennylane/optimize/rms_prop.py b/pennylane/optimize/rms_prop.py
index f52702117..48adc65ca 100644
--- a/pennylane/optimize/rms_prop.py
+++ b/pennylane/optimize/rms_prop.py
@@ -12,7 +12,7 @@
 # See the License for the specific language governing permissions and
 # limitations under the License.
 """Root mean square propagation optimizer"""
-from pennylane.numpy import sqrt
+from numpy import sqrt
 from .adagrad import AdagradOptimizer
 
 
diff --git a/pennylane/optimize/shot_adaptive.py b/pennylane/optimize/shot_adaptive.py
index 6ef47e2d2..78f649f52 100644
--- a/pennylane/optimize/shot_adaptive.py
+++ b/pennylane/optimize/shot_adaptive.py
@@ -14,10 +14,10 @@
 """Shot adaptive optimizer"""
 # pylint: disable=too-many-instance-attributes,too-many-arguments,too-many-branches
 from copy import copy
+import numpy as np
 from scipy.stats import multinomial
 
 import pennylane as qml
-from pennylane import numpy as np
 
 from .gradient_descent import GradientDescentOptimizer
 
diff --git a/pennylane/optimize/spsa.py b/pennylane/optimize/spsa.py
index a3a1e5faa..e517a7412 100644
--- a/pennylane/optimize/spsa.py
+++ b/pennylane/optimize/spsa.py
@@ -13,7 +13,7 @@
 # limitations under the License.
 """SPSA optimizer"""
 
-from pennylane import numpy as np
+import numpy as np
 from pennylane.measurements import Shots
 
 
diff --git a/pennylane/pulse/transmon.py b/pennylane/pulse/transmon.py
index 0db919c7b..598877f40 100644
--- a/pennylane/pulse/transmon.py
+++ b/pennylane/pulse/transmon.py
@@ -16,9 +16,9 @@ import warnings
 
 from dataclasses import dataclass
 from typing import Callable, List, Union
+import numpy as np
 
 import pennylane as qml
-import pennylane.numpy as np
 from pennylane.pulse import HardwareHamiltonian
 from pennylane.pulse.hardware_hamiltonian import HardwarePulse
 from pennylane.typing import TensorLike
diff --git a/pennylane/qchem/convert.py b/pennylane/qchem/convert.py
index e1a8d00aa..0ec8d544f 100644
--- a/pennylane/qchem/convert.py
+++ b/pennylane/qchem/convert.py
@@ -16,10 +16,10 @@ This module contains the functions for converting an external operator to a Penn
 """
 import warnings
 from itertools import product
+import numpy as np
 
-# pylint: disable= import-outside-toplevel,no-member
+# pylint: disable= import-outside-toplevel,no-member,too-many-function-args
 import pennylane as qml
-from pennylane import numpy as np
 from pennylane.operation import Tensor, active_new_opmath
 from pennylane.pauli import pauli_sentence
 from pennylane.wires import Wires
@@ -177,7 +177,7 @@ def _openfermion_to_pennylane(qubit_operator, wires=None):
         # example term: ((0,'X'), (2,'Z'), (3,'Y'))
     )
 
-    return np.real(np.array(coeffs, requires_grad=False)), list(ops)
+    return np.array(coeffs).real, list(ops)
 
 
 def _ps_to_coeff_term(ps, wire_order):
@@ -547,9 +547,9 @@ def _ucisd_state(cisd_solver, tol=1e-15):
     dict_fcimatr.update(dict(zip(list(zip(c2aa_configs, [ref_b] * size_aa)), c2aa * c2aa_signs)))
 
     # alpha, beta -> alpha, beta excitations
-    rowvals, colvals = np.array(list(product(c1a_configs, c1b_configs)), dtype=int).T.numpy()
+    rowvals, colvals = np.array(list(product(c1a_configs, c1b_configs)), dtype=int).T
     dict_fcimatr.update(
-        dict(zip(list(zip(rowvals, colvals)), c2ab * np.kron(c1a_signs, c1b_signs).numpy()))
+        dict(zip(list(zip(rowvals, colvals)), c2ab * np.kron(c1a_signs, c1b_signs)))
     )
 
     # beta, beta -> beta, beta excitations
@@ -745,10 +745,10 @@ def _rcisd_state(cisd_solver, tol=1e-15):
 
     # alpha, beta -> alpha, beta excitations
     # generate all possible pairwise combinations of _single_ excitations of alpha and beta sectors
-    rowvals, colvals = np.array(list(product(c1a_configs, c1a_configs)), dtype=int).T.numpy()
+    rowvals, colvals = np.array(list(product(c1a_configs, c1a_configs)), dtype=int).T
     c2ab = (c2.transpose(0, 2, 1, 3).reshape(nocc * nvir, -1)).ravel()
     dict_fcimatr.update(
-        dict(zip(list(zip(rowvals, colvals)), c2ab * np.kron(c1a_signs, c1a_signs).numpy()))
+        dict(zip(list(zip(rowvals, colvals)), c2ab * np.kron(c1a_signs, c1a_signs)))
     )
 
     # filter based on tolerance cutoff
@@ -822,18 +822,14 @@ def _rccsd_state(ccsd_solver, tol=1e-15):
     t2bb = t2aa
 
     # add in the disconnected part ( + 0.5 T_1^2) of double excitations
-    t2aa = (
-        t2aa
-        - 0.5
-        * np.kron(t1a, t1a).reshape(nelec_a, nvir_a, nelec_a, nvir_a).transpose(0, 2, 1, 3).numpy()
+    t2aa = t2aa - 0.5 * np.kron(t1a, t1a).reshape(nelec_a, nvir_a, nelec_a, nvir_a).transpose(
+        0, 2, 1, 3
     )
-    t2bb = (
-        t2bb
-        - 0.5
-        * np.kron(t1b, t1b).reshape(nelec_b, nvir_b, nelec_b, nvir_b).transpose(0, 2, 1, 3).numpy()
+    t2bb = t2bb - 0.5 * np.kron(t1b, t1b).reshape(nelec_b, nvir_b, nelec_b, nvir_b).transpose(
+        0, 2, 1, 3
     )
     # align the entries with how the excitations are ordered when generated by _excited_configurations()
-    t2ab = t2ab - 0.5 * np.kron(t1a, t1b).reshape(nelec_a, nvir_a, nelec_b, nvir_b).numpy()
+    t2ab = t2ab - 0.5 * np.kron(t1a, t1b).reshape(nelec_a, nvir_a, nelec_b, nvir_b)
 
     # numbers representing the Hartree-Fock vector, e.g., bin(ref_a)[::-1] = 1111...10...0
     ref_a = int(2**nelec_a - 1)
@@ -879,13 +875,13 @@ def _rccsd_state(ccsd_solver, tol=1e-15):
         )
 
     # alpha, beta -> alpha, beta excitations
-    rowvals, colvals = np.array(list(product(t1a_configs, t1b_configs)), dtype=int).T.numpy()
+    rowvals, colvals = np.array(list(product(t1a_configs, t1b_configs)), dtype=int).T
     dict_fcimatr.update(
-        dict(zip(list(zip(rowvals, colvals)), t2ab.ravel() * np.kron(t1a_signs, t1b_signs).numpy()))
+        dict(zip(list(zip(rowvals, colvals)), t2ab.ravel() * np.kron(t1a_signs, t1b_signs)))
     )
 
     # renormalize, to get the HF coefficient (CC wavefunction not normalized)
-    norm = np.sqrt(np.sum(np.array(list(dict_fcimatr.values())) ** 2)).numpy()
+    norm = np.sqrt(np.sum(np.array(list(dict_fcimatr.values())) ** 2))
     dict_fcimatr = {key: value / norm for (key, value) in dict_fcimatr.items()}
 
     # filter based on tolerance cutoff
@@ -954,20 +950,15 @@ def _uccsd_state(ccsd_solver, tol=1e-15):
     t1a, t1b = ccsd_solver.t1
     t2aa, t2ab, t2bb = ccsd_solver.t2
     # add in the disconnected part ( + 0.5 T_1^2) of double excitations
-    t2aa = (
-        t2aa
-        - 0.5
-        * np.kron(t1a, t1a).reshape(nelec_a, nvir_a, nelec_a, nvir_a).transpose(0, 2, 1, 3).numpy()
+    t2aa = t2aa - 0.5 * np.kron(t1a, t1a).reshape(nelec_a, nvir_a, nelec_a, nvir_a).transpose(
+        0, 2, 1, 3
     )
-    t2bb = (
-        t2bb
-        - 0.5
-        * np.kron(t1b, t1b).reshape(nelec_b, nvir_b, nelec_b, nvir_b).transpose(0, 2, 1, 3).numpy()
+    t2bb = t2bb - 0.5 * np.kron(t1b, t1b).reshape(nelec_b, nvir_b, nelec_b, nvir_b).transpose(
+        0, 2, 1, 3
     )
     # align the entries with how the excitations are ordered when generated by _excited_configurations()
-    t2ab = (
-        t2ab.transpose(0, 2, 1, 3)
-        - 0.5 * np.kron(t1a, t1b).reshape(nelec_a, nvir_a, nelec_b, nvir_b).numpy()
+    t2ab = t2ab.transpose(0, 2, 1, 3) - 0.5 * np.kron(t1a, t1b).reshape(
+        nelec_a, nvir_a, nelec_b, nvir_b
     )
 
     # numbers representing the Hartree-Fock vector, e.g., bin(ref_a)[::-1] = 1111...10...0
@@ -1014,13 +1005,13 @@ def _uccsd_state(ccsd_solver, tol=1e-15):
         )
 
     # alpha, beta -> alpha, beta excitations
-    rowvals, colvals = np.array(list(product(t1a_configs, t1b_configs)), dtype=int).T.numpy()
+    rowvals, colvals = np.array(list(product(t1a_configs, t1b_configs)), dtype=int).T
     dict_fcimatr.update(
-        dict(zip(list(zip(rowvals, colvals)), t2ab.ravel() * np.kron(t1a_signs, t1b_signs).numpy()))
+        dict(zip(list(zip(rowvals, colvals)), t2ab.ravel() * np.kron(t1a_signs, t1b_signs)))
     )
 
     # renormalize, to get the HF coefficient (CC wavefunction not normalized)
-    norm = np.sqrt(np.sum(np.array(list(dict_fcimatr.values())) ** 2)).numpy()
+    norm = np.sqrt(np.sum(np.array(list(dict_fcimatr.values())) ** 2))
     dict_fcimatr = {key: value / norm for (key, value) in dict_fcimatr.items()}
 
     # filter based on tolerance cutoff
diff --git a/pennylane/qchem/factorization.py b/pennylane/qchem/factorization.py
index 2c3ae7ea5..52c6b5595 100644
--- a/pennylane/qchem/factorization.py
+++ b/pennylane/qchem/factorization.py
@@ -14,8 +14,8 @@
 """
 This module contains the functions needed for two-electron tensor factorization.
 """
+import numpy as np
 import pennylane as qml
-from pennylane import numpy as np
 
 
 def factorize(two_electron, tol_factor=1.0e-5, tol_eigval=1.0e-5):
@@ -394,6 +394,7 @@ def _chemist_transform(one_body_tensor=None, two_body_tensor=None, spatial_basis
 
     if two_body_tensor is not None:
         chemist_two_body_coeffs = np.swapaxes(two_body_tensor, 1, 3)
+        # pylint:disable=invalid-unary-operand-type
         one_body_coeffs = -np.einsum("prrs", chemist_two_body_coeffs)
 
         if chemist_one_body_coeffs is None:
diff --git a/pennylane/qchem/givens_decomposition.py b/pennylane/qchem/givens_decomposition.py
index dc3f028b9..ee89c241b 100644
--- a/pennylane/qchem/givens_decomposition.py
+++ b/pennylane/qchem/givens_decomposition.py
@@ -15,8 +15,8 @@
 This module contains the functions needed for performing basis transformations defined by a set of fermionic ladder operators.
 """
 
+import numpy as np
 import pennylane as qml
-from pennylane import numpy as np
 
 
 def _givens_matrix(a, b, left=True, tol=1e-8):
diff --git a/pennylane/qchem/integrals.py b/pennylane/qchem/integrals.py
index b6065110e..e635e8878 100644
--- a/pennylane/qchem/integrals.py
+++ b/pennylane/qchem/integrals.py
@@ -17,10 +17,10 @@ This module contains the functions needed for computing integrals over basis fun
 # pylint: disable= unbalanced-tuple-unpacking, too-many-arguments
 import itertools as it
 
+import numpy as np
 from scipy.special import factorial2 as fac2
 
 import pennylane as qml
-from pennylane import numpy as np
 
 
 def primitive_norm(l, alpha):
diff --git a/pennylane/qchem/matrices.py b/pennylane/qchem/matrices.py
index 330aeb59a..699e237f2 100644
--- a/pennylane/qchem/matrices.py
+++ b/pennylane/qchem/matrices.py
@@ -17,8 +17,8 @@ This module contains the functions needed for computing matrices.
 # pylint: disable= too-many-branches
 import itertools as it
 
+import numpy as np
 import pennylane as qml
-from pennylane import numpy as np
 
 from .integrals import (
     attraction_integral,
diff --git a/pennylane/qchem/molecule.py b/pennylane/qchem/molecule.py
index a5b12b06b..c54db7e73 100644
--- a/pennylane/qchem/molecule.py
+++ b/pennylane/qchem/molecule.py
@@ -20,7 +20,7 @@ the necessary information to perform a Hartree-Fock calculation for a given mole
 import itertools
 import collections
 
-from pennylane import numpy as np
+from pennylane import numpy as pnp
 
 from .basis_data import atomic_numbers
 from .basis_set import BasisFunction, mol_basis_data
@@ -115,13 +115,13 @@ class Molecule:
             l = [i[0] for i in self.basis_data]
 
         if alpha is None:
-            alpha = [np.array(i[1], requires_grad=False) for i in self.basis_data]
+            alpha = [pnp.array(i[1], requires_grad=False) for i in self.basis_data]
 
         if coeff is None:
-            coeff = [np.array(i[2], requires_grad=False) for i in self.basis_data]
+            coeff = [pnp.array(i[2], requires_grad=False) for i in self.basis_data]
             if normalize:
                 coeff = [
-                    np.array(c * primitive_norm(l[i], alpha[i]), requires_grad=False)
+                    pnp.array(c * primitive_norm(l[i], alpha[i]), requires_grad=False)
                     for i, c in enumerate(coeff)
                 ]
 
@@ -193,8 +193,8 @@ class Molecule:
                 array[float]: value of a basis function
             """
             c = ((x - r[0]) ** lx) * ((y - r[1]) ** ly) * ((z - r[2]) ** lz)
-            e = [np.exp(-a * ((x - r[0]) ** 2 + (y - r[1]) ** 2 + (z - r[2]) ** 2)) for a in alpha]
-            return c * np.dot(coeff, e)
+            e = [pnp.exp(-a * ((x - r[0]) ** 2 + (y - r[1]) ** 2 + (z - r[2]) ** 2)) for a in alpha]
+            return c * pnp.dot(coeff, e)
 
         return orbital
 
diff --git a/pennylane/qchem/observable_hf.py b/pennylane/qchem/observable_hf.py
index 5cb96b52f..8f6909039 100644
--- a/pennylane/qchem/observable_hf.py
+++ b/pennylane/qchem/observable_hf.py
@@ -15,8 +15,8 @@
 This module contains the functions needed for creating fermionic and qubit observables.
 """
 # pylint: disable= too-many-branches, too-many-return-statements
+import numpy as np
 import pennylane as qml
-from pennylane import numpy as np
 from pennylane.fermi import FermiSentence, FermiWord
 from pennylane.operation import active_new_opmath
 from pennylane.pauli.utils import simplify
diff --git a/pennylane/qchem/spin.py b/pennylane/qchem/spin.py
index ce9f3fcbe..a7ada7ae8 100644
--- a/pennylane/qchem/spin.py
+++ b/pennylane/qchem/spin.py
@@ -14,7 +14,7 @@
 """
 This module contains the functions needed for computing the spin observables.
 """
-from pennylane import numpy as np
+import numpy as np
 from pennylane.fermi import FermiSentence, FermiWord
 
 from .observable_hf import qubit_observable
diff --git a/pennylane/qchem/structure.py b/pennylane/qchem/structure.py
index 1d9fe6bfe..0fe02bf52 100644
--- a/pennylane/qchem/structure.py
+++ b/pennylane/qchem/structure.py
@@ -19,7 +19,7 @@ import os
 import re
 from shutil import copyfile
 
-from pennylane import numpy as np
+import numpy as np
 
 # Bohr-Angstrom correlation coefficient (https://physics.nist.gov/cgi-bin/cuu/Value?bohrrada0)
 bohr_angs = 0.529177210903
diff --git a/pennylane/qchem/tapering.py b/pennylane/qchem/tapering.py
index 23bb2eafb..2a76c60f0 100644
--- a/pennylane/qchem/tapering.py
+++ b/pennylane/qchem/tapering.py
@@ -19,11 +19,10 @@ This module contains the functions needed for tapering qubits using symmetries.
 import functools
 import itertools
 
-import numpy
+import numpy as np
 import scipy
 
 import pennylane as qml
-from pennylane import numpy as np
 from pennylane.operation import active_new_opmath
 from pennylane.pauli import PauliSentence, PauliWord, pauli_sentence, simplify
 from pennylane.pauli.utils import _binary_matrix_from_pws
@@ -437,7 +436,7 @@ def optimal_sector(qubit_op, generators, active_electrons):
     perm = []
     for tau in generators:
         symmstr = np.array([1 if wire in tau.wires else 0 for wire in qubit_op.wires])
-        coeff = -1 if numpy.logical_xor.reduce(numpy.logical_and(symmstr, hf_str)) else 1
+        coeff = -1 if np.logical_xor.reduce(np.logical_and(symmstr, hf_str)) else 1
         perm.append(coeff)
 
     return perm
diff --git a/pennylane/qcut/cutcircuit_mc.py b/pennylane/qcut/cutcircuit_mc.py
index 864e59a97..688985835 100644
--- a/pennylane/qcut/cutcircuit_mc.py
+++ b/pennylane/qcut/cutcircuit_mc.py
@@ -18,11 +18,11 @@ Function cut_circuit_mc for cutting a quantum circuit into smaller circuit fragm
 import inspect
 from functools import partial
 from typing import Callable, List, Optional, Sequence, Tuple, Union
+import numpy as np
 
 from networkx import MultiDiGraph
 
 import pennylane as qml
-from pennylane import numpy as np
 from pennylane.measurements import SampleMP
 from pennylane.queuing import AnnotatedQueue
 from pennylane.tape import QuantumScript, QuantumTape
diff --git a/pennylane/qcut/kahypar.py b/pennylane/qcut/kahypar.py
index 94c006fda..e807b2363 100644
--- a/pennylane/qcut/kahypar.py
+++ b/pennylane/qcut/kahypar.py
@@ -21,10 +21,10 @@ from itertools import compress
 from pathlib import Path
 from typing import Any, List, Sequence, Tuple, Union
 
+import numpy as np
 from networkx import MultiDiGraph
 
 import pennylane as qml
-from pennylane import numpy as np
 from pennylane.operation import Operation
 
 
diff --git a/pennylane/qcut/processing.py b/pennylane/qcut/processing.py
index d768b14c3..19ee5e5e9 100644
--- a/pennylane/qcut/processing.py
+++ b/pennylane/qcut/processing.py
@@ -20,7 +20,7 @@ from typing import List, Sequence
 from networkx import MultiDiGraph
 
 import pennylane as qml
-from pennylane import numpy as np
+from pennylane import numpy as pnp
 
 from .utils import MeasureNode, PrepareNode
 
@@ -111,14 +111,14 @@ def qcut_processing_fn_sample(
         sample = []
         for fragment_result, out_degree in zip(result, out_degrees):
             sample.append(fragment_result[: -out_degree or None])
-        samples.append(np.hstack(sample))
-    return [qml.math.convert_like(np.array(samples), res0)]
+        samples.append(pnp.hstack(sample))
+    return [qml.math.convert_like(pnp.array(samples), res0)]
 
 
 def qcut_processing_fn_mc(
     results: Sequence,
     communication_graph: MultiDiGraph,
-    settings: np.ndarray,
+    settings: pnp.ndarray,
     shots: int,
     classical_processing_fn: callable,
 ):
@@ -163,11 +163,11 @@ def qcut_processing_fn_mc(
             sample_terminal.append(fragment_result[: -out_degree or None])
             sample_mid.append(fragment_result[-out_degree or len(fragment_result) :])
 
-        sample_terminal = np.hstack(sample_terminal)
-        sample_mid = np.hstack(sample_mid)
+        sample_terminal = pnp.hstack(sample_terminal)
+        sample_mid = pnp.hstack(sample_mid)
 
-        assert set(sample_terminal).issubset({np.array(0), np.array(1)})
-        assert set(sample_mid).issubset({np.array(-1), np.array(1)})
+        assert set(sample_terminal).issubset({pnp.array(0), pnp.array(1)})
+        assert set(sample_mid).issubset({pnp.array(-1), pnp.array(1)})
         # following Eq.(35) of Peng et.al: https://arxiv.org/abs/1904.00102
         f = classical_processing_fn(sample_terminal)
         if not -1 <= f <= 1:
@@ -175,13 +175,13 @@ def qcut_processing_fn_mc(
                 "The classical processing function supplied must "
                 "give output in the interval [-1, 1]"
             )
-        sigma_s = np.prod(sample_mid)
+        sigma_s = pnp.prod(sample_mid)
         t_s = f * sigma_s
-        c_s = np.prod([evals[s] for s in setting])
+        c_s = pnp.prod([evals[s] for s in setting])
         K = len(sample_mid)
         expvals.append(8**K * c_s * t_s)
 
-    return qml.math.convert_like(np.mean(expvals), res0)
+    return qml.math.convert_like(pnp.mean(expvals), res0)
 
 
 def _reshape_results(results: Sequence, shots: int) -> List[List]:
diff --git a/pennylane/qcut/utils.py b/pennylane/qcut/utils.py
index bdf74269c..2aa7f8ffa 100644
--- a/pennylane/qcut/utils.py
+++ b/pennylane/qcut/utils.py
@@ -16,13 +16,13 @@ Support functions for cut_circuit and cut_circuit_mc.
 """
 
 
-import warnings
 import uuid
 from typing import Any, Callable, Sequence, Tuple
+import warnings
+import numpy as np
 from networkx import MultiDiGraph, has_path, weakly_connected_components
 
 import pennylane as qml
-from pennylane import numpy as np
 from pennylane.measurements import MeasurementProcess
 from pennylane.ops.meta import WireCut
 from pennylane.queuing import WrappedObj
diff --git a/pennylane/resource/first_quantization.py b/pennylane/resource/first_quantization.py
index b696b5538..06809fc5e 100644
--- a/pennylane/resource/first_quantization.py
+++ b/pennylane/resource/first_quantization.py
@@ -16,10 +16,9 @@ This module contains the functions needed for estimating the number of logical q
 non-Clifford gates for quantum algorithms in first quantization using a plane-wave basis.
 """
 # pylint: disable=no-self-use disable=too-many-arguments disable=too-many-instance-attributes
-import numpy
+import numpy as np
 from scipy import integrate
 
-from pennylane import numpy as np
 from pennylane.operation import AnyWires, Operation
 
 
@@ -269,7 +268,7 @@ class FirstQuantization(Operation):
         if n <= 0:
             raise ValueError("The number of plane waves must be a positive number.")
 
-        if eta <= 0 or not isinstance(eta, (int, numpy.integer)):
+        if eta <= 0 or not isinstance(eta, (int, np.integer)):
             raise ValueError("The number of electrons must be a positive integer.")
 
         if omega <= 0:
@@ -360,7 +359,7 @@ class FirstQuantization(Operation):
         >>> _cost_qrom(lz)
         21
         """
-        if lz <= 0 or not isinstance(lz, (int, numpy.integer)):
+        if lz <= 0 or not isinstance(lz, (int, np.integer)):
             raise ValueError("The sum of the atomic numbers must be a positive integer.")
 
         k_f = np.floor(np.log2(lz) / 2)
@@ -402,7 +401,7 @@ class FirstQuantization(Operation):
         if n <= 0:
             raise ValueError("The number of plane waves must be a positive number.")
 
-        if eta <= 0 or not isinstance(eta, (int, numpy.integer)):
+        if eta <= 0 or not isinstance(eta, (int, np.integer)):
             raise ValueError("The number of electrons must be a positive integer.")
 
         if omega <= 0:
@@ -538,7 +537,7 @@ class FirstQuantization(Operation):
         if n <= 0:
             raise ValueError("The number of plane waves must be a positive number.")
 
-        if eta <= 0 or not isinstance(eta, (int, numpy.integer)):
+        if eta <= 0 or not isinstance(eta, (int, np.integer)):
             raise ValueError("The number of electrons must be a positive integer.")
 
         if omega <= 0:
@@ -597,7 +596,7 @@ class FirstQuantization(Operation):
         if n <= 0:
             raise ValueError("The number of plane waves must be a positive number.")
 
-        if eta <= 0 or not isinstance(eta, (int, numpy.integer)):
+        if eta <= 0 or not isinstance(eta, (int, np.integer)):
             raise ValueError("The number of electrons must be a positive integer.")
 
         if omega <= 0:
diff --git a/pennylane/resource/measurement.py b/pennylane/resource/measurement.py
index c06a5b8db..f9968311a 100644
--- a/pennylane/resource/measurement.py
+++ b/pennylane/resource/measurement.py
@@ -15,7 +15,7 @@
 This module contains the functions needed for estimating the number of measurements and the error
 for computing expectation values.
 """
-from pennylane import numpy as np
+import numpy as np
 
 
 def estimate_shots(coeffs, variances=None, error=0.0016):
diff --git a/pennylane/resource/second_quantization.py b/pennylane/resource/second_quantization.py
index 736e28ba5..602abeef7 100644
--- a/pennylane/resource/second_quantization.py
+++ b/pennylane/resource/second_quantization.py
@@ -16,8 +16,7 @@ This module contains the functions needed for resource estimation with the doubl
 method.
 """
 # pylint: disable=no-self-use disable=too-many-arguments disable=too-many-instance-attributes
-import numpy
-from pennylane import numpy as np
+import numpy as np
 from pennylane.operation import AnyWires, Operation
 from pennylane.qchem import factorize
 
@@ -265,7 +264,7 @@ class DoubleFactorization(Operation):
         >>> unitary_cost(n, rank_r, rank_m, rank_max, br, alpha, beta)
         2007
         """
-        if n <= 0 or not isinstance(n, (int, numpy.integer)) or n % 2 != 0:
+        if n <= 0 or not isinstance(n, (int, np.integer)) or n % 2 != 0:
             raise ValueError("The number of spin-orbitals must be a positive even integer.")
 
         if rank_r <= 0 or not isinstance(rank_r, int):
@@ -351,7 +350,7 @@ class DoubleFactorization(Operation):
         >>> gate_cost(n, lamb, error, rank_r, rank_m, rank_max, br, alpha, beta)
         167048631
         """
-        if n <= 0 or not isinstance(n, (int, numpy.integer)) or n % 2 != 0:
+        if n <= 0 or not isinstance(n, (int, np.integer)) or n % 2 != 0:
             raise ValueError("The number of spin-orbitals must be a positive even integer.")
 
         if error <= 0.0:
@@ -420,7 +419,7 @@ class DoubleFactorization(Operation):
         >>> qubit_cost(n, lamb, error, rank_r, rank_m, rank_max, br, alpha, beta)
         292
         """
-        if n <= 0 or not isinstance(n, (int, numpy.integer)) or n % 2 != 0:
+        if n <= 0 or not isinstance(n, (int, np.integer)) or n % 2 != 0:
             raise ValueError("The number of spin-orbitals must be a positive even integer.")
 
         if error <= 0.0:
diff --git a/pennylane/shadows/classical_shadow.py b/pennylane/shadows/classical_shadow.py
index 62e9d370a..55c180f17 100644
--- a/pennylane/shadows/classical_shadow.py
+++ b/pennylane/shadows/classical_shadow.py
@@ -17,7 +17,7 @@ import warnings
 from collections.abc import Iterable
 from string import ascii_letters as ABC
 
-import pennylane.numpy as np
+import numpy as np
 import pennylane as qml
 
 
diff --git a/pennylane/shadows/transforms.py b/pennylane/shadows/transforms.py
index 89f7de94c..ae38ab0ab 100644
--- a/pennylane/shadows/transforms.py
+++ b/pennylane/shadows/transforms.py
@@ -17,9 +17,9 @@ import warnings
 from functools import reduce, partial
 from itertools import product
 from typing import Sequence, Callable
+import numpy as np
 
 import pennylane as qml
-import pennylane.numpy as np
 from pennylane.measurements import ClassicalShadowMP
 from pennylane.tape import QuantumScript, QuantumTape
 from pennylane import transform
diff --git a/pennylane/templates/embeddings/basis.py b/pennylane/templates/embeddings/basis.py
index 8013e3b15..f88c56794 100644
--- a/pennylane/templates/embeddings/basis.py
+++ b/pennylane/templates/embeddings/basis.py
@@ -15,8 +15,8 @@ r"""
 Contains the BasisEmbedding template.
 """
 # pylint: disable-msg=too-many-branches,too-many-arguments,protected-access
+import numpy as np
 import pennylane as qml
-import pennylane.numpy as np
 from pennylane.operation import Operation, AnyWires
 from pennylane.wires import Wires
 
diff --git a/pennylane/templates/state_preparations/basis.py b/pennylane/templates/state_preparations/basis.py
index 0b309e383..8f04e1075 100644
--- a/pennylane/templates/state_preparations/basis.py
+++ b/pennylane/templates/state_preparations/basis.py
@@ -15,8 +15,8 @@ r"""
 Contains the BasisStatePreparation template.
 """
 
+import numpy as np
 import pennylane as qml
-import pennylane.numpy as np
 from pennylane.operation import Operation, AnyWires
 
 
diff --git a/pennylane/templates/subroutines/basis_rotation.py b/pennylane/templates/subroutines/basis_rotation.py
index fcaafe82e..75d018b81 100644
--- a/pennylane/templates/subroutines/basis_rotation.py
+++ b/pennylane/templates/subroutines/basis_rotation.py
@@ -15,8 +15,8 @@
 This module contains the template for performing basis transformation defined by a set of fermionic ladder operators.
 """
 
+import numpy as np
 import pennylane as qml
-from pennylane import numpy as np
 from pennylane.operation import AnyWires, Operation
 from pennylane.qchem.givens_decomposition import givens_decomposition
 
diff --git a/pennylane/templates/subroutines/fermionic_single_excitation.py b/pennylane/templates/subroutines/fermionic_single_excitation.py
index 01e3923fd..c82700d12 100644
--- a/pennylane/templates/subroutines/fermionic_single_excitation.py
+++ b/pennylane/templates/subroutines/fermionic_single_excitation.py
@@ -15,8 +15,8 @@ r"""
 Contains the FermionicSingleExcitation template.
 """
 # pylint: disable-msg=too-many-branches,too-many-arguments,protected-access
+import numpy as np
 import pennylane as qml
-from pennylane import numpy as np
 from pennylane.operation import Operation, AnyWires
 from pennylane.ops import RZ, RX, CNOT, Hadamard
 
diff --git a/pennylane/templates/subroutines/qsvt.py b/pennylane/templates/subroutines/qsvt.py
index 0c8b963d9..913b328a2 100644
--- a/pennylane/templates/subroutines/qsvt.py
+++ b/pennylane/templates/subroutines/qsvt.py
@@ -16,12 +16,12 @@ Contains the QSVT template and qsvt wrapper function.
 """
 # pylint: disable=too-many-arguments
 import copy
+import numpy as np
 import pennylane as qml
 from pennylane.queuing import QueuingManager
 from pennylane.ops import BlockEncode, PCPhase
 from pennylane.ops.op_math import adjoint
 from pennylane.operation import AnyWires, Operation
-from pennylane import numpy as np
 
 
 def qsvt(A, angles, wires, convention=None):
diff --git a/pennylane/templates/swapnetworks/ccl2.py b/pennylane/templates/swapnetworks/ccl2.py
index c56267179..f6804bd21 100644
--- a/pennylane/templates/swapnetworks/ccl2.py
+++ b/pennylane/templates/swapnetworks/ccl2.py
@@ -16,8 +16,8 @@ Contains the TwoLocalSwapNetwork template.
 """
 
 import warnings
+import numpy as np
 import pennylane as qml
-import pennylane.numpy as np
 from pennylane.operation import Operation, AnyWires
 from pennylane.ops import SWAP, FermionicSWAP
 
diff --git a/pennylane/templates/tensornetworks/mera.py b/pennylane/templates/tensornetworks/mera.py
index b67847994..fbeb5a742 100644
--- a/pennylane/templates/tensornetworks/mera.py
+++ b/pennylane/templates/tensornetworks/mera.py
@@ -17,10 +17,9 @@ Contains the MERA template.
 # pylint: disable-msg=too-many-branches,too-many-arguments,protected-access
 import warnings
 from typing import Callable
-
+import numpy as np
 
 import pennylane as qml
-import pennylane.numpy as np
 from pennylane.operation import Operation, AnyWires
 
 
@@ -51,7 +50,7 @@ def compute_indices(wires, n_block_wires):
             f"got n_block_wires = {n_block_wires} and number of wires = {n_wires}"
         )
 
-    if not np.log2(n_wires / n_block_wires).is_integer():
+    if not np.log2(n_wires / n_block_wires).is_integer():  # pylint:disable=no-member
         warnings.warn(
             f"The number of wires should be n_block_wires times 2^n; got n_wires/n_block_wires = {n_wires/n_block_wires}"
         )
@@ -257,7 +256,7 @@ class MERA(Operation):
         """
 
         n_wires = len(wires)
-        if not np.log2(n_wires / n_block_wires).is_integer():
+        if not np.log2(n_wires / n_block_wires).is_integer():  # pylint:disable=no-member
             warnings.warn(
                 f"The number of wires should be n_block_wires times 2^n; got n_wires/n_block_wires = {n_wires/n_block_wires}"
             )
diff --git a/pennylane/templates/tensornetworks/ttn.py b/pennylane/templates/tensornetworks/ttn.py
index 3ff39cd44..2f56e093f 100644
--- a/pennylane/templates/tensornetworks/ttn.py
+++ b/pennylane/templates/tensornetworks/ttn.py
@@ -16,8 +16,8 @@ Contains the TTN template.
 """
 # pylint: disable-msg=too-many-branches,too-many-arguments,protected-access
 import warnings
+import numpy as np
 import pennylane as qml
-import pennylane.numpy as np
 from pennylane.operation import Operation, AnyWires
 
 
@@ -48,7 +48,7 @@ def compute_indices(wires, n_block_wires):
             f"got n_block_wires = {n_block_wires} and number of wires = {n_wires}"
         )
 
-    if not np.log2(n_wires / n_block_wires).is_integer():
+    if not np.log2(n_wires / n_block_wires).is_integer():  # pylint:disable=no-member
         warnings.warn(
             f"The number of wires should be n_block_wires times 2^n; got n_wires/n_block_wires = {n_wires/n_block_wires}"
         )
@@ -228,7 +228,7 @@ class TTN(Operation):
         """
 
         n_wires = len(wires)
-        if not np.log2(n_wires / n_block_wires).is_integer():
+        if not np.log2(n_wires / n_block_wires).is_integer():  # pylint:disable=no-member
             warnings.warn(
                 f"The number of wires should be n_block_wires times 2^n; got n_wires/n_block_wires = {n_wires/n_block_wires}"
             )
diff --git a/pennylane/transforms/batch_input.py b/pennylane/transforms/batch_input.py
index 532c6e991..ff1cdda4d 100644
--- a/pennylane/transforms/batch_input.py
+++ b/pennylane/transforms/batch_input.py
@@ -15,8 +15,8 @@ Batch transformation for multiple (non-trainable) input examples following issue
 """
 from typing import Callable, Sequence, Union
 
+import numpy as np
 import pennylane as qml
-from pennylane import numpy as np
 from pennylane.tape import QuantumTape
 from pennylane.transforms.core import transform
 from pennylane.transforms.batch_params import _nested_stack, _split_operations
diff --git a/pennylane/transforms/sign_expand/sign_expand.py b/pennylane/transforms/sign_expand/sign_expand.py
index f92824813..2d834bfb0 100644
--- a/pennylane/transforms/sign_expand/sign_expand.py
+++ b/pennylane/transforms/sign_expand/sign_expand.py
@@ -17,8 +17,9 @@ import json
 from os import path
 from typing import Sequence, Callable
 
+import numpy as np
+
 import pennylane as qml
-from pennylane import numpy as np
 from pennylane.transforms import transform
 
 


Test patch:
diff --git a/tests/shadow/test_shadow_class.py b/tests/shadow/test_shadow_class.py
index dd8f4e055..69d3826a5 100644
--- a/tests/shadow/test_shadow_class.py
+++ b/tests/shadow/test_shadow_class.py
@@ -16,6 +16,7 @@
 # pylint:disable=no-self-use, import-outside-toplevel, redefined-outer-name, unpacking-non-sequence, too-few-public-methods, not-an-iterable, inconsistent-return-statements
 
 import pytest
+import numpy as onp
 
 import pennylane as qml
 import pennylane.numpy as np
@@ -260,8 +261,8 @@ class TestStateReconstruction:
 
         with monkeypatch.context() as m:
             # don't run the actual state computation since we only want the warning
-            m.setattr(np, "einsum", lambda *args, **kwargs: None)
-            m.setattr(np, "reshape", lambda *args, **kwargs: None)
+            m.setattr(onp, "einsum", lambda *args, **kwargs: None)
+            m.setattr(onp, "reshape", lambda *args, **kwargs: None)
 
             with pytest.warns(UserWarning, match=msg):
                 shadow.global_snapshots()
diff --git a/tests/transforms/test_qcut.py b/tests/transforms/test_qcut.py
index e0c2405bf..b026af35a 100644
--- a/tests/transforms/test_qcut.py
+++ b/tests/transforms/test_qcut.py
@@ -26,6 +26,7 @@ from os import environ
 from pathlib import Path
 from functools import partial
 
+import numpy as onp
 import pytest
 from flaky import flaky
 from networkx import MultiDiGraph, number_of_selfloops
@@ -1851,7 +1852,7 @@ class TestExpandFragmentTapesMC:
 
         fixed_choice = np.array([[4, 0, 1]])
         with monkeypatch.context() as m:
-            m.setattr(np.random, "choice", lambda a, size, replace: fixed_choice)
+            m.setattr(onp.random, "choice", lambda a, size, replace: fixed_choice)
             fragment_configurations, settings = qcut.expand_fragment_tapes_mc(
                 tapes, communication_graph, 3
             )
@@ -1917,7 +1918,7 @@ class TestExpandFragmentTapesMC:
         fixed_choice = np.array([[4, 6], [1, 2], [2, 3], [3, 0]])
         with monkeypatch.context() as m:
             m.setattr(
-                np.random,
+                onp.random,
                 "choice",
                 lambda a, size, replace: fixed_choice,
             )