From c1c8978b98cca00aaa9e2784891355da2a388ee8 Mon Sep 17 00:00:00 2001 From: Pradnya Khalate Date: Wed, 10 Sep 2025 12:29:33 -0700 Subject: [PATCH 1/3] [Python] [tests] Clear kernel registries in test set up WIP: Issue#1954 Signed-off-by: Pradnya Khalate --- python/tests/backends/emulateInfleqtion.py | 4 ++-- python/tests/backends/test_IQM.py | 8 ++++---- python/tests/backends/test_Infleqtion.py | 11 +++++++---- python/tests/backends/test_IonQ.py | 12 ++++++++---- .../backends/test_Ionq_LocalEmulation_kernel.py | 9 +++++---- python/tests/backends/test_OQC.py | 8 ++++---- python/tests/backends/test_Pasqal.py | 5 +++-- python/tests/backends/test_QCI.py | 2 +- python/tests/backends/test_QuEra.py | 11 ++++++----- .../test_Quantinuum_LocalEmulation_builder.py | 7 ++++--- .../test_Quantinuum_LocalEmulation_kernel.py | 10 ++++++---- python/tests/backends/test_Quantinuum_builder.py | 10 +++++++--- python/tests/backends/test_Quantinuum_kernel.py | 10 +++++++--- python/tests/backends/test_Quantum_Machines.py | 5 +++-- python/tests/backends/test_braket.py | 9 +++++---- python/tests/backends/test_resource_counter.py | 3 +-- python/tests/backends/test_stim.py | 2 +- python/tests/builder/test_NoiseModel.py | 11 ++++++++--- python/tests/builder/test_cupy_integration.py | 11 ++++++++--- python/tests/builder/test_kernel_builder.py | 12 +++++++++--- python/tests/builder/test_observe.py | 11 ++++++++--- python/tests/builder/test_optimizer.py | 11 ++++++++--- python/tests/builder/test_qalloc_init.py | 10 ++++++++-- python/tests/builder/test_qalloc_init_state.py | 11 ++++++++--- python/tests/builder/test_qpp_target.py | 7 +++++++ python/tests/builder/test_quake_value.py | 9 +++++++-- python/tests/builder/test_sample.py | 11 ++++++++--- python/tests/builder/test_state.py | 9 +++++++-- python/tests/builder/test_vqe.py | 9 +++++++-- python/tests/custom/test_custom_operations.py | 9 ++++----- python/tests/custom/test_euler_decomposition.py | 11 ++++++++--- python/tests/custom/test_kak_decomposition.py | 11 ++++++++--- python/tests/domains/test_chemistry.py | 10 ++++++++-- python/tests/domains/test_qnn.py | 11 ++++++++--- .../test_evolve_dynamics_torch_integrators.py | 7 ++++--- python/tests/dynamics/test_evolve_dynamics.py | 8 +++++--- python/tests/dynamics/test_evolve_simulators.py | 8 ++++---- python/tests/handlers/test_photonics_kernel.py | 7 +++---- python/tests/interop/test_interop.py | 7 ++++--- python/tests/kernel/test_adjoint_operations.py | 7 +++++++ python/tests/kernel/test_ast_compare.py | 3 ++- python/tests/kernel/test_cast_kernel.py | 6 ++++++ python/tests/kernel/test_control_operations.py | 10 ++++++++-- .../tests/kernel/test_direct_call_return_kernel.py | 4 ++-- python/tests/kernel/test_explicit_measurements.py | 9 +++++---- python/tests/kernel/test_get_unitary.py | 12 ++++++++++-- python/tests/kernel/test_ir_operations.py | 8 ++++---- python/tests/kernel/test_kernel_call_return.py | 7 +++++++ python/tests/kernel/test_kernel_complex.py | 9 +++++++-- python/tests/kernel/test_kernel_exp_pauli.py | 7 +++++++ python/tests/kernel/test_kernel_features.py | 13 +++++++------ python/tests/kernel/test_kernel_float.py | 9 +++++++-- python/tests/kernel/test_kernel_parameters.py | 11 +++++------ python/tests/kernel/test_kernel_qvector_init.py | 8 +++++++- .../tests/kernel/test_kernel_qvector_state_init.py | 10 ++++++++-- python/tests/kernel/test_kernel_qview.py | 8 +++++++- python/tests/kernel/test_kernel_return.py | 10 ++++++++-- python/tests/kernel/test_kernel_shift_operators.py | 7 +++++++ python/tests/kernel/test_kernel_translate.py | 9 +++++++-- python/tests/kernel/test_kernel_uccsd.py | 2 +- python/tests/kernel/test_library_kernels.py | 9 ++++----- python/tests/kernel/test_observe_kernel.py | 12 ++++++------ python/tests/kernel/test_run_async_kernel.py | 4 ++-- python/tests/kernel/test_run_kernel.py | 6 +++--- python/tests/kernel/test_sample_kernel.py | 12 ++++++------ python/tests/kernel/test_state_kernel.py | 8 ++++---- python/tests/kernel/test_state_mps.py | 8 ++++---- python/tests/kernel/test_target_attributes.py | 6 +++--- python/tests/kernel/test_trotter.py | 9 +++++++-- python/tests/kernel/test_vqe_kernel.py | 8 ++++---- python/tests/operator/test_boson_op.py | 5 ++++- python/tests/operator/test_conversions.py | 6 +++++- python/tests/operator/test_fermion_op.py | 5 ++++- python/tests/operator/test_matrix_op.py | 7 ++++++- python/tests/operator/test_scalar_op.py | 7 +++++-- python/tests/operator/test_spin_op.py | 6 +++++- python/tests/parallel/test_mpi_api.py | 11 ++++++++++- python/tests/parallel/test_mpi_dynamics.py | 10 +++++++--- python/tests/parallel/test_mpi_mqpu.py | 11 +++++++---- python/tests/parallel/test_mqpu.py | 13 +++++++++---- python/tests/remote/test_remote_code_exec.py | 13 ++++++------- python/tests/remote/test_remote_platform.py | 12 +++++++----- python/tests/utils/test_set_target_callback.py | 9 ++++++++- python/tests/visualization/test_bloch_sphere.py | 8 ++++---- python/tests/visualization/test_draw.py | 4 ++-- 85 files changed, 484 insertions(+), 231 deletions(-) diff --git a/python/tests/backends/emulateInfleqtion.py b/python/tests/backends/emulateInfleqtion.py index 100a9a6737b..3f2ebad554a 100644 --- a/python/tests/backends/emulateInfleqtion.py +++ b/python/tests/backends/emulateInfleqtion.py @@ -12,10 +12,10 @@ @pytest.fixture(scope="session", autouse=True) -def do_something(): +def setup_test_environment(): + cudaq.__clearKernelRegistries() cudaq.set_target("infleqtion", emulate=True) yield "Running the tests." - cudaq.__clearKernelRegistries() cudaq.reset_target() diff --git a/python/tests/backends/test_IQM.py b/python/tests/backends/test_IQM.py index 185de3c9351..c3bf0e24049 100644 --- a/python/tests/backends/test_IQM.py +++ b/python/tests/backends/test_IQM.py @@ -9,14 +9,14 @@ import os import shutil import tempfile -from typing import List from multiprocessing import Process -import numpy as np -from network_utils import check_server_connection +from typing import List import cudaq -from cudaq import spin +import numpy as np import pytest +from cudaq import spin +from network_utils import check_server_connection iqm_client = pytest.importorskip("iqm.iqm_client") diff --git a/python/tests/backends/test_Infleqtion.py b/python/tests/backends/test_Infleqtion.py index a3f7422908a..2801a1c2b7b 100644 --- a/python/tests/backends/test_Infleqtion.py +++ b/python/tests/backends/test_Infleqtion.py @@ -6,9 +6,12 @@ # the terms of the Apache License 2.0 which accompanies this distribution. # # ============================================================================ # -import cudaq, pytest, os -from cudaq import spin +import os + +import cudaq import numpy as np +import pytest +from cudaq import spin ## NOTE: Comment the following line which skips these tests in order to run in # local dev environment after setting the API key @@ -17,10 +20,10 @@ @pytest.fixture(scope="session", autouse=True) -def do_something(): +def setup_test_environment(): + cudaq.__clearKernelRegistries() cudaq.set_target("infleqtion") yield "Running the tests." - cudaq.__clearKernelRegistries() cudaq.reset_target() diff --git a/python/tests/backends/test_IonQ.py b/python/tests/backends/test_IonQ.py index 6c8587daf0b..22cc3bb5439 100644 --- a/python/tests/backends/test_IonQ.py +++ b/python/tests/backends/test_IonQ.py @@ -6,12 +6,16 @@ # the terms of the Apache License 2.0 which accompanies this distribution. # # ============================================================================ # -import cudaq, pytest, os -from cudaq import spin -import numpy as np -from typing import List +import os from multiprocessing import Process +from typing import List + +import cudaq +import numpy as np +import pytest +from cudaq import spin from network_utils import check_server_connection + try: from utils.mock_qpu.ionq import startServer except: diff --git a/python/tests/backends/test_Ionq_LocalEmulation_kernel.py b/python/tests/backends/test_Ionq_LocalEmulation_kernel.py index 59996f43212..3278f3b2c30 100644 --- a/python/tests/backends/test_Ionq_LocalEmulation_kernel.py +++ b/python/tests/backends/test_Ionq_LocalEmulation_kernel.py @@ -6,13 +6,14 @@ # the terms of the Apache License 2.0 which accompanies this distribution. # # ============================================================================ # -import cudaq -import cudaq.kernels -from cudaq import spin -import pytest import os from typing import List + +import cudaq +import cudaq.kernels import numpy as np +import pytest +from cudaq import spin def assert_close(want, got, tolerance=1.0e-1) -> bool: diff --git a/python/tests/backends/test_OQC.py b/python/tests/backends/test_OQC.py index 3b0cd47fbc5..79a45ec49e3 100644 --- a/python/tests/backends/test_OQC.py +++ b/python/tests/backends/test_OQC.py @@ -7,14 +7,14 @@ # ============================================================================ # import os -from typing import List -import pytest from multiprocessing import Process -from network_utils import check_server_connection +from typing import List import cudaq -from cudaq import spin import numpy as np +import pytest +from cudaq import spin +from network_utils import check_server_connection try: from utils.mock_qpu.oqc import startServer diff --git a/python/tests/backends/test_Pasqal.py b/python/tests/backends/test_Pasqal.py index 8380562c8c5..08f058cd3d2 100644 --- a/python/tests/backends/test_Pasqal.py +++ b/python/tests/backends/test_Pasqal.py @@ -6,9 +6,10 @@ # the terms of the Apache License 2.0 which accompanies this distribution. # # ============================================================================ # -import cudaq import json import os + +import cudaq import pytest skipIfPasqalNotInstalled = pytest.mark.skipif( @@ -17,7 +18,7 @@ @pytest.fixture(scope="session", autouse=True) -def do_something(): +def setup_test_environment(): # NOTE: Credentials can be set with environment variables cudaq.set_target("pasqal") yield "Running the tests." diff --git a/python/tests/backends/test_QCI.py b/python/tests/backends/test_QCI.py index 041d193af29..889ad41cc4d 100644 --- a/python/tests/backends/test_QCI.py +++ b/python/tests/backends/test_QCI.py @@ -10,8 +10,8 @@ from multiprocessing import Process import cudaq -from cudaq import spin import pytest +from cudaq import spin from network_utils import check_server_connection try: diff --git a/python/tests/backends/test_QuEra.py b/python/tests/backends/test_QuEra.py index 0ca0ee8bdb7..0112c6ae701 100644 --- a/python/tests/backends/test_QuEra.py +++ b/python/tests/backends/test_QuEra.py @@ -6,17 +6,18 @@ # the terms of the Apache License 2.0 which accompanies this distribution. # # ============================================================================ # -import cudaq -from cudaq.operators import RydbergHamiltonian, ScalarOperator -from cudaq.dynamics import Schedule import json -import numpy as np import os + +import cudaq +import numpy as np import pytest +from cudaq.dynamics import Schedule +from cudaq.operators import RydbergHamiltonian, ScalarOperator @pytest.fixture(scope="session", autouse=True) -def do_something(): +def setup_test_environment(): cudaq.set_target("quera") yield "Running the tests." cudaq.reset_target() diff --git a/python/tests/backends/test_Quantinuum_LocalEmulation_builder.py b/python/tests/backends/test_Quantinuum_LocalEmulation_builder.py index 9e968e6d2cb..1366d724869 100644 --- a/python/tests/backends/test_Quantinuum_LocalEmulation_builder.py +++ b/python/tests/backends/test_Quantinuum_LocalEmulation_builder.py @@ -6,12 +6,13 @@ # the terms of the Apache License 2.0 which accompanies this distribution. # # ============================================================================ # +import os +from typing import List + import cudaq +import numpy as np import pytest -import os from cudaq import spin -import numpy as np -from typing import List def assert_close(got) -> bool: diff --git a/python/tests/backends/test_Quantinuum_LocalEmulation_kernel.py b/python/tests/backends/test_Quantinuum_LocalEmulation_kernel.py index 153e8c18510..7518587f3ae 100644 --- a/python/tests/backends/test_Quantinuum_LocalEmulation_kernel.py +++ b/python/tests/backends/test_Quantinuum_LocalEmulation_kernel.py @@ -6,18 +6,20 @@ # the terms of the Apache License 2.0 which accompanies this distribution. # # ============================================================================ # +import os +from typing import List + import cudaq +import numpy as np import pytest -import os from cudaq import spin -import numpy as np -from typing import List def requires_openfermion(): open_fermion_found = True try: - import openfermion, openfermionpyscf + import openfermion + import openfermionpyscf except: open_fermion_found = False return pytest.mark.skipif(not open_fermion_found, diff --git a/python/tests/backends/test_Quantinuum_builder.py b/python/tests/backends/test_Quantinuum_builder.py index b01fb7c5781..6474b05de53 100644 --- a/python/tests/backends/test_Quantinuum_builder.py +++ b/python/tests/backends/test_Quantinuum_builder.py @@ -6,12 +6,16 @@ # the terms of the Apache License 2.0 which accompanies this distribution. # # ============================================================================ # -import cudaq, pytest, os -import numpy as np +import os +from multiprocessing import Process from typing import List + +import cudaq +import numpy as np +import pytest from cudaq import spin -from multiprocessing import Process from network_utils import check_server_connection + try: from utils.mock_qpu.quantinuum import startServer except: diff --git a/python/tests/backends/test_Quantinuum_kernel.py b/python/tests/backends/test_Quantinuum_kernel.py index 05cc5f023d6..0ac2cadaceb 100644 --- a/python/tests/backends/test_Quantinuum_kernel.py +++ b/python/tests/backends/test_Quantinuum_kernel.py @@ -6,12 +6,16 @@ # the terms of the Apache License 2.0 which accompanies this distribution. # # ============================================================================ # -import cudaq, pytest, os -import numpy as np -from cudaq import spin +import os from multiprocessing import Process from typing import List + +import cudaq +import numpy as np +import pytest +from cudaq import spin from network_utils import check_server_connection + try: from utils.mock_qpu.quantinuum import startServer except: diff --git a/python/tests/backends/test_Quantum_Machines.py b/python/tests/backends/test_Quantum_Machines.py index 5c47758f80f..f4499cdcc2c 100644 --- a/python/tests/backends/test_Quantum_Machines.py +++ b/python/tests/backends/test_Quantum_Machines.py @@ -6,10 +6,11 @@ # the terms of the Apache License 2.0 which accompanies this distribution. # # ============================================================================ # -import cudaq import os -import pytest from multiprocessing import Process + +import cudaq +import pytest from network_utils import check_server_connection try: diff --git a/python/tests/backends/test_braket.py b/python/tests/backends/test_braket.py index 892d7183ffa..b4492ef8201 100644 --- a/python/tests/backends/test_braket.py +++ b/python/tests/backends/test_braket.py @@ -6,11 +6,12 @@ # the terms of the Apache License 2.0 which accompanies this distribution. # # ============================================================================ # +import os + import cudaq +import numpy as np import pytest -import os from cudaq import spin -import numpy as np ## NOTE: Comment the following line which skips these tests in order to run in # local dev environment after setting AWS credentials. @@ -19,10 +20,10 @@ @pytest.fixture(scope="session", autouse=True) -def do_something(): +def setup_test_environment(): + cudaq.__clearKernelRegistries() cudaq.set_target("braket") yield "Running the tests." - cudaq.__clearKernelRegistries() cudaq.reset_target() diff --git a/python/tests/backends/test_resource_counter.py b/python/tests/backends/test_resource_counter.py index 5f63820e922..23b5fec2314 100644 --- a/python/tests/backends/test_resource_counter.py +++ b/python/tests/backends/test_resource_counter.py @@ -13,9 +13,8 @@ @pytest.fixture(scope="session", autouse=True) def clean(): cudaq.reset_target() - yield "Running the tests." - + cudaq.__clearKernelRegistries() cudaq.reset_target() diff --git a/python/tests/backends/test_stim.py b/python/tests/backends/test_stim.py index 53b549a2fa7..54a0f471296 100644 --- a/python/tests/backends/test_stim.py +++ b/python/tests/backends/test_stim.py @@ -8,10 +8,10 @@ import os from typing import List -import pytest import cudaq import numpy as np +import pytest @pytest.fixture(scope="session", autouse=True) diff --git a/python/tests/builder/test_NoiseModel.py b/python/tests/builder/test_NoiseModel.py index 33f1d2dfb44..36901503096 100644 --- a/python/tests/builder/test_NoiseModel.py +++ b/python/tests/builder/test_NoiseModel.py @@ -7,12 +7,17 @@ # ============================================================================ # import os +import random -import pytest +import cudaq import numpy as np +import pytest -import cudaq -import random + +@pytest.fixture(autouse=True) +def setup_test_environment(): + cudaq.__clearKernelRegistries() + yield @pytest.mark.parametrize('target', ['density-matrix-cpu', 'stim']) diff --git a/python/tests/builder/test_cupy_integration.py b/python/tests/builder/test_cupy_integration.py index 88e7daeeeb3..bd3ee166185 100644 --- a/python/tests/builder/test_cupy_integration.py +++ b/python/tests/builder/test_cupy_integration.py @@ -7,10 +7,9 @@ # ============================================================================ # import os -import pytest -import numpy as np - import cudaq +import numpy as np +import pytest cp = pytest.importorskip('cupy') @@ -18,6 +17,12 @@ pytest.skip("Skipping GPU tests", allow_module_level=True) +@pytest.fixture(autouse=True) +def setup_test_environment(): + cudaq.__clearKernelRegistries() + yield + + def assert_close(want, got, tolerance=1.e-5) -> bool: return abs(want - got) < tolerance diff --git a/python/tests/builder/test_kernel_builder.py b/python/tests/builder/test_kernel_builder.py index 455a4cc436d..93da8277d70 100644 --- a/python/tests/builder/test_kernel_builder.py +++ b/python/tests/builder/test_kernel_builder.py @@ -9,16 +9,22 @@ # This file is responsible for testing the accuracy of gates within # the kernel builder. -import pytest -import random -import numpy as np import os +import random from typing import List import cudaq +import numpy as np +import pytest from cudaq import spin +@pytest.fixture(autouse=True) +def setup_test_environment(): + cudaq.__clearKernelRegistries() + yield + + def test_sdg_0_state(): """Tests the adjoint S-gate on a qubit starting in the 0-state.""" kernel = cudaq.make_kernel() diff --git a/python/tests/builder/test_observe.py b/python/tests/builder/test_observe.py index 0074d16d035..31626bed8ad 100644 --- a/python/tests/builder/test_observe.py +++ b/python/tests/builder/test_observe.py @@ -7,13 +7,18 @@ # ============================================================================ # import os -import pytest -import numpy as np - import cudaq +import numpy as np +import pytest from cudaq import spin +@pytest.fixture(autouse=True) +def setup_test_environment(): + cudaq.__clearKernelRegistries() + yield + + def assert_close(want, got, tolerance=1.e-4) -> bool: return abs(want - got) < tolerance diff --git a/python/tests/builder/test_optimizer.py b/python/tests/builder/test_optimizer.py index 9819c674dd4..00491e09ffd 100644 --- a/python/tests/builder/test_optimizer.py +++ b/python/tests/builder/test_optimizer.py @@ -5,13 +5,18 @@ # This source code and the accompanying materials are made available under # # the terms of the Apache License 2.0 which accompanies this distribution. # # ============================================================================ # -import os import math +import os +from typing import Callable, List, Tuple +import cudaq import pytest -from typing import List, Tuple, Callable -import cudaq + +@pytest.fixture(autouse=True) +def setup_test_environment(): + cudaq.__clearKernelRegistries() + yield # Helper function for asserting two values are within a diff --git a/python/tests/builder/test_qalloc_init.py b/python/tests/builder/test_qalloc_init.py index df50c8eded1..0e22466b243 100644 --- a/python/tests/builder/test_qalloc_init.py +++ b/python/tests/builder/test_qalloc_init.py @@ -5,10 +5,9 @@ # This source code and the accompanying materials are made available under # # the terms of the Apache License 2.0 which accompanies this distribution. # # ============================================================================ # -import pytest - import cudaq import numpy as np +import pytest skipIfNvidiaFP64NotInstalled = pytest.mark.skipif( not (cudaq.num_available_gpus() > 0 and cudaq.has_target('nvidia-fp64')), @@ -18,6 +17,13 @@ not (cudaq.num_available_gpus() > 0 and cudaq.has_target('nvidia')), reason='Could not find nvidia in installation') + +@pytest.fixture(autouse=True) +def setup_test_environment(): + cudaq.__clearKernelRegistries() + yield + + # float diff --git a/python/tests/builder/test_qalloc_init_state.py b/python/tests/builder/test_qalloc_init_state.py index d50fa473e83..26dd92e38da 100644 --- a/python/tests/builder/test_qalloc_init_state.py +++ b/python/tests/builder/test_qalloc_init_state.py @@ -5,10 +5,9 @@ # This source code and the accompanying materials are made available under # # the terms of the Apache License 2.0 which accompanies this distribution. # # ============================================================================ # -import pytest -import numpy as np - import cudaq +import numpy as np +import pytest skipIfNvidiaFP64NotInstalled = pytest.mark.skipif( not (cudaq.num_available_gpus() > 0 and cudaq.has_target('nvidia-fp64')), @@ -19,6 +18,12 @@ reason='Could not find nvidia in installation') +@pytest.fixture(autouse=True) +def setup_test_environment(): + cudaq.__clearKernelRegistries() + yield + + def assert_close(want, got, tolerance=1.e-5) -> bool: return abs(want - got) < tolerance diff --git a/python/tests/builder/test_qpp_target.py b/python/tests/builder/test_qpp_target.py index fdbe48bc10f..168f84f6d72 100644 --- a/python/tests/builder/test_qpp_target.py +++ b/python/tests/builder/test_qpp_target.py @@ -7,6 +7,13 @@ # ============================================================================ # import cudaq +import pytest + + +@pytest.fixture(autouse=True) +def setup_test_environment(): + cudaq.__clearKernelRegistries() + yield def test_cpu_only_target(): diff --git a/python/tests/builder/test_quake_value.py b/python/tests/builder/test_quake_value.py index a5775034bee..94a62e855ff 100644 --- a/python/tests/builder/test_quake_value.py +++ b/python/tests/builder/test_quake_value.py @@ -6,10 +6,15 @@ # the terms of the Apache License 2.0 which accompanies this distribution. # # ============================================================================ # -import pytest - import cudaq import numpy as np +import pytest + + +@pytest.fixture(autouse=True) +def setup_test_environment(): + cudaq.__clearKernelRegistries() + yield @pytest.mark.parametrize("type_", [float, int]) diff --git a/python/tests/builder/test_sample.py b/python/tests/builder/test_sample.py index c1daf92d7f0..ad71572149e 100644 --- a/python/tests/builder/test_sample.py +++ b/python/tests/builder/test_sample.py @@ -8,13 +8,18 @@ import os -import pytest -import numpy as np - import cudaq +import numpy as np +import pytest from cudaq import spin +@pytest.fixture(autouse=True) +def setup_test_environment(): + cudaq.__clearKernelRegistries() + yield + + @pytest.mark.parametrize("qubit_count", [1, 5, 9]) @pytest.mark.parametrize("shots_count", [10, 100, 1000]) def test_sample_result_single_register(qubit_count, shots_count): diff --git a/python/tests/builder/test_state.py b/python/tests/builder/test_state.py index 6f0712af65e..d6dabeab1ae 100644 --- a/python/tests/builder/test_state.py +++ b/python/tests/builder/test_state.py @@ -7,10 +7,15 @@ # ============================================================================ # import os -import pytest +import cudaq import numpy as np +import pytest -import cudaq + +@pytest.fixture(autouse=True) +def setup_test_environment(): + cudaq.__clearKernelRegistries() + yield def assert_close(want, got, tolerance=1.e-5) -> bool: diff --git a/python/tests/builder/test_vqe.py b/python/tests/builder/test_vqe.py index 829bc06a513..8b34c2b1470 100644 --- a/python/tests/builder/test_vqe.py +++ b/python/tests/builder/test_vqe.py @@ -8,12 +8,17 @@ import os -import pytest - import cudaq +import pytest from cudaq import spin +@pytest.fixture(autouse=True) +def setup_test_environment(): + cudaq.__clearKernelRegistries() + yield + + # Helper function for asserting two values are within a # certain tolerance. If we make numpy a dependency, # this may be replaced in the future with `np.allclose`. diff --git a/python/tests/custom/test_custom_operations.py b/python/tests/custom/test_custom_operations.py index 454196f1fd6..6aba73c4e04 100644 --- a/python/tests/custom/test_custom_operations.py +++ b/python/tests/custom/test_custom_operations.py @@ -6,17 +6,16 @@ # the terms of the Apache License 2.0 which accompanies this distribution. # # ============================================================================ # -import pytest -import numpy as np import cudaq +import numpy as np +import pytest @pytest.fixture(autouse=True) -def do_something(): +def setup_test_environment(): + cudaq.__clearKernelRegistries() cudaq.reset_target() yield - ## Ref: https://github.com/NVIDIA/cuda-quantum/issues/1954 - # cudaq.__clearKernelRegistries() def check_bell(entity): diff --git a/python/tests/custom/test_euler_decomposition.py b/python/tests/custom/test_euler_decomposition.py index 37da2211c17..1028039a523 100644 --- a/python/tests/custom/test_euler_decomposition.py +++ b/python/tests/custom/test_euler_decomposition.py @@ -6,10 +6,9 @@ # the terms of the Apache License 2.0 which accompanies this distribution. # # ============================================================================ # -import pytest -import numpy as np - import cudaq +import numpy as np +import pytest ## NOTE: The random operations in this file are generated using # `scipy.stats.unitary_group.rvs(2)` with `seed=13`. The synthesized @@ -21,6 +20,12 @@ # generated. +@pytest.fixture(autouse=True) +def setup_test_environment(): + cudaq.__clearKernelRegistries() + yield + + def check_state(matrix, state): # state must match the first column of the custom unitary matrix assert np.isclose(matrix[0][0], state[0]) diff --git a/python/tests/custom/test_kak_decomposition.py b/python/tests/custom/test_kak_decomposition.py index 96cf5a2afe3..933f8a6087b 100644 --- a/python/tests/custom/test_kak_decomposition.py +++ b/python/tests/custom/test_kak_decomposition.py @@ -6,10 +6,9 @@ # the terms of the Apache License 2.0 which accompanies this distribution. # # ============================================================================ # -import pytest -import numpy as np - import cudaq +import numpy as np +import pytest ## NOTE: The random operations in this file are generated using # `scipy.stats.unitary_group.rvs(4)` with `seed=13`. The synthesized @@ -18,6 +17,12 @@ # in the `test/Transforms/UnitarySynthesis/random_unitary_*` tests. +@pytest.fixture(autouse=True) +def setup_test_environment(): + cudaq.__clearKernelRegistries() + yield + + def check_state(matrix, state): # state must match the first column of the custom unitary matrix assert np.isclose(matrix[:, 0], np.array(state), atol=1e-8).all() diff --git a/python/tests/domains/test_chemistry.py b/python/tests/domains/test_chemistry.py index 5f0123c1dd8..996e3f527a9 100644 --- a/python/tests/domains/test_chemistry.py +++ b/python/tests/domains/test_chemistry.py @@ -7,14 +7,20 @@ # ============================================================================ # import os -import pytest +import cudaq import numpy as np +import pytest from numpy import linalg as LA -import cudaq openfermion_pyscf = pytest.importorskip('openfermionpyscf') +@pytest.fixture(autouse=True) +def setup_test_environment(): + cudaq.__clearKernelRegistries() + yield + + def test_HamiltonianGenH2Sto3g(): geometry = [('H', (0., 0., 0.)), ('H', (0., 0., .7474))] diff --git a/python/tests/domains/test_qnn.py b/python/tests/domains/test_qnn.py index 61660338bb2..d9dd51bbfc4 100644 --- a/python/tests/domains/test_qnn.py +++ b/python/tests/domains/test_qnn.py @@ -7,16 +7,21 @@ # ============================================================================ # import os -import pytest -import numpy as np - import cudaq +import numpy as np +import pytest skipIfNoMQPU = pytest.mark.skipif( not (cudaq.num_available_gpus() > 0 and cudaq.has_target('nvidia-mqpu')), reason="nvidia-mqpu backend not available") +@pytest.fixture(autouse=True) +def setup_test_environment(): + cudaq.__clearKernelRegistries() + yield + + def test_simpleObserveN_QNN(): qubit_count = 2 samples_count = 5000 diff --git a/python/tests/dynamics/integrators/test_evolve_dynamics_torch_integrators.py b/python/tests/dynamics/integrators/test_evolve_dynamics_torch_integrators.py index a5913cd2c56..86302bb7557 100644 --- a/python/tests/dynamics/integrators/test_evolve_dynamics_torch_integrators.py +++ b/python/tests/dynamics/integrators/test_evolve_dynamics_torch_integrators.py @@ -5,10 +5,11 @@ # This source code and the accompanying materials are made available under # # the terms of the Apache License 2.0 which accompanies this distribution. # # ============================================================================ # -import pytest -import cudaq import os +import cudaq +import pytest + torch = pytest.importorskip("torch") # Note: the test model may create state, hence need to set the target to "dynamics" @@ -21,7 +22,7 @@ @pytest.fixture(autouse=True) -def do_something(): +def setup_test_environment(): cudaq.set_target("dynamics") yield cudaq.reset_target() diff --git a/python/tests/dynamics/test_evolve_dynamics.py b/python/tests/dynamics/test_evolve_dynamics.py index c7aad84daf4..586a404434c 100644 --- a/python/tests/dynamics/test_evolve_dynamics.py +++ b/python/tests/dynamics/test_evolve_dynamics.py @@ -5,9 +5,11 @@ # This source code and the accompanying materials are made available under # # the terms of the Apache License 2.0 which accompanies this distribution. # # ============================================================================ # -import os, pytest +import os + import cudaq -from cudaq import operators, boson +import pytest +from cudaq import boson, operators if cudaq.num_available_gpus() == 0: pytest.skip("Skipping GPU tests", allow_module_level=True) @@ -18,7 +20,7 @@ @pytest.fixture(autouse=True) -def do_something(): +def setup_test_environment(): cudaq.set_target("dynamics") yield cudaq.reset_target() diff --git a/python/tests/dynamics/test_evolve_simulators.py b/python/tests/dynamics/test_evolve_simulators.py index a12eb69be51..97ce1a4c703 100644 --- a/python/tests/dynamics/test_evolve_simulators.py +++ b/python/tests/dynamics/test_evolve_simulators.py @@ -7,15 +7,15 @@ # ============================================================================ # import os -import pytest import cudaq -from cudaq.operators import * -from cudaq.dynamics import * import numpy as np +import pytest +from cudaq.dynamics import * +from cudaq.operators import * @pytest.fixture(autouse=True) -def do_something(): +def setup_test_environment(): cudaq.set_target("density-matrix-cpu") yield cudaq.reset_target() diff --git a/python/tests/handlers/test_photonics_kernel.py b/python/tests/handlers/test_photonics_kernel.py index f6fa626b916..8b6a474b703 100644 --- a/python/tests/handlers/test_photonics_kernel.py +++ b/python/tests/handlers/test_photonics_kernel.py @@ -6,19 +6,18 @@ # the terms of the Apache License 2.0 which accompanies this distribution. # # ============================================================================ # -import pytest - from typing import List import cudaq +import pytest @pytest.fixture(autouse=True) -def do_something(): +def setup_test_environment(): + cudaq.__clearKernelRegistries() cudaq.set_target("orca-photonics") yield cudaq.reset_target() - cudaq.__clearKernelRegistries() def test_qudit(): diff --git a/python/tests/interop/test_interop.py b/python/tests/interop/test_interop.py index e63588408ac..13d6474deb5 100644 --- a/python/tests/interop/test_interop.py +++ b/python/tests/interop/test_interop.py @@ -6,15 +6,16 @@ # the terms of the Apache License 2.0 which accompanies this distribution. # # ============================================================================ # -import cudaq, pytest +import cudaq +import pytest cudaq_test_cpp_algo = pytest.importorskip('cudaq_test_cpp_algo') @pytest.fixture(autouse=True) -def do_something(): - yield +def setup_test_environment(): cudaq.__clearKernelRegistries() + yield def test_call_python_from_cpp(): diff --git a/python/tests/kernel/test_adjoint_operations.py b/python/tests/kernel/test_adjoint_operations.py index 877ac4bdf80..44195b5e70d 100644 --- a/python/tests/kernel/test_adjoint_operations.py +++ b/python/tests/kernel/test_adjoint_operations.py @@ -7,9 +7,16 @@ # ============================================================================ # import cudaq +import pytest from cudaq import spin +@pytest.fixture(autouse=True) +def setup_test_environment(): + cudaq.__clearKernelRegistries() + yield + + def test_sdg_0_state(): """Tests the adjoint S-gate on a qubit starting in the 0-state.""" diff --git a/python/tests/kernel/test_ast_compare.py b/python/tests/kernel/test_ast_compare.py index e6f9f4b492e..deb60e53802 100644 --- a/python/tests/kernel/test_ast_compare.py +++ b/python/tests/kernel/test_ast_compare.py @@ -7,8 +7,9 @@ # ============================================================================ # import os -import pytest + import cudaq +import pytest def cmpfop(predicate, left, right): diff --git a/python/tests/kernel/test_cast_kernel.py b/python/tests/kernel/test_cast_kernel.py index 2641742a04d..8a4309617cd 100644 --- a/python/tests/kernel/test_cast_kernel.py +++ b/python/tests/kernel/test_cast_kernel.py @@ -11,6 +11,12 @@ import pytest +@pytest.fixture(autouse=True) +def setup_test_environment(): + cudaq.__clearKernelRegistries() + yield + + # bool <-> int32 def testBoolInt32(): diff --git a/python/tests/kernel/test_control_operations.py b/python/tests/kernel/test_control_operations.py index 977967df971..46e2a5e71bf 100644 --- a/python/tests/kernel/test_control_operations.py +++ b/python/tests/kernel/test_control_operations.py @@ -6,12 +6,18 @@ # the terms of the Apache License 2.0 which accompanies this distribution. # # ============================================================================ # -import numpy as np - import cudaq +import numpy as np +import pytest from cudaq import spin +@pytest.fixture(autouse=True) +def setup_test_environment(): + cudaq.__clearKernelRegistries() + yield + + def test_ctrl_x(): """Tests the accuracy of the overloads for the controlled-X gate.""" diff --git a/python/tests/kernel/test_direct_call_return_kernel.py b/python/tests/kernel/test_direct_call_return_kernel.py index c977b14459c..8ec189f88e9 100644 --- a/python/tests/kernel/test_direct_call_return_kernel.py +++ b/python/tests/kernel/test_direct_call_return_kernel.py @@ -27,9 +27,9 @@ def is_close_array(actual, expected): @pytest.fixture(autouse=True) -def do_something(): - yield +def setup_test_environment(): cudaq.__clearKernelRegistries() + yield def test_return_bool(): diff --git a/python/tests/kernel/test_explicit_measurements.py b/python/tests/kernel/test_explicit_measurements.py index d14b764570e..d4528eb45ea 100644 --- a/python/tests/kernel/test_explicit_measurements.py +++ b/python/tests/kernel/test_explicit_measurements.py @@ -6,10 +6,11 @@ # the terms of the Apache License 2.0 which accompanies this distribution. # # ============================================================================ # -import cudaq -import pytest import os + +import cudaq import numpy as np +import pytest skipIfBraketNotInstalled = pytest.mark.skipif( not (cudaq.has_target("braket")), @@ -17,10 +18,10 @@ @pytest.fixture(autouse=True) -def do_something(): +def setup_test_environment(): + cudaq.__clearKernelRegistries() cudaq.reset_target() yield - cudaq.__clearKernelRegistries() cudaq.reset_target() diff --git a/python/tests/kernel/test_get_unitary.py b/python/tests/kernel/test_get_unitary.py index 36b189d32b4..49c44621dcf 100644 --- a/python/tests/kernel/test_get_unitary.py +++ b/python/tests/kernel/test_get_unitary.py @@ -5,10 +5,18 @@ # This source code and the accompanying materials are made available under # # the terms of the Apache License 2.0 which accompanies this distribution. # # ============================================================================ # -import pytest + +import cudaq import numpy as np +import pytest from scipy.linalg import block_diag -import cudaq + + +@pytest.fixture(autouse=True) +def setup_test_environment(): + cudaq.__clearKernelRegistries() + yield + H = (1 / np.sqrt(2)) * np.array([[1, 1], [1, -1]], dtype=np.complex128) X = np.array([[0, 1], [1, 0]], dtype=np.complex128) diff --git a/python/tests/kernel/test_ir_operations.py b/python/tests/kernel/test_ir_operations.py index c39f3cfc09c..4d1b5b0a515 100644 --- a/python/tests/kernel/test_ir_operations.py +++ b/python/tests/kernel/test_ir_operations.py @@ -5,19 +5,19 @@ # This source code and the accompanying materials are made available under # # the terms of the Apache License 2.0 which accompanies this distribution. # # ============================================================================ # -import pytest -import numpy as np import sys from typing import List import cudaq +import numpy as np +import pytest from cudaq import spin @pytest.fixture(autouse=True) -def do_something(): - yield +def setup_test_environment(): cudaq.__clearKernelRegistries() + yield def test_synthesize(): diff --git a/python/tests/kernel/test_kernel_call_return.py b/python/tests/kernel/test_kernel_call_return.py index 26eff86f752..c6c12ac4ea1 100644 --- a/python/tests/kernel/test_kernel_call_return.py +++ b/python/tests/kernel/test_kernel_call_return.py @@ -7,6 +7,13 @@ # ============================================================================ # import cudaq +import pytest + + +@pytest.fixture(autouse=True) +def setup_test_environment(): + cudaq.__clearKernelRegistries() + yield def test_call_with_callee_return_bool(): diff --git a/python/tests/kernel/test_kernel_complex.py b/python/tests/kernel/test_kernel_complex.py index dabf268de80..01b3ecf7c14 100644 --- a/python/tests/kernel/test_kernel_complex.py +++ b/python/tests/kernel/test_kernel_complex.py @@ -8,10 +8,15 @@ import sys -import pytest +import cudaq import numpy as np +import pytest -import cudaq + +@pytest.fixture(autouse=True) +def setup_test_environment(): + cudaq.__clearKernelRegistries() + yield def is_close(expected, actual): diff --git a/python/tests/kernel/test_kernel_exp_pauli.py b/python/tests/kernel/test_kernel_exp_pauli.py index a8c5584a9a3..d5a258e972b 100644 --- a/python/tests/kernel/test_kernel_exp_pauli.py +++ b/python/tests/kernel/test_kernel_exp_pauli.py @@ -7,6 +7,13 @@ # ============================================================================ # import cudaq +import pytest + + +@pytest.fixture(autouse=True) +def setup_test_environment(): + cudaq.__clearKernelRegistries() + yield def test_exp_pauli(): diff --git a/python/tests/kernel/test_kernel_features.py b/python/tests/kernel/test_kernel_features.py index ad0adce288a..badc3d49450 100644 --- a/python/tests/kernel/test_kernel_features.py +++ b/python/tests/kernel/test_kernel_features.py @@ -7,20 +7,19 @@ # ============================================================================ # import os - -import pytest -import numpy as np -from typing import Callable, List import sys +from typing import Callable, List import cudaq +import numpy as np +import pytest from cudaq import spin @pytest.fixture(autouse=True) -def do_something(): - yield +def setup_test_environment(): cudaq.__clearKernelRegistries() + yield def test_argument_int(): @@ -2025,6 +2024,7 @@ def run(): def test_disallow_hybrid_types(): from dataclasses import dataclass + # Ensure we don't allow hybrid type s @dataclass(slots=True) class hybrid: @@ -2051,6 +2051,7 @@ def testtest(h: hybrid): def test_disallow_quantum_struct_return(): from dataclasses import dataclass + # Ensure we don't allow hybrid type s @dataclass(slots=True) class T: diff --git a/python/tests/kernel/test_kernel_float.py b/python/tests/kernel/test_kernel_float.py index f580807aa37..dd11d17c19f 100644 --- a/python/tests/kernel/test_kernel_float.py +++ b/python/tests/kernel/test_kernel_float.py @@ -8,10 +8,15 @@ import sys -import pytest +import cudaq import numpy as np +import pytest -import cudaq + +@pytest.fixture(autouse=True) +def setup_test_environment(): + cudaq.__clearKernelRegistries() + yield def is_close(expected, actual) -> bool: diff --git a/python/tests/kernel/test_kernel_parameters.py b/python/tests/kernel/test_kernel_parameters.py index a7d61c87086..82008321334 100644 --- a/python/tests/kernel/test_kernel_parameters.py +++ b/python/tests/kernel/test_kernel_parameters.py @@ -7,20 +7,19 @@ # ============================================================================ # import os - -import pytest -import numpy as np -from typing import Callable, List import sys +from typing import Callable, List import cudaq +import numpy as np +import pytest from cudaq import spin @pytest.fixture(autouse=True) -def do_something(): - yield +def setup_test_environment(): cudaq.__clearKernelRegistries() + yield def test_list_bool(): diff --git a/python/tests/kernel/test_kernel_qvector_init.py b/python/tests/kernel/test_kernel_qvector_init.py index 63f358b4ab1..51ef4bf0e9c 100644 --- a/python/tests/kernel/test_kernel_qvector_init.py +++ b/python/tests/kernel/test_kernel_qvector_init.py @@ -7,10 +7,10 @@ # ============================================================================ # import sys -import pytest import cudaq import numpy as np +import pytest skipIfNvidiaFP64NotInstalled = pytest.mark.skipif( not (cudaq.num_available_gpus() > 0 and cudaq.has_target('nvidia-fp64')), @@ -21,6 +21,12 @@ reason='Could not find nvidia in installation') +@pytest.fixture(autouse=True) +def setup_test_environment(): + cudaq.__clearKernelRegistries() + yield + + def swap(arr, index1, index2): t = arr[index2] arr[index2] = arr[index1] diff --git a/python/tests/kernel/test_kernel_qvector_state_init.py b/python/tests/kernel/test_kernel_qvector_state_init.py index fbc703fe372..9a5819fa5e4 100644 --- a/python/tests/kernel/test_kernel_qvector_state_init.py +++ b/python/tests/kernel/test_kernel_qvector_state_init.py @@ -5,10 +5,9 @@ # This source code and the accompanying materials are made available under # # the terms of the Apache License 2.0 which accompanies this distribution. # # ============================================================================ # -import pytest - import cudaq import numpy as np +import pytest skipIfNvidiaFP64NotInstalled = pytest.mark.skipif( not (cudaq.num_available_gpus() > 0 and cudaq.has_target('nvidia-fp64')), @@ -18,6 +17,13 @@ not (cudaq.num_available_gpus() > 0 and cudaq.has_target('nvidia')), reason='Could not find nvidia in installation') + +@pytest.fixture(autouse=True) +def setup_test_environment(): + cudaq.__clearKernelRegistries() + yield + + # synthesis diff --git a/python/tests/kernel/test_kernel_qview.py b/python/tests/kernel/test_kernel_qview.py index 69d639fefaf..763128bca3c 100644 --- a/python/tests/kernel/test_kernel_qview.py +++ b/python/tests/kernel/test_kernel_qview.py @@ -6,8 +6,14 @@ # the terms of the Apache License 2.0 which accompanies this distribution. # # ============================================================================ # -import pytest import cudaq +import pytest + + +@pytest.fixture(autouse=True) +def setup_test_environment(): + cudaq.__clearKernelRegistries() + yield def test_qview_zero_length(): diff --git a/python/tests/kernel/test_kernel_return.py b/python/tests/kernel/test_kernel_return.py index 259a32095dc..5de6b6931a9 100644 --- a/python/tests/kernel/test_kernel_return.py +++ b/python/tests/kernel/test_kernel_return.py @@ -6,11 +6,17 @@ # the terms of the Apache License 2.0 which accompanies this distribution. # # ============================================================================ # -import pytest -import numpy as np import sys import cudaq +import numpy as np +import pytest + + +@pytest.fixture(autouse=True) +def setup_test_environment(): + cudaq.__clearKernelRegistries() + yield def test_return_float_param(): diff --git a/python/tests/kernel/test_kernel_shift_operators.py b/python/tests/kernel/test_kernel_shift_operators.py index 2e7e487196c..20dbc9730c4 100644 --- a/python/tests/kernel/test_kernel_shift_operators.py +++ b/python/tests/kernel/test_kernel_shift_operators.py @@ -7,10 +7,17 @@ # ============================================================================ # import os + import cudaq import pytest +@pytest.fixture(autouse=True) +def setup_test_environment(): + cudaq.__clearKernelRegistries() + yield + + def test_integer_left_shift(): @cudaq.kernel diff --git a/python/tests/kernel/test_kernel_translate.py b/python/tests/kernel/test_kernel_translate.py index 83eb4edd1b2..7feb4e4973d 100644 --- a/python/tests/kernel/test_kernel_translate.py +++ b/python/tests/kernel/test_kernel_translate.py @@ -6,10 +6,15 @@ # the terms of the Apache License 2.0 which accompanies this distribution. # # ============================================================================ # -import pytest import cudaq - import numpy as np +import pytest + + +@pytest.fixture(autouse=True) +def setup_test_environment(): + cudaq.__clearKernelRegistries() + yield @cudaq.kernel diff --git a/python/tests/kernel/test_kernel_uccsd.py b/python/tests/kernel/test_kernel_uccsd.py index 4b608a9eccb..7675e752099 100644 --- a/python/tests/kernel/test_kernel_uccsd.py +++ b/python/tests/kernel/test_kernel_uccsd.py @@ -6,8 +6,8 @@ # the terms of the Apache License 2.0 which accompanies this distribution. # # ============================================================================ # -import pytest import cudaq +import pytest # Use a snapshot of the uccsd.py to make sure we can compile diff --git a/python/tests/kernel/test_library_kernels.py b/python/tests/kernel/test_library_kernels.py index 3d086e37277..effc6dfd3f9 100644 --- a/python/tests/kernel/test_library_kernels.py +++ b/python/tests/kernel/test_library_kernels.py @@ -6,16 +6,15 @@ # the terms of the Apache License 2.0 which accompanies this distribution. # # ============================================================================ # -import pytest -import numpy as np - import cudaq +import numpy as np +import pytest @pytest.fixture(autouse=True) -def do_something(): - yield +def setup_test_environment(): cudaq.__clearKernelRegistries() + yield def test_internal_library_kernels(): diff --git a/python/tests/kernel/test_observe_kernel.py b/python/tests/kernel/test_observe_kernel.py index e4a8a0d8cb9..3ae9f296806 100644 --- a/python/tests/kernel/test_observe_kernel.py +++ b/python/tests/kernel/test_observe_kernel.py @@ -6,20 +6,20 @@ # the terms of the Apache License 2.0 which accompanies this distribution. # # ============================================================================ # -import sys, random - -import pytest -import numpy as np +import random +import sys from typing import List import cudaq +import numpy as np +import pytest from cudaq import spin @pytest.fixture(autouse=True) -def do_something(): - yield +def setup_test_environment(): cudaq.__clearKernelRegistries() + yield def test_simple_observe(): diff --git a/python/tests/kernel/test_run_async_kernel.py b/python/tests/kernel/test_run_async_kernel.py index c95cccc5336..4223f15de97 100644 --- a/python/tests/kernel/test_run_async_kernel.py +++ b/python/tests/kernel/test_run_async_kernel.py @@ -30,9 +30,9 @@ def is_close_array(actual, expected): @pytest.fixture(autouse=True) -def do_something(): - yield +def setup_test_environment(): cudaq.__clearKernelRegistries() + yield @cudaq.kernel diff --git a/python/tests/kernel/test_run_kernel.py b/python/tests/kernel/test_run_kernel.py index a01ea5f25f9..d6e533b6454 100644 --- a/python/tests/kernel/test_run_kernel.py +++ b/python/tests/kernel/test_run_kernel.py @@ -7,11 +7,11 @@ # ============================================================================ # import os +import warnings from dataclasses import dataclass import cudaq import numpy as np -import warnings import pytest list_err_msg = 'does not yet support returning `list` from entry-point kernels' @@ -34,9 +34,9 @@ def is_close_array(actual, expected): @pytest.fixture(autouse=True) -def do_something(): - yield +def setup_test_environment(): cudaq.__clearKernelRegistries() + yield @cudaq.kernel diff --git a/python/tests/kernel/test_sample_kernel.py b/python/tests/kernel/test_sample_kernel.py index 03d531ddc8b..990e7e14580 100644 --- a/python/tests/kernel/test_sample_kernel.py +++ b/python/tests/kernel/test_sample_kernel.py @@ -6,19 +6,19 @@ # the terms of the Apache License 2.0 which accompanies this distribution. # # ============================================================================ # -import sys, os - -import pytest -import numpy as np +import os +import sys from typing import Callable, List import cudaq +import numpy as np +import pytest @pytest.fixture(autouse=True) -def do_something(): - yield +def setup_test_environment(): cudaq.__clearKernelRegistries() + yield def test_simple_sampling_ghz(): diff --git a/python/tests/kernel/test_state_kernel.py b/python/tests/kernel/test_state_kernel.py index 476e1c63597..5ef5c86ff34 100644 --- a/python/tests/kernel/test_state_kernel.py +++ b/python/tests/kernel/test_state_kernel.py @@ -6,12 +6,12 @@ # the terms of the Apache License 2.0 which accompanies this distribution. # # ============================================================================ # -import pytest -import numpy as np import sys from typing import List import cudaq +import numpy as np +import pytest skipIfNoGQPU = pytest.mark.skipif( not (cudaq.num_available_gpus() > 0 and cudaq.has_target('nvidia')), @@ -19,9 +19,9 @@ @pytest.fixture(autouse=True) -def do_something(): - yield +def setup_test_environment(): cudaq.__clearKernelRegistries() + yield @skipIfNoGQPU diff --git a/python/tests/kernel/test_state_mps.py b/python/tests/kernel/test_state_mps.py index 33edb73ac3c..e70712636f6 100644 --- a/python/tests/kernel/test_state_mps.py +++ b/python/tests/kernel/test_state_mps.py @@ -7,11 +7,11 @@ # ============================================================================ # import os -import pytest -import numpy as np import sys import cudaq +import numpy as np +import pytest cp = pytest.importorskip('cupy') @@ -21,9 +21,9 @@ @pytest.fixture(autouse=True) -def do_something(): - yield +def setup_test_environment(): cudaq.__clearKernelRegistries() + yield @skipIfNoGPU diff --git a/python/tests/kernel/test_target_attributes.py b/python/tests/kernel/test_target_attributes.py index a9cdd1d7802..7cbb7989904 100644 --- a/python/tests/kernel/test_target_attributes.py +++ b/python/tests/kernel/test_target_attributes.py @@ -6,8 +6,8 @@ # the terms of the Apache License 2.0 which accompanies this distribution. # # ============================================================================ # -import pytest import cudaq +import pytest skipIfNoGPU = pytest.mark.skipif( not (cudaq.num_available_gpus() > 0 and cudaq.has_target('nvidia')), @@ -15,10 +15,10 @@ @pytest.fixture -def do_something(): +def setup_test_environment(): + cudaq.__clearKernelRegistries() cudaq.set_target("nvidia", option="fp32") yield "Running the tests." - cudaq.__clearKernelRegistries() cudaq.reset_target() diff --git a/python/tests/kernel/test_trotter.py b/python/tests/kernel/test_trotter.py index c103ef36bc4..ecbd1071551 100644 --- a/python/tests/kernel/test_trotter.py +++ b/python/tests/kernel/test_trotter.py @@ -5,10 +5,9 @@ # This source code and the accompanying materials are made available under # # the terms of the Apache License 2.0 which accompanies this distribution. # # ============================================================================ # -import pytest - import cudaq import numpy as np +import pytest skipIfNvidiaFP64NotInstalled = pytest.mark.skipif( not (cudaq.num_available_gpus() > 0 and cudaq.has_target('nvidia-fp64')), @@ -19,6 +18,12 @@ reason='Could not find nvidia in installation') +@pytest.fixture(autouse=True) +def setup_test_environment(): + cudaq.__clearKernelRegistries() + yield + + def trotter(): # Alternating up/down spins diff --git a/python/tests/kernel/test_vqe_kernel.py b/python/tests/kernel/test_vqe_kernel.py index b29afe81148..d1ff054c78e 100644 --- a/python/tests/kernel/test_vqe_kernel.py +++ b/python/tests/kernel/test_vqe_kernel.py @@ -6,13 +6,13 @@ # the terms of the Apache License 2.0 which accompanies this distribution. # # ============================================================================ # -import pytest import sys from typing import List import cudaq -from cudaq import spin import numpy as np +import pytest +from cudaq import spin # Helper function for asserting two values are within a @@ -23,9 +23,9 @@ def assert_close(want, got, tolerance=1.e-4) -> bool: @pytest.fixture(autouse=True) -def do_something(): - yield +def setup_test_environment(): cudaq.__clearKernelRegistries() + yield def test_two_qubit_vqe_float(): diff --git a/python/tests/operator/test_boson_op.py b/python/tests/operator/test_boson_op.py index 4a0a08e0cac..46498a07ae1 100644 --- a/python/tests/operator/test_boson_op.py +++ b/python/tests/operator/test_boson_op.py @@ -6,7 +6,10 @@ # the terms of the Apache License 2.0 which accompanies this distribution. # # ============================================================================ # -import numpy as np, pytest, random +import random + +import numpy as np +import pytest from cudaq import boson from cudaq.operators.boson import * from op_utils import * # test helpers diff --git a/python/tests/operator/test_conversions.py b/python/tests/operator/test_conversions.py index 099797e9229..b0f3f1ecde7 100644 --- a/python/tests/operator/test_conversions.py +++ b/python/tests/operator/test_conversions.py @@ -6,7 +6,11 @@ # the terms of the Apache License 2.0 which accompanies this distribution. # # ============================================================================ # -import cudaq, numpy as np, operator, pytest +import operator + +import cudaq +import numpy as np +import pytest from cudaq import boson, fermion, operators, spin from op_utils import * # test helpers diff --git a/python/tests/operator/test_fermion_op.py b/python/tests/operator/test_fermion_op.py index b6456e030d6..6bb1e2bbde0 100644 --- a/python/tests/operator/test_fermion_op.py +++ b/python/tests/operator/test_fermion_op.py @@ -6,7 +6,10 @@ # the terms of the Apache License 2.0 which accompanies this distribution. # # ============================================================================ # -import numpy as np, pytest, random +import random + +import numpy as np +import pytest from cudaq import fermion from cudaq.operators.fermion import * from op_utils import * # test helpers diff --git a/python/tests/operator/test_matrix_op.py b/python/tests/operator/test_matrix_op.py index 9351ebce215..332496ee244 100644 --- a/python/tests/operator/test_matrix_op.py +++ b/python/tests/operator/test_matrix_op.py @@ -6,7 +6,11 @@ # the terms of the Apache License 2.0 which accompanies this distribution. # # ============================================================================ # -import cmath, numpy as np, pytest, random +import cmath +import random + +import numpy as np +import pytest from cudaq import operators from cudaq.operators import * from op_utils import * # test helpers @@ -16,6 +20,7 @@ def setup(): random.seed(10) yield + cudaq.__clearKernelRegistries() def test_definitions(): diff --git a/python/tests/operator/test_scalar_op.py b/python/tests/operator/test_scalar_op.py index 0cc099887f1..66a98a23a8e 100644 --- a/python/tests/operator/test_scalar_op.py +++ b/python/tests/operator/test_scalar_op.py @@ -6,9 +6,12 @@ # the terms of the Apache License 2.0 which accompanies this distribution. # # ============================================================================ # -import numpy as np, operator, pytest +import operator + +import numpy as np +import pytest +from cudaq import operators, spin from cudaq.operators import ScalarOperator -from cudaq import spin, operators def test_construction(): diff --git a/python/tests/operator/test_spin_op.py b/python/tests/operator/test_spin_op.py index 22ec5b308fd..085beccaa78 100644 --- a/python/tests/operator/test_spin_op.py +++ b/python/tests/operator/test_spin_op.py @@ -6,7 +6,11 @@ # the terms of the Apache License 2.0 which accompanies this distribution. # # ============================================================================ # -import numpy as np, os, pytest, random +import os +import random + +import numpy as np +import pytest from cudaq import spin from cudaq.operators.spin import * from op_utils import * # test helpers diff --git a/python/tests/parallel/test_mpi_api.py b/python/tests/parallel/test_mpi_api.py index 8bdc6eec43e..a62129bf6bb 100644 --- a/python/tests/parallel/test_mpi_api.py +++ b/python/tests/parallel/test_mpi_api.py @@ -6,14 +6,23 @@ # the terms of the Apache License 2.0 which accompanies this distribution. # # ============================================================================ # -import os, pytest, importlib +import importlib +import os + import cudaq +import pytest skipIfUnsupported = pytest.mark.skipif(importlib.util.find_spec('mpi4py') is None, reason="mpi4py not found") +@pytest.fixture(autouse=True) +def setup_test_environment(): + cudaq.__clearKernelRegistries() + yield + + @skipIfUnsupported def testMPI(): cudaq.mpi.initialize() diff --git a/python/tests/parallel/test_mpi_dynamics.py b/python/tests/parallel/test_mpi_dynamics.py index a245dad2575..1a200f7e9f5 100644 --- a/python/tests/parallel/test_mpi_dynamics.py +++ b/python/tests/parallel/test_mpi_dynamics.py @@ -6,9 +6,12 @@ # the terms of the Apache License 2.0 which accompanies this distribution. # # ============================================================================ # -import cudaq, os, pytest -from cudaq import spin, Schedule, RungeKuttaIntegrator +import os + +import cudaq import numpy as np +import pytest +from cudaq import RungeKuttaIntegrator, Schedule, spin skipIfUnsupported = pytest.mark.skipif( not (cudaq.num_available_gpus() > 1 and cudaq.has_target('dynamics')), @@ -16,7 +19,8 @@ @pytest.fixture(autouse=True) -def do_something(): +def setup_test_environment(): + cudaq.__clearKernelRegistries() cudaq.mpi.initialize() cudaq.set_target('dynamics') yield diff --git a/python/tests/parallel/test_mpi_mqpu.py b/python/tests/parallel/test_mpi_mqpu.py index 233af7d387c..762300d1c46 100644 --- a/python/tests/parallel/test_mpi_mqpu.py +++ b/python/tests/parallel/test_mpi_mqpu.py @@ -6,9 +6,12 @@ # the terms of the Apache License 2.0 which accompanies this distribution. # # ============================================================================ # -import cudaq, os, pytest -from cudaq import spin +import os + +import cudaq import numpy as np +import pytest +from cudaq import spin skipIfUnsupported = pytest.mark.skipif( not (cudaq.num_available_gpus() > 0 and cudaq.has_target('nvidia-mqpu')), @@ -23,10 +26,10 @@ def mpi_init_finalize(): @pytest.fixture(autouse=True) -def do_something(): +def setup_test_environment(): + cudaq.__clearKernelRegistries() cudaq.set_target('nvidia-mqpu') yield - cudaq.__clearKernelRegistries() cudaq.reset_target() diff --git a/python/tests/parallel/test_mqpu.py b/python/tests/parallel/test_mqpu.py index 2431193136f..6ce356fa3b4 100644 --- a/python/tests/parallel/test_mqpu.py +++ b/python/tests/parallel/test_mqpu.py @@ -6,9 +6,14 @@ # the terms of the Apache License 2.0 which accompanies this distribution. # # ============================================================================ # -import cudaq, os, pytest, random, timeit -from cudaq import spin +import os +import random +import timeit + +import cudaq import numpy as np +import pytest +from cudaq import spin skipIfNoMQPU = pytest.mark.skipif( not (cudaq.num_available_gpus() > 0 and cudaq.has_target('nvidia-mqpu')), @@ -16,10 +21,10 @@ @pytest.fixture(autouse=True) -def do_something(): +def setup_test_environment(): + cudaq.__clearKernelRegistries() cudaq.set_target('nvidia-mqpu') yield - cudaq.__clearKernelRegistries() cudaq.reset_target() diff --git a/python/tests/remote/test_remote_code_exec.py b/python/tests/remote/test_remote_code_exec.py index 8ff617f15e4..903da5ded10 100644 --- a/python/tests/remote/test_remote_code_exec.py +++ b/python/tests/remote/test_remote_code_exec.py @@ -5,20 +5,19 @@ # This source code and the accompanying materials are made available under # # the terms of the Apache License 2.0 which accompanies this distribution. # # ============================================================================ # -import pytest import os -import sys import subprocess +import sys import time -import numpy as np import cudaq -from cudaq import spin import numpy as np +import pytest +from cudaq import spin try: - import requests import psutil + import requests have_requests = True except ImportError: have_requests = False @@ -108,9 +107,9 @@ def startUpMockServer(): @pytest.fixture(autouse=True) -def do_something(): - yield +def setup_test_environment(): cudaq.__clearKernelRegistries() + yield @skipIfModulesNotInstalled diff --git a/python/tests/remote/test_remote_platform.py b/python/tests/remote/test_remote_platform.py index 30d3c5d8bbf..c796826e81d 100644 --- a/python/tests/remote/test_remote_platform.py +++ b/python/tests/remote/test_remote_platform.py @@ -5,11 +5,13 @@ # This source code and the accompanying materials are made available under # # the terms of the Apache License 2.0 which accompanies this distribution. # # ============================================================================ # -import pytest -import os, math, sys -import numpy as np +import math +import os +import sys import cudaq +import numpy as np +import pytest from cudaq import spin num_qpus = 3 @@ -27,9 +29,9 @@ def startUpMockServer(): @pytest.fixture(autouse=True) -def do_something(): - yield +def setup_test_environment(): cudaq.__clearKernelRegistries() + yield def test_setup(): diff --git a/python/tests/utils/test_set_target_callback.py b/python/tests/utils/test_set_target_callback.py index db3208ba94c..77d61cc2ab9 100644 --- a/python/tests/utils/test_set_target_callback.py +++ b/python/tests/utils/test_set_target_callback.py @@ -6,11 +6,18 @@ # the terms of the Apache License 2.0 which accompanies this distribution. # # ============================================================================ # -import cudaq import os + +import cudaq import pytest +@pytest.fixture(autouse=True) +def setup_test_environment(): + cudaq.__clearKernelRegistries() + yield + + def test_register_callback(): cudaq.set_target("density-matrix-cpu") diff --git a/python/tests/visualization/test_bloch_sphere.py b/python/tests/visualization/test_bloch_sphere.py index f05ae5b9431..2fdc88d194a 100644 --- a/python/tests/visualization/test_bloch_sphere.py +++ b/python/tests/visualization/test_bloch_sphere.py @@ -7,10 +7,10 @@ # ============================================================================ # import os -import pytest -import numpy as np import cudaq +import numpy as np +import pytest qutip = pytest.importorskip("qutip") @@ -19,9 +19,9 @@ @pytest.fixture(autouse=True) -def do_something(): - yield +def setup_test_environment(): cudaq.__clearKernelRegistries() + yield # write sample kernels diff --git a/python/tests/visualization/test_draw.py b/python/tests/visualization/test_draw.py index 33db2632330..212a624fb12 100644 --- a/python/tests/visualization/test_draw.py +++ b/python/tests/visualization/test_draw.py @@ -13,10 +13,10 @@ @pytest.fixture(autouse=True) -def do_something(): +def setup_test_environment(): + cudaq.__clearKernelRegistries() cudaq.reset_target() yield - cudaq.__clearKernelRegistries() def test_draw(): From 3221e3c2f411ee802c57465ef1710d4abb3a671c Mon Sep 17 00:00:00 2001 From: Pradnya Khalate Date: Wed, 10 Sep 2025 16:28:14 -0700 Subject: [PATCH 2/3] * Refactor `uccsd` tests by creating a copy / "fresh" version of the UCCSD module that bypasses kernel registry dependencies, so as to ensure reliable test execution. Signed-off-by: Pradnya Khalate --- python/tests/domains/test_chemistry.py | 63 --- python/tests/domains/test_uccsd.py | 161 +++++++ python/tests/kernel/test_kernel_uccsd.py | 553 ----------------------- python/tests/visualization/test_draw.py | 3 +- 4 files changed, 163 insertions(+), 617 deletions(-) create mode 100644 python/tests/domains/test_uccsd.py delete mode 100644 python/tests/kernel/test_kernel_uccsd.py diff --git a/python/tests/domains/test_chemistry.py b/python/tests/domains/test_chemistry.py index 996e3f527a9..c07437b1bd3 100644 --- a/python/tests/domains/test_chemistry.py +++ b/python/tests/domains/test_chemistry.py @@ -38,37 +38,6 @@ def test_HamiltonianGenH2631g(): assert np.isclose(energy, -1.1516, rtol=1e-3) -def testUCCSD(): - geometry = [('H', (0., 0., 0.)), ('H', (0., 0., .7474))] - molecule, data = cudaq.chemistry.create_molecular_hamiltonian( - geometry, 'sto-3g', 1, 0) - - # Get the number of fermions and orbitals / qubits - numElectrons = data.n_electrons - numQubits = 2 * data.n_orbitals - - from cudaq.kernels import uccsd - - # create the ansatz - kernel, thetas = cudaq.make_kernel(list) - qubits = kernel.qalloc(4) - # hartree fock - kernel.x(qubits[0]) - kernel.x(qubits[1]) - kernel.apply_call(uccsd, qubits, thetas, numElectrons, numQubits) - - num_parameters = cudaq.kernels.uccsd_num_parameters(numElectrons, numQubits) - - # Run VQE - optimizer = cudaq.optimizers.COBYLA() - energy, params = cudaq.vqe(kernel, - molecule, - optimizer, - parameter_count=num_parameters) - print(energy, params) - assert np.isclose(-1.137, energy, rtol=1e-3) - - def testHWE(): geometry = [('H', (0., 0., 0.)), ('H', (0., 0., .7474))] molecule, data = cudaq.chemistry.create_molecular_hamiltonian( @@ -102,38 +71,6 @@ def testHWE(): assert np.isclose(-1.13, energy, rtol=1e-2) -def test_uccsd_kernel(): - - from cudaq.kernels import uccsd - - @cudaq.kernel - def ansatz(thetas: list[float]): #, numElectrons:int, numQubits:int): - q = cudaq.qvector(4) - x(q[0]) - x(q[1]) - uccsd(q, thetas, 2, 4) - - geometry = [('H', (0., 0., 0.)), ('H', (0., 0., .7474))] - molecule, data = cudaq.chemistry.create_molecular_hamiltonian( - geometry, 'sto-3g', 1, 0) - - # Get the number of fermions and orbitals / qubits - numElectrons = data.n_electrons - numQubits = 2 * data.n_orbitals - num_parameters = cudaq.kernels.uccsd_num_parameters(numElectrons, numQubits) - - xInit = [0.0] * num_parameters - - print(cudaq.observe(ansatz, molecule, xInit).expectation()) - - optimizer = cudaq.optimizers.COBYLA() - energy, params = cudaq.vqe(ansatz, - molecule, - optimizer, - parameter_count=num_parameters) - print(energy, params) - - def test_doubles_alpha_bug(): # AST Bridge was not loading pointers # when building lists, hence the following would diff --git a/python/tests/domains/test_uccsd.py b/python/tests/domains/test_uccsd.py new file mode 100644 index 00000000000..b628d7bf673 --- /dev/null +++ b/python/tests/domains/test_uccsd.py @@ -0,0 +1,161 @@ +# ============================================================================ # +# Copyright (c) 2022 - 2025 NVIDIA Corporation & Affiliates. # +# All rights reserved. # +# # +# This source code and the accompanying materials are made available under # +# the terms of the Apache License 2.0 which accompanies this distribution. # +# ============================================================================ # + +import importlib +import os +import shutil +from pathlib import Path + +import cudaq +import numpy as np +import pytest + + +@pytest.fixture(scope="session", autouse=True) +def setup_test_environment(): + """ + Ref: https://github.com/NVIDIA/cuda-quantum/issues/1954 + """ + import cudaq + + if not cudaq.globalAstRegistry: + print("AST registry empty, patching uccsd.") + # Now we make a copy for running the tests + current_dir = Path(__file__).parent # tests/domains directory + src_file = current_dir.parent.parent / "cudaq" / "kernels" / "uccsd.py" + temp_file = Path("/tmp/fresh_uccsd.py") + shutil.copy(src_file, temp_file) + + # Import the module from the temporary file + spec = importlib.util.spec_from_file_location("fresh_uccsd", temp_file) + fresh_uccsd = importlib.util.module_from_spec(spec) + spec.loader.exec_module(fresh_uccsd) + + # Save references to original module functions if they exist + import cudaq.kernels + original_uccsd = getattr(cudaq.kernels, "uccsd", None) + original_num_params = getattr(cudaq.kernels, "uccsd_num_parameters", + None) + + # Patch our fresh functions into cudaq.kernels + cudaq.kernels.uccsd = fresh_uccsd.uccsd + cudaq.kernels.uccsd_num_parameters = fresh_uccsd.uccsd_num_parameters + + # Run the tests + yield + + # Clean up - remove the temporary file + if temp_file.exists(): + os.unlink(temp_file) + + # Restore the original module functions + cudaq.kernels.uccsd = original_uccsd + cudaq.kernels.uccsd_num_parameters = original_num_params + + else: + # When running the tests standalone, this is the path taken. + print("AST registry not empty, skipping uccsd patching.") + yield + + +def test_uccsd_builder(): + from cudaq.kernels import uccsd + + geometry = [('H', (0., 0., 0.)), ('H', (0., 0., .7474))] + molecule, data = cudaq.chemistry.create_molecular_hamiltonian( + geometry, 'sto-3g', 1, 0) + + # Get the number of fermions and orbitals / qubits + numElectrons = data.n_electrons + numQubits = 2 * data.n_orbitals + + # create the ansatz + kernel, thetas = cudaq.make_kernel(list) + qubits = kernel.qalloc(4) + # hartree fock + kernel.x(qubits[0]) + kernel.x(qubits[1]) + kernel.apply_call(uccsd, qubits, thetas, numElectrons, numQubits) + + num_parameters = cudaq.kernels.uccsd_num_parameters(numElectrons, numQubits) + + # Run VQE + optimizer = cudaq.optimizers.COBYLA() + energy, params = cudaq.vqe(kernel, + molecule, + optimizer, + parameter_count=num_parameters) + print(energy, params) + assert np.isclose(-1.137, energy, rtol=1e-3) + + +def test_uccsd_kernel(): + + from cudaq.kernels import uccsd + + @cudaq.kernel + def ansatz(thetas: list[float]): #, numElectrons:int, numQubits:int): + q = cudaq.qvector(4) + x(q[0]) + x(q[1]) + uccsd(q, thetas, 2, 4) + + geometry = [('H', (0., 0., 0.)), ('H', (0., 0., .7474))] + molecule, data = cudaq.chemistry.create_molecular_hamiltonian( + geometry, 'sto-3g', 1, 0) + + # Get the number of fermions and orbitals / qubits + numElectrons = data.n_electrons + numQubits = 2 * data.n_orbitals + num_parameters = cudaq.kernels.uccsd_num_parameters(numElectrons, numQubits) + + xInit = [0.0] * num_parameters + + print(cudaq.observe(ansatz, molecule, xInit).expectation()) + + optimizer = cudaq.optimizers.COBYLA() + energy, params = cudaq.vqe(ansatz, + molecule, + optimizer, + parameter_count=num_parameters) + print(energy, params) + + +def test_uccsd_sample(): + + from cudaq.kernels import uccsd + + num_electrons = 2 + num_qubits = 8 + + thetas = [ + -0.00037043841404585794, 0.0003811110195084151, 0.2286823796532558, + -0.00037043841404585794, 0.0003811110195084151, 0.2286823796532558, + -0.00037043841404585794, 0.0003811110195084151, 0.2286823796532558, + -0.00037043841404585794, 0.0003811110195084151, 0.2286823796532558, + -0.00037043841404585794, 0.0003811110195084151, 0.2286823796532558, + -0.00037043841404585794, 0.0003811110195084151, 0.2286823796532558, + -0.00037043841404585794, 0.0003811110195084151, 0.2286823796532558, + -0.00037043841404585794, 0.0003811110195084151, 0.2286823796532558 + ] + + @cudaq.kernel + def kernel(): + qubits = cudaq.qvector(num_qubits) + for i in range(num_electrons): + x(qubits[i]) + uccsd(qubits, thetas, num_electrons, num_qubits) + + counts = cudaq.sample(kernel, shots_count=1000) + assert len(counts) == 6 + assert '00000011' in counts + assert '00000110' in counts + assert '00010010' in counts + assert '01000010' in counts + assert '10000001' in counts + assert '11000000' in counts diff --git a/python/tests/kernel/test_kernel_uccsd.py b/python/tests/kernel/test_kernel_uccsd.py deleted file mode 100644 index 7675e752099..00000000000 --- a/python/tests/kernel/test_kernel_uccsd.py +++ /dev/null @@ -1,553 +0,0 @@ -# ============================================================================ # -# Copyright (c) 2022 - 2025 NVIDIA Corporation & Affiliates. # -# All rights reserved. # -# # -# This source code and the accompanying materials are made available under # -# the terms of the Apache License 2.0 which accompanies this distribution. # -# ============================================================================ # - -import cudaq -import pytest - - -# Use a snapshot of the uccsd.py to make sure we can compile -# complex code. Importing uccsd from cudaq.kernels fails due -# clearing the caches in the tests. -# Issue: https://github.com/NVIDIA/cuda-quantum/issues/1954 -def test_cudaq_uccsd1(): - - @cudaq.kernel - def single_excitation1(qubits: cudaq.qview, p_occ: int, q_virt: int, - theta: float): - - # Y_p X_q - rx(np.pi / 2.0, qubits[p_occ]) - h(qubits[q_virt]) - - for i in range(p_occ, q_virt): - x.ctrl(qubits[i], qubits[i + 1]) - - rz(0.5 * theta, qubits[q_virt]) - - for i in range(q_virt, p_occ, -1): - x.ctrl(qubits[i - 1], qubits[i]) - - h(qubits[q_virt]) - rx(-np.pi / 2.0, qubits[p_occ]) - - # -X_p Y_q - h(qubits[p_occ]) - rx(np.pi / 2.0, qubits[q_virt]) - - for i in range(p_occ, q_virt): - x.ctrl(qubits[i], qubits[i + 1]) - - rz(-0.5 * theta, qubits[q_virt]) - - for i in range(q_virt, p_occ, -1): - x.ctrl(qubits[i - 1], qubits[i]) - - rx(-np.pi / 2.0, qubits[q_virt]) - h(qubits[p_occ]) - - @cudaq.kernel - def double_excitation_opt1(qubits: cudaq.qview, p_occ: int, q_occ: int, - r_virt: int, s_virt: int, theta: float): - - i_occ = 0 - j_occ = 0 - a_virt = 0 - b_virt = 0 - if (p_occ < q_occ) and (r_virt < s_virt): - i_occ = p_occ - j_occ = q_occ - a_virt = r_virt - b_virt = s_virt - - elif (p_occ > q_occ) and (r_virt > s_virt): - i_occ = q_occ - j_occ = p_occ - a_virt = s_virt - b_virt = r_virt - - elif (p_occ < q_occ) and (r_virt > s_virt): - i_occ = p_occ - j_occ = q_occ - a_virt = s_virt - b_virt = r_virt - # theta *= -1.0 FIXME - theta *= -1. - - elif (p_occ > q_occ) and (r_virt < s_virt): - i_occ = q_occ - j_occ = p_occ - a_virt = r_virt - b_virt = s_virt - theta *= -1.0 - #Block I: x_i x_j x_a y_b + x_i x_j y_a x_b + x_i y_i y_a y_b - x_i y_j x_a x_b - #Block II: - y_i x_j x_a x_b +y_i x_j y_a y_b - y_i x_j x_a x_b - y_i y_j y_a x_b - - h(qubits[i_occ]) - h(qubits[j_occ]) - h(qubits[a_virt]) - rx(np.pi / 2.0, qubits[b_virt]) - - for i in range(i_occ, j_occ): - x.ctrl(qubits[i], qubits[i + 1]) - x.ctrl(qubits[j_occ], qubits[a_virt]) - for i in range(a_virt, b_virt): - x.ctrl(qubits[i], qubits[i + 1]) - - rz(0.125 * theta, qubits[b_virt]) - - for i in range(b_virt, a_virt, -1): - x.ctrl(qubits[i - 1], qubits[i]) - x.ctrl(qubits[j_occ], qubits[a_virt]) - - rx(-np.pi / 2.0, qubits[b_virt]) - h(qubits[a_virt]) - - rx(np.pi / 2.0, qubits[a_virt]) - h(qubits[b_virt]) - - x.ctrl(qubits[j_occ], qubits[a_virt]) - for i in range(a_virt, b_virt): - x.ctrl(qubits[i], qubits[i + 1]) - - rz(0.125 * theta, qubits[b_virt]) - - for i in range(b_virt, a_virt, -1): - x.ctrl(qubits[i - 1], qubits[i]) - x.ctrl(qubits[j_occ], qubits[a_virt]) - for i in range(j_occ, i_occ, -1): - x.ctrl(qubits[i - 1], qubits[i]) - - rx(-np.pi / 2.0, qubits[a_virt]) - h(qubits[j_occ]) - - rx(np.pi / 2.0, qubits[j_occ]) - h(qubits[a_virt]) - - for i in range(i_occ, j_occ): - x.ctrl(qubits[i], qubits[i + 1]) - x.ctrl(qubits[j_occ], qubits[a_virt]) - for i in range(a_virt, b_virt): - x.ctrl(qubits[i], qubits[i + 1]) - - rz(-0.125 * theta, qubits[b_virt]) - - for i in range(b_virt, a_virt, -1): - x.ctrl(qubits[i - 1], qubits[i]) - x.ctrl(qubits[j_occ], qubits[a_virt]) - - h(qubits[b_virt]) - h(qubits[a_virt]) - - rx(np.pi / 2.0, qubits[a_virt]) - rx(np.pi / 2.0, qubits[b_virt]) - - x.ctrl(qubits[j_occ], qubits[a_virt]) - for i in range(a_virt, b_virt): - x.ctrl(qubits[i], qubits[i + 1]) - - rz(0.125 * theta, qubits[b_virt]) - - for i in range(b_virt, a_virt, -1): - x.ctrl(qubits[i - 1], qubits[i]) - x.ctrl(qubits[j_occ], qubits[a_virt]) - for i in range(j_occ, i_occ, -1): - x.ctrl(qubits[i - 1], qubits[i]) - - rx(-np.pi / 2.0, qubits[j_occ]) - h(qubits[i_occ]) - - rx(np.pi / 2.0, qubits[i_occ]) - h(qubits[j_occ]) - - for i in range(i_occ, j_occ): - x.ctrl(qubits[i], qubits[i + 1]) - x.ctrl(qubits[j_occ], qubits[a_virt]) - for i in range(a_virt, b_virt): - x.ctrl(qubits[i], qubits[i + 1]) - - rz(0.125 * theta, qubits[b_virt]) - - for i in range(b_virt, a_virt, -1): - x.ctrl(qubits[i - 1], qubits[i]) - x.ctrl(qubits[j_occ], qubits[a_virt]) - - rx(-np.pi / 2.0, qubits[b_virt]) - rx(-np.pi / 2.0, qubits[a_virt]) - - h(qubits[a_virt]) - h(qubits[b_virt]) - - x.ctrl(qubits[j_occ], qubits[a_virt]) - for i in range(a_virt, b_virt): - x.ctrl(qubits[i], qubits[i + 1]) - - rz(-0.125 * theta, qubits[b_virt]) - - for i in range(b_virt, a_virt, -1): - x.ctrl(qubits[i - 1], qubits[i]) - x.ctrl(qubits[j_occ], qubits[a_virt]) - for i in range(j_occ, i_occ, -1): - x.ctrl(qubits[i - 1], qubits[i]) - - h(qubits[b_virt]) - h(qubits[j_occ]) - - rx(np.pi / 2.0, qubits[j_occ]) - rx(np.pi / 2.0, qubits[b_virt]) - - for i in range(i_occ, j_occ): - x.ctrl(qubits[i], qubits[i + 1]) - x.ctrl(qubits[j_occ], qubits[a_virt]) - for i in range(a_virt, b_virt): - x.ctrl(qubits[i], qubits[i + 1]) - - rz(-0.125 * theta, qubits[b_virt]) - - for i in range(b_virt, a_virt, -1): - x.ctrl(qubits[i - 1], qubits[i]) - x.ctrl(qubits[j_occ], qubits[a_virt]) - - rx(-np.pi / 2.0, qubits[b_virt]) - h(qubits[a_virt]) - - rx(np.pi / 2.0, qubits[a_virt]) - h(qubits[b_virt]) - - x.ctrl(qubits[j_occ], qubits[a_virt]) - for i in range(a_virt, b_virt): - x.ctrl(qubits[i], qubits[i + 1]) - - rz(-0.125 * theta, qubits[b_virt]) - - for i in range(b_virt, a_virt, -1): - x.ctrl(qubits[i - 1], qubits[i]) - x.ctrl(qubits[j_occ], qubits[a_virt]) - for i in range(j_occ, i_occ, -1): - x.ctrl(qubits[i - 1], qubits[i]) - - h(qubits[b_virt]) - rx(-np.pi / 2.0, qubits[a_virt]) - rx(-np.pi / 2.0, qubits[j_occ]) - rx(-np.pi / 2.0, qubits[i_occ]) - - @cudaq.kernel - def uccsd1_odd_electrons(qubits: cudaq.qview, thetas: list[float], - n_electrons: int, n_qubits: int): - n_spatial_orbitals = n_qubits // 2 - n_occupied = int(np.ceil(n_electrons / 2)) - n_virtual = n_spatial_orbitals - n_occupied - - occupied_alpha_indices = [i * 2 for i in range(n_occupied)] - virtual_alpha_indices = [ - i * 2 + n_electrons + 1 for i in range(n_virtual) - ] - - occupied_beta_indices = [i * 2 + 1 for i in range(n_occupied - 1)] - virtual_beta_indices = [0 for k in range(n_virtual + 1)] - virtual_beta_indices[0] = 2 * n_occupied - 1 - for i in range(n_virtual): - virtual_beta_indices[i + 1] = i * 2 + 1 + n_electrons - - lenOccA = len(occupied_alpha_indices) - lenOccB = len(occupied_beta_indices) - lenVirtA = len(virtual_alpha_indices) - lenVirtB = len(virtual_beta_indices) - - singles_a0 = [0 for k in range(lenOccA * lenVirtA)] - singles_a1 = [0 for k in range(lenOccA * lenVirtA)] - counter = 0 - for p in occupied_alpha_indices: - for q in virtual_alpha_indices: - singles_a0[counter] = p - singles_a1[counter] = q - counter = counter + 1 - - counter = 0 - singles_b0 = [0 for k in range(lenOccB * lenVirtB)] - singles_b1 = [0 for k in range(lenOccB * lenVirtB)] - for p in occupied_beta_indices: - for q in virtual_beta_indices: - singles_b0[counter] = p - singles_b1[counter] = q - counter = counter + 1 - - counter = 0 - doubles_m0 = [0 for k in range(lenOccB * lenVirtB * lenOccA * lenVirtA)] - doubles_m1 = [0 for k in range(lenOccB * lenVirtB * lenOccA * lenVirtA)] - doubles_m2 = [0 for k in range(lenOccB * lenVirtB * lenOccA * lenVirtA)] - doubles_m3 = [0 for k in range(lenOccB * lenVirtB * lenOccA * lenVirtA)] - for p in occupied_alpha_indices: - for q in occupied_beta_indices: - for r in virtual_beta_indices: - for s in virtual_alpha_indices: - doubles_m0[counter] = p - doubles_m1[counter] = q - doubles_m2[counter] = r - doubles_m3[counter] = s - counter = counter + 1 - - counter = 0 - nEle = 0 - for p in range(lenOccA - 1): - for q in range(p + 1, lenOccA): - for r in range(lenVirtA - 1): - for s in range(r + 1, lenVirtA): - nEle = nEle + 1 - - counter = 0 - doubles_a0 = [0 for k in range(nEle)] - doubles_a1 = [0 for k in range(nEle)] - doubles_a2 = [0 for k in range(nEle)] - doubles_a3 = [0 for k in range(nEle)] - for p in range(lenOccA - 1): - for q in range(p + 1, lenOccA): - for r in range(lenVirtA - 1): - for s in range(r + 1, lenVirtA): - doubles_a0[counter] = occupied_alpha_indices[p] - doubles_a1[counter] = occupied_alpha_indices[q] - doubles_a2[counter] = virtual_alpha_indices[r] - doubles_a3[counter] = virtual_alpha_indices[s] - counter = counter + 1 - - counter = 0 - nEle = 0 - for p in range(lenOccB - 1): - for q in range(p + 1, lenOccB): - for r in range(lenVirtB - 1): - for s in range(r + 1, lenVirtB): - nEle = nEle + 1 - - doubles_b0 = [0 for k in range(nEle)] - doubles_b1 = [0 for k in range(nEle)] - doubles_b2 = [0 for k in range(nEle)] - doubles_b3 = [0 for k in range(nEle)] - for p in range(lenOccB - 1): - for q in range(p + 1, lenOccB): - for r in range(lenVirtB - 1): - for s in range(r + 1, lenVirtB): - doubles_b0[counter] = occupied_beta_indices[p] - doubles_b1[counter] = occupied_beta_indices[q] - doubles_b2[counter] = virtual_beta_indices[r] - doubles_b3[counter] = virtual_beta_indices[s] - counter = counter + 1 - - n_alpha_singles = len(singles_a0) - n_beta_singles = len(singles_b0) - n_mixed_doubles = len(doubles_m0) - n_alpha_doubles = len(doubles_a0) - n_beta_doubles = len(doubles_b0) - - thetaCounter = 0 - for i in range(n_alpha_singles): - single_excitation1(qubits, singles_a0[i], singles_a1[i], - thetas[thetaCounter]) - thetaCounter += 1 - - for i in range(n_beta_singles): - single_excitation1(qubits, singles_b0[i], singles_b1[i], - thetas[thetaCounter]) - thetaCounter += 1 - - for i in range(n_mixed_doubles): - double_excitation_opt1(qubits, doubles_m0[i], doubles_m1[i], - doubles_m2[i], doubles_m3[i], - thetas[thetaCounter]) - thetaCounter += 1 - - for i in range(n_alpha_doubles): - double_excitation_opt1(qubits, doubles_a0[i], doubles_a1[i], - doubles_a2[i], doubles_a3[i], - thetas[thetaCounter]) - thetaCounter += 1 - - for i in range(n_beta_doubles): - double_excitation_opt1(qubits, doubles_b0[i], doubles_b1[i], - doubles_b2[i], doubles_b3[i], - thetas[thetaCounter]) - thetaCounter += 1 - - @cudaq.kernel - def uccsd1_even_electrons(qubits: cudaq.qview, thetas: list[float], - n_electrons: int, n_qubits: int): - n_spatial_orbitals = n_qubits // 2 - n_occupied = int(np.ceil(n_electrons / 2)) - n_virtual = n_spatial_orbitals - n_occupied - - occupied_alpha_indices = [i * 2 for i in range(n_occupied)] - virtual_alpha_indices = [i * 2 + n_electrons for i in range(n_virtual)] - - occupied_beta_indices = [i * 2 + 1 for i in range(n_occupied)] - virtual_beta_indices = [ - i * 2 + 1 + n_electrons for i in range(n_virtual) - ] - - lenOccA = len(occupied_alpha_indices) - lenOccB = len(occupied_beta_indices) - lenVirtA = len(virtual_alpha_indices) - lenVirtB = len(virtual_beta_indices) - - singles_a0 = [0 for k in range(lenOccA * lenVirtA)] - singles_a1 = [0 for k in range(lenOccA * lenVirtA)] - counter = 0 - for p in occupied_alpha_indices: - for q in virtual_alpha_indices: - singles_a0[counter] = p - singles_a1[counter] = q - counter = counter + 1 - - counter = 0 - singles_b0 = [0 for k in range(lenOccB * lenVirtB)] - singles_b1 = [0 for k in range(lenOccB * lenVirtB)] - for p in occupied_beta_indices: - for q in virtual_beta_indices: - singles_b0[counter] = p - singles_b1[counter] = q - counter = counter + 1 - - counter = 0 - doubles_m0 = [0 for k in range(lenOccB * lenVirtB * lenOccA * lenVirtA)] - doubles_m1 = [0 for k in range(lenOccB * lenVirtB * lenOccA * lenVirtA)] - doubles_m2 = [0 for k in range(lenOccB * lenVirtB * lenOccA * lenVirtA)] - doubles_m3 = [0 for k in range(lenOccB * lenVirtB * lenOccA * lenVirtA)] - for p in occupied_alpha_indices: - for q in occupied_beta_indices: - for r in virtual_beta_indices: - for s in virtual_alpha_indices: - doubles_m0[counter] = p - doubles_m1[counter] = q - doubles_m2[counter] = r - doubles_m3[counter] = s - counter = counter + 1 - - counter = 0 - nEle = 0 - for p in range(lenOccA - 1): - for q in range(p + 1, lenOccA): - for r in range(lenVirtA - 1): - for s in range(r + 1, lenVirtA): - nEle = nEle + 1 - - counter = 0 - doubles_a0 = [0 for k in range(nEle)] - doubles_a1 = [0 for k in range(nEle)] - doubles_a2 = [0 for k in range(nEle)] - doubles_a3 = [0 for k in range(nEle)] - for p in range(lenOccA - 1): - for q in range(p + 1, lenOccA): - for r in range(lenVirtA - 1): - for s in range(r + 1, lenVirtA): - doubles_a0[counter] = occupied_alpha_indices[p] - doubles_a1[counter] = occupied_alpha_indices[q] - doubles_a2[counter] = virtual_alpha_indices[r] - doubles_a3[counter] = virtual_alpha_indices[s] - counter = counter + 1 - - counter = 0 - nEle = 0 - for p in range(lenOccB - 1): - for q in range(p + 1, lenOccB): - for r in range(lenVirtB - 1): - for s in range(r + 1, lenVirtB): - nEle = nEle + 1 - - doubles_b0 = [0 for k in range(nEle)] - doubles_b1 = [0 for k in range(nEle)] - doubles_b2 = [0 for k in range(nEle)] - doubles_b3 = [0 for k in range(nEle)] - for p in range(lenOccB - 1): - for q in range(p + 1, lenOccB): - for r in range(lenVirtB - 1): - for s in range(r + 1, lenVirtB): - doubles_b0[counter] = occupied_beta_indices[p] - doubles_b1[counter] = occupied_beta_indices[q] - doubles_b2[counter] = virtual_beta_indices[r] - doubles_b3[counter] = virtual_beta_indices[s] - counter = counter + 1 - - n_alpha_singles = len(singles_a0) - n_beta_singles = len(singles_b0) - n_mixed_doubles = len(doubles_m0) - n_alpha_doubles = len(doubles_a0) - n_beta_doubles = len(doubles_b0) - - thetaCounter = 0 - for i in range(n_alpha_singles): - single_excitation1(qubits, singles_a0[i], singles_a1[i], - thetas[thetaCounter]) - thetaCounter += 1 - - for i in range(n_beta_singles): - single_excitation1(qubits, singles_b0[i], singles_b1[i], - thetas[thetaCounter]) - thetaCounter += 1 - - for i in range(n_mixed_doubles): - double_excitation_opt1(qubits, doubles_m0[i], doubles_m1[i], - doubles_m2[i], doubles_m3[i], - thetas[thetaCounter]) - thetaCounter += 1 - - for i in range(n_alpha_doubles): - double_excitation_opt1(qubits, doubles_a0[i], doubles_a1[i], - doubles_a2[i], doubles_a3[i], - thetas[thetaCounter]) - thetaCounter += 1 - - for i in range(n_beta_doubles): - double_excitation_opt1(qubits, doubles_b0[i], doubles_b1[i], - doubles_b2[i], doubles_b3[i], - thetas[thetaCounter]) - thetaCounter += 1 - - @cudaq.kernel - def uccsd1(qubits: cudaq.qview, thetas: list[float], n_electrons: int, - n_qubits: int): - """ - Generate the unitary coupled cluster singlet doublet CUDA-Q kernel. - - Args: - qubits (:class:`qview`): Pre-allocated qubits - thetas (list[float]): List of parameters - n_electrons (int): Number of electrons - n_qubits (int): Number of qubits - """ - - if n_electrons % 2 == 0: - uccsd1_even_electrons(qubits, thetas, n_electrons, n_qubits) - else: - uccsd1_odd_electrons(qubits, thetas, n_electrons, n_qubits) - - num_electrons = 2 - num_qubits = 8 - - thetas = [ - -0.00037043841404585794, 0.0003811110195084151, 0.2286823796532558, - -0.00037043841404585794, 0.0003811110195084151, 0.2286823796532558, - -0.00037043841404585794, 0.0003811110195084151, 0.2286823796532558, - -0.00037043841404585794, 0.0003811110195084151, 0.2286823796532558, - -0.00037043841404585794, 0.0003811110195084151, 0.2286823796532558, - -0.00037043841404585794, 0.0003811110195084151, 0.2286823796532558, - -0.00037043841404585794, 0.0003811110195084151, 0.2286823796532558, - -0.00037043841404585794, 0.0003811110195084151, 0.2286823796532558 - ] - - @cudaq.kernel - def kernel(): - qubits = cudaq.qvector(num_qubits) - for i in range(num_electrons): - x(qubits[i]) - uccsd1(qubits, thetas, num_electrons, num_qubits) - - counts = cudaq.sample(kernel, shots_count=1000) - assert len(counts) == 6 - assert '00000011' in counts - assert '00000110' in counts - assert '00010010' in counts - assert '01000010' in counts - assert '10000001' in counts - assert '11000000' in counts diff --git a/python/tests/visualization/test_draw.py b/python/tests/visualization/test_draw.py index 212a624fb12..0c1c2d7d761 100644 --- a/python/tests/visualization/test_draw.py +++ b/python/tests/visualization/test_draw.py @@ -6,9 +6,10 @@ # the terms of the Apache License 2.0 which accompanies this distribution. # # ============================================================================ # +import os + import cudaq import numpy as np -import os import pytest From ad053e22c45e0cf78948fdfce484b56482609cc2 Mon Sep 17 00:00:00 2001 From: Pradnya Khalate Date: Mon, 15 Sep 2025 09:47:59 -0700 Subject: [PATCH 3/3] * If only test files are copied over, then the UCCSD source file cannot be found,. In this case, we cannot proceed with testing. Signed-off-by: Pradnya Khalate --- python/tests/domains/test_uccsd.py | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/python/tests/domains/test_uccsd.py b/python/tests/domains/test_uccsd.py index b628d7bf673..a00007c3c52 100644 --- a/python/tests/domains/test_uccsd.py +++ b/python/tests/domains/test_uccsd.py @@ -28,6 +28,11 @@ def setup_test_environment(): # Now we make a copy for running the tests current_dir = Path(__file__).parent # tests/domains directory src_file = current_dir.parent.parent / "cudaq" / "kernels" / "uccsd.py" + + if not src_file.exists(): + pytest.skip( + f"Source file {src_file} not found. Skipping `uccsd` tests.") + temp_file = Path("/tmp/fresh_uccsd.py") shutil.copy(src_file, temp_file)