Giter Club home page Giter Club logo

pennylaneai / pennylane-lightning Goto Github PK

View Code? Open in Web Editor NEW
70.0 17.0 32.0 6.9 MB

The PennyLane-Lightning plugin provides a fast state-vector simulator written in C++ for use with PennyLane

Home Page: https://docs.pennylane.ai/projects/lightning

License: Apache License 2.0

Makefile 0.16% Python 13.28% C++ 83.32% CMake 2.77% Dockerfile 0.31% Cuda 0.16%
hpc parallel quantum-computing cuda distributed-computing gpu mpi openmp quantum-machine-learning rocm

pennylane-lightning's People

Contributors

albi3ro avatar amintordusko avatar antalszava avatar chaeyeunpark avatar co9olguy avatar dime10 avatar doctorperceptron avatar erick-xanadu avatar github-actions[bot] avatar isaacdevlugt avatar isschoch avatar jaybsoni avatar jedimunees avatar josh146 avatar lillian542 avatar maliasadi avatar mandrenkov avatar mlxd avatar monitsharma avatar multiphasecfd avatar rashidnhm avatar rmoyard avatar thisac avatar thomasloke avatar timmysilv avatar trbromley avatar trevor-vincent avatar vincentmr avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

pennylane-lightning's Issues

Add support for controlled phase gate (ControlledPhaseShift/CPhase)

Use of the ControlledPhaseShift gate is currently supported by PennyLane default_qubit in Python (see here for supported gates and here for the Python implementation). This gate should also be natively supported in the C++ layer by lightning.qubit.

This will require the following steps:

  • A new ControlledPhaseShift class is created mirroring existing C++ gate structures (see here).
  • The new class is added to the list of supported gates.
  • The new class matches the functionality of the Python implementation.
  • Tests are added for the new gate (see here).

Re-add `add_library(pennylane_lightning INTERFACE)` for derived packages

Issue description

The cmake interface to Lightning without the use of Pybind11 is beneficial for packages that depend on Lightning's structure. To ensure this can be supported, we should keep the add_library(pennylane_lightning INTERFACE) and subsequent lines in the CMakeLists.txt file for current development. This will be a temporary measure until a future refactor and integration.

Copying data vs passing by reference

If my memory does not fail, if you decide to use Eigen, every time you transfer some data between C++ and python the data will be copied.
Eigen will not easily deliver a pointer to the data but, instead once Eigen is done doing it's thing it will deallocate the data causing issues, thus data has to be copied every time, significantly decreasing performance.
The only place in the Walrus were we moved large chunks of data was in the hermite_multidimensional.hpp where the data is transferred cleanly (without copying) using the classes ArrayWrapper and ArrayWrapperFloat in https://github.com/XanaduAI/thewalrus/blob/master/thewalrus/libwalrus.pyx . In C++ this data is just a pointer and the de-allocation is handled by the python classes.

Hopefully a better way can be found to make Eigen play nicely with python. In our case we simply ditched Eigen for hermite_multidimensional since the vector class from C++ was enough.

Adjoint jacobian throws std::range_error

Issue description

Description of the issue - include code snippets and screenshots here
if relevant. You may use the following template below

  • Expected behavior: (What you expect to happen) AdjointJacobian<T>::adjointJacobian should work for all compilers.

  • Actual behavior: (What actually happens) It throws std::range_error in some compilers (especially in MSVC)

This is because we reference an iterator below std::begin(). I will make a fixing PR soon.

Support Python 3.9

At the upcoming v0.16 release of Lightning, we should deprecate Python 3.6 support and enable building Python 3.9 wheels.

Add C++ coverage checks to Lightning

Issue description

To ensure the codebase if fully tested for coverage, we should ensure that coverage testing is performed not only for the Python code, but C++ also.

For example, this can be enabled and tested under Linux using gcov and Windows using MSVC option /EnableCodeCoverage.

Provide LRU caching support for index operations

Issue description

Often calls to the gate methods of the StateVector class can be repeated, and hence have some amount of repeated work. By enabling the use of LRU caching for the outputs from the StateVector::generateBitPatterns and StateVector::getIndicesAfterExclusion methods, we can avoid some amount of repeated work, and reuse the previously called method results, at the expense of some additional RAM.

Tasks:

  • Implement a C++ LRU cache class in pennylane_lightning/src/util.
  • Adapt calls to StateVector::generateBitPatterns and StateVector::getIndicesAfterExclusion to enable use of caching (see StateVector.hpp).
  • Add suitable tests to verify correct operation of the LRU cache.

Pytest fails on Windows

Before posting an issue

Search existing GitHub issues to make sure the issue does not already exist:
https://github.com/xanaduai/pennylane-lightning/issues

If posting a PennyLane-Lightning issue, delete everything above the dashed line, and fill
in the template. If the issue is a bug, start the title of the issue with [BUG].

If making a feature request, delete the following template and describe, in detail,
the feature and why it is needed.

For general technical details check out our documentation:
https://pennylane-lightning.readthedocs.io/


Issue description

Description of the issue - include code snippets and screenshots here
if relevant. You may use the following template below

  • Expected behavior: (What you expect to happen) pytest should work on Windows

  • Actual behavior: (What actually happens) pytest fails due to np.complex256 which is not available on Windows (see https://numpy.org/doc/stable/reference/arrays.scalars.html#numpy.clongdouble)

  • Reproduces how often: (What percentage of the time does it reproduce?) Always

  • System information: (post the output of import pennylane as qml; qml.about()) Windows

Source code and tracebacks

Please include any additional code snippets and error tracebacks related
to the issue here.

Additional information

Any additional information, configuration or data that might be necessary
to reproduce the issue.

As this only a few people use Pennylane on Windows and this is almost nothing to do with a user code, I don't think this is an urgent issue.

PowerPC wheel fails to compile

Issue description

With the recent modifications to the repository, the wheel-builder for PowerPC (ppc64le) fails to compile the C++ modules.

  • Expected behavior: ppc64le wheels are successfully compiled.

  • Actual behavior: Wheel-builder fails to build ppc64le.

  • Reproduces how often: Always for PPC

Source code and tracebacks

Sample offending step:

|   gcc -pthread -Wno-unused-result -Wsign-compare -DNDEBUG -g -fwrapv -O3 -Wall -fPIC -DVERSION_INFO="0.16.0.dev0" -I/opt/_internal/cpython-3.7.10/lib/python3.7/site-packages/pybind11/include -I./include -I/opt/_internal/cpython-3.7.10/include/python3.7m -c pennylane_lightning/src/StateVector.cpp -o build/temp.linux-ppc64le-3.7/pennylane_lightning/src/StateVector.o -O3 -W -fPIC -shared -fopenmp -std=c++17 -fvisibility=hidden
|   In file included from pennylane_lightning/src/Gates.hpp:7:0,
|                    from pennylane_lightning/src/StateVector.hpp:33,
|                    from pennylane_lightning/src/StateVector.cpp:15:
|   pennylane_lightning/src/Util.hpp: In function ‘constexpr T Pennylane::Util::SQRT2()’:
|   pennylane_lightning/src/Util.hpp:90:8: error: expected ‘(’ before ‘constexpr’
|        if constexpr (std::is_same_v<T, float>) {
|           ^~~~~~~~~
|   pennylane_lightning/src/StateVector.cpp:19:46: error: expected ‘}’ at end of input
|    template class Pennylane::StateVector<double>;
|                                                 ^
|   pennylane_lightning/src/StateVector.cpp: At global scope:
|   pennylane_lightning/src/StateVector.cpp:19:46: error: expected ‘}’ at end of input
|   pennylane_lightning/src/StateVector.cpp:19:46: error: expected ‘}’ at end of input
|   error: command 'gcc' failed with exit status 1

Additional information

Any additional information, configuration or data that might be necessary
to reproduce the issue.

Update MacOS min version support to MacOS 11

Issue description

Github actions are currently deprecating the MacOS 10.15 runners (actions/runner-images#5583). We currently use these runners to build backwards compatible wheels for MacOS machines targeting both 10.15 and above. With the minimum version of MacOS 11 we may lose the ability to easily build support for older versions of MacOS due in large to the structural differences between the major OS versions.

An upgrade to MacOS 11 runners on x86 is currently being assessed in PR #319 as part of a reduction in CI redundant tests.

Add `ENABLE_BLAS` build to CI checks

Issue description

To ensure Lightning works correctly with all compiler & macro defined behaviour, we should ensure all options are built and tested in the CI. Using ENABLE_BLAS is one such option that we can enable for a CI test, to ensure that all features work when using the CBLAS APIs.

[BUG] Compilation on Windows fails

Issue description

Description of the issue - include code snippets and screenshots here
if relevant. You may use the following template below

  • Expected behavior: (What you expect to happen)

Compilations succeeds.

  • Actual behavior: (What actually happens)

Compilation fails on windows with error C2039: 'all_of': is not a member of 'std'

  • Reproduces how often: (What percentage of the time does it reproduce?)

Every time

  • System information: (post the output of import pennylane as qml; qml.about())

Azure pipelines

Source code and tracebacks

Please include any additional code snippets and error tracebacks related
to the issue here.

Logs: https://dev.azure.com/conda-forge/feedstock-builds/_build/results?buildId=428105&view=logs&j=171a126d-c574-5c8c-1269-ff3b989e923d&t=1183ba29-a0b5-5324-8463-2a49ace9e213&l=633

Additional information

Any additional information, configuration or data that might be necessary
to reproduce the issue.

This occurs in the context of building the package for conda-forge.

Pytest tests hang on Windows

Two test cases were found to cause hanging behaviour when using pytest on a Windows machine:

  1. test_four_qubit_random_circuit from the PennyLane device test suite;
  2. test_apply_operation_single_wire_with_parameters from the PennyLane-Lightning test suite when passing the Rot gate and the second input parameter.

Running these tests cause the suites to run without termination. When run as a stand-alone case, the code for 1. could be executed with/without using pytest.

#59 includes a small fix to split up running 1. and the rest of the device tests when building the wheel.

Docker Creation Fail GCC version and Test Fail

Issue description

After cloning the repo, and running the docker commands from the README, it fails twice:

  1. Missing a GCC version >10 (solved by editing the Dockerfile and adding it)
  2. Once GCC version is fixed, then the docker does not pass its own tests.
Expected behavior:

A Docker is created.

Actual behavior:

It fails to run the test scripts.

System information:

WSL2 but creating a docker, so it should not matter.

Source code and tracebacks

For error 1, GCC version update to 10 these commands were added to the Dockerfile: (this works)

RUN apt-get update
RUN apt-get upgrade -y
RUN apt-get install gcc-10 g++-10 cpp-10 -y
RUN update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-10 100 --slave /usr/bin/g++ g++ /usr/bin/g++-10 --slave /usr/bin/gcov gcov /usr/bin/gcov-10
  1. Not passing tests: (Not adding the traces from before the tests, all good.)
#13 125.5 ============================= test session starts ==============================
#13 125.5 platform linux -- Python 3.8.10, pytest-7.1.2, pluggy-1.0.0
#13 125.5 rootdir: /opt/pennylane-lightning
#13 125.5 plugins: mock-3.8.2, cov-3.0.0, flaky-3.7.0
#13 125.5 collected 1693 items
#13 125.5
#13 125.5 tests/test_adjoint_jacobian.py ......................................... [  2%]
#13 125.8 ........................................................................ [  6%]
#13 126.3 ........................................................................ [ 10%]
#13 127.5 ........................................................................ [ 15%]
#13 128.3 .................ssssss........................                          [ 17%]
#13 143.7 tests/test_apply.py .................................................... [ 21%]
#13 143.7 ........................................................................ [ 25%]
#13 143.8 ........................................................................ [ 29%]
#13 143.9 ........................................................................ [ 33%]
#13 144.0 ........................................................................ [ 38%]
#13 144.1 ........................................................................ [ 42%]
#13 144.1 ........................................................................ [ 46%]
#13 144.2 ......FF................................................................ [ 50%]
#13 144.5 ........................................................................ [ 55%]
#13 144.6 ........................................................................ [ 59%]
#13 144.8 ........................................................................ [ 63%]
#13 145.0 .......................s                                                 [ 64%]
#13 145.0 tests/test_array.py ..                                                   [ 65%]
#13 145.0 tests/test_binary_info.py ..                                             [ 65%]
#13 145.0 tests/test_comparison.py ............................................... [ 67%]
#13 145.6 ........................................................................ [ 72%]
#13 146.9 .................................................................        [ 76%]
#13 148.4 tests/test_device.py ....F                                               [ 76%]
#13 148.5 tests/test_expval.py ................................................    [ 79%]
#13 148.5 tests/test_gates.py .s.s...s..s.s..s.......s.....s........sss.....s..... [ 82%]
#13 148.8 .s..s.s...s..s.s..s.......s.....s........sss.....s......s...             [ 85%]
#13 149.0 tests/test_measures.py .....xXxX........................................ [ 88%]
#13 149.2 ........................................................................ [ 92%]
#13 149.4 ..                                                                       [ 93%]
#13 149.4 tests/test_measures_sparse.py ................                           [ 94%]
#13 149.5 tests/test_serialize.py .........................................        [ 96%]
#13 149.5 tests/test_var.py .........                                              [ 96%]
#13 149.5 tests/test_vjp.py ...................................................    [100%]
#13 149.7
#13 149.7 =================================== FAILURES ===================================
#13 149.7 __________ TestApply.test_apply_errors_qubit_state_vector[complex64] ___________
#13 149.7 tests/test_apply.py:514: in test_apply_errors_qubit_state_vector
#13 149.7     qubit_device_2_wires.apply([qml.QubitStateVector(p, wires=[0, 1])])
#13 149.7 ../venv/lib/python3.8/site-packages/PennyLane_Lightning-0.25.0.dev10-py3.8-linux-x86_64.egg/pennylane_lightning/lightning_qubit.py:165: in apply
#13 149.7     self._apply_state_vector(operations[0].parameters[0].copy(), operations[0].wires)
#13 149.7 ../venv/lib/python3.8/site-packages/pennylane/devices/default_qubit.py:619: in _apply_state_vector
#13 149.7     raise ValueError("State vector must be of length 2**wires.")
#13 149.7 E   ValueError: State vector must be of length 2**wires.
#13 149.7
#13 149.7 During handling of the above exception, another exception occurred:
#13 149.7 tests/test_apply.py:514: in test_apply_errors_qubit_state_vector
#13 149.7     qubit_device_2_wires.apply([qml.QubitStateVector(p, wires=[0, 1])])
#13 149.7 E   AssertionError: Regex pattern 'State vector must have shape \\(2\\*\\*wires,\\) or \\(batch_size, 2\\*\\*wires\\).' does not match 'State vector must be of length 2**wires.'.
#13 149.7 __________ TestApply.test_apply_errors_qubit_state_vector[complex128] __________
#13 149.7 tests/test_apply.py:514: in test_apply_errors_qubit_state_vector
#13 149.7     qubit_device_2_wires.apply([qml.QubitStateVector(p, wires=[0, 1])])
#13 149.7 ../venv/lib/python3.8/site-packages/PennyLane_Lightning-0.25.0.dev10-py3.8-linux-x86_64.egg/pennylane_lightning/lightning_qubit.py:165: in apply
#13 149.7     self._apply_state_vector(operations[0].parameters[0].copy(), operations[0].wires)
#13 149.7 ../venv/lib/python3.8/site-packages/pennylane/devices/default_qubit.py:619: in _apply_state_vector
#13 149.7     raise ValueError("State vector must be of length 2**wires.")
#13 149.7 E   ValueError: State vector must be of length 2**wires.
#13 149.7
#13 149.7 During handling of the above exception, another exception occurred:
#13 149.7 tests/test_apply.py:514: in test_apply_errors_qubit_state_vector
#13 149.7     qubit_device_2_wires.apply([qml.QubitStateVector(p, wires=[0, 1])])
#13 149.7 E   AssertionError: Regex pattern 'State vector must have shape \\(2\\*\\*wires,\\) or \\(batch_size, 2\\*\\*wires\\).' does not match 'State vector must be of length 2**wires.'.
#13 149.7 ________________________ test_no_op_arithmetic_support _________________________
#13 149.7 tests/test_device.py:51: in test_no_op_arithmetic_support
#13 149.7     obs = qml.prod(qml.PauliX(0), qml.PauliY(1))
#13 149.7 E   AttributeError: module 'pennylane' has no attribute 'prod'
#13 149.7 =============================== warnings summary ===============================
#13 149.7 tests/test_adjoint_jacobian.py::test_qchem_expvalcost_correct[float32-complex64]
#13 149.7 tests/test_adjoint_jacobian.py::test_qchem_expvalcost_correct[float64-complex128]
#13 149.7   /opt/venv/lib/python3.8/site-packages/pennylane/vqe/vqe.py:153: UserWarning: ExpvalCost is deprecated, use qml.expval() instead. For optimizing Hamiltonian measurements with measuring commuting terms in parallel, use the grouping_type keyword in qml.Hamiltonian.
#13 149.7     warnings.warn(
#13 149.7
#13 149.7 tests/test_vjp.py::TestVectorJacobianProduct::test_statevector_ry[complex64]
#13 149.7 tests/test_vjp.py::TestVectorJacobianProduct::test_statevector_ry[complex128]
#13 149.7 tests/test_vjp.py::TestVectorJacobianProduct::test_statevector_complex_circuit[complex64]
#13 149.7 tests/test_vjp.py::TestVectorJacobianProduct::test_statevector_complex_circuit[complex128]
#13 149.7   /opt/venv/lib/python3.8/site-packages/PennyLane_Lightning-0.25.0.dev10-py3.8-linux-x86_64.egg/pennylane_lightning/lightning_qubit.py:488: UserWarning: The vjp method only works with complex-valued dy when the tape is returning a statevector. Upcasting dy.
#13 149.7     warn(
#13 149.7
#13 149.7 -- Docs: https://docs.pytest.org/en/stable/how-to/capture-warnings.html
#13 149.7 =========================== short test summary info ============================
#13 149.7 FAILED tests/test_apply.py::TestApply::test_apply_errors_qubit_state_vector[complex64]
#13 149.7 FAILED tests/test_apply.py::TestApply::test_apply_errors_qubit_state_vector[complex128]
#13 149.7 FAILED tests/test_device.py::test_no_op_arithmetic_support - AttributeError: ...
#13 149.7 = 3 failed, 1653 passed, 33 skipped, 2 xfailed, 2 xpassed, 6 warnings in 30.94s =
#13 150.0 make: *** [Makefile:63: test-builtin] Error 1
------
executor failed running [/bin/sh -c pip install --no-cache-dir wheel     pytest     pytest-cov     pytest-mock     flaky     sphinx     && pip install --no-cache-dir -r requirements.txt     && pip uninstall -y PennyLane_Lightning     && make install     && make test-python     && make test-cpp]: exit code: 2

Add LM implementations of CSWAP & Toffoli gates

Before posting an issue

Search existing GitHub issues to make sure the issue does not already exist:
https://github.com/xanaduai/pennylane-lightning/issues

If posting a PennyLane-Lightning issue, delete everything above the dashed line, and fill
in the template. If the issue is a bug, start the title of the issue with [BUG].

If making a feature request, delete the following template and describe, in detail,
the feature and why it is needed.

For general technical details check out our documentation:
https://pennylane-lightning.readthedocs.io/


Issue description

Description of the issue - include code snippets and screenshots here
if relevant. You may use the following template below

  • Expected behavior: (What you expect to happen)

  • Actual behavior: (What actually happens)

  • Reproduces how often: (What percentage of the time does it reproduce?)

  • System information: (post the output of import pennylane as qml; qml.about())

Source code and tracebacks

Please include any additional code snippets and error tracebacks related
to the issue here.

Additional information

Any additional information, configuration or data that might be necessary
to reproduce the issue.

Disable `qml.Snapshot` operation

Issue description

PennyLane will soon receive an operation to examine the values of the statevector over the course of a given circuit, using qml.Snapshot (see PennyLaneAI/pennylane#2233). As a debug feature, this is not required to be currently supported in Lightning and so should be explicitly disabled

PR documentation builds

Currently, if the environment variable MOCK_DOCS is set, the setup.py file will skip the building of the wheels. This is required for ReadTheDocs, where C++ extensions cannot be built.

Unfortunately, ReadTheDocs environment variables are not passed to PRs and forks, so we cannot activate the option to build the docs for PRs. An alternative option would be to simply mock out the C++ extensions in the conf.py file, like we do for The Walrus.

Add virtual destructor to `StateVector` class

Issue description

The Lightning StateVector class currently does not define a virtual destructor. This raises the usual problems when subclassing.

Note: Add ~virtual StateVector(){} to class definition.

MacOS arm64 wheels installed via pip result in ImportError

Issue description

Running the following code:

from numpy import gradient
import pennylane as qml
from pennylane import qchem
from pennylane import numpy as np
from functools import partial
from time import perf_counter

# Build the electronic Hamiltonian
symbols, coordinates = (['H', 'H'], np.array([0., 0., -0.66140414, 0., 0., 0.66140414]))
h, qubits = qml.qchem.molecular_hamiltonian(symbols, coordinates)

# Number of electrons
electrons = 2

# Define the HF state
ref_state = qchem.hf_state(electrons, qubits)

# Generate single and double excitations
singles, doubles = qchem.excitations(electrons, qubits)

# Map excitations to the wires the UCCSD circuit will act on
s_wires, d_wires = qchem.excitations_to_wires(singles, doubles)

# Define the device
dev = qml.device('lightning.qubit', wires=qubits)

# Define the UCCSD ansatz
ansatz = partial(qml.UCCSD, init_state=ref_state, s_wires=s_wires, d_wires=d_wires)

# Define the cost function
cost_fn = qml.ExpvalCost(ansatz, h, dev)

# Compute the expectation value of 'h' for given set of parameters 'params'
params = np.array(np.zeros(len(singles) + len(doubles)), requires_grad=True)
print(cost_fn(params))

opt = qml.GradientDescentOptimizer(stepsize=0.4)
max_iterations = 100
conv_tol = 1e-06


energy = [cost_fn(params)]


for n in range(max_iterations):
    start_time = perf_counter()
    theta, prev_energy = opt.step_and_cost(cost_fn, params)

    energy.append(cost_fn(theta))

    conv = np.abs(energy[-1] - prev_energy)

    #if n % 2 == 0:
    print(f"Step = {n},  Energy = {energy[-1]:.8f} Ha")

    if conv <= conv_tol:
        break

print("\n" f"Final value of the ground-state energy = {energy[-1]:.8f} Ha")

Results in the following error traceback:

Traceback (most recent call last):
  File "/Users/joelbierman/Desktop/pennylane/tutorial_vqe.py", line 26, in <module>
    dev = qml.device('lightning.qubit', wires=qubits)
  File "/Users/joelbierman/miniforge3/envs/pennylane-test/lib/python3.9/site-packages/pennylane/__init__.py", line 297, in device
    plugin_device_class = plugin_devices[name].load()
  File "/Users/joelbierman/miniforge3/envs/pennylane-test/lib/python3.9/site-packages/pkg_resources/__init__.py", line 2472, in load
    return self.resolve()
  File "/Users/joelbierman/miniforge3/envs/pennylane-test/lib/python3.9/site-packages/pkg_resources/__init__.py", line 2478, in resolve
    module = __import__(self.module_name, fromlist=['__name__'], level=0)
  File "/Users/joelbierman/miniforge3/envs/pennylane-test/lib/python3.9/site-packages/pennylane_lightning/__init__.py", line 17, in <module>
    from .lightning_qubit import LightningQubit
  File "/Users/joelbierman/miniforge3/envs/pennylane-test/lib/python3.9/site-packages/pennylane_lightning/lightning_qubit.py", line 48, in <module>
    from .lightning_qubit_ops import (
ImportError: dlopen(/Users/joelbierman/miniforge3/envs/pennylane-test/lib/python3.9/site-packages/pennylane_lightning/lightning_qubit_ops.cpython-39-darwin.so, 2): no suitable image found.  Did find:
        /Users/joelbierman/miniforge3/envs/pennylane-test/lib/python3.9/site-packages/pennylane_lightning/lightning_qubit_ops.cpython-39-darwin.so: mach-o, but wrong architecture
        /Users/joelbierman/miniforge3/envs/pennylane-test/lib/python3.9/site-packages/pennylane_lightning/lightning_qubit_ops.cpython-39-darwin.so: mach-o, but wrong architecture*

Setting "default.qubit" instead of "lightning.qubit" for the device works fine. There seems to be an issue with the lightning builds.

Expected behavior:

No ImportError

  • Actual behavior:

ImportError.

  • Reproduces how often:

100%

  • System information:
Name: PennyLane
Version: 0.23.1
Summary: PennyLane is a Python quantum machine learning library by Xanadu Inc.
Home-page: https://github.com/XanaduAI/pennylane
Author: None
Author-email: None
License: Apache License 2.0
Location: /Users/joelbierman/miniforge3/envs/pennylane-test/lib/python3.9/site-packages
Requires: autoray, numpy, scipy, semantic-version, pennylane-lightning, networkx, retworkx, appdirs, cachetools, toml, autograd
Required-by: PennyLane-Qchem, PennyLane-Lightning

Platform info:           macOS-11.6.2-arm64-arm-64bit
Python version:          3.9.6
Numpy version:           1.21.0
Scipy version:           1.7.0
Installed devices:
- default.gaussian (PennyLane-0.23.1)
- default.mixed (PennyLane-0.23.1)
- default.qubit (PennyLane-0.23.1)
- default.qubit.autograd (PennyLane-0.23.1)
- default.qubit.jax (PennyLane-0.23.1)
- default.qubit.tf (PennyLane-0.23.1)
- default.qubit.torch (PennyLane-0.23.1)
- lightning.qubit (PennyLane-Lightning-0.23.0)

Source code and tracebacks

See above.

Additional information

In the past when I have encountered this sort of error for other packages, it was because while the wheel names indicated that they were built for arm64, the actual wheel contents contained code compiled to x86. My guess is that there's something buggy with the build process for these published wheels.

Allow further extensibility for non-standard data types

Issue description

The static polymorphic methods for getting the data pointer in Lightning assume std::complex data types. Certain platforms assume C-like data structs instead (eg struct cmplx { float x; float y;}). We can ensure that all CRTP-like uses of the StateVectorBase class supports such data extensions by allowing the return datatype to be decltype(auto), which will infer the type from the cast derived method.

A modification from:

    [[nodiscard]] inline auto getData() -> ComplexPrecisionT * {
        return static_cast<Derived *>(this)->getData();

to

    [[nodiscard]] inline auto getData() -> decltype(auto) {
        return static_cast<Derived &>(*this).getData();

should allow this.

Add support for `qml.Hamiltonian` with `lightning.qubit` for `diff_method='adjoint'`

Issue description

Description of the issue:
When running the following simple code block, it throws the NotImplementedError. There is no issue if I change to other simulators such as default.qubit, or replace the observable to simple observables such as qml.PauliX(0).

import pennylane as qml
import numpy as np

dev = qml.device("lightning.qubit", wires=4)
H, qubits = qml.qchem.molecular_hamiltonian(['H','H'], np.array([0.0, 0.1, 0.0, 0.0, -0.1, 0.0]))

@qml.qnode(dev, diff_method='adjoint')
def circuit(params):
    qml.RX(params, wires=1)
    return qml.expval(H)

circuit(0.123)
  • Expected behavior: It returns the expectation value of the Hamiltonian.

  • Actual behavior: It throws NotImplementedError.

  • Reproduces how often: Every time

  • System information:

Name: PennyLane
Version: 0.20.0
Summary: PennyLane is a Python quantum machine learning library by Xanadu Inc.
Home-page: https://github.com/XanaduAI/pennylane
Author:
Author-email:
License: Apache License 2.0
Location: /usr/local/lib/python3.7/site-packages
Requires: appdirs, autograd, autoray, cachetools, networkx, numpy, pennylane-lightning, scipy, semantic-version, toml
Required-by: amazon-braket-pennylane-plugin, PennyLane-Lightning, PennyLane-Qchem
Platform info: Linux-4.14.256-197.484.amzn2.x86_64-x86_64-with-debian-buster-sid
Python version: 3.7.10
Numpy version: 1.19.2
Scipy version: 1.5.2
Installed devices:

  • default.gaussian (PennyLane-0.20.0)
  • default.mixed (PennyLane-0.20.0)
  • default.qubit (PennyLane-0.20.0)
  • default.qubit.autograd (PennyLane-0.20.0)
  • default.qubit.jax (PennyLane-0.20.0)
  • default.qubit.tf (PennyLane-0.20.0)
  • default.qubit.torch (PennyLane-0.20.0)
  • lightning.qubit (PennyLane-Lightning-0.20.2)
  • braket.aws.qubit (amazon-braket-pennylane-plugin-1.3.0)
  • braket.local.qubit (amazon-braket-pennylane-plugin-1.3.0)

Add CMake build support for tests

Currently, the package has compilation support using a Makefile, and additional build/install support within setup.py. Replacing the tests Makefile (Linux/Mac only) with CMake will allow for a much easier compilation experience.

The following CMake features will be required:

  • Use features of CMake language from version 3.14 and previous only.
  • Enable C++11 as required C++ standard.
  • Link against dependent libraries: Pybind11
  • Build generates test binary (see here) that runs C++ test suite and mirrors existing Makefile build.

The following features are currently optional:

  • Testing and verification of cross-platform compilation (CMake is supported on Win, Mac, Linux).
  • Enable compile-time flags for different optimizations (e.g -march=native, -flto, etc.).
  • Tie tests into CMake CTest infrastructure.
  • Support for entire package to be compiled using CMake.

T-gate constexpr function definition is incorrect

Issue description

The definition of the T-gate in Gates.hpp currently mirrors the S gate. This should be rectified. The gate definitions are not currently used in gate applications, and so does not affect program correctness.

  • Expected behavior: T-gate definition should be correct.

  • Actual behavior: (What actually happens)

  • Reproduces how often: (What percentage of the time does it reproduce?)

  • System information: (post the output of import pennylane as qml; qml.about())

Support the same set of observables in forward/backward path

Now we support expval of a sparse Hamiltonian (with Kokkos), but not for the adjoint differentiation method.

On the other hand, expval of a Hamiltonian involving Hermitian is not supported in the forward path (as default.qubit does not support it), but we support it in the adjoint differentiation method.

Wheel from cibuildwheel on Windows with Python3.8 is buggy

Before posting an issue

Search existing GitHub issues to make sure the issue does not already exist:
https://github.com/xanaduai/pennylane-lightning/issues

If posting a PennyLane-Lightning issue, delete everything above the dashed line, and fill
in the template. If the issue is a bug, start the title of the issue with [BUG].

If making a feature request, delete the following template and describe, in detail,
the feature and why it is needed.

For general technical details check out our documentation:
https://pennylane-lightning.readthedocs.io/


Issue description

Description of the issue - include code snippets and screenshots here
if relevant. You may use the following template below

  • Expected behavior: (What you expect to happen)
qml.device('lightning.qubit', wires=4)

should work on Windows+Python(>=3.8)+using wheel built from cibuildwheel

  • Actual behavior: (What actually happens)
    It fails in this particular set-ups. It seems like the cibuildwheel does not use cl.exe and adds some MinGW dependencies (libgcc_s_seh-1.dll and ligstdc++-6.dll). In Python<3.8, Python has no difficulty in finding the required dependencies. However, due to changed dll path policy in Python 3.8, it does not find the required dll files and raises error.

  • Reproduces how often: (What percentage of the time does it reproduce?)

  • System information: (post the output of import pennylane as qml; qml.about())

Source code and tracebacks

Please include any additional code snippets and error tracebacks related
to the issue here.

Additional information

Any additional information, configuration or data that might be necessary
to reproduce the issue.

Use GCC for macOS wheels/tests

As Lightning compiled with GCC is better performing than with Clang, it is better to use GCC for building wheels for macOS. In addition, GCC supports new C++20/23 functionalities better. Still, for robustness, we may have a Clang test in CI.

Memory loss in lightning.qubit

Issue description

Memory loss occurs when training a Variational Quantum Classifier with lightning.qubit. This Python code brings out the difference of memory usage between lightning.qubit and default.qubit.

Here is the plot of memory usage over time of lightning.qubit vs. default.qubit:
lightning_bug_plot
And a few screenshots taken over time:
lightning_bug_1
lightning_bug_2
lightning_bug_3

  • Expected behavior: Similar behavior for lightning and default

  • Actual behavior: lightning has an increasing memory usage over time

  • Reproduces how often: Reproductible anytime

  • System information:
    Name: PennyLane
    Version: 0.19.1
    Summary: PennyLane is a Python quantum machine learning library by Xanadu Inc.
    Home-page: https://github.com/XanaduAI/pennylane
    Author: Aymeric Degroote
    Author-email: [email protected]
    License: Apache License 2.0
    Location: /home/aymeric/.local/lib/python3.8/site-packages
    Requires: appdirs, autograd, autoray, cachetools, networkx, numpy, pennylane-lightning, scipy, semantic-version, toml
    Required-by: PennyLane-Lightning, PennyLane-SF, prevision-quantum-nn
    Platform info: Linux-5.11.0-44-generic-x86_64-with-glibc2.29
    Python version: 3.8.10
    Numpy version: 1.21.2
    Scipy version: 1.7.1
    Installed devices:

  • default.gaussian (PennyLane-0.19.1)
  • default.mixed (PennyLane-0.19.1)
  • default.qubit (PennyLane-0.19.1)
  • default.qubit.autograd (PennyLane-0.19.1)
  • default.qubit.jax (PennyLane-0.19.1)
  • default.qubit.tf (PennyLane-0.19.1)
  • default.qubit.torch (PennyLane-0.19.1)
  • default.tensor (PennyLane-0.19.1)
  • default.tensor.tf (PennyLane-0.19.1)
  • strawberryfields.fock (PennyLane-SF-0.19.0)
  • strawberryfields.gaussian (PennyLane-SF-0.19.0)
  • strawberryfields.gbs (PennyLane-SF-0.19.0)
  • strawberryfields.remote (PennyLane-SF-0.19.0)
  • strawberryfields.tf (PennyLane-SF-0.19.0)
  • lightning.qubit (PennyLane-Lightning-0.20.2)

[BUG] qml.qnn.TorchLayer breaks multi GPU usage

Issue description

  • Expected behavior: (What you expect to happen)
    Setup: 4 Nvidia GPUs

Expected return:

Let's use 4 GPUs!
Average loss over epoch 1: 0.4943
Average loss over epoch 2: 0.4226
Accuracy: 75.5%
  • Actual behavior: (What actually happens)
    Got back:
Let's use 4 GPUs!
....(the full error message can be found in Traceback below)...
RuntimeError: stack expects each tensor to be equal size, but got [0] at entry 0 and [2] at entry 1
  • Reproduces how often: (What percentage of the time does it reproduce?)
    Error occurs always.

  • System information: (post the output of import pennylane as qml; qml.about())

>>> import pennylane as qml; qml.about()
Name: PennyLane
Version: 0.21.0
Summary: PennyLane is a Python quantum machine learning library by Xanadu Inc.
Home-page: https://github.com/XanaduAI/pennylane
Author: 
Author-email: 
License: Apache License 2.0
Location: /home/miniconda3/envs/py9/lib/python3.9/site-packages
Requires: autoray, retworkx, cachetools, semantic-version, scipy, pennylane-lightning, networkx, numpy, toml, appdirs, autograd
Required-by: PennyLane-Lightning
Platform info:           Linux-4.18.0-348.7.1.el8_5.x86_64-x86_64-with-glibc2.28
Python version:          3.9.7
Numpy version:           1.22.2
Scipy version:           1.8.0
Installed devices:
- default.gaussian (PennyLane-0.21.0)
- default.mixed (PennyLane-0.21.0)
- default.qubit (PennyLane-0.21.0)
- default.qubit.autograd (PennyLane-0.21.0)
- default.qubit.jax (PennyLane-0.21.0)
- default.qubit.tf (PennyLane-0.21.0)
- default.qubit.torch (PennyLane-0.21.0)
- lightning.qubit (PennyLane-Lightning-0.21.0)

Source code and tracebacks

  • Source code
# Coping and pasting code from: https://pennylane.ai/qml/demos/tutorial_qnn_module_torch.html

import torch
import matplotlib.pyplot as plt
import numpy as np
from sklearn.datasets import make_moons

# Set random seeds
torch.manual_seed(42)
np.random.seed(42)

X, y = make_moons(n_samples=200, noise=0.1)
y_ = torch.unsqueeze(torch.tensor(y), 1)  # used for one-hot encoded labels
y_hot = torch.scatter(torch.zeros((200, 2)), 1, y_, 1)

c = ["#1f77b4" if y_ == 0 else "#ff7f0e" for y_ in y]  # colours for each class
# Removing the plot since we don't need it for now
#plt.axis("off")
#plt.scatter(X[:, 0], X[:, 1], c=c)
#plt.show()

import pennylane as qml

n_qubits = 2
#dev = qml.device("default.qubit", wires=n_qubits)
dev = qml.device("lightning.qubit", wires=n_qubits)

@qml.qnode(dev)
def qnode(inputs, weights):
    qml.AngleEmbedding(inputs, wires=range(n_qubits))
    qml.BasicEntanglerLayers(weights, wires=range(n_qubits))
    return [qml.expval(qml.PauliZ(wires=i)) for i in range(n_qubits)]

n_layers = 6
weight_shapes = {"weights": (n_layers, n_qubits)}

qlayer = qml.qnn.TorchLayer(qnode, weight_shapes)

clayer_1 = torch.nn.Linear(2, 2)
clayer_2 = torch.nn.Linear(2, 2)
softmax = torch.nn.Softmax(dim=1)
layers = [clayer_1, qlayer, clayer_2, softmax]
#layers = [clayer_1, clayer_2, softmax]
model = torch.nn.Sequential(*layers)

if torch.cuda.device_count() > 1:
  print("Let's use", torch.cuda.device_count(), "GPUs!")
  #dim = 0 [30, xxx] -> [10, ...], [10, ...], [10, ...] on 3 GPUs
  model = torch.nn.DataParallel(model)
  
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")

model.to(device)

opt = torch.optim.SGD(model.parameters(), lr=0.2)
loss = torch.nn.L1Loss()

X = torch.tensor(X, requires_grad=True).float()
y_hot = y_hot.float()

batch_size = 5
batches = 200 // batch_size

data_loader = torch.utils.data.DataLoader(
    list(zip(X, y_hot)), batch_size=5, shuffle=True, drop_last=True
)

epochs = 2

for epoch in range(epochs):

    running_loss = 0

    for xs, ys in data_loader:
        opt.zero_grad()

        # Moving data to device as needed
        xs=xs.to(device)
        ys=ys.to(device)

        loss_evaluated = loss(model(xs), ys)
        loss_evaluated.backward()

        opt.step()

        running_loss += loss_evaluated

    avg_loss = running_loss / batches
    print("Average loss over epoch {}: {:.4f}".format(epoch + 1, avg_loss))

# Moving data to device as needed
X = X.to(device)

y_pred = model(X)
#predictions = torch.argmax(y_pred, axis=1).detach().numpy()
predictions = torch.argmax(y_pred, axis=1).detach().cpu().numpy()

correct = [1 if p == p_true else 0 for p, p_true in zip(predictions, y)]
accuracy = sum(correct) / len(correct)
print(f"Accuracy: {accuracy * 100}%")
  • Trackback
Traceback (most recent call last):
  File "/home/GPU_PL_lightning.py", line 85, in <module>
    loss_evaluated = loss(model(xs), ys)
  File "/home/miniconda3/envs/py9/lib/python3.9/site-packages/torch/nn/modules/module.py", line 1102, in _call_impl
    return forward_call(*input, **kwargs)
  File "/home/miniconda3/envs/py9/lib/python3.9/site-packages/torch/nn/parallel/data_parallel.py", line 168, in forward
    outputs = self.parallel_apply(replicas, inputs, kwargs)
  File "/home/miniconda3/envs/py9/lib/python3.9/site-packages/torch/nn/parallel/data_parallel.py", line 178, in parallel_apply
    return parallel_apply(replicas, inputs, kwargs, self.device_ids[:len(replicas)])
  File "/home/miniconda3/envs/py9/lib/python3.9/site-packages/torch/nn/parallel/parallel_apply.py", line 86, in parallel_apply
    output.reraise()
  File "/home/miniconda3/envs/py9/lib/python3.9/site-packages/torch/_utils.py", line 434, in reraise
    raise exception
RuntimeError: Caught RuntimeError in replica 1 on device 1.
Original Traceback (most recent call last):
  File "/home/miniconda3/envs/py9/lib/python3.9/site-packages/torch/nn/parallel/parallel_apply.py", line 61, in _worker
    output = module(*input, **kwargs)
  File "/home/miniconda3/envs/py9/lib/python3.9/site-packages/torch/nn/modules/module.py", line 1102, in _call_impl
    return forward_call(*input, **kwargs)
  File "/home/miniconda3/envs/py9/lib/python3.9/site-packages/torch/nn/modules/container.py", line 141, in forward
    input = module(input)
  File "/home/miniconda3/envs/py9/lib/python3.9/site-packages/torch/nn/modules/module.py", line 1102, in _call_impl
    return forward_call(*input, **kwargs)
  File "/home/miniconda3/envs/py9/lib/python3.9/site-packages/pennylane/qnn/torch.py", line 278, in forward
    return torch.stack(reconstructor)
RuntimeError: stack expects each tensor to be equal size, but got [0] at entry 0 and [2] at entry 1

Additional information

This error is surprisingly different from PennyLaneAI/pennylane#2203

Handle IsingXY gate

As IsingXY gate is being added to PennyLane (PennyLaneAI/pennylane#2649), we need to check it does not break forward/backward computation in Lightning. Otherwise, we need to add its implementation in Lightning.

Update Python version support

We should add support for Python 3.9 and drop support for 3.6, and have this reflected in the wheels uploaded to PyPI.

Add git tag `latest` for most recent tagged release

Issue description

The goal here is to have a reproducible way to obtain the latest version of the released package from git. When tagging with a given release, we should also create/update an additional tag latest to allow this to be used with dependent packages.

  • Expected behavior: (What you expect to happen)

  • Actual behavior: (What actually happens)

  • Reproduces how often: (What percentage of the time does it reproduce?)

  • System information: (post the output of import pennylane as qml; qml.about())

Source code and tracebacks

Please include any additional code snippets and error tracebacks related
to the issue here.

Additional information

Any additional information, configuration or data that might be necessary
to reproduce the issue.

Update `pennylane.measure` usage due to recent changes in PennyLane

Recent updates to PennyLane have caused some dependent modules to be moved. These paths should be updated in Lightning.

==================================== ERRORS ====================================
___________________ ERROR collecting tests/test_measures.py ____________________
ImportError while importing test module '/home/runner/work/pennylane-lightning/pennylane-lightning/main/tests/test_measures.py'.
Hint: make sure your test modules/packages have valid Python names.
Traceback:
/opt/hostedtoolcache/Python/3.7.12/x64/lib/python3.7/importlib/__init__.py:127: in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
tests/test_measures.py:19: in <module>
    from pennylane.measure import (
E   ModuleNotFoundError: No module named 'pennylane.measure'

Update CI wheel-builder images

Currently the Linux x86_64 wheelbuilder image depends on an older version of the manylinux images, resulting in binaries compiled with older (v8.x) of GCC. Newer versions of GCC see to perform better optimisations of fundamental complex kernel operations, and should be favoured. We should upgrade the image from manylinux2010 to manylinux2014, which upgrades the GCC version to 10+

Add pre-release semantic versioned wheels to PyPI

Issue description

With changes to the current master of PennyLane, we expect Lightning to work in tandem. Adding rc releases to PyPI will help in testing and development infrastructure with modifcations to the core PennyLane functionality, and dependent projects.

Add wheels for Python 3.10

Given the new release of Python 3.10, Lightning will require updates to the wheelbuilder to support it.

Build stand-alone lightning binary for gate aggregate performance tests

Issue description

Benchmarking lightning directly without the Python interface can help in isolating performance regressions between the bindings and the underlying kernels. The purpose of this task is to create a PennyLane Lightning binary without the Python interface, and test the aggregate gate performance.

Your task will be the following:

  • Build a quantum circuit simulation binary directly in C++ using PennyLane Lightning in the new examples directory. You can make use of the class StateVectorManaged to create and allocate the required memory for your simulation. Examples of use are located within the src/tests/Test_StateVectorManaged_*.cpp files. You can use either the dispatcher (gate-string call) or direct gate call to make use of gates. You can also use CMake to assist with the build process (see the JET guide for an example of how this may be achieved).

Your simulation binary should make a user-defined number of calls to a user-defined number of qubits for the following built-in parametric and non-parametric gates:
- Non-parametric: (PauliX, PauliY, PauliZ, Hadamard, CNOT, CZ)
- Parametric: (RX, RY, RZ, CRX, CRY, CRZ)
- User-defined call number can be read from a command-line argument (eg ./binary 10 6 will run each gate ten times in the circuit per qubit, with 6 qubits overall).

Run your simulation for qubit counts ranging from 6 - 22 in steps of 2, and plot the timing results, noting your compiler type, and optimization level. Wall-clock time will be sufficient here.

Compilation fails on windows with `error C2641: cannot deduce template argument for 'std::array'`

Issue description

Description of the issue - include code snippets and screenshots here
if relevant. You may use the following template below

  • Expected behavior: (What you expect to happen)

Compilation succeeds

  • Actual behavior: (What actually happens)

Compilations fails

  • Reproduces how often: (What percentage of the time does it reproduce?)

Every time

  • System information: (post the output of import pennylane as qml; qml.about())

Azure Pipelines

Source code and tracebacks

Please include any additional code snippets and error tracebacks related
to the issue here.

Logs: https://dev.azure.com/conda-forge/feedstock-builds/_build/results?buildId=455620&view=logs&j=171a126d-c574-5c8c-1269-ff3b989e923d&t=1183ba29-a0b5-5324-8463-2a49ace9e213&l=1172

Build instructions: https://github.com/regro-cf-autotick-bot/pennylane-lightning-feedstock/blob/0.21.0_h5d7f77/recipe/meta.yaml

Additional information

Any additional information, configuration or data that might be necessary
to reproduce the issue.

This is in the contetxt of the conda-forge feedstock: https://github.com/conda-forge/pennylane-lightning-feedstock

Fix the EXPECT_EQ parameter's order

EXPECT_EQ is expecting "expected_value, actual_value". But code is having the parameters in reverse order. Fix is to swap the parameter's order.

Custom gate fails to run on Lightning backend


Issue description

Description of the issue - include code snippets and screenshots here
if relevant. You may use the following template below

  • Expected behavior: (What you expect to happen)
    Get gradient value.
  • Actual behavior: (What actually happens)
    Errors out
  • Reproduces how often: (What percentage of the time does it reproduce?)
    100%. tried updating to no avail.
  • System information: (post the output of import pennylane as qml; qml.about())
    Name: PennyLane
    Version: 0.16.0
    Summary: PennyLane is a Python quantum machine learning library by Xanadu Inc.
    Home-page: https://github.com/XanaduAI/pennylane
    Author:
    Author-email:
    License: Apache License 2.0
    Location: \lib\site-packages
    Requires: appdirs, scipy, autograd, autoray, semantic-version, numpy, toml, networkx
    Required-by: pennylane-qulacs, PennyLane-qiskit, PennyLane-Lightning
    Platform info: Windows-10-10.0.19043-SP0
    Python version: 3.9.6
    Numpy version: 1.20.3
    Scipy version: 1.6.2
    Installed devices:
  • default.gaussian (PennyLane-0.16.0)
  • default.mixed (PennyLane-0.16.0)
  • default.qubit (PennyLane-0.16.0)
  • default.qubit.autograd (PennyLane-0.16.0)
  • default.qubit.jax (PennyLane-0.16.0)
  • default.qubit.tf (PennyLane-0.16.0)
  • default.tensor (PennyLane-0.16.0)
  • default.tensor.tf (PennyLane-0.16.0)
  • qulacs.simulator (pennylane-qulacs-0.16.0)
  • qiskit.aer (PennyLane-qiskit-0.16.0)
  • qiskit.basicaer (PennyLane-qiskit-0.16.0)
  • qiskit.ibmq (PennyLane-qiskit-0.16.0)
  • lightning.qubit (PennyLane-Lightning-0.17.0)

Source code and tracebacks

import pennylane as qml
import numpy as np

class MyRX(qml.operation.Operation):
    num_params = 1
    num_wires = 1
    par_domain = "R"
    is_composable_rotation = True
    basis = "X"
    grad_method = "F"

    @classmethod
    def _matrix(cls, *params):
        return qml.RX._matrix(*params)

dev = qml.device('lightning.qubit', wires=3)
dev.operations.add("MyRX")

@qml.qnode(dev, diff_method='best')
def circuit(x):
    MyRX(x, wires=1)
    return qml.expval(qml.PauliZ(1))

par = qml.numpy.array(0.3)
qml.grad(circuit)(par)

Results in :

Traceback (most recent call last):
  .
  .
    qml.grad(circuit)(par)
  File "\pennylane\_grad.py", line 101, in __call__
    grad_value, ans = self._get_grad_fn(args)(*args, **kwargs)
  File "\autograd\wrap_util.py", line 20, in nary_f
    return unary_operator(unary_f, x, *nary_op_args, **nary_op_kwargs)
  File "\pennylane\_grad.py", line 118, in _grad_with_forward
    vjp, ans = _make_vjp(fun, x)
  File "\autograd\core.py", line 10, in make_vjp
    end_value, end_node =  trace(start_node, fun, x)
  File "\autograd\tracer.py", line 10, in trace
    end_box = fun(start_box)
  File "\autograd\wrap_util.py", line 15, in unary_f
    return fun(*subargs, **kwargs)
  File "\pennylane\qnode.py", line 602, in __call__
    res = self.qtape.execute(device=self.device)
  File "\pennylane\tape\tape.py", line 1277, in execute
    return self._execute(params, device=device)
  File "\autograd\tracer.py", line 44, in f_wrapped
    ans = f_wrapped(*argvals, **kwargs)
  File "\autograd\tracer.py", line 48, in f_wrapped
    return f_raw(*args, **kwargs)
  File "\pennylane\interfaces\autograd.py", line 165, in _execute
    res = self.execute_device(params, device=device)
  File "\pennylane\tape\tape.py", line 1308, in execute_device
    res = device.execute(self)
  File "\pennylane\_qubit_device.py", line 194, in execute
    self.apply(circuit.operations, rotations=circuit.diagonalizing_gates, **kwargs)
  File "\pennylane_lightning\lightning_qubit.py", line 112, in apply
    self._pre_rotated_state = self.apply_lightning(self._state, operations)
  File "\pennylane_lightning\lightning_qubit.py", line 140, in apply_lightning
    apply(state_vector, op_names, op_wires, op_inverse, op_param)
IndexError: invalid unordered_map<K, T> key

Please include any additional code snippets and error tracebacks related
to the issue here.

Additional information

Any additional information, configuration or data that might be necessary
to reproduce the issue.

Util::matrixMatrixProduct produces a wrong result with BLAS

Before posting an issue

Search existing GitHub issues to make sure the issue does not already exist:
https://github.com/xanaduai/pennylane-lightning/issues

If posting a PennyLane-Lightning issue, delete everything above the dashed line, and fill
in the template. If the issue is a bug, start the title of the issue with [BUG].

If making a feature request, delete the following template and describe, in detail,
the feature and why it is needed.

For general technical details check out our documentation:
https://pennylane-lightning.readthedocs.io/


Issue description

Description of the issue - include code snippets and screenshots here
if relevant. You may use the following template below

  • Expected behavior: (What you expect to happen)
    C++ tests should pass with BLAS

  • Actual behavior: (What actually happens)
    Tests fail

  • Reproduces how often: (What percentage of the time does it reproduce?)

  • System information: (post the output of import pennylane as qml; qml.about())

This is in fact caused by two convoluted problems:

  1. matrixMatProd(m_left, m_right, .., transpose=true) function in Util.hpp transpose m_right (expected behaviour) when BLAS is not used, but BLAS version transpose m_left.
  2. Currently C++ tests do not use BLAS even when -DENABLE_BLAS=ON is given as tests/CMakeLists.txt does not include external library or compile flags set by the options.

Fortunately, as wheels are built with DENABLE_BLAS=OFF, this does not cause an issue for usual users (unless someone compiles from the source directly). Still, I will fix this ASAP.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.