bloqade-circuit 0.4.5__py3-none-any.whl → 0.5.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of bloqade-circuit might be problematic. Click here for more details.

Files changed (37) hide show
  1. bloqade/cirq_utils/__init__.py +7 -0
  2. bloqade/cirq_utils/lineprog.py +295 -0
  3. bloqade/cirq_utils/parallelize.py +400 -0
  4. bloqade/pyqrack/squin/op.py +7 -2
  5. bloqade/pyqrack/squin/runtime.py +4 -2
  6. bloqade/qasm2/dialects/expr/stmts.py +2 -20
  7. bloqade/qasm2/parse/lowering.py +1 -0
  8. bloqade/qasm2/passes/parallel.py +18 -0
  9. bloqade/qasm2/rewrite/__init__.py +1 -0
  10. bloqade/qasm2/rewrite/parallel_to_glob.py +82 -0
  11. bloqade/squin/__init__.py +1 -0
  12. bloqade/squin/_typeinfer.py +20 -0
  13. bloqade/squin/analysis/nsites/impls.py +6 -1
  14. bloqade/squin/cirq/lowering.py +19 -6
  15. bloqade/squin/op/__init__.py +1 -0
  16. bloqade/squin/op/_wrapper.py +4 -0
  17. bloqade/squin/op/stmts.py +20 -2
  18. bloqade/squin/qubit.py +8 -5
  19. bloqade/squin/rewrite/__init__.py +1 -0
  20. bloqade/squin/rewrite/canonicalize.py +60 -0
  21. bloqade/squin/rewrite/desugar.py +52 -5
  22. bloqade/squin/types.py +8 -0
  23. bloqade/squin/wire.py +91 -5
  24. bloqade/stim/__init__.py +1 -0
  25. bloqade/stim/_wrappers.py +4 -0
  26. bloqade/stim/dialects/noise/emit.py +1 -0
  27. bloqade/stim/dialects/noise/stmts.py +5 -0
  28. bloqade/stim/passes/squin_to_stim.py +16 -1
  29. bloqade/stim/rewrite/__init__.py +1 -0
  30. bloqade/stim/rewrite/qubit_to_stim.py +10 -6
  31. bloqade/stim/rewrite/squin_noise.py +120 -0
  32. bloqade/stim/rewrite/util.py +44 -9
  33. bloqade/stim/rewrite/wire_to_stim.py +8 -3
  34. {bloqade_circuit-0.4.5.dist-info → bloqade_circuit-0.5.0.dist-info}/METADATA +4 -2
  35. {bloqade_circuit-0.4.5.dist-info → bloqade_circuit-0.5.0.dist-info}/RECORD +37 -29
  36. {bloqade_circuit-0.4.5.dist-info → bloqade_circuit-0.5.0.dist-info}/WHEEL +0 -0
  37. {bloqade_circuit-0.4.5.dist-info → bloqade_circuit-0.5.0.dist-info}/licenses/LICENSE +0 -0
@@ -96,10 +96,15 @@ class PyQrackMethods(interp.MethodTable):
96
96
  return (PhaseOpRuntime(theta, global_=global_),)
97
97
 
98
98
  @interp.impl(op.stmts.Reset)
99
+ @interp.impl(op.stmts.ResetToOne)
99
100
  def reset(
100
- self, interp: PyQrackInterpreter, frame: interp.Frame, stmt: op.stmts.Reset
101
+ self,
102
+ interp: PyQrackInterpreter,
103
+ frame: interp.Frame,
104
+ stmt: op.stmts.Reset | op.stmts.ResetToOne,
101
105
  ) -> tuple[OperatorRuntimeABC]:
102
- return (ResetRuntime(),)
106
+ target_state = isinstance(stmt, op.stmts.ResetToOne)
107
+ return (ResetRuntime(target_state=target_state),)
103
108
 
104
109
  @interp.impl(op.stmts.X)
105
110
  @interp.impl(op.stmts.Y)
@@ -43,7 +43,9 @@ class OperatorRuntimeABC:
43
43
 
44
44
  @dataclass(frozen=True)
45
45
  class ResetRuntime(OperatorRuntimeABC):
46
- """Reset the qubit to |0> state"""
46
+ """Reset the qubit to the target state"""
47
+
48
+ target_state: bool
47
49
 
48
50
  @property
49
51
  def n_sites(self) -> int:
@@ -55,7 +57,7 @@ class ResetRuntime(OperatorRuntimeABC):
55
57
  continue
56
58
 
57
59
  res: bool = qubit.sim_reg.m(qubit.addr)
58
- if res:
60
+ if res != self.target_state:
59
61
  qubit.sim_reg.x(qubit.addr)
60
62
 
61
63
 
@@ -1,34 +1,16 @@
1
1
  from kirin import ir, types, lowering
2
2
  from kirin.decl import info, statement
3
+ from kirin.dialects import func
3
4
  from kirin.print.printer import Printer
4
- from kirin.dialects.func.attrs import Signature
5
5
 
6
6
  from ._dialect import dialect
7
7
 
8
8
 
9
- class GateFuncOpCallableInterface(ir.CallableStmtInterface["GateFunction"]):
10
-
11
- @classmethod
12
- def get_callable_region(cls, stmt: "GateFunction") -> ir.Region:
13
- return stmt.body
14
-
15
-
16
9
  @statement(dialect=dialect)
17
- class GateFunction(ir.Statement):
10
+ class GateFunction(func.Function):
18
11
  """Special Function for qasm2 gate subroutine."""
19
12
 
20
13
  name = "gate.func"
21
- traits = frozenset(
22
- {
23
- ir.IsolatedFromAbove(),
24
- ir.SymbolOpInterface(),
25
- ir.HasSignature(),
26
- GateFuncOpCallableInterface(),
27
- }
28
- )
29
- sym_name: str = info.attribute()
30
- signature: Signature = info.attribute()
31
- body: ir.Region = info.region(multi=True)
32
14
 
33
15
  def print_impl(self, printer: Printer) -> None:
34
16
  with printer.rich(style="red"):
@@ -36,6 +36,7 @@ class QASM2(lowering.LoweringABC[ast.Node]):
36
36
  file=file,
37
37
  lineno_offset=lineno_offset,
38
38
  col_offset=col_offset,
39
+ compactify=compactify,
39
40
  )
40
41
 
41
42
  return frame.curr_region
@@ -26,6 +26,7 @@ from bloqade.qasm2.rewrite import (
26
26
  ParallelToUOpRule,
27
27
  RaiseRegisterRule,
28
28
  UOpToParallelRule,
29
+ ParallelToGlobalRule,
29
30
  SimpleOptimalMergePolicy,
30
31
  RydbergGateSetRewriteRule,
31
32
  )
@@ -183,3 +184,20 @@ class UOpToParallel(Pass):
183
184
  CommonSubexpressionElimination(),
184
185
  )
185
186
  return Fixpoint(Walk(rule)).rewrite(mt.code).join(result)
187
+
188
+
189
+ @dataclass
190
+ class ParallelToGlobal(Pass):
191
+
192
+ def generate_rule(self, mt: ir.Method) -> ParallelToGlobalRule:
193
+ address_analysis = address.AddressAnalysis(mt.dialects)
194
+ frame, _ = address_analysis.run_analysis(mt)
195
+ return ParallelToGlobalRule(frame.entries)
196
+
197
+ def unsafe_run(self, mt: ir.Method) -> abc.RewriteResult:
198
+ rule = self.generate_rule(mt)
199
+
200
+ result = Walk(rule).rewrite(mt.code)
201
+ result = Walk(DeadCodeElimination()).rewrite(mt.code).join(result)
202
+
203
+ return result
@@ -11,5 +11,6 @@ from .uop_to_parallel import (
11
11
  SimpleGreedyMergePolicy as SimpleGreedyMergePolicy,
12
12
  SimpleOptimalMergePolicy as SimpleOptimalMergePolicy,
13
13
  )
14
+ from .parallel_to_glob import ParallelToGlobalRule as ParallelToGlobalRule
14
15
  from .noise.remove_noise import RemoveNoisePass as RemoveNoisePass
15
16
  from .noise.heuristic_noise import NoiseRewriteRule as NoiseRewriteRule
@@ -0,0 +1,82 @@
1
+ from typing import Dict
2
+ from dataclasses import dataclass
3
+
4
+ from kirin import ir
5
+ from kirin.rewrite import abc
6
+ from kirin.analysis import const
7
+ from kirin.dialects import ilist
8
+
9
+ from bloqade.analysis import address
10
+
11
+ from ..dialects import core, glob, parallel
12
+
13
+
14
+ @dataclass
15
+ class ParallelToGlobalRule(abc.RewriteRule):
16
+ address_analysis: Dict[ir.SSAValue, address.Address]
17
+
18
+ def rewrite_Statement(self, node: ir.Statement) -> abc.RewriteResult:
19
+ if not isinstance(node, parallel.UGate):
20
+ return abc.RewriteResult()
21
+
22
+ qargs = node.qargs
23
+ qarg_addresses = self.address_analysis.get(qargs, None)
24
+
25
+ if isinstance(qarg_addresses, address.AddressReg):
26
+ # NOTE: we only have an AddressReg if it's an entire register, definitely rewrite that
27
+ return self._rewrite_parallel_to_glob(node)
28
+
29
+ if not isinstance(qarg_addresses, address.AddressTuple):
30
+ return abc.RewriteResult()
31
+
32
+ idxs, qreg = self._find_qreg(qargs.owner, set())
33
+
34
+ if qreg is None:
35
+ # NOTE: no unique register found
36
+ return abc.RewriteResult()
37
+
38
+ if not isinstance(hint := qreg.n_qubits.hints.get("const"), const.Value):
39
+ # NOTE: non-constant number of qubits
40
+ return abc.RewriteResult()
41
+
42
+ n = hint.data
43
+ if len(idxs) != n:
44
+ # NOTE: not all qubits of the register are there
45
+ return abc.RewriteResult()
46
+
47
+ return self._rewrite_parallel_to_glob(node)
48
+
49
+ @staticmethod
50
+ def _rewrite_parallel_to_glob(node: parallel.UGate) -> abc.RewriteResult:
51
+ theta, phi, lam = node.theta, node.phi, node.lam
52
+ global_u = glob.UGate(node.qargs, theta=theta, phi=phi, lam=lam)
53
+ node.replace_by(global_u)
54
+ return abc.RewriteResult(has_done_something=True)
55
+
56
+ @staticmethod
57
+ def _find_qreg(
58
+ qargs_owner: ir.Statement | ir.Block, idxs: set
59
+ ) -> tuple[set, core.stmts.QRegNew | None]:
60
+
61
+ if isinstance(qargs_owner, core.stmts.QRegGet):
62
+ idxs.add(qargs_owner.idx)
63
+ qreg = qargs_owner.reg.owner
64
+ if not isinstance(qreg, core.stmts.QRegNew):
65
+ # NOTE: this could potentially be casted
66
+ qreg = None
67
+ return idxs, qreg
68
+
69
+ if isinstance(qargs_owner, ilist.New):
70
+ vals = qargs_owner.values
71
+ if len(vals) == 0:
72
+ return idxs, None
73
+
74
+ idxs, first_qreg = ParallelToGlobalRule._find_qreg(vals[0].owner, idxs)
75
+ for val in vals[1:]:
76
+ idxs, qreg = ParallelToGlobalRule._find_qreg(val.owner, idxs)
77
+ if qreg != first_qreg:
78
+ return idxs, None
79
+
80
+ return idxs, first_qreg
81
+
82
+ return idxs, None
bloqade/squin/__init__.py CHANGED
@@ -4,6 +4,7 @@ from . import (
4
4
  noise as noise,
5
5
  qubit as qubit,
6
6
  lowering as lowering,
7
+ _typeinfer as _typeinfer,
7
8
  )
8
9
  from .groups import wired as wired, kernel as kernel
9
10
 
@@ -0,0 +1,20 @@
1
+ from kirin import types, interp
2
+ from kirin.analysis import TypeInference, const
3
+ from kirin.dialects import ilist
4
+
5
+ from bloqade import squin
6
+
7
+
8
+ @squin.qubit.dialect.register(key="typeinfer")
9
+ class TypeInfer(interp.MethodTable):
10
+ @interp.impl(squin.qubit.New)
11
+ def _call(self, interp: TypeInference, frame: interp.Frame, stmt: squin.qubit.New):
12
+ # based on Xiu-zhe (Roger) Luo's get_const_value function
13
+
14
+ if (hint := stmt.n_qubits.hints.get("const")) is None:
15
+ return (ilist.IListType[squin.qubit.QubitType, types.Any],)
16
+
17
+ if isinstance(hint, const.Value) and isinstance(hint.data, int):
18
+ return (ilist.IListType[squin.qubit.QubitType, types.Literal(hint.data)],)
19
+
20
+ return (ilist.IListType[squin.qubit.QubitType, types.Any],)
@@ -1,5 +1,5 @@
1
1
  from kirin import interp
2
- from kirin.dialects import scf
2
+ from kirin.dialects import scf, func
3
3
  from kirin.dialects.scf.typeinfer import TypeInfer as ScfTypeInfer
4
4
 
5
5
  from bloqade.squin import op, wire
@@ -85,3 +85,8 @@ class SquinOp(interp.MethodTable):
85
85
  @scf.dialect.register(key="op.nsites")
86
86
  class ScfSquinOp(ScfTypeInfer):
87
87
  pass
88
+
89
+
90
+ @func.dialect.register(key="op.nsites")
91
+ class FuncSquinOp(func.typeinfer.TypeInfer):
92
+ pass
@@ -368,11 +368,24 @@ class Squin(lowering.LoweringABC[CirqNode]):
368
368
  state: lowering.State[CirqNode],
369
369
  node: cirq.GeneralizedAmplitudeDampingChannel,
370
370
  ):
371
- raise NotImplementedError("TODO: needs a new operator statement")
372
- # p = state.current_frame.push(py.Constant(node.p))
373
- # gamma = state.current_frame.push(py.Constant(node.gamma))
371
+ p = state.current_frame.push(py.Constant(node.p)).result
372
+ gamma = state.current_frame.push(py.Constant(node.gamma)).result
374
373
 
375
- # p1 =
374
+ # NOTE: cirq has a weird convention here: if p == 1, we have AmplitudeDampingChannel,
375
+ # which basically means p is the probability of the environment being in the vacuum state
376
+ prob0 = state.current_frame.push(py.binop.Mult(p, gamma)).result
377
+ one_ = state.current_frame.push(py.Constant(1)).result
378
+ p_minus_1 = state.current_frame.push(py.binop.Sub(one_, p)).result
379
+ prob1 = state.current_frame.push(py.binop.Mult(p_minus_1, gamma)).result
376
380
 
377
- # x = state.current_frame.push(op.stmts.X())
378
- # noise_channel1 = noise.stmts.PauliError(basis=x.result, p=)
381
+ r0 = state.current_frame.push(op.stmts.Reset()).result
382
+ r1 = state.current_frame.push(op.stmts.ResetToOne()).result
383
+
384
+ probs = state.current_frame.push(ilist.New(values=(prob0, prob1))).result
385
+ ops = state.current_frame.push(ilist.New(values=(r0, r1))).result
386
+
387
+ noise_channel = state.current_frame.push(
388
+ noise.stmts.StochasticUnitaryChannel(probabilities=probs, operators=ops)
389
+ )
390
+
391
+ return noise_channel
@@ -37,4 +37,5 @@ from ._wrapper import (
37
37
  control as control,
38
38
  identity as identity,
39
39
  pauli_string as pauli_string,
40
+ reset_to_one as reset_to_one,
40
41
  )
@@ -41,6 +41,10 @@ def control(op: types.Op, *, n_controls: int) -> types.Op:
41
41
  def reset() -> types.Op: ...
42
42
 
43
43
 
44
+ @wraps(stmts.ResetToOne)
45
+ def reset_to_one() -> types.Op: ...
46
+
47
+
44
48
  @wraps(stmts.Identity)
45
49
  def identity(*, sites: int) -> types.Op: ...
46
50
 
bloqade/squin/op/stmts.py CHANGED
@@ -98,6 +98,15 @@ class ConstantUnitary(ConstantOp):
98
98
 
99
99
  @statement(dialect=dialect)
100
100
  class U3(PrimitiveOp):
101
+ """
102
+ The rotation operator U3(theta, phi, lam).
103
+ Note that we use the convention from the QASM2 specification, namely
104
+
105
+ $$
106
+ U_3(\theta, \phi, \lambda) = R_z(\phi) R_y(\theta) R_z(\lambda)
107
+ $$
108
+ """
109
+
101
110
  traits = frozenset({ir.Pure(), lowering.FromPythonCall(), Unitary(), FixedSites(1)})
102
111
  theta: ir.SSAValue = info.argument(types.Float)
103
112
  phi: ir.SSAValue = info.argument(types.Float)
@@ -110,7 +119,7 @@ class PhaseOp(PrimitiveOp):
110
119
  A phase operator.
111
120
 
112
121
  $$
113
- PhaseOp(theta) = e^{i \theta} I
122
+ PhaseOp(\theta) = e^{i \theta} I
114
123
  $$
115
124
  """
116
125
 
@@ -124,7 +133,7 @@ class ShiftOp(PrimitiveOp):
124
133
  A phase shift operator.
125
134
 
126
135
  $$
127
- Shift(theta) = \\begin{bmatrix} 1 & 0 \\\\ 0 & e^{i \\theta} \\end{bmatrix}
136
+ Shift(\theta) = \\begin{bmatrix} 1 & 0 \\\\ 0 & e^{i \\theta} \\end{bmatrix}
128
137
  $$
129
138
  """
130
139
 
@@ -141,6 +150,15 @@ class Reset(PrimitiveOp):
141
150
  traits = frozenset({ir.Pure(), lowering.FromPythonCall(), FixedSites(1)})
142
151
 
143
152
 
153
+ @statement(dialect=dialect)
154
+ class ResetToOne(PrimitiveOp):
155
+ """
156
+ Reset qubits to the one state. Mainly needed to accommodate cirq's GeneralizedAmplitudeDampingChannel
157
+ """
158
+
159
+ traits = frozenset({ir.Pure(), lowering.FromPythonCall(), FixedSites(1)})
160
+
161
+
144
162
  @statement
145
163
  class CliffordOp(ConstantUnitary):
146
164
  pass
bloqade/squin/qubit.py CHANGED
@@ -17,6 +17,7 @@ from kirin.lowering import wraps
17
17
  from bloqade.types import Qubit, QubitType
18
18
  from bloqade.squin.op.types import Op, OpType
19
19
 
20
+ from .types import MeasurementResult, MeasurementResultType
20
21
  from .lowering import ApplyAnyCallLowering
21
22
 
22
23
  dialect = ir.Dialect("squin.qubit")
@@ -65,8 +66,8 @@ class MeasureQubit(ir.Statement):
65
66
  name = "measure.qubit"
66
67
 
67
68
  traits = frozenset({lowering.FromPythonCall()})
68
- qubit: ir.SSAValue = info.argument(ilist.IListType[QubitType])
69
- result: ir.ResultValue = info.result(ilist.IListType[types.Bool])
69
+ qubit: ir.SSAValue = info.argument(QubitType)
70
+ result: ir.ResultValue = info.result(MeasurementResultType)
70
71
 
71
72
 
72
73
  @statement(dialect=dialect)
@@ -75,7 +76,7 @@ class MeasureQubitList(ir.Statement):
75
76
 
76
77
  traits = frozenset({lowering.FromPythonCall()})
77
78
  qubits: ir.SSAValue = info.argument(ilist.IListType[QubitType])
78
- result: ir.ResultValue = info.result(ilist.IListType[types.Bool])
79
+ result: ir.ResultValue = info.result(ilist.IListType[MeasurementResultType])
79
80
 
80
81
 
81
82
  # NOTE: no dependent types in Python, so we have to mark it Any...
@@ -131,9 +132,11 @@ def apply(operator: Op, *qubits) -> None: ...
131
132
 
132
133
 
133
134
  @overload
134
- def measure(input: Qubit) -> bool: ...
135
+ def measure(input: Qubit) -> MeasurementResult: ...
135
136
  @overload
136
- def measure(input: ilist.IList[Qubit, Any] | list[Qubit]) -> ilist.IList[bool, Any]: ...
137
+ def measure(
138
+ input: ilist.IList[Qubit, Any] | list[Qubit],
139
+ ) -> ilist.IList[MeasurementResult, Any]: ...
137
140
 
138
141
 
139
142
  @wraps(MeasureAny)
@@ -4,4 +4,5 @@ from .wrap_analysis import (
4
4
  WrapOpSiteAnalysis as WrapOpSiteAnalysis,
5
5
  WrapAddressAnalysis as WrapAddressAnalysis,
6
6
  )
7
+ from .U3_to_clifford import SquinU3ToClifford as SquinU3ToClifford
7
8
  from .remove_dangling_qubits import RemoveDeadRegister as RemoveDeadRegister
@@ -0,0 +1,60 @@
1
+ from typing import cast
2
+
3
+ from kirin import ir
4
+ from kirin.rewrite import abc
5
+ from kirin.dialects import cf
6
+
7
+ from .. import wire
8
+
9
+
10
+ class CanonicalizeWired(abc.RewriteRule):
11
+ def rewrite_Statement(self, node: ir.Statement) -> abc.RewriteResult:
12
+
13
+ if (
14
+ not isinstance(node, wire.Wired)
15
+ or len(node.qubits) != 0
16
+ or (parent_region := node.parent_region) is None
17
+ ):
18
+ return abc.RewriteResult()
19
+
20
+ parent_block = cast(ir.Block, node.parent_block)
21
+
22
+ # the body doesn't contain any quantum operations so we can safely inline the
23
+ # body into the parent block
24
+
25
+ # move all statements after `node` in the current block into another block
26
+ after_block = ir.Block()
27
+
28
+ stmt = node.next_stmt
29
+ while stmt is not None:
30
+ stmt.detach()
31
+ after_block.stmts.append(stmt)
32
+ stmt = node.next_stmt
33
+
34
+ # remap all results of the node to the arguments of the after_block
35
+ for result in node.results:
36
+ arg = after_block.args.append_from(result.type, result.name)
37
+ result.replace_by(arg)
38
+
39
+ parent_block_idx = parent_region._block_idx[parent_block]
40
+ # insert goto of parent block to the body block of the node.
41
+ parent_region.blocks.insert(parent_block_idx + 1, after_block)
42
+ # insert all blocks of the body of the node after the parent region
43
+ # making sure to convert any yield statements to jump statements to the after_block
44
+ parent_block.stmts.append(
45
+ cf.Branch(
46
+ arguments=(),
47
+ successor=node.body.blocks[0],
48
+ )
49
+ )
50
+ for block in reversed(node.body.blocks):
51
+ block.detach()
52
+ if isinstance((yield_stmt := block.last_stmt), wire.Yield):
53
+ yield_stmt.replace_by(
54
+ cf.Branch(yield_stmt.values, successor=after_block)
55
+ )
56
+
57
+ parent_region.blocks.insert(parent_block_idx + 1, block)
58
+
59
+ node.delete()
60
+ return abc.RewriteResult(has_done_something=True)
@@ -1,5 +1,5 @@
1
1
  from kirin import ir, types
2
- from kirin.dialects import ilist
2
+ from kirin.dialects import py, ilist
3
3
  from kirin.rewrite.abc import RewriteRule, RewriteResult
4
4
 
5
5
  from bloqade.squin.qubit import (
@@ -53,12 +53,59 @@ class ApplyDesugarRule(RewriteRule):
53
53
  op = node.operator
54
54
  qubits = node.qubits
55
55
 
56
- if len(qubits) == 1 and qubits[0].type.is_subseteq(ilist.IListType):
57
- # NOTE: already calling with just a single argument that is already an ilist
56
+ if len(qubits) > 1 and all(q.type.is_subseteq(QubitType) for q in qubits):
57
+ (qubits_ilist_stmt := ilist.New(qubits)).insert_before(node)
58
+ qubits_ilist = qubits_ilist_stmt.result
59
+
60
+ elif len(qubits) == 1 and qubits[0].type.is_subseteq(QubitType):
61
+ (qubits_ilist_stmt := ilist.New(qubits)).insert_before(node)
62
+ qubits_ilist = qubits_ilist_stmt.result
63
+
64
+ elif len(qubits) == 1 and qubits[0].type.is_subseteq(
65
+ ilist.IListType[QubitType, types.Any]
66
+ ):
58
67
  qubits_ilist = qubits[0]
59
- else:
60
- (qubits_ilist_stmt := ilist.New(values=qubits)).insert_before(node)
68
+
69
+ elif len(qubits) == 1:
70
+ # TODO: remove this elif clause once we're at kirin v0.18
71
+ # NOTE: this is a temporary workaround for kirin#408
72
+ # currently type inference fails here in for loops since the loop var
73
+ # is an IList for some reason
74
+
75
+ if not isinstance(qubits[0], ir.ResultValue):
76
+ return RewriteResult()
77
+
78
+ is_ilist = isinstance(qbit_stmt := qubits[0].stmt, ilist.New)
79
+ if is_ilist:
80
+ if len(qbit_stmt.values) != 1:
81
+ return RewriteResult()
82
+
83
+ if not isinstance(
84
+ qbit_getindex_result := qbit_stmt.values[0], ir.ResultValue
85
+ ):
86
+ return RewriteResult()
87
+
88
+ qbit_getindex = qbit_getindex_result.stmt
89
+ else:
90
+ qbit_getindex = qubits[0].stmt
91
+
92
+ if not isinstance(qbit_getindex, py.indexing.GetItem):
93
+ return RewriteResult()
94
+
95
+ if not qbit_getindex.obj.type.is_subseteq(
96
+ ilist.IListType[QubitType, types.Any]
97
+ ):
98
+ return RewriteResult()
99
+
100
+ if is_ilist:
101
+ values = qbit_stmt.values
102
+ else:
103
+ values = [qubits[0]]
104
+
105
+ (qubits_ilist_stmt := ilist.New(values=values)).insert_before(node)
61
106
  qubits_ilist = qubits_ilist_stmt.result
107
+ else:
108
+ return RewriteResult()
62
109
 
63
110
  stmt = Apply(operator=op, qubits=qubits_ilist)
64
111
  node.replace_by(stmt)
bloqade/squin/types.py ADDED
@@ -0,0 +1,8 @@
1
+ from kirin import types
2
+
3
+
4
+ class MeasurementResult:
5
+ pass
6
+
7
+
8
+ MeasurementResultType = types.PyClass(MeasurementResult)
bloqade/squin/wire.py CHANGED
@@ -6,12 +6,15 @@ circuits. Thus we do not define wrapping functions for the statements in this
6
6
  dialect.
7
7
  """
8
8
 
9
- from kirin import ir, types, lowering
9
+ from kirin import ir, types, lowering, exception
10
10
  from kirin.decl import info, statement
11
+ from kirin.dialects import func
11
12
  from kirin.lowering import wraps
13
+ from kirin.ir.attrs.types import TypeAttribute
12
14
 
13
15
  from bloqade.types import Qubit, QubitType
14
16
 
17
+ from .types import MeasurementResultType
15
18
  from .op.types import Op, OpType
16
19
 
17
20
  # from kirin.lowering import wraps
@@ -49,11 +52,87 @@ class Unwrap(ir.Statement):
49
52
  result: ir.ResultValue = info.result(WireType)
50
53
 
51
54
 
55
+ @statement(dialect=dialect)
56
+ class Wired(ir.Statement):
57
+ traits = frozenset()
58
+
59
+ qubits: tuple[ir.SSAValue, ...] = info.argument(QubitType)
60
+ memory_zone: str = info.attribute()
61
+ body: ir.Region = info.region(multi=True)
62
+
63
+ def __init__(
64
+ self,
65
+ body: ir.Region,
66
+ *qubits: ir.SSAValue,
67
+ memory_zone: str,
68
+ result_types: tuple[TypeAttribute, ...] | None = None,
69
+ ):
70
+ if result_types is None:
71
+ for block in body.blocks:
72
+ if isinstance(block.last_stmt, Yield):
73
+ result_types = tuple(arg.type for arg in block.last_stmt.values)
74
+ break
75
+
76
+ if result_types is None:
77
+ result_types = ()
78
+
79
+ super().__init__(
80
+ args=qubits,
81
+ args_slice={
82
+ "qubits": slice(0, None),
83
+ },
84
+ regions=[body],
85
+ attributes={
86
+ "memory_zone": ir.PyAttr(memory_zone)
87
+ }, # body of the wired statement
88
+ result_types=result_types,
89
+ )
90
+
91
+ def check(self):
92
+ entry_block = self.body.blocks[0]
93
+
94
+ if len(entry_block.args) != len(self.qubits):
95
+ raise exception.StaticCheckError(
96
+ f"Expected {len(self.qubits)} arguments, got {len(entry_block.args)}."
97
+ )
98
+ for arg in entry_block.args:
99
+ if not arg.type.is_subseteq(WireType):
100
+ raise exception.StaticCheckError(
101
+ f"Expected argument of type {WireType}, got {arg.type}."
102
+ )
103
+ for block in self.body.blocks:
104
+ last_stmt = block.last_stmt
105
+ if isinstance(last_stmt, func.Return):
106
+ raise exception.StaticCheckError(
107
+ "Return statements are not allowed in the body of a Wired statement."
108
+ )
109
+ elif isinstance(last_stmt, Yield) and len(last_stmt.values) != len(
110
+ self.results
111
+ ):
112
+ raise exception.StaticCheckError(
113
+ f"Expected {len(self.results)} return values, got {len(last_stmt.values)}."
114
+ )
115
+
116
+
117
+ @statement(dialect=dialect)
118
+ class Yield(ir.Statement):
119
+ traits = frozenset({})
120
+ values: tuple[ir.SSAValue, ...] = info.argument(WireType)
121
+
122
+ def __init__(self, *args: ir.SSAValue):
123
+ super().__init__(
124
+ args=args,
125
+ args_slice={
126
+ "values": slice(0, None),
127
+ },
128
+ )
129
+
130
+
52
131
  # In Quake, you put a wire in and get a wire out when you "apply" an operator
53
132
  # In this case though we just need to indicate that an operator is applied to list[wires]
54
133
  @statement(dialect=dialect)
55
134
  class Apply(ir.Statement): # apply(op, w1, w2, ...)
56
- traits = frozenset({lowering.FromPythonCall(), ir.Pure()})
135
+ traits = frozenset({lowering.FromPythonCall()})
57
136
  operator: ir.SSAValue = info.argument(OpType)
58
137
  inputs: tuple[ir.SSAValue, ...] = info.argument(WireType)
59
138
 
@@ -88,6 +167,13 @@ class Broadcast(ir.Statement):
88
167
  ) # custom lowering required for wrapper to work here
89
168
 
90
169
 
170
+ @statement(dialect=dialect)
171
+ class RegionMeasure(ir.Statement):
172
+ traits = frozenset({lowering.FromPythonCall(), WireTerminator()})
173
+ wire: ir.SSAValue = info.argument(WireType)
174
+ result: ir.ResultValue = info.result(MeasurementResultType)
175
+
176
+
91
177
  # NOTE: measurement cannot be pure because they will collapse the state
92
178
  # of the qubit. The state is a hidden state that is not visible to
93
179
  # the user in the wire dialect.
@@ -96,14 +182,14 @@ class Measure(ir.Statement):
96
182
  traits = frozenset({lowering.FromPythonCall(), WireTerminator()})
97
183
  wire: ir.SSAValue = info.argument(WireType)
98
184
  qubit: ir.SSAValue = info.argument(QubitType)
99
- result: ir.ResultValue = info.result(types.Int)
185
+ result: ir.ResultValue = info.result(MeasurementResultType)
100
186
 
101
187
 
102
188
  @statement(dialect=dialect)
103
- class NonDestructiveMeasure(ir.Statement):
189
+ class LossResolvingMeasure(ir.Statement):
104
190
  traits = frozenset({lowering.FromPythonCall()})
105
191
  input_wire: ir.SSAValue = info.argument(WireType)
106
- result: ir.ResultValue = info.result(types.Int)
192
+ result: ir.ResultValue = info.result(MeasurementResultType)
107
193
  out_wire: ir.ResultValue = info.result(WireType)
108
194
 
109
195