pennylane-qrack 0.24.1__py3-none-win_amd64.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.
@@ -0,0 +1,447 @@
1
+ # Copyright 2020 Xanadu Quantum Technologies Inc.
2
+
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ """
15
+ Base device class for PennyLane-Qrack.
16
+ """
17
+ from functools import reduce
18
+ import cmath, math
19
+ import os
20
+ import pathlib
21
+ import sys
22
+ import itertools as it
23
+
24
+ import numpy as np
25
+
26
+ # PennyLane v0.42 introduced the `exceptions` module and will raise
27
+ # deprecation warnings if they are imported from the top-level module.
28
+
29
+ # This ensures backwards compatibility with older versions of PennyLane.
30
+ try:
31
+ from pennylane.exceptions import DeviceError, QuantumFunctionError
32
+ except (ModuleNotFoundError, ImportError) as import_error:
33
+ from pennylane import DeviceError, QuantumFunctionError
34
+
35
+ from pennylane.devices import QubitDevice
36
+ from pennylane.ops import (
37
+ BasisState,
38
+ Adjoint,
39
+ )
40
+ from pennylane.wires import Wires
41
+
42
+ from pyqrack import QrackAceBackend, Pauli
43
+
44
+ from ._version import __version__
45
+ from sys import platform as _platform
46
+
47
+ # tolerance for numerical errors
48
+ tolerance = 1e-10
49
+
50
+
51
+ class QrackAceDevice(QubitDevice):
52
+ """Qrack Ace device"""
53
+
54
+ name = "Qrack Ace device"
55
+ short_name = "qrack.ace"
56
+ pennylane_requires = ">=0.11.0"
57
+ version = __version__
58
+ author = "Daniel Strano, adapted from Steven Oud and Xanadu"
59
+
60
+ _capabilities = {
61
+ "model": "qubit",
62
+ "tensor_observables": True,
63
+ "inverse_operations": True,
64
+ "returns_state": False,
65
+ }
66
+
67
+ _observable_map = {
68
+ "PauliX": Pauli.PauliX,
69
+ "PauliY": Pauli.PauliY,
70
+ "PauliZ": Pauli.PauliZ,
71
+ "Identity": Pauli.PauliI,
72
+ "Hadamard": None,
73
+ "Hermitian": None,
74
+ "Prod": None,
75
+ # "Sum": None,
76
+ # "SProd": None,
77
+ # "Exp": None,
78
+ # "Projector": None,
79
+ # "Hamiltonian": None,
80
+ # "SparseHamiltonian": None
81
+ }
82
+
83
+ observables = _observable_map.keys()
84
+ operations = {
85
+ "Identity",
86
+ "C(Identity)",
87
+ "MultiRZ",
88
+ "SWAP",
89
+ "ISWAP",
90
+ "PSWAP",
91
+ "CNOT",
92
+ "CY",
93
+ "CZ",
94
+ "S",
95
+ "T",
96
+ "RX",
97
+ "RY",
98
+ "RZ",
99
+ "PauliX",
100
+ "C(PauliX)",
101
+ "PauliY",
102
+ "C(PauliY)",
103
+ "PauliZ",
104
+ "C(PauliZ)",
105
+ "Hadamard",
106
+ "SX",
107
+ "PhaseShift",
108
+ "U3",
109
+ "Rot",
110
+ }
111
+
112
+ config_filepath = pathlib.Path(
113
+ os.path.dirname(sys.modules[__name__].__file__) + "/QrackAceDeviceConfig.toml"
114
+ )
115
+
116
+ # Use "hybrid" stabilizer optimization? (Default is "true"; non-Clifford circuits will fall back to near-Clifford or universal simulation)
117
+ isStabilizerHybrid = False
118
+ # Use "tensor network" optimization? (Default is "false"; prevents dynamic qubit de-allocation; might function sub-optimally with "hybrid" stabilizer enabled)
119
+ isTensorNetwork = False
120
+ # Use Schmidt decomposition optimizations? (Default is "true")
121
+ isSchmidtDecompose = True
122
+ # Distribute Schmidt-decomposed qubit subsystems to multiple GPUs or accelerators, if available? (Default is "true"; mismatched device capacities might hurt overall performance)
123
+ isSchmidtDecomposeMulti = True
124
+ # Use "quantum binary decision diagram" ("QBDD") methods? (Default is "false"; note that QBDD is CPU-only)
125
+ isBinaryDecisionTree = False
126
+ # Use GPU acceleration? (Default is "true")
127
+ isOpenCL = True
128
+ # Use multi-GPU (or "multi-page") acceleration? (Default is "false")
129
+ isPaged = True
130
+ # Use CPU/GPU method hybridization? (Default is "false")
131
+ isCpuGpuHybrid = True
132
+ # Allocate GPU buffer from general host heap? (Default is "false"; "true" might improve performance or reliability in certain cases, like if using an Intel HD as accelerator)
133
+ isHostPointer = True if os.environ.get("PYQRACK_HOST_POINTER_DEFAULT_ON") else False
134
+ # Noise parameter. (Default is "0"; depolarizing noise intensity can also be controlled by "QRACK_GATE_DEPOLARIZATION" environment variable)
135
+ noise = 0
136
+ # How many full simulation columns, between border columns
137
+ long_range_columns = 4
138
+ # How many full simulation rows, between border rows
139
+ long_range_rows = 4
140
+ # Whether to transpose rows and columns
141
+ is_transpose = False
142
+
143
+ def __init__(self, wires=0, shots=None, **kwargs):
144
+ options = dict(kwargs)
145
+ if "isStabilizerHybrid" in options:
146
+ self.isStabilizerHybrid = options["isStabilizerHybrid"]
147
+ if "isTensorNetwork" in options:
148
+ self.isTensorNetwork = options["isTensorNetwork"]
149
+ if "isSchmidtDecompose" in options:
150
+ self.isSchmidtDecompose = options["isSchmidtDecompose"]
151
+ if "isBinaryDecisionTree" in options:
152
+ self.isBinaryDecisionTree = options["isBinaryDecisionTree"]
153
+ if "isOpenCL" in options:
154
+ self.isOpenCL = options["isOpenCL"]
155
+ if "isPaged" in options:
156
+ self.isPaged = options["isPaged"]
157
+ if "isCpuGpuHybrid" in options:
158
+ self.isCpuGpuHybrid = options["isCpuGpuHybrid"]
159
+ if "isHostPointer" in options:
160
+ self.isHostPointer = options["isHostPointer"]
161
+ if "noise" in options:
162
+ self.noise = options["noise"]
163
+ if (self.noise != 0) and (shots is None):
164
+ raise ValueError("Shots must be finite for noisy simulation (not analytical mode).")
165
+ if "long_range_columns" in options:
166
+ self.long_range_columns = options["long_range_columns"]
167
+ if "long_range_rows" in options:
168
+ self.long_range_rows = options["long_range_rows"]
169
+ if "is_transpose" in options:
170
+ self.is_transpose = options["is_transpose"]
171
+
172
+ super().__init__(wires=wires, shots=shots)
173
+ self.shots = shots
174
+ self._state = QrackAceBackend(
175
+ self.num_wires,
176
+ long_range_columns=self.long_range_columns,
177
+ long_range_rows=self.long_range_rows,
178
+ is_transpose=self.is_transpose,
179
+ isStabilizerHybrid=self.isStabilizerHybrid,
180
+ isTensorNetwork=self.isTensorNetwork,
181
+ isSchmidtDecompose=self.isSchmidtDecompose,
182
+ isBinaryDecisionTree=self.isBinaryDecisionTree,
183
+ isOpenCL=self.isOpenCL,
184
+ isCpuGpuHybrid=self.isCpuGpuHybrid,
185
+ isHostPointer=self.isHostPointer,
186
+ noise=self.noise,
187
+ )
188
+ self.device_kwargs = {
189
+ "long_range_columns": self.long_range_columns,
190
+ "long_range_rows": self.long_range_rows,
191
+ "is_transpose": self.is_transpose,
192
+ "is_hybrid_stabilizer": self.isStabilizerHybrid,
193
+ "is_tensor_network": self.isTensorNetwork,
194
+ "is_schmidt_decompose": self.isSchmidtDecompose,
195
+ "is_schmidt_decompose_parallel": self.isSchmidtDecomposeMulti,
196
+ "is_qpdd": self.isBinaryDecisionTree,
197
+ "is_gpu": self.isOpenCL,
198
+ "is_paged": self.isPaged,
199
+ "is_hybrid_cpu_gpu": self.isCpuGpuHybrid,
200
+ "is_host_pointer": self.isHostPointer,
201
+ "noise": self.noise,
202
+ }
203
+ self._circuit = []
204
+
205
+ def _reverse_state(self):
206
+ end = self.num_wires - 1
207
+ mid = self.num_wires >> 1
208
+ for i in range(mid):
209
+ self._state.swap(i, end - i)
210
+
211
+ def apply(self, operations, **kwargs):
212
+ """Apply the circuit operations to the state.
213
+
214
+ This method serves as an auxiliary method to :meth:`~.QrackDevice.apply`.
215
+
216
+ Args:
217
+ operations (List[pennylane.Operation]): operations to be applied
218
+ """
219
+
220
+ self._circuit = self._circuit + operations
221
+ if self.noise == 0:
222
+ self._apply()
223
+ self._circuit = []
224
+ # else: Defer application until shots or expectation values are requested
225
+
226
+ def _apply(self):
227
+ for op in self._circuit:
228
+ if isinstance(op, BasisState):
229
+ self._apply_basis_state(op)
230
+ else:
231
+ self._apply_gate(op)
232
+
233
+ def _apply_basis_state(self, op):
234
+ """Initialize a basis state"""
235
+ wires = self.map_wires(Wires(op.wires))
236
+ par = op.parameters[0]
237
+ wire_count = len(wires)
238
+ n_basis_state = len(par)
239
+
240
+ if not set(par).issubset({0, 1}):
241
+ raise ValueError("BasisState parameter must consist of 0 or 1 integers.")
242
+ if n_basis_state != wire_count:
243
+ raise ValueError("BasisState parameter and wires must be of equal length.")
244
+
245
+ for i in range(wire_count):
246
+ index = wires.labels[i]
247
+ if par[i] != self._state.m(index):
248
+ self._state.x(index)
249
+
250
+ def _apply_gate(self, op):
251
+ """Apply native qrack gate"""
252
+
253
+ opname = op.name
254
+ if isinstance(op, Adjoint):
255
+ op = op.base
256
+ opname = op.name + ".inv"
257
+
258
+ par = op.parameters
259
+
260
+ if opname == "MultiRZ":
261
+ device_wires = self.map_wires(op.wires)
262
+ for q in device_wires:
263
+ self._state.r(Pauli.PauliZ, par[0], q)
264
+ return
265
+
266
+ # translate op wire labels to consecutive wire labels used by the device
267
+ device_wires = self.map_wires(
268
+ (op.control_wires + op.wires) if op.control_wires else op.wires
269
+ )
270
+
271
+ if opname in [
272
+ "".join(p)
273
+ for p in it.product(
274
+ [
275
+ "CNOT",
276
+ "C(PauliX)",
277
+ ],
278
+ ["", ".inv"],
279
+ )
280
+ ]:
281
+ self._state.mcx(device_wires.labels[:-1], device_wires.labels[-1])
282
+ elif opname in ["C(PauliY)", "C(PauliY).inv"]:
283
+ self._state.mcy(device_wires.labels[:-1], device_wires.labels[-1])
284
+ elif opname in ["C(PauliZ)", "C(PauliZ).inv"]:
285
+ self._state.mcz(device_wires.labels[:-1], device_wires.labels[-1])
286
+ elif opname in ["SWAP", "SWAP.inv"]:
287
+ self._state.swap(device_wires.labels[0], device_wires.labels[1])
288
+ elif opname == "ISWAP":
289
+ self._state.iswap(device_wires.labels[0], device_wires.labels[1])
290
+ elif opname == "ISWAP.inv":
291
+ self._state.adjiswap(device_wires.labels[0], device_wires.labels[1])
292
+ elif opname in ["CY", "CY.inv", "C(CY)", "C(CY).inv"]:
293
+ self._state.mcy(device_wires.labels[:-1], device_wires.labels[-1])
294
+ elif opname in ["CZ", "CZ.inv", "C(CZ)", "C(CZ).inv"]:
295
+ self._state.mcz(device_wires.labels[:-1], device_wires.labels[-1])
296
+ elif opname == "S":
297
+ for label in device_wires.labels:
298
+ self._state.s(label)
299
+ elif opname == "S.inv":
300
+ for label in device_wires.labels:
301
+ self._state.adjs(label)
302
+ elif opname == "T":
303
+ for label in device_wires.labels:
304
+ self._state.t(label)
305
+ elif opname == "T.inv":
306
+ for label in device_wires.labels:
307
+ self._state.adjt(label)
308
+ elif opname == "RX":
309
+ for label in device_wires.labels:
310
+ self._state.r(Pauli.PauliX, par[0], label)
311
+ elif opname == "RX.inv":
312
+ for label in device_wires.labels:
313
+ self._state.r(Pauli.PauliX, -par[0], label)
314
+ elif opname == "RY":
315
+ for label in device_wires.labels:
316
+ self._state.r(Pauli.PauliY, par[0], label)
317
+ elif opname == "RY.inv":
318
+ for label in device_wires.labels:
319
+ self._state.r(Pauli.PauliY, -par[0], label)
320
+ elif opname == "RZ":
321
+ for label in device_wires.labels:
322
+ self._state.r(Pauli.PauliZ, par[0], label)
323
+ elif opname == "RZ.inv":
324
+ for label in device_wires.labels:
325
+ self._state.r(Pauli.PauliZ, -par[0], label)
326
+ elif opname in ["PauliX", "PauliX.inv"]:
327
+ for label in device_wires.labels:
328
+ self._state.x(label)
329
+ elif opname in ["PauliY", "PauliY.inv"]:
330
+ for label in device_wires.labels:
331
+ self._state.y(label)
332
+ elif opname in ["PauliZ", "PauliZ.inv"]:
333
+ for label in device_wires.labels:
334
+ self._state.z(label)
335
+ elif opname in ["Hadamard", "Hadamard.inv"]:
336
+ for label in device_wires.labels:
337
+ self._state.h(label)
338
+ elif opname == "SX":
339
+ half_pi = math.pi / 2
340
+ for label in device_wires.labels:
341
+ self._state.u(label, half_pi, -half_pi, half.pi)
342
+ elif opname == "SX.inv":
343
+ half_pi = math.pi / 2
344
+ for label in device_wires.labels:
345
+ self._state.u(label, -half_pi, -half.pi, half_pi)
346
+ elif opname == "PhaseShift":
347
+ half_par = par[0] / 2
348
+ for label in device_wires.labels:
349
+ self._state.u(label, 0, half_par, half_par)
350
+ elif opname == "PhaseShift.inv":
351
+ half_par = par[0] / 2
352
+ for label in device_wires.labels:
353
+ self._state.u(label, 0, -half_par, -half_par)
354
+ elif opname == "U3":
355
+ for label in device_wires.labels:
356
+ self._state.u(label, par[0], par[1], par[2])
357
+ elif opname == "U3.inv":
358
+ for label in device_wires.labels:
359
+ self._state.u(label, -par[0], -par[2], -par[1])
360
+ elif opname == "Rot":
361
+ for label in device_wires.labels:
362
+ self._state.r(Pauli.PauliZ, par[0], label)
363
+ self._state.r(Pauli.PauliY, par[1], label)
364
+ self._state.r(Pauli.PauliZ, par[2], label)
365
+ elif opname == "Rot.inv":
366
+ for label in device_wires.labels:
367
+ self._state.r(Pauli.PauliZ, -par[2], label)
368
+ self._state.r(Pauli.PauliY, -par[1], label)
369
+ self._state.r(Pauli.PauliZ, -par[0], label)
370
+ elif opname not in [
371
+ "Identity",
372
+ "Identity.inv",
373
+ "C(Identity)",
374
+ "C(Identity).inv",
375
+ ]:
376
+ raise DeviceError(f"Operation {opname} is not supported on a {self.short_name} device.")
377
+
378
+ def analytic_probability(self, wires=None):
379
+ raise DeviceError(
380
+ f"analytic_probability is not supported on a {self.short_name} device. (Specify a finite number of shots, instead.)"
381
+ )
382
+
383
+ def expval(self, observable, **kwargs):
384
+ if self.shots is None:
385
+ if isinstance(observable.name, list):
386
+ b = [self._observable_map[obs] for obs in observable.name]
387
+ elif observable.name == "Prod":
388
+ b = [self._observable_map[obs.name] for obs in observable.operands]
389
+ else:
390
+ b = [self._observable_map[observable.name]]
391
+
392
+ # exact expectation value
393
+ if callable(observable.eigvals):
394
+ eigvals = self._asarray(observable.eigvals(), dtype=self.R_DTYPE)
395
+ else: # older version of pennylane
396
+ eigvals = self._asarray(observable.eigvals, dtype=self.R_DTYPE)
397
+ prob = self.probability(wires=observable.wires)
398
+ return self._dot(eigvals, prob)
399
+
400
+ # estimate the ev
401
+ return np.mean(self.sample(observable))
402
+
403
+ def _generate_sample(self):
404
+ rev_sample = self._state.m_all()
405
+ sample = 0
406
+ for i in range(self.num_wires):
407
+ if (rev_sample & (1 << i)) > 0:
408
+ sample |= 1 << (self.num_wires - (i + 1))
409
+ return sample
410
+
411
+ def generate_samples(self):
412
+ if self.shots is None:
413
+ raise QuantumFunctionError(
414
+ "The number of shots has to be explicitly set on the device "
415
+ "when using sample-based measurements."
416
+ )
417
+
418
+ if self.noise != 0:
419
+ samples = []
420
+ for _ in range(self.shots):
421
+ self._state.reset_all()
422
+ self._apply()
423
+ samples.append(self._generate_sample())
424
+ self._samples = QubitDevice.states_to_binary(np.array(samples), self.num_wires)
425
+ self._circuit = []
426
+
427
+ return self._samples
428
+
429
+ if self.shots == 1:
430
+ self._samples = QubitDevice.states_to_binary(
431
+ np.array([self._generate_sample()]), self.num_wires
432
+ )
433
+
434
+ return self._samples
435
+
436
+ # QubitDevice.states_to_binary() doesn't work for >64qb. (Fix by Elara, the custom OpenAI GPT)
437
+ samples = self._state.measure_shots(list(range(self.num_wires - 1, -1, -1)), self.shots)
438
+ self._samples = np.array(
439
+ [list(format(b, f"0{self.num_wires}b")) for b in samples], dtype=np.int8
440
+ )
441
+
442
+ return self._samples
443
+
444
+ def reset(self):
445
+ for i in range(self.num_wires):
446
+ if self._state.m(i):
447
+ self._state.x(i)