Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add native PCPhase to Lightning #922

Draft
wants to merge 5 commits into
base: master
Choose a base branch
from
Draft
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
8 changes: 6 additions & 2 deletions mpitests/test_adjoint_jacobian.py
Original file line number Diff line number Diff line change
Expand Up @@ -1384,7 +1384,9 @@ def test_qubit_unitary(dev, n_targets):

np.random.seed(1337)
par = 2 * np.pi * np.random.rand(n_wires)
U = np.random.rand(2**n_targets, 2**n_targets) + 1j * np.random.rand(2**n_targets, 2**n_targets)
U = np.random.rand(2**n_targets, 2**n_targets) + 1j * np.random.rand(
2**n_targets, 2**n_targets
)
U, _ = np.linalg.qr(U)
init_state = np.random.rand(2**n_wires) + 1j * np.random.rand(2**n_wires)
init_state /= np.sqrt(np.dot(np.conj(init_state), init_state))
Expand Down Expand Up @@ -1432,7 +1434,9 @@ def test_diff_qubit_unitary(dev, n_targets):

np.random.seed(1337)
par = 2 * np.pi * np.random.rand(n_wires)
U = np.random.rand(2**n_targets, 2**n_targets) + 1j * np.random.rand(2**n_targets, 2**n_targets)
U = np.random.rand(2**n_targets, 2**n_targets) + 1j * np.random.rand(
2**n_targets, 2**n_targets
)
U, _ = np.linalg.qr(U)
init_state = np.random.rand(2**n_wires) + 1j * np.random.rand(2**n_wires)
init_state /= np.sqrt(np.dot(np.conj(init_state), init_state))
Expand Down
4 changes: 3 additions & 1 deletion pennylane_lightning/core/_serialize.py
Original file line number Diff line number Diff line change
Expand Up @@ -367,7 +367,9 @@ def serialize_observables(self, tape: QuantumTape, wires_map: dict = None) -> Li
obs_indices.append(i)
return serialized_obs, obs_indices

def serialize_ops(self, tape: QuantumTape, wires_map: dict = None) -> Tuple[
def serialize_ops(
self, tape: QuantumTape, wires_map: dict = None
) -> Tuple[
List[List[str]],
List[np.ndarray],
List[List[int]],
Expand Down
1 change: 0 additions & 1 deletion pennylane_lightning/core/_state_vector_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,6 @@ class LightningBaseStateVector(ABC):
"""

def __init__(self, num_wires: int, dtype: Union[np.complex128, np.complex64]):

if dtype not in [np.complex64, np.complex128]:
raise TypeError(f"Unsupported complex type: {dtype}")

Expand Down
2 changes: 1 addition & 1 deletion pennylane_lightning/core/_version.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,4 +16,4 @@
Version number (major.minor.patch[-label])
"""

__version__ = "0.39.0-dev31"
__version__ = "0.39.0-dev33"
13 changes: 11 additions & 2 deletions pennylane_lightning/core/src/gates/Constant.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -26,9 +26,14 @@ namespace Pennylane::Gates::Constant {
/**
* @brief List of multi-qubit gates
*/
[[maybe_unused]] constexpr std::array multi_qubit_gates{GateOperation::MultiRZ};
[[maybe_unused]] constexpr std::array multi_qubit_gates{
GateOperation::MultiRZ,
GateOperation::PCPhase,
};
[[maybe_unused]] constexpr std::array controlled_multi_qubit_gates{
ControlledGateOperation::MultiRZ};
ControlledGateOperation::MultiRZ,
ControlledGateOperation::PCPhase,
};
/**
* @brief List of multi-qubit generators
*/
Expand Down Expand Up @@ -84,6 +89,7 @@ using GateView = typename std::pair<GateOperation, std::string_view>;
GateView{GateOperation::DoubleExcitationMinus, "DoubleExcitationMinus"},
GateView{GateOperation::DoubleExcitationPlus, "DoubleExcitationPlus"},
GateView{GateOperation::MultiRZ, "MultiRZ"},
GateView{GateOperation::PCPhase, "PCPhase"},
GateView{GateOperation::GlobalPhase, "GlobalPhase"}};

using CGateView = typename std::pair<ControlledGateOperation, std::string_view>;
Expand Down Expand Up @@ -115,6 +121,7 @@ using CGateView = typename std::pair<ControlledGateOperation, std::string_view>;
CGateView{ControlledGateOperation::DoubleExcitationPlus,
"DoubleExcitationPlus"},
CGateView{ControlledGateOperation::MultiRZ, "MultiRZ"},
CGateView{ControlledGateOperation::PCPhase, "PCPhase"},
CGateView{ControlledGateOperation::GlobalPhase, "GlobalPhase"},
};

Expand Down Expand Up @@ -349,6 +356,7 @@ using GateNParams = typename std::pair<GateOperation, std::size_t>;
GateNParams{GateOperation::DoubleExcitationPlus, 1},
GateNParams{GateOperation::CSWAP, 0},
GateNParams{GateOperation::MultiRZ, 1},
GateNParams{GateOperation::PCPhase, 1},
GateNParams{GateOperation::GlobalPhase, 1},
};

Expand Down Expand Up @@ -380,6 +388,7 @@ using CGateNParams = typename std::pair<ControlledGateOperation, std::size_t>;
CGateNParams{ControlledGateOperation::DoubleExcitationMinus, 1},
CGateNParams{ControlledGateOperation::DoubleExcitationPlus, 1},
CGateNParams{ControlledGateOperation::MultiRZ, 1},
CGateNParams{ControlledGateOperation::PCPhase, 1},
CGateNParams{ControlledGateOperation::GlobalPhase, 1},
};
} // namespace Pennylane::Gates::Constant
2 changes: 2 additions & 0 deletions pennylane_lightning/core/src/gates/GateOperation.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,7 @@ enum class GateOperation : uint32_t {
DoubleExcitationPlus,
/* Multi-qubit gates */
MultiRZ,
PCPhase,
GlobalPhase,
/* END (placeholder) */
END
Expand Down Expand Up @@ -98,6 +99,7 @@ enum class ControlledGateOperation : uint32_t {
DoubleExcitationPlus,
/* Multi-qubit gates */
MultiRZ,
PCPhase,
GlobalPhase,
/* END (placeholder) */
END
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1161,6 +1161,19 @@ void applyGlobalPhase(Kokkos::View<Kokkos::complex<PrecisionT> *> arr_,
KOKKOS_LAMBDA(const std::size_t k) { arr_(k) *= phase; });
}

template <class ExecutionSpace, class PrecisionT>
void applyPCPhase(Kokkos::View<Kokkos::complex<PrecisionT> *> arr_,
const std::size_t num_qubits,
[[maybe_unused]] const std::vector<std::size_t> &wires,
const bool inverse = false,
const std::vector<PrecisionT> &params = {}) {
const Kokkos::complex<PrecisionT> phase = Kokkos::exp(
Kokkos::complex<PrecisionT>{0, (inverse) ? params[0] : -params[0]});
Kokkos::parallel_for(
Kokkos::RangePolicy<ExecutionSpace>(0, exp2(num_qubits)),
KOKKOS_LAMBDA(const std::size_t k) { arr_(k) *= phase; });
}

template <class ExecutionSpace, class PrecisionT>
void applyNamedOperation(const GateOperation gateop,
Kokkos::View<Kokkos::complex<PrecisionT> *> arr_,
Expand Down Expand Up @@ -1277,6 +1290,9 @@ void applyNamedOperation(const GateOperation gateop,
applyGlobalPhase<ExecutionSpace>(arr_, num_qubits, wires, inverse,
params);
return;
case GateOperation::PCPhase:
applyPCPhase<ExecutionSpace>(arr_, num_qubits, wires, inverse, params);
return;
case GateOperation::MultiRZ:
applyMultiRZ<ExecutionSpace>(arr_, num_qubits, wires, inverse, params);
return;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -150,6 +150,9 @@ void assignKernelsForGateOp_Default() {
instance.assignKernelForOp(GateOperation::MultiRZ, all_threading,
all_memory_model, all_qubit_numbers,
KernelType::LM);
instance.assignKernelForOp(GateOperation::PCPhase, all_threading,
all_memory_model, all_qubit_numbers,
KernelType::LM);
instance.assignKernelForOp(GateOperation::GlobalPhase, all_threading,
all_memory_model, all_qubit_numbers,
KernelType::LM);
Expand Down Expand Up @@ -307,6 +310,9 @@ void assignKernelsForControlledGateOp_Default() {
instance.assignKernelForOp(ControlledGateOperation::MultiRZ, all_threading,
all_memory_model, all_qubit_numbers,
KernelType::LM);
instance.assignKernelForOp(ControlledGateOperation::PCPhase, all_threading,
all_memory_model, all_qubit_numbers,
KernelType::LM);
instance.assignKernelForOp(ControlledGateOperation::GlobalPhase,
all_threading, all_memory_model,
all_qubit_numbers, KernelType::LM);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -260,6 +260,12 @@ struct GateOpToMemberFuncPtr<PrecisionT, ParamT, GateImplementation,
&GateImplementation::template applyMultiRZ<PrecisionT, ParamT>;
};
template <class PrecisionT, class ParamT, class GateImplementation>
struct GateOpToMemberFuncPtr<PrecisionT, ParamT, GateImplementation,
GateOperation::PCPhase> {
constexpr static auto value =
&GateImplementation::template applyPCPhase<PrecisionT, ParamT>;
};
template <class PrecisionT, class ParamT, class GateImplementation>
struct GateOpToMemberFuncPtr<PrecisionT, ParamT, GateImplementation,
GateOperation::GlobalPhase> {
constexpr static auto value =
Expand Down Expand Up @@ -423,6 +429,12 @@ struct ControlledGateOpToMemberFuncPtr<PrecisionT, ParamT, GateImplementation,
&GateImplementation::template applyNCMultiRZ<PrecisionT, ParamT>;
};
template <class PrecisionT, class ParamT, class GateImplementation>
struct ControlledGateOpToMemberFuncPtr<PrecisionT, ParamT, GateImplementation,
ControlledGateOperation::PCPhase> {
constexpr static auto value =
&GateImplementation::template applyNCPCPhase<PrecisionT, ParamT>;
};
template <class PrecisionT, class ParamT, class GateImplementation>
struct ControlledGateOpToMemberFuncPtr<PrecisionT, ParamT, GateImplementation,
ControlledGateOperation::GlobalPhase> {
constexpr static auto value =
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -241,6 +241,12 @@ template void GateImplementationsLM::applyMultiRZ<float, float>(
template void GateImplementationsLM::applyMultiRZ<double, double>(
std::complex<double> *, std::size_t, const std::vector<std::size_t> &, bool,
double);
template void GateImplementationsLM::applyPCPhase<float, float>(
std::complex<float> *, std::size_t, const std::vector<std::size_t> &, bool,
float);
template void GateImplementationsLM::applyPCPhase<double, double>(
std::complex<double> *, std::size_t, const std::vector<std::size_t> &, bool,
double);
template void GateImplementationsLM::applyGlobalPhase<float, float>(
std::complex<float> *, std::size_t, const std::vector<std::size_t> &, bool,
float);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -153,6 +153,7 @@ class GateImplementationsLM : public PauliGenerator<GateImplementationsLM> {
GateOperation::DoubleExcitationMinus,
GateOperation::DoubleExcitationPlus,
GateOperation::MultiRZ,
GateOperation::PCPhase,
GateOperation::GlobalPhase,
};

Expand Down Expand Up @@ -180,6 +181,7 @@ class GateImplementationsLM : public PauliGenerator<GateImplementationsLM> {
ControlledGateOperation::DoubleExcitationMinus,
ControlledGateOperation::DoubleExcitationPlus,
ControlledGateOperation::MultiRZ,
ControlledGateOperation::PCPhase,
ControlledGateOperation::GlobalPhase,
};

Expand Down Expand Up @@ -1869,6 +1871,63 @@ class GateImplementationsLM : public PauliGenerator<GateImplementationsLM> {
applyNCN(arr, num_qubits, controlled_wires, controlled_values, wires,
core_function);
}

template <class PrecisionT, class ParamT>
static void applyPCPhase(std::complex<PrecisionT> *arr,
std::size_t num_qubits,
const std::vector<std::size_t> &wires,
bool inverse, ParamT angle) {
const std::complex<PrecisionT> first =
std::complex<PrecisionT>{std::cos(angle), -std::sin(angle)};
const std::complex<PrecisionT> second =
std::complex<PrecisionT>{std::cos(angle), std::sin(angle)};
const std::array<std::complex<PrecisionT>, 2> shifts = {
(inverse) ? std::conj(first) : first,
(inverse) ? std::conj(second) : second};
std::size_t wires_parity{0U};
for (std::size_t wire : wires) {
wires_parity |=
(static_cast<std::size_t>(1U) << (num_qubits - wire - 1));
}

PL_LOOP_PARALLEL(1)
for (std::size_t k = 0; k < exp2(num_qubits); k++) {
arr[k] *= shifts[std::popcount(k & wires_parity) % 2];
}
}

template <class PrecisionT, class ParamT>
static void applyNCPCPhase(std::complex<PrecisionT> *arr,
std::size_t num_qubits,
const std::vector<std::size_t> &controlled_wires,
const std::vector<bool> &controlled_values,
const std::vector<std::size_t> &wires,
bool inverse, ParamT angle) {
const std::complex<PrecisionT> first =
std::complex<PrecisionT>{std::cos(angle / 2), -std::sin(angle / 2)};
const std::complex<PrecisionT> second =
std::complex<PrecisionT>{std::cos(angle / 2), std::sin(angle / 2)};
const std::array<std::complex<PrecisionT>, 2> shifts = {
(inverse) ? std::conj(first) : first,
(inverse) ? std::conj(second) : second};
std::size_t wires_parity = 0U;
for (std::size_t wire : wires) {
wires_parity |=
(static_cast<std::size_t>(1U) << (num_qubits - wire - 1));
}
auto core_function = [wires_parity,
&shifts](std::complex<PrecisionT> *arr,
const std::vector<std::size_t> &indices,
const std::size_t offset) {
for (auto k : indices) {
arr[(k + offset)] *=
shifts[std::popcount((k + offset) & wires_parity) % 2];
}
};
applyNCN(arr, num_qubits, controlled_wires, controlled_values, wires,
core_function);
}

template <class PrecisionT, class ParamT>
static void
applyGlobalPhase(std::complex<PrecisionT> *arr, std::size_t num_qubits,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,8 @@ TEST_CASE("Test several limiting cases of default kernels", "[KernelMap]") {
[&gate_map](Pennylane::Gates::GateOperation gate_op) {
INFO(lookup(Pennylane::Gates::Constant::gate_names, gate_op));
if (gate_op == Pennylane::Gates::GateOperation::GlobalPhase ||
gate_op == Pennylane::Gates::GateOperation::MultiRZ) {
gate_op == Pennylane::Gates::GateOperation::MultiRZ ||
gate_op == Pennylane::Gates::GateOperation::PCPhase) {
REQUIRE(gate_map[gate_op] ==
Pennylane::Gates::KernelType::LM);
} else if (lookup(Pennylane::Gates::Constant::gate_wires,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -165,6 +165,7 @@ class DummyImplementation {
PENNYLANE_TESTS_DEFINE_GATE_OP(DoubleExcitationMinus, 1)
PENNYLANE_TESTS_DEFINE_GATE_OP(DoubleExcitationPlus, 1)
PENNYLANE_TESTS_DEFINE_GATE_OP(MultiRZ, 1)
PENNYLANE_TESTS_DEFINE_GATE_OP(PCPhase, 1)
PENNYLANE_TESTS_DEFINE_GATE_OP(GlobalPhase, 1)

PENNYLANE_TESTS_DEFINE_GENERATOR_OP(PhaseShift)
Expand Down
2 changes: 2 additions & 0 deletions pennylane_lightning/lightning_gpu/lightning_gpu.py
Original file line number Diff line number Diff line change
Expand Up @@ -130,6 +130,8 @@ def _mebibytesToBytes(mebibytes):
"MultiRZ",
"GlobalPhase",
"C(GlobalPhase)",
"PCPhase",
"C(PCPhase)",
"Hadamard",
"S",
"Adjoint(S)",
Expand Down
1 change: 1 addition & 0 deletions pennylane_lightning/lightning_gpu/lightning_gpu.toml
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,7 @@ MultiControlledX = {}

BlockEncode = {properties = [ "controllable" ]}
GlobalPhase = {properties = [ "controllable" ]}
PCPhase = {properties = [ "controllable" ]}
ControlledQubitUnitary = {}
ECR = {}
SX = {}
Expand Down
1 change: 0 additions & 1 deletion pennylane_lightning/lightning_kokkos/_measurements.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,6 @@ def __init__(
self,
kokkos_state,
) -> None:

super().__init__(kokkos_state)

self._measurement_lightning = self._measurement_dtype()(kokkos_state.state_vector)
Expand Down
2 changes: 0 additions & 2 deletions pennylane_lightning/lightning_kokkos/_state_vector.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,6 @@ def __init__(
kokkos_args=None,
sync=True,
): # pylint: disable=too-many-arguments

super().__init__(num_wires, dtype)

self._device_name = "lightning.kokkos"
Expand Down Expand Up @@ -280,7 +279,6 @@ def _apply_lightning(
elif isinstance(operation, qml.ops.Controlled) and isinstance(
operation.base, qml.GlobalPhase
): # apply n-controlled gate

# Kokkos do not support the controlled gates except for GlobalPhase
self._apply_lightning_controlled(operation)
else: # apply gate as a matrix
Expand Down
2 changes: 2 additions & 0 deletions pennylane_lightning/lightning_kokkos/lightning_kokkos.py
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,8 @@
"MultiRZ",
"GlobalPhase",
"C(GlobalPhase)",
"PCPhase",
"C(PCPhase)",
"Hadamard",
"S",
"Adjoint(S)",
Expand Down
3 changes: 2 additions & 1 deletion pennylane_lightning/lightning_kokkos/lightning_kokkos.toml
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,8 @@ ControlledQubitUnitary = {}
# Gates which should be translated to QubitUnitary
[operators.gates.matrix]

BlockEncode = {}
BlockEncode = {properties = [ "controllable" ]}
PCPhase = {properties = [ "controllable" ]}
DiagonalQubitUnitary = {}
ECR = {}
ISWAP = {}
Expand Down
1 change: 0 additions & 1 deletion pennylane_lightning/lightning_qubit/_measurements.py
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,6 @@ def __init__(
kernel_name: str = None,
num_burnin: int = None,
) -> None:

super().__init__(qubit_state)

self._mcmc = mcmc
Expand Down
1 change: 0 additions & 1 deletion pennylane_lightning/lightning_qubit/_state_vector.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,6 @@ class LightningStateVector(LightningBaseStateVector): # pylint: disable=too-few
"""

def __init__(self, num_wires, dtype=np.complex128):

super().__init__(num_wires, dtype)

self._device_name = "lightning.qubit"
Expand Down
2 changes: 2 additions & 0 deletions pennylane_lightning/lightning_qubit/lightning_qubit.py
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,7 @@
"PauliZ",
"MultiRZ",
"GlobalPhase",
"PCPhase",
"Hadamard",
"S",
"Adjoint(S)",
Expand Down Expand Up @@ -124,6 +125,7 @@
"C(DoubleExcitationPlus)",
"C(MultiRZ)",
"C(GlobalPhase)",
"C(PCPhase)",
"C(QubitUnitary)",
"CRot",
"IsingXX",
Expand Down
1 change: 1 addition & 0 deletions pennylane_lightning/lightning_qubit/lightning_qubit.toml
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@ QFT = {}
[operators.gates.matrix]

BlockEncode = {properties = [ "controllable" ]}
PCPhase = {properties = [ "controllable" ]}
DiagonalQubitUnitary = {}
ECR = {}
ISWAP = {}
Expand Down
Loading
Loading