Skip to content
New issue

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

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

Already on GitHub? Sign in to your account

[Stretch] Support Float type in classical expressions. #13832

Merged
merged 65 commits into from
Mar 1, 2025
Merged
Show file tree
Hide file tree
Changes from 64 commits
Commits
Show all changes
65 commits
Select commit Hold shift + click to select a range
af4ba52
WIP
kevinhartman Feb 7, 2025
e423bf9
Add try_const to lift.
kevinhartman Feb 7, 2025
0a5917b
Try multiple singletons, new one for const.
kevinhartman Feb 7, 2025
a97434d
Revert "Try multiple singletons, new one for const."
kevinhartman Feb 7, 2025
1afc965
Remove Bool singleton test.
kevinhartman Feb 7, 2025
86655f1
Add const handling for stores, fix test bugs.
kevinhartman Feb 7, 2025
aaeae9b
Fix formatting.
kevinhartman Feb 7, 2025
a2a444b
Remove Duration and Stretch for now.
kevinhartman Feb 7, 2025
8ac2dc3
Cleanup, fix const bug in index.
kevinhartman Feb 7, 2025
9f8313c
Fix ordering issue for types with differing const-ness.
kevinhartman Feb 9, 2025
db9d9cb
Fix QPY serialization.
kevinhartman Feb 10, 2025
71b7e7a
Make expr.Lift default to non-const.
kevinhartman Feb 11, 2025
2091557
Revert to old test_expr_constructors.py.
kevinhartman Feb 11, 2025
7307be9
Make binary_logical lift independent again.
kevinhartman Feb 11, 2025
9b30284
Update tests, handle a few edge cases.
kevinhartman Feb 12, 2025
ce1faf1
Fix docstring.
kevinhartman Feb 12, 2025
4fee48f
Remove now redundant arg from tests.
kevinhartman Feb 12, 2025
88ab046
Add const testing for ordering.
kevinhartman Feb 12, 2025
c5a230f
Add const tests for shifts.
kevinhartman Feb 12, 2025
7c88d88
Add release note.
kevinhartman Feb 12, 2025
c58a7b8
Add const store tests.
kevinhartman Feb 12, 2025
d9e9a8c
Address lint, minor cleanup.
kevinhartman Feb 13, 2025
4a56150
Add Float type to classical expressions.
kevinhartman Feb 12, 2025
23b5961
Allow DANGEROUS conversion from Float to Bool.
kevinhartman Feb 12, 2025
8bf2e4f
Test Float ordering.
kevinhartman Feb 12, 2025
111eb32
Improve error messages for using Float with logical operators.
kevinhartman Feb 12, 2025
a839d51
Float tests for constructors.
kevinhartman Feb 12, 2025
a19b39a
Add release note.
kevinhartman Feb 12, 2025
25508bf
Reject const vars in add_var and add_input.
kevinhartman Feb 17, 2025
2c8ce43
Merge branch 'main' of github.com:Qiskit/qiskit into const-expr
kevinhartman Feb 17, 2025
ccf9441
Implement QPY support for const-typed expressions.
kevinhartman Feb 18, 2025
c6eab02
Remove invalid test.
kevinhartman Feb 18, 2025
edd7806
Update QPY version 14 desc.
kevinhartman Feb 18, 2025
8afa92e
Fix lint.
kevinhartman Feb 18, 2025
4e0f2df
Add serialization testing.
kevinhartman Feb 18, 2025
15ba943
Merge branch 'main' of github.com:Qiskit/qiskit into const-expr
kevinhartman Feb 18, 2025
81c5833
Merge branch 'const-expr' into expr-float
kevinhartman Feb 18, 2025
50c31d3
Test pre-v14 QPY rejects const-typed exprs.
kevinhartman Feb 18, 2025
7e43322
Merge branch 'main' of github.com:Qiskit/qiskit into const-expr
kevinhartman Feb 18, 2025
2449ee6
Merge branch 'const-expr' into expr-float
kevinhartman Feb 18, 2025
e55e189
QASM export for floats.
kevinhartman Feb 18, 2025
1d51022
QPY support for floats.
kevinhartman Feb 18, 2025
eb8f150
Fix lint.
kevinhartman Feb 18, 2025
07771f1
Merge branch 'main' of github.com:Qiskit/qiskit into const-expr
kevinhartman Feb 20, 2025
9332ed3
Merge branch 'const-expr' into expr-float
kevinhartman Feb 20, 2025
d3bca5f
Merge branch 'main' of github.com:Qiskit/qiskit into const-expr
kevinhartman Feb 24, 2025
50deb93
Revert visitors.py.
kevinhartman Feb 24, 2025
f1dc1a1
Address review comments.
kevinhartman Feb 24, 2025
1f439a0
Merge branch 'main' of github.com:Qiskit/qiskit into const-expr
kevinhartman Feb 25, 2025
166d7b2
Improve type docs.
kevinhartman Feb 26, 2025
10b2c8d
Merge branch 'main' of github.com:Qiskit/qiskit into const-expr
kevinhartman Feb 26, 2025
9d6cf39
Revert QPY, since the old format can support constexprs.
kevinhartman Feb 26, 2025
8021e00
Move const-ness from Type to Expr.
kevinhartman Feb 26, 2025
a15141b
Revert QPY testing, no longer needed.
kevinhartman Feb 26, 2025
ca2785d
Add explicit validation of const expr.
kevinhartman Feb 26, 2025
e902009
Revert stuff I didn't need to touch.
kevinhartman Feb 26, 2025
16475c3
Update release note.
kevinhartman Feb 26, 2025
6b5930d
A few finishing touches.
kevinhartman Feb 27, 2025
be73180
Merge branch 'const-expr-expr' into expr-float-expr
kevinhartman Feb 27, 2025
25f1693
Fix-up after merge.
kevinhartman Feb 27, 2025
6bc728a
Fix comment and release note.
kevinhartman Feb 27, 2025
42258b8
Merge branch 'main' of github.com:Qiskit/qiskit into expr-float
kevinhartman Feb 28, 2025
cbd55db
Address review comments.
kevinhartman Feb 28, 2025
f12afb4
Update release note.
kevinhartman Feb 28, 2025
0f14cca
Address review comments.
kevinhartman Mar 1, 2025
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 24 additions & 11 deletions qiskit/circuit/classical/expr/constructors.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@

__all__ = [
"lift",
"cast",
"bit_not",
"logic_not",
"bit_and",
Expand All @@ -32,6 +33,9 @@
"less_equal",
"greater",
"greater_equal",
"shift_left",
"shift_right",
"index",
"lift_legacy_condition",
]

Expand All @@ -45,19 +49,17 @@
import qiskit


def _coerce_lossless(expr: Expr, type: types.Type) -> Expr:
def _coerce_lossless(expr: Expr, type: types.Type) -> Expr | None:
"""Coerce ``expr`` to ``type`` by inserting a suitable :class:`Cast` node, if the cast is
lossless. Otherwise, raise a ``TypeError``."""
lossless. Otherwise, return ``None``."""
kind = cast_kind(expr.type, type)
if kind is CastKind.EQUAL:
return expr
if kind is CastKind.IMPLICIT:
return Cast(expr, type, implicit=True)
if kind is CastKind.LOSSLESS:
return Cast(expr, type, implicit=False)
if kind is CastKind.DANGEROUS:
raise TypeError(f"cannot cast '{expr}' to '{type}' without loss of precision")
raise TypeError(f"no cast is defined to take '{expr}' to '{type}'")
return None
Comment on lines -58 to +62
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Checking this branch out locally, I can see several uses of _coerce_lossless in this file that appear to have unchecked return values after this change.

In particular: _equal_like, _binary_relation, and _shift_like (but I might have missed one or two).

I think the _equal_like and _binary_relation ones shake out ok because of type.kind checks higher up, but it would be good to put a one-liner comment into each explaining that.

The _shift_like one has a potential bug:

from qiskit.circuit.classical import expr, types

expr.shift_left(expr.lift(5.0), 3, types.Uint(8))

is an AttributeError.

I don't know why I gave shift_left and shift_right a cast field within them - I think I must have been attempting to save some typing with inserting an extra expr.lift on the left operand when passing an integer literal and trying to fix the width (since the left- and right operands don't need to have equal widths in shifts, so there's no inference) - but at any rate, now it's possible to fail the cast in there.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good catch. I've fixed this and added a test in 0f14cca



def lift_legacy_condition(
Expand Down Expand Up @@ -121,6 +123,9 @@ def lift(value: typing.Any, /, type: types.Type | None = None) -> Expr:
raise ValueError("cannot represent a negative value")
inferred = types.Uint(width=value.bit_length() or 1)
constructor = Value
elif isinstance(value, float):
inferred = types.Float()
constructor = Value
else:
raise TypeError(f"failed to infer a type for '{value}'")
if type is None:
Expand Down Expand Up @@ -181,11 +186,15 @@ def logic_not(operand: typing.Any, /) -> Expr:
>>> expr.logic_not(ClassicalRegister(3, "c"))
Unary(\
Unary.Op.LOGIC_NOT, \
Cast(Var(ClassicalRegister(3, 'c'), Uint(3)), Bool(), implicit=True), \
Cast(Var(ClassicalRegister(3, 'c'), Uint(3)), \
Bool(), implicit=True), \
Bool())
"""
operand = _coerce_lossless(lift(operand), types.Bool())
return Unary(Unary.Op.LOGIC_NOT, operand, operand.type)
operand = lift(operand)
coerced_operand = _coerce_lossless(operand, types.Bool())
if coerced_operand is None:
raise TypeError(f"cannot apply '{Unary.Op.LOGIC_NOT}' to type '{operand.type}'")
return Unary(Unary.Op.LOGIC_NOT, coerced_operand, coerced_operand.type)


def _lift_binary_operands(left: typing.Any, right: typing.Any) -> tuple[Expr, Expr]:
Expand Down Expand Up @@ -300,9 +309,13 @@ def bit_xor(left: typing.Any, right: typing.Any, /) -> Expr:

def _binary_logical(op: Binary.Op, left: typing.Any, right: typing.Any) -> Expr:
bool_ = types.Bool()
left = _coerce_lossless(lift(left), bool_)
right = _coerce_lossless(lift(right), bool_)
return Binary(op, left, right, bool_)
left = lift(left)
right = lift(right)
coerced_left = _coerce_lossless(left, bool_)
coerced_right = _coerce_lossless(right, bool_)
if coerced_left is None or coerced_right is None:
raise TypeError(f"invalid types for '{op}': '{left.type}' and '{right.type}'")
return Binary(op, coerced_left, coerced_right, bool_)


def logic_and(left: typing.Any, right: typing.Any, /) -> Expr:
Expand Down
13 changes: 9 additions & 4 deletions qiskit/circuit/classical/types/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,12 +33,13 @@
heap-allocating a new version of the same thing. Where possible, the class constructors will return
singleton instances to facilitate this.

The two different types available are for Booleans (corresponding to :class:`.Clbit` and the
literals ``True`` and ``False``), and unsigned integers (corresponding to
:class:`.ClassicalRegister` and Python integers).
The :class:`Bool` type represents :class:`.Clbit` and the literals ``True`` and ``False``, the
:class:`Uint` type represents :class:`.ClassicalRegister` and Python integers, and the
:class:`Float` type represents Python floats.

.. autoclass:: Bool
.. autoclass:: Uint
.. autoclass:: Float

Note that :class:`Uint` defines a family of types parametrized by their width; it is not one single
type, which may be slightly different to the 'classical' programming languages you are used to.
Expand Down Expand Up @@ -89,12 +90,16 @@
The return values from this function are an enumeration explaining the types of cast that are
allowed from the left type to the right type.

Note that casts between :class:`Float` and :class:`Uint` are considered dangerous in either
direction, and must be done explicitly.

.. autoclass:: CastKind
"""

__all__ = [
"Type",
"Bool",
"Float",
"Uint",
"Ordering",
"order",
Expand All @@ -105,5 +110,5 @@
"cast_kind",
]

from .types import Type, Bool, Uint
from .types import Type, Bool, Float, Uint
from .ordering import Ordering, order, is_subtype, is_supertype, greater, CastKind, cast_kind
14 changes: 8 additions & 6 deletions qiskit/circuit/classical/types/ordering.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@

import enum

from .types import Type, Bool, Uint
from .types import Type, Bool, Float, Uint


# While the type system is simple, it's overkill to represent the complete partial ordering graph of
Expand Down Expand Up @@ -55,10 +55,6 @@ def __repr__(self):
return str(self)


def _order_bool_bool(_a: Bool, _b: Bool, /) -> Ordering:
return Ordering.EQUAL


def _order_uint_uint(left: Uint, right: Uint, /) -> Ordering:
if left.width < right.width:
return Ordering.LESS
Expand All @@ -68,8 +64,9 @@ def _order_uint_uint(left: Uint, right: Uint, /) -> Ordering:


_ORDERERS = {
(Bool, Bool): _order_bool_bool,
(Bool, Bool): lambda _a, _b, /: Ordering.EQUAL,
(Uint, Uint): _order_uint_uint,
(Float, Float): lambda _a, _b, /: Ordering.EQUAL,
}


Expand Down Expand Up @@ -195,8 +192,13 @@ def _uint_cast(from_: Uint, to_: Uint, /) -> CastKind:
_ALLOWED_CASTS = {
(Bool, Bool): lambda _a, _b, /: CastKind.EQUAL,
(Bool, Uint): lambda _a, _b, /: CastKind.LOSSLESS,
(Bool, Float): lambda _a, _b, /: CastKind.LOSSLESS,
(Uint, Bool): lambda _a, _b, /: CastKind.IMPLICIT,
(Uint, Uint): _uint_cast,
(Uint, Float): lambda _a, _b, /: CastKind.DANGEROUS,
(Float, Float): lambda _a, _b, /: CastKind.EQUAL,
(Float, Uint): lambda _a, _b, /: CastKind.DANGEROUS,
(Float, Bool): lambda _a, _b, /: CastKind.DANGEROUS,
}


Expand Down
19 changes: 19 additions & 0 deletions qiskit/circuit/classical/types/types.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
__all__ = [
"Type",
"Bool",
"Float",
"Uint",
]

Expand Down Expand Up @@ -115,3 +116,21 @@ def __hash__(self):

def __eq__(self, other):
return isinstance(other, Uint) and self.width == other.width


@typing.final
class Float(Type, metaclass=_Singleton):
"""An IEE-754 double-precision floating point number.
In the future, this may also be used to represent other fixed-width floats.
"""

__slots__ = ()

def __repr__(self):
return "Float()"

def __hash__(self):
return hash(self.__class__)

def __eq__(self, other):
return isinstance(other, Float)
7 changes: 7 additions & 0 deletions qiskit/qasm3/ast.py
Original file line number Diff line number Diff line change
Expand Up @@ -242,6 +242,13 @@ def __init__(self, value):
self.value = value


class FloatLiteral(Expression):
__slots__ = ("value",)

def __init__(self, value):
self.value = value


class BooleanLiteral(Expression):
__slots__ = ("value",)

Expand Down
4 changes: 4 additions & 0 deletions qiskit/qasm3/exporter.py
Original file line number Diff line number Diff line change
Expand Up @@ -1253,6 +1253,8 @@ def _build_ast_type(type_: types.Type) -> ast.ClassicalType:
return ast.BoolType()
if type_.kind is types.Uint:
return ast.UintType(type_.width)
if type_.kind is types.Float:
return ast.FloatType.DOUBLE
raise RuntimeError(f"unhandled expr type '{type_}'")


Expand All @@ -1274,6 +1276,8 @@ def visit_value(self, node, /):
return ast.BooleanLiteral(node.value)
if node.type.kind is types.Uint:
return ast.IntegerLiteral(node.value)
if node.type.kind is types.Float:
return ast.FloatLiteral(node.value)
raise RuntimeError(f"unhandled Value type '{node}'")

def visit_cast(self, node, /):
Expand Down
7 changes: 5 additions & 2 deletions qiskit/qasm3/printer.py
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ class BasicPrinter:
ast.QuantumGateModifierName.POW: "pow",
}

_FLOAT_WIDTH_LOOKUP = {type: str(type.value) for type in ast.FloatType}
_FLOAT_TYPE_LOOKUP = {type: f"float[{type.value}]" for type in ast.FloatType}

# The visitor names include the class names, so they mix snake_case with PascalCase.
# pylint: disable=invalid-name
Expand Down Expand Up @@ -205,7 +205,7 @@ def _visit_CalibrationGrammarDeclaration(self, node: ast.CalibrationGrammarDecla
self._write_statement(f'defcalgrammar "{node.name}"')

def _visit_FloatType(self, node: ast.FloatType) -> None:
self.stream.write(f"float[{self._FLOAT_WIDTH_LOOKUP[node]}]")
self.stream.write(self._FLOAT_TYPE_LOOKUP[node])

def _visit_BoolType(self, _node: ast.BoolType) -> None:
self.stream.write("bool")
Expand Down Expand Up @@ -282,6 +282,9 @@ def _visit_QuantumDelay(self, node: ast.QuantumDelay) -> None:
def _visit_IntegerLiteral(self, node: ast.IntegerLiteral) -> None:
self.stream.write(str(node.value))

def _visit_FloatLiteral(self, node: ast.FloatLiteral) -> None:
self.stream.write(str(node.value))

def _visit_BooleanLiteral(self, node: ast.BooleanLiteral):
self.stream.write("true" if node.value else "false")

Expand Down
31 changes: 31 additions & 0 deletions qiskit/qpy/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -377,6 +377,37 @@ def open(*args):
by ``num_circuits`` in the file header). There is no padding between the
circuits in the data.

.. _qpy_version_14:

Version 14
----------

Version 14 adds support for additional :class:`~.types.Type` classes.

Changes to EXPR_TYPE
~~~~~~~~~~~~~~~~~~~~

The following table shows the new type classes added in the version:

====================== ========= =================================================================
Qiskit class Type code Payload
====================== ========= =================================================================
:class:`~.types.Float` ``f`` None.
====================== ========= =================================================================

Changes to EXPR_VALUE
~~~~~~~~~~~~~~~~~~~~~

The classical expression's type system now supports new encoding types for value literals, in
addition to the existing encodings for int and bool. The new value type encodings are below:

=========== ========= ============================================================================
Python type Type code Payload
=========== ========= ============================================================================
``float`` ``f`` One ``double value``.

=========== ========= ============================================================================

.. _qpy_version_13:

Version 13
Expand Down
2 changes: 1 addition & 1 deletion qiskit/qpy/binary_io/circuits.py
Original file line number Diff line number Diff line change
Expand Up @@ -1236,7 +1236,7 @@ def write_circuit(
file_obj.write(metadata_raw)
# Write header payload
file_obj.write(registers_raw)
standalone_var_indices = value.write_standalone_vars(file_obj, circuit)
standalone_var_indices = value.write_standalone_vars(file_obj, circuit, version)
else:
if circuit.num_vars:
raise exceptions.UnsupportedFeatureForVersion(
Expand Down
Loading
Loading