目录
Matthew Treinish

Fix QPY loading delay integers durations incorrectly (#16076)

  • Fix QPY loading delay integers durations incorrectly

This commit fixes an issue with parsing QPY payloads which have circuits that contain delays with duration of units dt. Durations of dt are integers and that is preserved in the QPY data. However our rust data model doesn’t have support for an integer in a Rust PackedInstruction’s parameters (this is an inconsistency which we should arguably fix but that is separate from this bugfix). To workaround this the QPY reader in rust was sticking the integer into a ParameterExpression as a constant without any symbols. This resulted in storing the integer in Rust but treating the object as a ParameterExpression and not an int, which in Qiskit’s rust data model is mapped to a Param::Obj (indicating a Python object parameter). This mismatch in types was not really noticeable to Python because the ParameterExpression with the constant integer was coerced to an integer when it’s passed to Python. However, this would break underlying assumptions for Rust code that is interacting with the delay. For example, the experimental rust qasm3 exporter would encounter the ParameterExpression on the delay and error because it can’t handle parameter expressions yet. However fundamentally it could because this is just an integer. The reproducer for this failure is:

import io
from qiskit import qpy, qasm3, QuantumCircuit

qc = QuantumCircuit(1)
qc.delay(1, 0)

qasm3.dumps_experimental(qc)

with io.BytesIO() as fptr:
    qpy.dump(qc, fptr)
    fptr.seek(0)
    qc2 = qpy.load(fptr)[0]

qasm3.dumps_experimental(qc2)

The OQ3 experimental exporter is wrong not to handle ParameterExpression::try_as_value returning an int, but it’s more wrong that QPY is producing a ParameterExpression on deserialisation in the first place.

To fix this issue this commit removes the conversion of the int in the qpy payload into a ParameterExpression and just retains an integer until we write out the Delay’s PackedInstruction where we convert that rust int into a python int for the parameter. Doing this unraveled a deeper issue in how endianess is handled in QPY. In general everything in QPY is supposed to be encoded using network byte order (i.e. big endian). However, in the case of instructions’ parameters there was a mistake made in QPY where the integer and float values for an instruction’s parameters were encoded in little endian. All other uses of floats or ints are correctly big endian. When the raw int was returned to Python it was incorrectly assuming all integers were a big endian bytes value. To fix this an endian arg is added to the function which is converting the bytes arrays into a GenericValue enum for floats and ints. Then the callers of this function in circuit_reader are updated to explicitly assert what endianess the data in the circuit payload is if there are any floats or ints. This is Endian::Little for any instruction params that are in the parameters list explicitly and Endian::Big everywhere else. At the same time the handling of flipping the endianess of value in several places was fixed because this was no longer necessary as the data was read now using the correct byte order.

This fundamentally stems from all the base values being stored in a single binrw generic value pack which is trying to encode all the primitive types in a single place. Ideally we should be handling the primitive types explicitly for each data pack field. But this was not changed to keep the diff minimal for backport

Co-authored-by: Jake Lishman jake.lishman@ibm.com

  • Fix typo in qpy compat test

  • Fix tests again

  • Fix delay stretch expr test typo

  • Add more round-trip tests

  • Remove dead control-flow switching logic

All the entries in this list either take zero parameters, or would have caused program control flow to enter unpack_control_flow and not unpack_py_instruction, so this switching logic is dead.

  • Remove endianness switching from BigUint parsing

The BigUint keys are only valid in contexts where they are guaranteed to be in network order. The pack_biguint function knew this, but unpack_biguint mistakenly gained an endian argument, which was required to always be Big.

  • Reword release note

Co-authored-by: Jake Lishman jake.lishman@ibm.com

18小时前10212次提交

Qiskit

License Current Release Extended Support Release Downloads Coverage Status PyPI - Python Version Minimum rustc 1.87 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://quantum.cloud.ibm.com/docs/

Installation

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 Sampler primitive to sample outcomes or the Estimator primitive to estimate expectation 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> / √2
qc = QuantumCircuit(3)
qc.h(0)             # generate superposition
qc.p(np.pi / 2, 0)  # add quantum phase
qc.cx(0, 1)         # 0th-qubit-Controlled-NOT gate on 1st qubit
qc.cx(0, 2)         # 0th-qubit-Controlled-NOT gate on 2nd qubit

This simple example creates an entangled state known as a GHZ state (000+i111)/2(|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 you will use. Starting with the 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.measure_all(inplace=False)

# 3. Execute using the Sampler primitive
from qiskit.primitives import StatevectorSampler
sampler = StatevectorSampler()
job = sampler.run([qc_measured], shots=1000)
result = job.result()
print(f" > Counts: {result[0].data['meas'].get_counts()}")

Running this will give an outcome similar to {'000': 497, '111': 503} which is 000 50% of the time and 111 50% of the time up to statistical fluctuations. To illustrate the power of the Estimator, we now use the quantum information toolbox to create the operator XXY+XYX+YXXYYYXXY+XYX+YXX-YYY and pass it to the run() function, along with our quantum circuit. Note that the Estimator requires a circuit without measurements, so we use the qc 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 StatevectorEstimator
estimator = StatevectorEstimator()
job = estimator.run([(qc, operator)], precision=1e-3)
result = job.result()
print(f" > Expectation values: {result[0].data.evs}")

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.StatevectorSampler and qiskit.primitives.StatevectorEstimator 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 bidirectional linear chain of qubits 0120 \leftrightarrow 1 \leftrightarrow 2 with the coupling_map = [[0, 1], [1, 0], [1, 2], [2, 1]].

from qiskit import transpile
from qiskit.transpiler import Target, CouplingMap
target = Target.from_configuration(
    basis_gates=["cz", "sx", "rz"],
    coupling_map=CouplingMap.from_line(3),
)
qc_transpiled = transpile(qc, target=target)

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.BaseSamplerV2 and qiskit.primitives.BaseEstimatorV2 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 1.2.0 release here:

https://github.com/Qiskit/qiskit/releases/tag/1.2.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

邀请码
    Gitlink(确实开源)
  • 加入我们
  • 官网邮箱:gitlink@ccf.org.cn
  • QQ群
  • QQ群
  • 公众号
  • 公众号

版权所有:中国计算机学会技术支持:开源发展技术委员会
京ICP备13000930号-9 京公网安备 11010802032778号