Code Monkey home page Code Monkey logo

prototype-qrao's Introduction

This repository, which implements quantum random access optimization (QRAO), has been contributed upstream to Qiskit Optimization, and is included with Qiskit Optimization version 0.6.0 and higher. Any future development will continue in the Qiskit Optimization repository instead of in this repository.


Platform Python Qiskit Qiskit Optimization License Code style: Black Tests Coverage

Launch Demo

Quantum Random Access Optimization

Table of Contents


About This Project

The Quantum Random Access Optimization (QRAO) module is designed to enable users to leverage a new quantum method for combinatorial optimization problems. This approach incorporates Quantum Random Access Codes (QRACs) as a tool to encode multiple classical binary variables into a single qubit, thereby saving quantum resources and enabling exploration of larger problem instances on a quantum computer. The encodings produce a local quantum Hamiltonian whose ground state can be approximated with standard algorithms such as VQE and QAOA, and then rounded to yield approximation solutions of the original problem.

The figure at the top of this page illustrates a simple example of encoding a degree-3 graph with 10 vertices into just 4 qubits, instead of 10. The graph is colored (with a largest-degree-first greedy algorithm) such that adjacent vertices are of a different color. Then, vertices of a given color are encoded using a (3,1,p) QRAC so that a maximum of 3 vertices are associated with a single qubit. Check out the background documentation to learn more about the coloring algorithm, QRACs, and building associated local quantum Hamiltonians.

This project evolved out of research at IBM Quantum on Approximate Solutions of Combinatorial Problems via Quantum Relaxations.

Problem Statement

Given a quadratic unconstrained binary optimization (QUBO) problem represented by a relaxation to a local quantum Hamiltonian, find an approximate solution by rounding the energy associated with a candidate ground state. This Hamiltonian is constructed using quantum random access codes for memory compression, which allows each qubit to encode more than one binary variable.

QRAO Flowchart

Quantum random access optimization is composed of two main steps as shown in the flowchart below.

  1. The input problem is encoded into a quantum Hamiltonian using the QuantumRandomAccessEncoding class. The maximum number of original classical binary variables encoded into each qubit is specified by max_vars_per_qubit.
  2. The encoded problem is solved with the QuantumRandomAccessOptimizer, which uses a minimum eigensolver on the quantum Hamiltonian, rounds the solution, and returns the processed results.


Installation

Python 3.7 or higher is required. Full installation instructions are provided in INSTALL.md, but here is a quick summary:

$ git clone https://github.com/qiskit-community/prototype-qrao.git
$ cd prototype-qrao
$ python3 -m venv venv
$ source venv/bin/activate
$ pip install tox notebook -e '.[notebook-dependencies]'
$ jupyter notebook

Documentation

Documentation is stored in the docs/ directory. It is organized according to the Diátaxis framework:


Important Usage Notes

The current version of this module has some important usage notes and limitations.

Supported Problem Types

As with qiskit-optimization, this module currently only supports input problems that are of type QuadraticProgram and that can be converted to a QUBO. Furthermore, the conversion to a QUBO must be made before encoding the problem into a quantum Hamiltonian with QuantumRandomAccessEncoding (refer to the tutorial to see an example of this).

Check out the documentation for qiskit-optimization to see how to construct a QuadraticProgram and apply converters to it (including a wrapper that converts a QuadraticProgram to a QUBO).

Statevector Simulator Usage

If you would like to use a statevector simulation for Magic Rounding, we advise using the new AerSimulator (source) with the "statevector" method and not the (soon-to-be-deprecated) StatevectorSimulator. The latter suffers from a very poor runtime scaling when used with the Magic Rounding scheme, as it effectively brute-forces all possible solutions.


How to Give Feedback

We encourage your feedback! You can share your thoughts with us by:


Contribution Guidelines

For information on how to contribute to this project, please take a look at our contribution guidelines.


Acknowledgements

This prototype is based on the research described in [1].

The initial codebase was written by Takashi Imamichi, Toshinari Itoko, and Bryce Fuller.


About Prototypes

Prototypes is a collaboration between developers and researchers that will give users access to prototypes from cutting-edge research in areas like quantum simulation and machine learning. These software packages are built on top of, and may eventually be integrated into the Qiskit SDK. They are a contribution as part of the Qiskit community.

Check out our blog post for more information!


Deprecation Policy

Prototypes are meant to evolve rapidly and, as such, do not follow Qiskit's deprecation policy. We may occasionally make breaking changes in order to improve the user experience. When possible, we will keep old interfaces and mark them as deprecated, as long as they can co-exist with the new ones. Each substantial improvement, breaking change, or deprecation will be documented in NEWS.md.


References

[1] Bryce Fuller, Charles Hadfield, Jennifer R. Glick, Takashi Imamichi, Toshinari Itoko, Richard J. Thompson, Yang Jiao, Marna M. Kagele, Adriana W. Blom-Schieber, Rudy Raymond, and Antonio Mezzacapo. Approximate Solutions of Combinatorial Problems via Quantum Relaxations. arXiv:2111.03167.


License

Apache License 2.0

prototype-qrao's People

Contributors

areeq-hasan avatar garrison avatar jenglick avatar mtreinish 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

Watchers

 avatar  avatar  avatar  avatar  avatar

prototype-qrao's Issues

Implement "implicit" `solve(problem)` interface, able to generate `encoding` on the fly

What is the expected enhancement?

The typical interface in Qiskit Optimzation for performing a quantum optimization is the OptimizationAlgorithm.solve(problem: QuadraticProgram) method. However, a lot happens "underneath the hood" when calling this, and when developing this prototype, we wanted to give users a bit more control over and understanding of what is happening. For instance, if one simply calls this method, they have no way of knowing beforehand how many qubits are necessary for the computation, so they won't know if it can run on a given piece of hardware until they try. So, we provided a more "explicit" interface, where the user must construct the QuantumRandomAccessEncoding explicitly, encode() it with a QuadraticProgram, and then pass it when constructing the optimizer.

However, it would be nice to implement the standard, implicit interface as well. One benefit is that users would then be able to use QRAO with the ADMM optimizer (and we should add a test case for this, once it becomes possible). Another benefit is that it is a prerequisite in case we want to enable the implicit conversion of any convertible QuadraticProgram into a QUBO (#10), just as the other optimization algorithms permit.

Potentially related: qiskit-community/qiskit-optimization#325, if it results in a more general overhaul of the solve() interface.

Implement alternative Qiskit gates for (3,1,p) QRAC basis rotation

What is the expected enhancement?

Currently, we use the the Qiskit r gate to return the basis rotation corresponding to the (3,1,p) QRAC:

if base == 0:
circ.r(-BETA, -np.pi / 4, i)
elif base == 1:
circ.r(np.pi - BETA, np.pi / 4, i)
elif base == 2:
circ.r(np.pi + BETA, np.pi / 4, i)
elif base == 3:
circ.r(BETA, -np.pi / 4, i)

However, this obscures the connection to the math in the paper. It would be more clear and helpful to the user if we instead implemented these basis transformations explicitly as written in Appendix IV of the paper (that is, with the relevant combination of rx, rz, and pauli x, y, z gates).

I have previously considered that we ought to keep it as a single gate, as that is the most precise way to specify the operation. However, I've since learned abou the Optimize1qGates[Decomposition] passes, which should be able to transpile to the optimal operations on hardware even if given as multiple single-qubit gates.

However, this might be at odds with parameterizing the gates for use with the primitives (#21), so we might want to see how that goes first.

mypy lint broken on `main`

Steps to reproduce the problem

tox -elint is currently broken, as can be seen from the Actions run resulting from the most recent commit to main. The previous run was successful, and the version of mypy has not changed since then. I am suspecting that this has been triggered by a new release of numpy.

What is the current behavior?

lint run-test: commands[3] | mypy qrao tests
qrao/encoding.py:445: error: Invalid index type "Union[int, str]" for "ndarray[Any, dtype[floating[_64Bit]]]"; expected type "Union[SupportsIndex, Tuple[SupportsIndex, ...]]"
qrao/encoding.py:453: error: Invalid index type "Union[int, str]" for "ndarray[Any, dtype[floating[_64Bit]]]"; expected type "Union[SupportsIndex, Tuple[SupportsIndex, ...]]"
qrao/encoding.py:456: error: Invalid index type "Tuple[Union[int, str], Union[int, str]]" for "ndarray[Any, dtype[floating[_64Bit]]]"; expected type "Union[SupportsIndex, Tuple[SupportsIndex, ...]]"
qrao/encoding.py:457: error: Invalid index type "Union[int, str]" for "ndarray[Any, dtype[floating[_64Bit]]]"; expected type "Union[SupportsIndex, Tuple[SupportsIndex, ...]]"
qrao/encoding.py:458: error: Invalid index type "Union[int, str]" for "ndarray[Any, dtype[floating[_64Bit]]]"; expected type "Union[SupportsIndex, Tuple[SupportsIndex, ...]]"
Found 5 errors in 1 file (checked 17 source files)
ERROR: InvocationError for command /home/runner/work/prototype-qrao/prototype-qrao/.tox/lint/bin/mypy qrao tests (exited with code 1)

What is the expected behavior?

It should not error.

And perhaps we should also run the linter Action on a cron job to notice issues like this sooner.

Please link to GH Page in GitHub's About section

It is useful to have the link to the project docs on the GitHub home page for this repo. (Right now, it's currently the research paper, which would instead be better to be a link from the docs.)

To fix this, go to the "Code"/home page of the repo. Then click the wheel on the "about" section on the right. Set the website to your GitHub pages.

Screenshot 2023-05-15 at 9 55 20 AM

Thanks!

Adaptive QRAC

What is the expected enhancement?

Let n represent the value of max_vars_per_qubit. Let's further assume that n is not 1, i.e. it is either 2 or 3. Depending on the variables-to-qubits assignment, it is possible that some qubits will have fewer than n decision variables assigned. However, at the moment, such qubits will still be encoded as an (n,1,p) QRAC. Ideally, the encoding on each qubit will be "adaptive," such that it uses an (m_i,1,p) QRAC, where m_i is the precise number of decision variables assigned to that qubit.

This is not difficult to fix, but we need to fix #7 first (update: done!); otherwise, magic rounding would no longer work generally.

Add tests of small known solutions for translator

What is the expected enhancement?

It would be nice to test whether QuantumRandomAccessEncoding.encode() (see encoding.py) encodes the Hamiltonian correctly (as stored in qubit_op, and -- for now, until #14 is merged -- offset) when given some small QuadraticPrograms explicitly. Having some explicit tests would fully ensure all the factors of 2 and minus signs are right. We are confident in its current state, but it's always better to have tests so things don't regress.

Qiskit Optimization has tests of a similar method, to_ising(), in test_ising.py.

Relevant information for understanding what the encode() method is meant to do can be found in the QRACs section of the background material.

No version of cplex available for M1 chip

Following the instructions in INSTALL.md , got an error on the line

$ pip install -e '.[notebook-dependencies]'

Which read:

ERROR: Could not find a version that satisfies the requirement cplex>=12.10 (from qrao[notebook-dependencies]) (from versions: none)
ERROR: No matching distribution found for cplex>=12.10

I am using Python version 3.10.4, but I believe the error is due to my laptops M1 chip (as it worked on my second laptop, which has the same OS/python version, but a different chip type)

Since cplex (to my knowledge) is only used as a check at the end of one tutorial, my solution was to just comment out the line in setup.py which makes cplex a dependency, namely

notebook_requirements = [
   # "cplex>=12.10",
    "tqdm[notebook]>=4.64",
]

However, I wanted to make the dev team aware of this issue going forward. Thanks

Implement implicit conversion to a QUBO (and interpretation of results)

What is the expected enhancement?

In Qiskit Optimization, it is customary for an OptimizationAlgorithm to attempt to convert a problem to a QUBO if necessary, by invoking QuadraticProgramToQubo (see also the converter tutorial). However, QRAO requires the user to perform this conversion manually, in large part because the current explicit interface requires the problem to be in its final form before the QuantumRandomAccessOptimizer is even constructed (#9). Once this requirement is dropped, it would be nice to allow implicit conversion to QUBOs as well.

When closing this, we should also remove the corresponding usage note from the README.

Provide access to rounding post-processing as a method

What is the expected enhancement?

Currently, QuantumRandomAccessOptimizer.solve() performs some post-processing on the rounding results. However, if one calls solve_relaxed() and then performs rounding manually, there is no convenient way to perform this post-processing. We should add such a way.

Once complete, we should also update the second tutorial with the new method and remove the following text:

Note: in the future, we will expose functionality to easily translate the results obtained by manually rounding back to the solution of original problem. Currently, this happens automatically when calling QuantumRandomAccessOptimizer.solve(problem).

Enable all pylint checks.

What is the expected enhancement?

Currently, a number of pylint checks are disabled throughout the code base. As we improve the code, we should either fix each check or disable it locally, in preparation for potential contribution to qiskit-optimization.

  • fixme
  • invalid-name
  • too-few-public-methods
  • missing-function-docstring
  • protected-access (waiting on #7)
  • redefined-outer-name
  • no-member
  • pointless-statement
  • too-many-locals
  • useless-super-delegation
  • consider-using-f-string
  • too-many-statements
  • too-many-branches
  • consider-using-enumerate
  • duplicate-code
  • docstring plugin tests (temporarily disabled in de3bf52)

Currently disabled within notebooks only

  • wrong-import-order
  • wrong-import-position (seems irrelevant, actually)
  • line-too-long

Duplicated classes and methods in Sphinx API docs

What is the expected enhancement?

Currently, there is a build of the API reference at https://qiskit-community.github.io/prototype-qrao/apidocs/. However, the use of Sphinx could be improved. Most notably, some classes and functions are duplicated, e.g. on the encoding page. The duplication is presumably because those identifiers are included explicitly in the autosummary directive; however, if identifiers aren't included there, they end up not being clickable for additional detail (e.g., as is currently the case with EncodingCommutationVerifier). I've not been able to figure out Sphinx sufficiently to fix this.

Improve magic rounding to work with all available encodings

What is the expected enhancement?

As the README currently says:

The Magic Rounding scheme is currently only compatible with the (3,1,p) QRAC for encoding classical binary variables onto qubits. [...] We plan to make Magic Rounding compatible with additional encoding options in the future.

Let's improve magic rounding to work regardless of whether max_vars_per_qubit is 1, 2, or 3 (i.e., with all available encodings).

Once this is complete, we can also remove the _encoding attribute from the RoundingContext and enable the protected-access pylint check throughout the code base.

Incorporate qiskit primitives into magic rounding

What is the expected enhancement?

Once we have migrated to qiskit-ibm-provider (#15), the next step is to adopt and move toward the qiskit primitives. We use the VQE implementation from Terra, so the only thing to migrate in QRAO itself is the magic rounding scheme (and for that we will use the Sampler primitive).

We will probably begin by parameterizing the various basis rotations, so that a single circuit can be sent to the primitives, along with various parameter sets.

Potentially alias `relaxed_results` to `min_eigen_solver_result`

What is the expected enhancement?

Currently, we have

@property
def relaxed_results(self) -> MinimumEigensolverResult:
return self._relaxed_results

but the parallel class in qiskit-optimization calls it min_eigen_solver_result. We've decided against renaming it in QRAO in this way because we feel it obscures the meaning of the relaxed Hamiltonian, but we might want to consider aliasing the property, such that either property works, for consistency with qiskit-optimization.

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.