Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions python/runtime/cudaq/algorithms/py_evolve.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -281,6 +281,15 @@ pyEvolveAsync(state initial_state, std::vector<nanobind::object> kernels,
nanobind::arg("noise_model") = std::nullopt, \
nanobind::arg("shots_count") = -1);

#define DEFINE_ASYNC_CALLABLE_OVERLOAD(pyMod) \
pyMod.def( \
"evolve_async", \
[](std::function<evolve_result()> evolveFunctor, std::size_t qpu_id) { \
return detail::evolve_async(std::move(evolveFunctor), qpu_id); \
}, \
"Asynchronously execute a callable that returns an evolution result.", \
nanobind::arg("evolve_function"), nanobind::arg("qpu_id") = 0);

/// @brief Bind the evolve cudaq function for circuit simulator
void bindPyEvolve(nanobind::module_ &mod) {
// Sync evolve overloads
Expand All @@ -298,6 +307,7 @@ void bindPyEvolve(nanobind::module_ &mod) {
DEFINE_ASYNC_PARAM_TYPE_OVERLOAD(long, mod);
DEFINE_ASYNC_PARAM_TYPE_OVERLOAD(double, mod);
DEFINE_ASYNC_PARAM_TYPE_OVERLOAD(std::complex<double>, mod);
DEFINE_ASYNC_CALLABLE_OVERLOAD(mod);
}

} // namespace cudaq
78 changes: 78 additions & 0 deletions python/tests/dynamics/test_evolve_dynamics.py
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,84 @@ def test_euler_integrator():
np.testing.assert_allclose(expected_answer, expt, 1e-3)


def test_evolve_async_dynamics_target():
"""Test async evolution on the dynamics target."""
steps = np.linspace(0, 0.1, 3)
hamiltonian = operators.number(0)
dimensions = {0: 2}
save_all = cudaq.IntermediateResultSave.ALL
save_expectations = cudaq.IntermediateResultSave.EXPECTATION_VALUE
psi0_ = cp.zeros(2, dtype=cp.complex128)
psi0_[1] = 1.0
psi0 = cudaq.State.from_data(psi0_)

expected = cudaq.evolve(hamiltonian, dimensions, Schedule(steps, ["t"]),
psi0)
evolution_result = cudaq.evolve_async(hamiltonian, dimensions,
Schedule(steps, ["t"]), psi0).get()

assert len(evolution_result.intermediate_states()) == 1
np.testing.assert_allclose(np.array(evolution_result.final_state()),
np.array(expected.final_state()),
atol=1e-12)

expected = cudaq.evolve(hamiltonian,
dimensions,
Schedule(steps, ["t"]),
psi0,
store_intermediate_results=save_all)
evolution_result = cudaq.evolve_async(
hamiltonian,
dimensions,
Schedule(steps, ["t"]),
psi0,
store_intermediate_results=save_all).get()

assert len(evolution_result.intermediate_states()) == len(steps)
np.testing.assert_allclose(np.array(evolution_result.final_state()),
np.array(expected.final_state()),
atol=1e-12)

expected = cudaq.evolve(hamiltonian,
dimensions,
Schedule(steps, ["t"]),
psi0,
observables=[hamiltonian],
store_intermediate_results=save_expectations)
evolution_result = cudaq.evolve_async(
hamiltonian,
dimensions,
Schedule(steps, ["t"]),
psi0,
observables=[hamiltonian],
store_intermediate_results=save_expectations).get()

assert len(evolution_result.intermediate_states()) == 1
assert len(evolution_result.expectation_values()) == len(steps)
expected_values = [[obs.expectation()
for obs in step]
for step in expected.expectation_values()]
actual_values = [[obs.expectation()
for obs in step]
for step in evolution_result.expectation_values()]
np.testing.assert_allclose(actual_values, expected_values, atol=1e-12)


def test_evolve_async_dynamics_target_propagates_errors():
"""Test async dynamics errors are reported through get()."""
steps = np.linspace(0, 0.1, 3)
schedule = Schedule(steps, ["t"])
hamiltonian = operators.number(0)
psi0_ = cp.zeros(2, dtype=cp.complex128)
psi0_[1] = 1.0
psi0 = cudaq.State.from_data(psi0_)

result = cudaq.evolve_async(hamiltonian, {1: 2}, schedule, psi0)

with pytest.raises(Exception):
result.get()


def test_save_all_intermediate_states():
"""
Test save all option for intermediate states
Expand Down
49 changes: 33 additions & 16 deletions runtime/cudaq/algorithms/evolve_internal.h
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
#include "cudaq/platform.h"
#include "cudaq/platform/QuantumExecutionQueue.h"
#include "cudaq/schedule.h"
#include <exception>

namespace cudaq {
class base_integrator;
Expand Down Expand Up @@ -108,13 +109,19 @@ evolve_async(state initial_state, QuantumKernel &&kernel,
[p = std::move(promise), func = std::forward<QuantumKernel>(kernel),
initial_state, observables, noise_model, shots_count,
&platform]() mutable {
if (noise_model.has_value())
platform.set_noise(&noise_model.value());
with_platform_in_library_mode libraryMode(platform);
auto result = evolve(initial_state, func, observables, shots_count);
if (noise_model.has_value())
platform.set_noise(nullptr);
p.set_value(std::move(result));
try {
if (noise_model.has_value())
platform.set_noise(&noise_model.value());
with_platform_in_library_mode libraryMode(platform);
auto result = evolve(initial_state, func, observables, shots_count);
if (noise_model.has_value())
platform.set_noise(nullptr);
p.set_value(std::move(result));
} catch (...) {
if (noise_model.has_value())
platform.set_noise(nullptr);
p.set_exception(std::current_exception());
}
});

platform.enqueueAsyncTask(qpu_id, wrapped);
Expand All @@ -135,14 +142,20 @@ evolve_async(state initial_state, std::vector<QuantumKernel> kernels,
QuantumTask wrapped = detail::make_copyable_function(
[p = std::move(promise), kernels, initial_state, observables, noise_model,
shots_count, &platform, save_intermediate_states]() mutable {
if (noise_model.has_value())
platform.set_noise(&noise_model.value());
with_platform_in_library_mode libraryMode(platform);
auto result = evolve(initial_state, kernels, observables, shots_count,
save_intermediate_states);
if (noise_model.has_value())
platform.set_noise(nullptr);
p.set_value(std::move(result));
try {
if (noise_model.has_value())
platform.set_noise(&noise_model.value());
with_platform_in_library_mode libraryMode(platform);
auto result = evolve(initial_state, kernels, observables, shots_count,
save_intermediate_states);
if (noise_model.has_value())
platform.set_noise(nullptr);
p.set_value(std::move(result));
} catch (...) {
if (noise_model.has_value())
platform.set_noise(nullptr);
p.set_exception(std::current_exception());
}
});

platform.enqueueAsyncTask(qpu_id, wrapped);
Expand All @@ -164,7 +177,11 @@ evolve_async(std::function<evolve_result()> evolveFunctor,

QuantumTask wrapped = detail::make_copyable_function(
[p = std::move(promise), evolveFunctor]() mutable {
p.set_value(evolveFunctor());
try {
p.set_value(evolveFunctor());
} catch (...) {
p.set_exception(std::current_exception());
}
Comment on lines +180 to +184

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: Should we apply this try/catch block in the other 2 overloads?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

updated. The other two evolve_async overloads now also catch worker exceptions and propagate them through the returned future.

});

platform.enqueueAsyncTask(qpu_id, wrapped);
Expand Down
Loading