Repository navigation
Expand file tree
/
Copy pathlowering.py
More file actions
325 lines (275 loc) · 11.7 KB
/
Copy pathlowering.py
File metadata and controls
325 lines (275 loc) · 11.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
from typing import Dict, List, Tuple, Sequence
from dataclasses import field, dataclass
from kirin import ir, types, passes
from kirin.dialects import func, ilist
from bloqade import qasm2
from bloqade.qbraid import schema
from bloqade.qasm2.dialects import glob, noise, parallel
@ir.dialect_group(
[func, qasm2.core, qasm2.uop, parallel, glob, qasm2.expr, noise, ilist]
)
def qbraid_noise(
self,
):
fold_pass = passes.Fold(self)
typeinfer_pass = passes.TypeInfer(self)
def run_pass(
method: ir.Method,
*,
fold: bool = True,
):
method.verify()
if fold:
fold_pass(method)
typeinfer_pass(method)
method.code.verify_type()
return run_pass
@dataclass
class Lowering:
qubit_list: List[ir.SSAValue] = field(init=False, default_factory=list)
qubit_id_map: Dict[int, ir.SSAValue] = field(init=False, default_factory=dict)
bit_id_map: Dict[int, ir.SSAValue] = field(init=False, default_factory=dict)
block_list: List[ir.Statement] = field(init=False, default_factory=list)
def lower(
self,
sym_name: str,
noise_model: schema.NoiseModel,
return_qreg: bool = False,
) -> ir.Method:
"""Lower the noise model to a method.
Args:
name (str): The name of the method to generate.
return_qreg (bool): Use the quantum register as the return value.
Returns:
Method: The generated kirin method.
"""
self.process_noise_model(noise_model, return_qreg)
block = ir.Block(stmts=self.block_list)
ret_type = qasm2.types.QRegType if return_qreg else qasm2.types.CRegType
block.args.append_from(types.MethodType[[], ret_type], name=f"{sym_name}_self")
region = ir.Region(block)
func_stmt = func.Function(
sym_name=sym_name,
signature=func.Signature(inputs=(), output=qasm2.types.QRegType),
body=region,
)
mt = ir.Method(
mod=None,
py_func=None,
sym_name=sym_name,
dialects=qbraid_noise,
code=func_stmt,
arg_names=[],
)
qbraid_noise.run_pass(mt) # type: ignore
return mt
def process_noise_model(self, noise_model: schema.NoiseModel, return_qreg: bool):
num_qubits = self.lower_number(noise_model.num_qubits)
reg = qasm2.core.QRegNew(num_qubits)
creg = qasm2.core.CRegNew(num_qubits)
self.block_list.append(reg)
self.block_list.append(creg)
for idx_value, qubit in enumerate(noise_model.all_qubits):
idx = self.lower_number(idx_value)
self.block_list.append(qubit_stmt := qasm2.core.QRegGet(reg.result, idx))
self.block_list.append(bit_stmt := qasm2.core.CRegGet(creg.result, idx))
self.qubit_id_map[qubit] = qubit_stmt.result
self.bit_id_map[qubit] = bit_stmt.result
self.qubit_list.append(qubit_stmt.result)
for gate_event in noise_model.gate_events:
self.process_gate_event(gate_event)
if return_qreg:
self.block_list.append(func.Return(reg.result))
else:
self.block_list.append(func.Return(creg.result))
def process_gate_event(self, node: schema.GateEvent):
self.lower_atom_loss(node.error.survival_prob)
if isinstance(node.operation, schema.CZ):
assert isinstance(node.error, schema.CZError), "Only CZError is supported"
self.process_cz_pauli_error(node.operation.participants, node.error)
self.lower_cz_gates(node.operation)
else:
error = node.error
assert isinstance(
error, schema.SingleQubitError
), "Only SingleQubitError is supported"
self.lower_pauli_errors(error.operator_error)
operation = node.operation
assert isinstance(
operation,
(
schema.GlobalW,
schema.LocalW,
schema.GlobalRz,
schema.LocalRz,
schema.Measurement,
),
), f"Only W and Rz gates are supported, found {type(operation)}.__name__"
if isinstance(operation, schema.GlobalW):
self.lower_w_gates(
tuple(self.qubit_id_map.keys()), operation.theta, operation.phi
)
elif isinstance(operation, schema.LocalW):
self.lower_w_gates(
operation.participants, operation.theta, operation.phi
)
elif isinstance(operation, schema.GlobalRz):
self.lower_rz_gates(tuple(self.qubit_id_map.keys()), operation.phi)
elif isinstance(operation, schema.LocalRz):
self.lower_rz_gates(operation.participants, operation.phi)
elif isinstance(operation, schema.Measurement):
self.lower_measurement(operation)
def process_cz_pauli_error(
self,
participants: Tuple[Tuple[int] | Tuple[int, int], ...],
node: schema.CZError[schema.PauliErrorModel],
):
storage_error = node.storage_error
single_error = node.single_error
entangled_error = node.entangled_error
assert isinstance(
storage_error, schema.PauliErrorModel
), "Only PauliErrorModel is supported"
assert isinstance(
single_error, schema.PauliErrorModel
), "Only PauliErrorModel is supported"
assert isinstance(
entangled_error, schema.PauliErrorModel
), "Only PauliErrorModel is supported"
self.lower_pauli_errors(storage_error)
single_error_dict = dict(single_error.errors)
entangled_error_dict = dict(entangled_error.errors)
single_layers = {}
paired_layers = {}
unpaired_layers = {}
for participant in participants:
if len(participant) == 1:
p_single = single_error_dict[participant[0]]
single_layers.setdefault(p_single, []).append(participant[0])
elif len(participant) == 2:
p_ctrl = entangled_error_dict[participant[0]]
up_ctrl = single_error_dict[participant[0]]
p_qarg = entangled_error_dict[participant[1]]
up_qarg = single_error_dict[participant[1]]
paired_layers.setdefault((p_ctrl, p_qarg), []).append(participant)
unpaired_layers.setdefault((up_ctrl, up_qarg), []).append(participant)
for (px, py, pz), qubits in single_layers.items():
self.block_list.append(
qargs := ilist.New(values=tuple(self.qubit_id_map[q] for q in qubits))
)
self.block_list.append(
noise.PauliChannel(px=px, py=py, pz=pz, qargs=qargs.result)
)
for (p_ctrl, p_qarg), qubits in paired_layers.items():
ctrls, qargs = list(zip(*qubits))
self.block_list.append(
ctrls := ilist.New(values=tuple(self.qubit_id_map[q] for q in ctrls))
)
self.block_list.append(
qargs := ilist.New(values=tuple(self.qubit_id_map[q] for q in qargs))
)
self.block_list.append(
noise.CZPauliChannel(
paired=True,
px_ctrl=p_ctrl[0],
py_ctrl=p_ctrl[1],
pz_ctrl=p_ctrl[2],
px_qarg=p_qarg[0],
py_qarg=p_qarg[1],
pz_qarg=p_qarg[2],
ctrls=ctrls.result,
qargs=qargs.result,
)
)
for (p_ctrl, p_qarg), qubits in unpaired_layers.items():
ctrls, qargs = list(zip(*qubits))
self.block_list.append(
ctrls := ilist.New(values=tuple(self.qubit_id_map[q] for q in ctrls))
)
self.block_list.append(
qargs := ilist.New(values=tuple(self.qubit_id_map[q] for q in qargs))
)
self.block_list.append(
noise.CZPauliChannel(
paired=False,
px_ctrl=p_ctrl[0],
py_ctrl=p_ctrl[1],
pz_ctrl=p_ctrl[2],
px_qarg=p_qarg[0],
py_qarg=p_qarg[1],
pz_qarg=p_qarg[2],
ctrls=ctrls.result,
qargs=qargs.result,
)
)
def lower_cz_gates(self, node: schema.CZ):
ctrls, qargs = list(zip(*(p for p in node.participants if len(p) == 2)))
self.block_list.append(
ctrls := ilist.New(values=tuple(self.qubit_id_map[q] for q in ctrls))
)
self.block_list.append(
qargs := ilist.New(values=tuple(self.qubit_id_map[q] for q in qargs))
)
self.block_list.append(parallel.CZ(ctrls=ctrls.result, qargs=qargs.result))
def lower_w_gates(self, participants: Sequence[int], theta: float, phi: float):
self.block_list.append(
qargs := ilist.New(values=tuple(self.qubit_id_map[q] for q in participants))
)
self.block_list.append(
parallel.UGate(
theta=self.lower_full_turns(theta),
phi=self.lower_full_turns(phi + 0.5),
lam=self.lower_full_turns(-(0.5 + phi)),
qargs=qargs.result,
)
)
def lower_rz_gates(self, participants: Tuple[int, ...], phi: float):
self.block_list.append(
qargs := ilist.New(values=tuple(self.qubit_id_map[q] for q in participants))
)
self.block_list.append(
parallel.RZ(theta=self.lower_full_turns(phi), qargs=qargs.result)
)
def lower_pauli_errors(self, operator_error: schema.PauliErrorModel):
assert isinstance(
operator_error, schema.PauliErrorModel
), "Only PauliErrorModel is supported"
layers = {}
for qubit_num, pauli_errors in operator_error.errors:
layers.setdefault(pauli_errors, []).append(qubit_num)
for (px, py, pz), qubits in layers.items():
self.block_list.append(
qargs := ilist.New(values=tuple(self.qubit_id_map[q] for q in qubits))
)
self.block_list.append(
noise.PauliChannel(px=px, py=py, pz=pz, qargs=qargs.result)
)
def lower_measurement(self, operation: schema.Measurement):
for participant in operation.participants:
qubit = self.qubit_id_map[participant]
bit = self.bit_id_map[participant]
self.block_list.append(qasm2.core.Measure(qarg=qubit, carg=bit))
def lower_atom_loss(self, survival_probs: Tuple[float, ...]):
layers = {}
for qubit_num, survival_prob in zip(self.qubit_list, survival_probs):
layers.setdefault(survival_prob, []).append(qubit_num)
for survival_prob, qubits in layers.items():
self.block_list.append(qargs := ilist.New(values=qubits))
self.block_list.append(
noise.AtomLossChannel(prob=survival_prob, qargs=qargs.result)
)
def lower_number(self, value: float | int) -> ir.SSAValue:
if isinstance(value, int):
stmt = qasm2.expr.ConstInt(value=value)
else:
stmt = qasm2.expr.ConstFloat(value=value)
self.block_list.append(stmt)
return stmt.result
def lower_full_turns(self, value: float) -> ir.SSAValue:
const_pi = qasm2.expr.ConstPI()
self.block_list.append(const_pi)
turns = self.lower_number(2 * value)
mul = qasm2.expr.Mul(const_pi.result, turns)
mul.result.type = types.Float
self.block_list.append(mul)
return mul.result