GithubHelp home page GithubHelp logo

red-queen's Introduction

Qiskit

License Current Release Extended Support Release Downloads Coverage Status PyPI - Python Version Minimum rustc 1.70 Downloads DOI

Qiskit is an open-source SDK for working with quantum computers at the level of extended quantum circuits, operators, and primitives.

This library is the core component of Qiskit, which contains the building blocks for creating and working with quantum circuits, quantum operators, and primitive functions (Sampler and Estimator). It also contains a transpiler that supports optimizing quantum circuits, and a quantum information toolbox for creating advanced operators.

For more details on how to use Qiskit, refer to the documentation located here:

https://docs.quantum.ibm.com/

Installation

Warning

Do not try to upgrade an existing Qiskit 0.* environment to Qiskit 1.0 in-place. Read more.

We encourage installing Qiskit via pip:

pip install qiskit

Pip will handle all dependencies automatically and you will always install the latest (and well-tested) version.

To install from source, follow the instructions in the documentation.

Create your first quantum program in Qiskit

Now that Qiskit is installed, it's time to begin working with Qiskit. The essential parts of a quantum program are:

  1. Define and build a quantum circuit that represents the quantum state
  2. Define the classical output by measurements or a set of observable operators
  3. Depending on the output, use the primitive function sampler to sample outcomes or the estimator to estimate values.

Create an example quantum circuit using the QuantumCircuit class:

import numpy as np
from qiskit import QuantumCircuit

# 1. A quantum circuit for preparing the quantum state |000> + i |111>
qc_example = QuantumCircuit(3)
qc_example.h(0)          # generate superpostion
qc_example.p(np.pi/2,0)  # add quantum phase
qc_example.cx(0,1)       # 0th-qubit-Controlled-NOT gate on 1st qubit
qc_example.cx(0,2)       # 0th-qubit-Controlled-NOT gate on 2nd qubit

This simple example makes an entangled state known as a GHZ state $(|000\rangle + i|111\rangle)/\sqrt{2}$. It uses the standard quantum gates: Hadamard gate (h), Phase gate (p), and CNOT gate (cx).

Once you've made your first quantum circuit, choose which primitive function you will use. Starting with sampler, we use measure_all(inplace=False) to get a copy of the circuit in which all the qubits are measured:

# 2. Add the classical output in the form of measurement of all qubits
qc_measured = qc_example.measure_all(inplace=False)

# 3. Execute using the Sampler primitive
from qiskit.primitives.sampler import Sampler
sampler = Sampler()
job = sampler.run(qc_measured, shots=1000)
result = job.result()
print(f" > Quasi probability distribution: {result.quasi_dists}")

Running this will give an outcome similar to {0: 0.497, 7: 0.503} which is 000 50% of the time and 111 50% of the time up to statistical fluctuations. To illustrate the power of Estimator, we now use the quantum information toolbox to create the operator $XXY+XYX+YXX-YYY$ and pass it to the run() function, along with our quantum circuit. Note the Estimator requires a circuit without measurement, so we use the qc_example circuit we created earlier.

# 2. Define the observable to be measured 
from qiskit.quantum_info import SparsePauliOp
operator = SparsePauliOp.from_list([("XXY", 1), ("XYX", 1), ("YXX", 1), ("YYY", -1)])

# 3. Execute using the Estimator primitive
from qiskit.primitives import Estimator
estimator = Estimator()
job = estimator.run(qc_example, operator, shots=1000)
result = job.result()
print(f" > Expectation values: {result.values}")

Running this will give the outcome 4. For fun, try to assign a value of +/- 1 to each single-qubit operator X and Y and see if you can achieve this outcome. (Spoiler alert: this is not possible!)

Using the Qiskit-provided qiskit.primitives.Sampler and qiskit.primitives.Estimator will not take you very far. The power of quantum computing cannot be simulated on classical computers and you need to use real quantum hardware to scale to larger quantum circuits. However, running a quantum circuit on hardware requires rewriting to the basis gates and connectivity of the quantum hardware. The tool that does this is the transpiler, and Qiskit includes transpiler passes for synthesis, optimization, mapping, and scheduling. However, it also includes a default compiler, which works very well in most examples. The following code will map the example circuit to the basis_gates = ['cz', 'sx', 'rz'] and a linear chain of qubits $0 \rightarrow 1 \rightarrow 2$ with the coupling_map =[[0, 1], [1, 2]].

from qiskit import transpile
qc_transpiled = transpile(qc_example, basis_gates = ['cz', 'sx', 'rz'], coupling_map =[[0, 1], [1, 2]] , optimization_level=3)

Executing your code on real quantum hardware

Qiskit provides an abstraction layer that lets users run quantum circuits on hardware from any vendor that provides a compatible interface. The best way to use Qiskit is with a runtime environment that provides optimized implementations of sampler and estimator for a given hardware platform. This runtime may involve using pre- and post-processing, such as optimized transpiler passes with error suppression, error mitigation, and, eventually, error correction built in. A runtime implements qiskit.primitives.BaseSampler and qiskit.primitives.BaseEstimator interfaces. For example, some packages that provide implementations of a runtime primitive implementation are:

Qiskit also provides a lower-level abstract interface for describing quantum backends. This interface, located in qiskit.providers, defines an abstract BackendV2 class that providers can implement to represent their hardware or simulators to Qiskit. The backend class includes a common interface for executing circuits on the backends; however, in this interface each provider may perform different types of pre- and post-processing and return outcomes that are vendor-defined. Some examples of published provider packages that interface with real hardware are:

You can refer to the documentation of these packages for further instructions on how to get access and use these systems.

Contribution Guidelines

If you'd like to contribute to Qiskit, please take a look at our contribution guidelines. By participating, you are expected to uphold our code of conduct.

We use GitHub issues for tracking requests and bugs. Please join the Qiskit Slack community for discussion, comments, and questions. For questions related to running or using Qiskit, Stack Overflow has a qiskit. For questions on quantum computing with Qiskit, use the qiskit tag in the Quantum Computing Stack Exchange (please, read first the guidelines on how to ask in that forum).

Authors and Citation

Qiskit is the work of many people who contribute to the project at different levels. If you use Qiskit, please cite as per the included BibTeX file.

Changelog and Release Notes

The changelog for a particular release is dynamically generated and gets written to the release page on Github for each release. For example, you can find the page for the 0.46.0 release here:

https://github.com/Qiskit/qiskit/releases/tag/0.46.0

The changelog for the current release can be found in the releases tab: Releases The changelog provides a quick overview of notable changes for a given release.

Additionally, as part of each release, detailed release notes are written to document in detail what has changed as part of a release. This includes any documentation on potential breaking changes on upgrade and new features. See all release notes here.

Acknowledgements

We acknowledge partial support for Qiskit development from the DOE Office of Science National Quantum Information Science Research Centers, Co-design Center for Quantum Advantage (C2QA) under contract number DE-SC0012704.

License

Apache License 2.0

red-queen's People

Contributors

ajavadia avatar danielleodigie avatar hunterkemeny avatar hwajungkang avatar keilydluna avatar lementknight avatar mtreinish avatar raynelfss avatar yelissal avatar

Stargazers

 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

red-queen's Issues

Add options for user specifiable parameter values

One common thing we have in some benchmarks is sweeping on a parameter, like number of qubits. It would be great if there was a way a user could specify as a runtime flag values (or a sweep either linear or log) to use as a value for these parameters. Something like:

pytest games/applications/test_bv.py -m qiskit --param num_qubits=linear:10:100:50

would run that benchmark with a linear sweep from 10 to 100 with 50 elements on the num_qubits parameter (obviously the syntax is just an example, and doesn't necessarily have to be like that). This would make it a lot easier to quickly benchmark things over a wide range and also do arbitrary scale testing with red queen.

Add CI job that runs new or changed benchmarks

Right now the CI jobs configured on CI do not attempt to run benchmarks at all, we only run the lint job. This is primarily because running benchmarks can be slow so for CI we started just with the lint jobs. However, to aid in review and catching potential issues prior to merging we should add a new github actions job that detects when a new benchmark file is added or we're modifying an existing benchmark file and run pytest on that file. This should hopefully limit the runtime to be manageable (except for PRs that touch every benchmark I guess) so that we can run it in our CI time budget.

Simplify benchmarking between compiler changes.

Currently the test code seems set up for comparing different compilers. When making a pr potentially affecting compiler performance it is often asked to characterize the effect before deciding to merge it. Currently the way to do this would be to e.g. git checkout one version, run the benchmarks, check out another version, run the benchmarks, gather the results and write code to compare.

In the spirit of the CLI pr (#27) it might be nice to be able to do something like,

red-queen -c <compiler> --compare <commit id 1> <commit id 2>

Perhaps it's possible to do this with virtual environments, e.g. tox, so it doesn't touch your git repo?

Double check overhead computation for `t|ket>` mapper

IIRC, t|ket> mapper is not exclusively SWAP-based, i.e., it might choose to
add CNOTs directly (bridges). If that is the case, we need to double check that
we are calculating the overhead correctly for the case we use the vanilla
mapper.

Add visualization summary of benchmark output

The table-based output from req-queen is currently a bit unwieldy, especially as the number of benchmarks, compilers, versions and platforms grow. We should find a way to quickly visualize and compare results generated by red-queen across the above dimensions. There are many prior examples of this being done for other languages or other compilers, e.g.:

https://perf.rust-lang.org/index.html
https://benchmarksgame-team.pages.debian.net/benchmarksgame/fastest/rust-gpp.html

Also, the MetriQ platform has a section focused on quantum compilers ( https://metriq.info/Task/57 ) which also allows for comparisons across compilers and metrics, to which we could submit red-queen results.

Not able to execute tests as mentioned in README.md

pytest red_queen/games/mapping/map_queko.py -m tweedledum --store
Namespace(assertmode='rewrite', basetemp=None, cacheclear=False, cacheshow=None, capture='fd', code_highlight='yes', collect_in_virtualenv=False, collectonly=False, color='auto', confcutdir=None, continue_on_collection_errors=False, debug=None, deselect=None, disable_warnings=False, doctest_continue_on_failure=False, doctest_ignore_import_errors=False, doctestglob=[], doctestmodules=False, doctestreport='udiff', durations=None, durations_min=0.005, failedfirst=False, file_or_dir=['red_queen/games/mapping/map_queko.py'], fulltrace=False, help=False, ignore=None, ignore_glob=None, importmode='prepend', inifilename=None, junitprefix=None, keepduplicates=False, keyword='', last_failed_no_failures='all', lf=False, log_auto_indent=None, log_cli_date_format=None, log_cli_format=None, log_cli_level=None, log_date_format=None, log_file=None, log_file_date_format=None, log_file_format=None, log_file_level=None, log_format=None, log_level=None, markers=False, markexpr='tweedledum', maxfail=0, newfirst=False, no_header=False, no_summary=False, noconftest=False, num_pawns=0, override_ini=None, pastebin=None, plugins=[], pyargs=False, pythonwarnings=None, reportchars='fE', rootdir=None, runxfail=False, setuponly=False, setupplan=False, setupshow=False, show_fixtures_per_test=False, showcapture='all', showfixtures=False, showlocals=False, stepwise=False, stepwise_skip=False, storage_dir=PosixPath('results'), store_data=True, strict=False, strict_config=False, strict_markers=False, tbstyle='auto', trace=False, traceconfig=False, usepdb=False, usepdb_cls=None, verbose=0, version=0, xmlpath=None)
/home/vagrant/red-queen/red_queen/queen.py:35: PytestDeprecationWarning: The hookimpl RedQueen.pytest_sessionstart uses old-style configuration options (marks or attributes).
Please use the pytest.hookimpl(trylast=True) decorator instead
 to configure the hooks.
 See https://docs.pytest.org/en/latest/deprecations.html#configuring-hook-specs-impls-using-markers
  @pytest.mark.trylast
============================= test session starts ==============================
platform linux -- Python 3.8.15, pytest-7.2.0, pluggy-1.0.0
rootdir: /home/vagrant/red-queen, configfile: pytest.ini

=============================== warnings summary ===============================
../../../Users/Shraddha/red-queen/conftest.py:52
  /Users/Shraddha/red-queen/conftest.py:52: PytestDeprecationWarning: The hookimpl pytest_configure uses old-style configuration options (marks or attributes).
  Please use the pytest.hookimpl(trylast=True) decorator instead
   to configure the hooks.
   See https://docs.pytest.org/en/latest/deprecations.html#configuring-hook-specs-impls-using-markers

-- Docs: https://docs.pytest.org/en/stable/how-to/capture-warnings.html
============================== 1 warning in 0.02s ==================

When I run tests they are failing with above error. No tests were run. Please let me know how to fix them.

Create a Command Line Application to Make Benchmarking Easier to Use

I want to create a command line application for Red Queen that would make it easier for people to perform benchmarks. At the moment, to use this benchmark it requires knowledge on Pytest.

Instead of a user having to type up:
$ pytest games/mapping/map_queko.py -m tweedledum --store

I believe that it would better if we could instead type out this
$ red-queen map_queko tweedledum
$ red-queen [file_name] [benchmark]

I believe that down the line we could also use this proposed CLI to create graphs and better visuals for the end user. Ultimately, by reducing the complexity needed to use this benchmarking suite. I hope to make Red Queen more user friendly and more robust.

No errors thrown when running pytest

When running the example command pytest red_queen/games/mapping/map_queko.py -m tweedledum --store , no errors of any kind are reported to the console, even when every function in map_queko.py is altered or removed.

This is related to issue #50, because the tweedledum import error should have been reported to the console. Instead, only the Namespace output was reported when running pytest, even though import tweedledum was throwing an import error behind the scenes from __init__ in the mapping folder.

Shown output:
Screenshot 2023-09-27 at 11 29 03 AM

Adding methods for managing parallelism

Since Qiskit Terra 0.20.0 dense layout and stochastic swap are now multithreaded (via new rust extensions). When running a red queen benchmarks though this causes some issues as red queen will run workers for all the available CPUs on a system and qiskit will spawn a thread pool with the same number of threads. This causes things to bog down as we're running n processes each with n threads so we end up trying to run n^2 CPU bound things in parallel. While this can be dealt with manually either by exporting RAYON_NUM_THREADS=1 or leveraging pytest options to limit concurrency we should think about the interface we want for this and we definitely should provide some guidance on this in the README because it can significantly affect the recorded runtime performance.

Add sort option to results table

Right now the table output order is dictated by the order in the input json results file. This can make it hard to read as this is basically a function of execution order for the benchmarks. To make it easier to work with the data it'd be nice to have a sort argument where we could specify a column and have the tables sorted by that column.

Dependency error: tweedledum

When trying to run map_queko.py on M2 mac, getting this error message.

Screenshot 2023-09-27 at 11 58 20 AM

Unsure if this is a problem with my environment configuration, dependency versions, or a problem with tweedledum.

Removing tweedledum imports solved the problem, but also obviously removes tweedledum functionality.

Improve Documentation for Red Queen

Red Queen has many nuances that should be properly documented so that fellow open sources developers have an easier time both developing for Red Queen and using it.

-Add documentation to explain how to add new benchmarks

-Add guidance on how to use virtual environments in the README.md

-Update README.md to reflect its transition to a python package [#27 Addresses This]

-Add Docstrings to files

-Add description of quantum circuit each benchmark uses

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.