pennylane-lightning-tensor 0.42.0__cp313-cp313-manylinux_2_28_x86_64.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.
- pennylane_lightning/lightning_tensor/__init__.py +18 -0
- pennylane_lightning/lightning_tensor/_measurements.py +426 -0
- pennylane_lightning/lightning_tensor/_tensornet.py +787 -0
- pennylane_lightning/lightning_tensor/lightning_tensor.py +615 -0
- pennylane_lightning/lightning_tensor_ops.cpython-313-x86_64-linux-gnu.so +0 -0
- pennylane_lightning_tensor-0.42.0.dist-info/METADATA +220 -0
- pennylane_lightning_tensor-0.42.0.dist-info/RECORD +12 -0
- pennylane_lightning_tensor-0.42.0.dist-info/WHEEL +5 -0
- pennylane_lightning_tensor-0.42.0.dist-info/entry_points.txt +2 -0
- pennylane_lightning_tensor-0.42.0.dist-info/licenses/LICENSE +212 -0
- pennylane_lightning_tensor-0.42.0.dist-info/top_level.txt +2 -0
- pennylane_lightning_tensor.libs/libgomp-24e2ab19.so.1.0.0 +0 -0
@@ -0,0 +1,787 @@
|
|
1
|
+
# Copyright 2024 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
|
+
Class implementation for tensornet manipulation.
|
16
|
+
"""
|
17
|
+
|
18
|
+
# pylint: disable=import-error, no-name-in-module, ungrouped-imports
|
19
|
+
try:
|
20
|
+
from pennylane_lightning.lightning_tensor_ops import (
|
21
|
+
exactTensorNetC64,
|
22
|
+
exactTensorNetC128,
|
23
|
+
mpsTensorNetC64,
|
24
|
+
mpsTensorNetC128,
|
25
|
+
)
|
26
|
+
except ImportError:
|
27
|
+
pass
|
28
|
+
|
29
|
+
import numpy as np
|
30
|
+
import pennylane as qml
|
31
|
+
from pennylane import BasisState, MPSPrep, StatePrep
|
32
|
+
from pennylane.exceptions import DeviceError
|
33
|
+
from pennylane.ops.op_math import Adjoint
|
34
|
+
from pennylane.tape import QuantumScript
|
35
|
+
from pennylane.wires import Wires
|
36
|
+
|
37
|
+
|
38
|
+
def svd_split(
|
39
|
+
Mat: np.ndarray, site_shape: list[int], max_bond_dim: int, is_right: bool = True
|
40
|
+
) -> tuple[np.ndarray, np.ndarray]:
|
41
|
+
"""Perform SVD decomposition of a matrix using numpy linalg.
|
42
|
+
|
43
|
+
This function allows selecting which orthonormal singular vector to return.
|
44
|
+
If `is_right` is True, it returns Vd; otherwise, it returns U.
|
45
|
+
Note that this function is intended to be moved to the C++ layer.
|
46
|
+
|
47
|
+
Args:
|
48
|
+
Mat (np.ndarray): Input matrix.
|
49
|
+
site_shape (list[int]): Shape of the site tensor.
|
50
|
+
max_bond_dim (int): Maximum bond dimension.
|
51
|
+
is_right (bool): Direction of the SVD decomposition. Default is True.
|
52
|
+
|
53
|
+
Returns:
|
54
|
+
tuple[np.ndarray, np.ndarray]: U and Vd matrices.
|
55
|
+
"""
|
56
|
+
# TODO: Check if cutensornet allows us to remove all zero (or < tol) singular values and the respective rows and columns of U and Vd
|
57
|
+
|
58
|
+
U, S, Vd = np.linalg.svd(Mat, full_matrices=False)
|
59
|
+
|
60
|
+
# Removing noise from singular values
|
61
|
+
# Reference: https://scicomp.stackexchange.com/questions/350/what-should-be-the-criteria-for-accepting-rejecting-singular-values/355#355
|
62
|
+
epsilon = np.finfo(Mat.dtype).eps * S[0] if S[0] > 1.0 else np.finfo(Mat.dtype).eps
|
63
|
+
S[S < epsilon] = 0.0
|
64
|
+
|
65
|
+
bonds = len(S)
|
66
|
+
chi = min(bonds, max_bond_dim)
|
67
|
+
|
68
|
+
# Crop the singular values and the corresponding singular vectors
|
69
|
+
S = S[:chi]
|
70
|
+
U = U[:, :chi]
|
71
|
+
Vd = Vd[:chi]
|
72
|
+
|
73
|
+
if is_right: # Vd as orthonormal singular vectors
|
74
|
+
U = U * S # Append singular values to U
|
75
|
+
else: # U as orthonormal singular vectors
|
76
|
+
Vd = (S * Vd.T).T # Append singular values to Vd, equivalent operation to np.diag(S) @ Vd
|
77
|
+
|
78
|
+
# keep only chi bonds and reshape to fit the bond dimension and site shape
|
79
|
+
Vd = Vd.reshape([chi] + site_shape + [-1])
|
80
|
+
U = U.reshape([-1] + site_shape + [chi])
|
81
|
+
|
82
|
+
if is_right:
|
83
|
+
return U, Vd
|
84
|
+
else:
|
85
|
+
return Vd, U
|
86
|
+
|
87
|
+
|
88
|
+
def decompose_dense(
|
89
|
+
psi: np.ndarray,
|
90
|
+
n_wires: int,
|
91
|
+
site_shape: list[int],
|
92
|
+
max_bond_dim: int,
|
93
|
+
canonical_right: bool = True,
|
94
|
+
) -> list[np.ndarray]:
|
95
|
+
"""Decompose a dense state vector/gate matrix into MPS/MPO sites.
|
96
|
+
|
97
|
+
Args:
|
98
|
+
psi (np.ndarray): input state vector or gate matrix
|
99
|
+
n_wires (int): number of wires
|
100
|
+
site_shape (list[int]): shape of the site tensor
|
101
|
+
max_bond_dim (int): maximum bond dimension
|
102
|
+
canonical_right (bool): right-canonical form if True; left-canonical form if False. Default is True.
|
103
|
+
|
104
|
+
Returns:
|
105
|
+
list[np.ndarray]: MPS/MPO sites
|
106
|
+
"""
|
107
|
+
|
108
|
+
Ms = []
|
109
|
+
site_len = np.prod(site_shape)
|
110
|
+
|
111
|
+
psi = np.reshape(psi, (-1, site_len) if canonical_right else (site_len, -1))
|
112
|
+
psi, A = svd_split(psi, site_shape, max_bond_dim, is_right=canonical_right)
|
113
|
+
|
114
|
+
Ms.append(A)
|
115
|
+
bondL = psi.shape[-1 if canonical_right else 0]
|
116
|
+
|
117
|
+
for _ in range(1, n_wires - 1):
|
118
|
+
psi = np.reshape(psi, (-1, site_len * bondL) if canonical_right else (site_len * bondL, -1))
|
119
|
+
psi, A = svd_split(psi, site_shape, max_bond_dim, is_right=canonical_right)
|
120
|
+
Ms.append(A)
|
121
|
+
|
122
|
+
bondL = psi.shape[-1 if canonical_right else 0]
|
123
|
+
|
124
|
+
Ms.append(psi)
|
125
|
+
|
126
|
+
if canonical_right:
|
127
|
+
Ms.reverse()
|
128
|
+
|
129
|
+
# Removing the virtual bond dimension of 1 from the first and last sites
|
130
|
+
Ms[0] = np.reshape(Ms[0], Ms[0].shape[1:])
|
131
|
+
Ms[-1] = np.reshape(Ms[-1], Ms[-1].shape[:-1])
|
132
|
+
|
133
|
+
return Ms
|
134
|
+
|
135
|
+
|
136
|
+
def gate_matrix_decompose(
|
137
|
+
gate_ops_matrix: np.ndarray,
|
138
|
+
wires: list[int],
|
139
|
+
max_mpo_bond_dim: int,
|
140
|
+
c_dtype: np.complex64 | np.complex128,
|
141
|
+
) -> tuple[list[np.ndarray], list[int]]:
|
142
|
+
"""Permute and decompose a gate matrix into MPO sites.
|
143
|
+
|
144
|
+
This method return the MPO sites in the Fortran order of the ``cutensornet`` backend. Note that MSB in the Pennylane convention is the LSB in the ``cutensornet`` convention.
|
145
|
+
|
146
|
+
Args:
|
147
|
+
gate_ops_matrix (np.ndarray): input gate matrix
|
148
|
+
wires (list): list of wires
|
149
|
+
max_mpo_bond_dim (int): maximum bond dimension
|
150
|
+
c_dtype (np.complex64 | np.complex128): complex dtype
|
151
|
+
|
152
|
+
Returns:
|
153
|
+
[list[np.ndarray], list[int]]: MPO sites and sorted wires
|
154
|
+
"""
|
155
|
+
sorted_indexed_wires = sorted(enumerate(wires), key=lambda x: x[1])
|
156
|
+
|
157
|
+
original_axes, sorted_wires = zip(*sorted_indexed_wires)
|
158
|
+
|
159
|
+
tensor_shape = [2] * len(wires) * 2
|
160
|
+
|
161
|
+
matrix = gate_ops_matrix.astype(c_dtype)
|
162
|
+
|
163
|
+
# Convert the gate matrix to the correct shape and complex dtype
|
164
|
+
gate_tensor = matrix.reshape(tensor_shape)
|
165
|
+
|
166
|
+
# Create the correct order of indices for the gate tensor to be decomposed
|
167
|
+
indices_order = []
|
168
|
+
for i in range(len(wires)):
|
169
|
+
indices_order.extend([original_axes[i], original_axes[i] + len(wires)])
|
170
|
+
# Reverse the indices order to match the target wire order of cutensornet backend
|
171
|
+
indices_order.reverse()
|
172
|
+
|
173
|
+
# Permutation of the gate tensor
|
174
|
+
gate_tensor = np.transpose(gate_tensor, axes=indices_order)
|
175
|
+
|
176
|
+
mpo_site_shape = [2] * 2
|
177
|
+
|
178
|
+
# The indices order of MPOs: 1. left-most site: [ket, bra, bondR]; 2. right-most sites: [bondL, ket, bra]; 3. sites in-between: [bondL, ket, bra, bondR].
|
179
|
+
MPOs = decompose_dense(gate_tensor, len(wires), mpo_site_shape, max_mpo_bond_dim)
|
180
|
+
|
181
|
+
# Convert the MPOs to the correct order for the cutensornet backend
|
182
|
+
mpos = []
|
183
|
+
for index, MPO in enumerate(MPOs):
|
184
|
+
if index == 0:
|
185
|
+
# [ket, bra, bond](0, 1, 2) -> [ket, bond, bra](0, 2, 1) -> Fortran order or reverse indices(1, 2, 0) to match the order requirement of cutensornet backend.
|
186
|
+
mpos.append(np.transpose(MPO, axes=(1, 2, 0)))
|
187
|
+
elif index == len(MPOs) - 1:
|
188
|
+
# [bond, ket, bra](0, 1, 2) -> Fortran order or reverse indices(2, 1, 0) to match the order requirement of cutensornet backend.
|
189
|
+
mpos.append(np.transpose(MPO, axes=(2, 1, 0)))
|
190
|
+
else:
|
191
|
+
# [bondL, ket, bra, bondR](0, 1, 2, 3) -> [bondL, ket, bondR, bra](0, 1, 3, 2) -> Fortran order or reverse indices(2, 3, 1, 0) to match the requirement of cutensornet backend.
|
192
|
+
mpos.append(np.transpose(MPO, axes=(2, 3, 1, 0)))
|
193
|
+
|
194
|
+
return mpos, sorted_wires
|
195
|
+
|
196
|
+
|
197
|
+
def check_canonical_form(mps: list[np.ndarray], is_right: bool = True) -> bool:
|
198
|
+
"""Check if the MPS is in the canonical form.
|
199
|
+
|
200
|
+
The computation of expectation values and matrix elements is simpler if the MPS is built from orthonormal tensors, i.e. in canonical form (either in the left or right direction).
|
201
|
+
|
202
|
+
Args:
|
203
|
+
mps (list[np.ndarray]): MPS state
|
204
|
+
is_right (bool): True if the MPS is in the right canonical form; False if the MPS is in the left canonical form. Default is True.
|
205
|
+
|
206
|
+
Returns:
|
207
|
+
bool: True if the MPS is in the canonical form specified by the direction
|
208
|
+
"""
|
209
|
+
|
210
|
+
for sites in mps:
|
211
|
+
|
212
|
+
sites_conj_t = sites.conj().T
|
213
|
+
|
214
|
+
if not is_right:
|
215
|
+
sites, sites_conj_t = sites_conj_t, sites
|
216
|
+
|
217
|
+
C = np.tensordot(sites, sites_conj_t, axes=[[-1, -2], [0, 1]])
|
218
|
+
|
219
|
+
# Compare C with the identity matrix
|
220
|
+
if not np.allclose(C, np.eye(C.shape[0], dtype=C.dtype), atol=np.finfo(C.dtype).eps * 1e4):
|
221
|
+
return False
|
222
|
+
|
223
|
+
# Return True if all the values of canon_values are True
|
224
|
+
return True
|
225
|
+
|
226
|
+
|
227
|
+
def expand_mps_first_site(state_MPS: list[np.ndarray], max_bond_dim: int = 128) -> list[np.ndarray]:
|
228
|
+
"""Expand the MPS to match the size of the target wires.
|
229
|
+
|
230
|
+
This function modifies the original MPS state by adding a single wire at the beginning of the MPS state. The algorithm to expand the input MPS state to fit into the device MPS state is based on the following steps:
|
231
|
+
|
232
|
+
- Set the device MPS state as $B$ and the input MPS state as $A$.
|
233
|
+
- Padding with zeros the tensor $B_i$ to fit the tensor shape $A_{i+1}$ up to $i = N/2$ where $N$ is the total number of tensors in $B$.
|
234
|
+
- Add the identity matrix with shape `(1,2,2)` at the beginning of $B$.
|
235
|
+
- Restore the $B$ MPS into the initial canonical form to spread the new site information across the entire MPS $A$.
|
236
|
+
|
237
|
+
The details about how to create a MPS state can be found in the PennyLane tutorial: [Introducing matrix product states for quantum practitioners](https://pennylane.ai/qml/demos/tutorial_mps)
|
238
|
+
|
239
|
+
Args:
|
240
|
+
state_MPS (list[np.ndarray]): The MPS state to be expanded.
|
241
|
+
max_bond_dim (int): The maximum bond dimension.
|
242
|
+
|
243
|
+
Returns:
|
244
|
+
list[np.ndarray]: The expanded MPS state.
|
245
|
+
"""
|
246
|
+
|
247
|
+
expanded_MPS = state_MPS
|
248
|
+
|
249
|
+
# Number of sites that should be changed from the first site
|
250
|
+
n_sites = len(state_MPS)
|
251
|
+
n_sites_change = (n_sites + 1) // 2
|
252
|
+
odd_n_sites = n_sites % 2 == 1
|
253
|
+
|
254
|
+
for i in range(n_sites_change - 1):
|
255
|
+
# Create the new site for expanded_MPS
|
256
|
+
new_site = expanded_MPS[i]
|
257
|
+
|
258
|
+
# Horizontal padding with zeros
|
259
|
+
horizontal_pad = 2**i if 2**i < max_bond_dim else 0
|
260
|
+
new_site = np.pad(new_site, ((0, horizontal_pad), (0, 0), (0, 0)), mode="constant")
|
261
|
+
|
262
|
+
# Vertical padding with zeros
|
263
|
+
target_l, _, target_r = state_MPS[i + 1].shape
|
264
|
+
|
265
|
+
if odd_n_sites: # odd sites need to double the bond dimension
|
266
|
+
target_r = target_l * 2 if target_l * 2 < max_bond_dim else max_bond_dim
|
267
|
+
|
268
|
+
site_r = new_site.shape[-1]
|
269
|
+
|
270
|
+
new_site = np.pad(
|
271
|
+
new_site.reshape(target_l, 2, site_r),
|
272
|
+
((0, 0), (0, 0), (0, target_r - site_r)),
|
273
|
+
mode="constant",
|
274
|
+
)
|
275
|
+
|
276
|
+
# Assign the new site
|
277
|
+
expanded_MPS[i] = new_site
|
278
|
+
|
279
|
+
# Padding mid site
|
280
|
+
new_site = expanded_MPS[n_sites_change - 1]
|
281
|
+
|
282
|
+
# Horizontal padding
|
283
|
+
horizontal_pad = 2 ** (n_sites_change - 1) if 2 ** (n_sites_change - 1) < max_bond_dim else 0
|
284
|
+
new_site = np.pad(new_site, ((0, horizontal_pad), (0, 0), (0, 0)), mode="constant")
|
285
|
+
|
286
|
+
# Vertical padding
|
287
|
+
target_l, _, target_r = state_MPS[n_sites_change].shape
|
288
|
+
|
289
|
+
# if the mid + 1 site is odd, the bond dimension needs to be doubled
|
290
|
+
if odd_n_sites:
|
291
|
+
target_l *= 2
|
292
|
+
target_r *= 2
|
293
|
+
else: # even
|
294
|
+
target_r = target_l
|
295
|
+
|
296
|
+
site_r = new_site.shape[-1]
|
297
|
+
|
298
|
+
new_site = new_site.reshape(target_l, 2, target_r)
|
299
|
+
new_site = np.pad(new_site, ((0, 0), (0, 0), (0, target_r - site_r)), mode="constant")
|
300
|
+
|
301
|
+
# Assign the last new site
|
302
|
+
expanded_MPS[n_sites_change - 1] = new_site
|
303
|
+
|
304
|
+
# Add the initial site
|
305
|
+
expanded_MPS = [np.eye(2, dtype=state_MPS[0].dtype).reshape(1, 2, 2)] + expanded_MPS
|
306
|
+
|
307
|
+
return expanded_MPS
|
308
|
+
|
309
|
+
|
310
|
+
def restore_left_canonical_form(mps: list[np.ndarray], site_shape: list[int]) -> list[np.ndarray]:
|
311
|
+
"""Restore the left canonical form of the MPS.
|
312
|
+
|
313
|
+
The left canonical form is defined as the form where the tensors are orthonormal in the left direction.
|
314
|
+
|
315
|
+
Args:
|
316
|
+
mps (list[np.ndarray]): MPS state
|
317
|
+
site_shape (list[int]): shape of the site tensor
|
318
|
+
|
319
|
+
Returns:
|
320
|
+
list[np.ndarray]: MPS state in the left canonical form
|
321
|
+
"""
|
322
|
+
|
323
|
+
new_mps = []
|
324
|
+
Vd = np.eye(1, dtype=mps[0].dtype)
|
325
|
+
|
326
|
+
for site in mps:
|
327
|
+
site_p = np.tensordot(Vd, site, axes=[[-1], [0]])
|
328
|
+
site_p = site_p.reshape(-1, site.shape[-1])
|
329
|
+
|
330
|
+
U, S, Vd = np.linalg.svd(site_p, full_matrices=False)
|
331
|
+
|
332
|
+
# Removing noise from singular values
|
333
|
+
epsilon = np.finfo(site.dtype).eps * S[0] if S[0] > 1.0 else np.finfo(site.dtype).eps
|
334
|
+
S[S < epsilon] = 0.0
|
335
|
+
|
336
|
+
bonds = len(S)
|
337
|
+
|
338
|
+
Vd = S * Vd
|
339
|
+
U = U.reshape([-1] + site_shape + [bonds])
|
340
|
+
|
341
|
+
new_mps.append(U)
|
342
|
+
|
343
|
+
return new_mps
|
344
|
+
|
345
|
+
|
346
|
+
def restore_right_canonical_form(mps: list[np.ndarray], site_shape: list[int]) -> list[np.ndarray]:
|
347
|
+
"""Restore the right canonical form of the MPS.
|
348
|
+
|
349
|
+
The right canonical form is defined as the form where the tensors are orthonormal in the right direction.
|
350
|
+
|
351
|
+
Args:
|
352
|
+
mps (list[np.ndarray]): MPS state
|
353
|
+
site_shape (list[int]): shape of the site tensor
|
354
|
+
|
355
|
+
Returns:
|
356
|
+
list[np.ndarray]: MPS state in the right canonical form
|
357
|
+
"""
|
358
|
+
|
359
|
+
new_mps = []
|
360
|
+
U = np.eye(1, dtype=mps[0].dtype)
|
361
|
+
|
362
|
+
for site in reversed(mps):
|
363
|
+
site_p = np.tensordot(site, U, axes=[[-1], [0]])
|
364
|
+
site_p = site_p.reshape(site.shape[0], -1)
|
365
|
+
|
366
|
+
U, S, Vd = np.linalg.svd(site_p, full_matrices=False)
|
367
|
+
|
368
|
+
# Removing noise from singular values
|
369
|
+
epsilon = np.finfo(site.dtype).eps * S[0] if S[0] > 1.0 else np.finfo(site.dtype).eps
|
370
|
+
S[S < epsilon] = 0.0
|
371
|
+
|
372
|
+
bonds = len(S)
|
373
|
+
|
374
|
+
U = U * S
|
375
|
+
Vd = Vd.reshape([bonds] + site_shape + [-1])
|
376
|
+
|
377
|
+
new_mps.append(Vd)
|
378
|
+
|
379
|
+
new_mps.reverse()
|
380
|
+
|
381
|
+
return new_mps
|
382
|
+
|
383
|
+
|
384
|
+
# pylint: disable=too-many-instance-attributes
|
385
|
+
class LightningTensorNet:
|
386
|
+
"""Lightning tensornet class.
|
387
|
+
|
388
|
+
Interfaces with C++ python binding methods for tensornet manipulation.
|
389
|
+
|
390
|
+
Args:
|
391
|
+
num_wires(int): the number of wires to initialize the device with
|
392
|
+
c_dtype: Datatypes for tensor network representation. Must be one of
|
393
|
+
``np.complex64`` or ``np.complex128``. Default is ``np.complex128``
|
394
|
+
method(string): tensor network method. Supported methods are "mps" (Matrix Product State) and
|
395
|
+
"tn" (Exact Tensor Network). Options: ["mps", "tn"].
|
396
|
+
device_name(string): tensor network device name. Options: ["lightning.tensor"]
|
397
|
+
Keyword Args:
|
398
|
+
max_bond_dim (int): The maximum bond dimension to be used in the MPS simulation. Default is 128.
|
399
|
+
The accuracy of the wavefunction representation comes with a memory tradeoff which can be
|
400
|
+
tuned with `max_bond_dim`. The larger the internal bond dimension, the more entanglement can
|
401
|
+
be described but the larger the memory requirements. Note that GPUs are ill-suited (i.e. less
|
402
|
+
competitive compared with CPUs) for simulating circuits with low bond dimensions and/or circuit
|
403
|
+
layers with a single or few gates because the arithmetic intensity is lower.
|
404
|
+
cutoff (float): The threshold used to truncate the singular values of the MPS tensors. Default is 0.
|
405
|
+
cutoff_mode (str): Singular value truncation mode for MPS tensors can be done either by
|
406
|
+
considering the absolute values of the singular values (``"abs"``) or by considering
|
407
|
+
the relative values of the singular values (``"rel"``). Default is ``"abs"``.
|
408
|
+
"""
|
409
|
+
|
410
|
+
# pylint: disable=too-many-arguments, too-many-positional-arguments
|
411
|
+
def __init__(
|
412
|
+
self,
|
413
|
+
num_wires=None,
|
414
|
+
method: str = "mps",
|
415
|
+
c_dtype=np.complex128,
|
416
|
+
device_name="lightning.tensor",
|
417
|
+
**kwargs,
|
418
|
+
):
|
419
|
+
if device_name != "lightning.tensor":
|
420
|
+
raise DeviceError(f'The device name "{device_name}" is not a valid option.')
|
421
|
+
|
422
|
+
if num_wires < 2:
|
423
|
+
raise ValueError("Number of wires must be greater than 1.")
|
424
|
+
|
425
|
+
self._num_wires = num_wires
|
426
|
+
self._method = method
|
427
|
+
self._c_dtype = c_dtype
|
428
|
+
self._device_name = device_name
|
429
|
+
|
430
|
+
self._wires = Wires(range(num_wires))
|
431
|
+
|
432
|
+
if self._method == "mps":
|
433
|
+
self._max_bond_dim = kwargs.get("max_bond_dim", 128)
|
434
|
+
self._cutoff = kwargs.get("cutoff", 0)
|
435
|
+
self._cutoff_mode = kwargs.get("cutoff_mode", "abs")
|
436
|
+
self._tensornet = self._tensornet_dtype()(self._num_wires, self._max_bond_dim)
|
437
|
+
elif self._method == "tn":
|
438
|
+
self._tensornet = self._tensornet_dtype()(self._num_wires)
|
439
|
+
else:
|
440
|
+
raise DeviceError(f"The method {self._method} is not supported.")
|
441
|
+
|
442
|
+
@property
|
443
|
+
def dtype(self):
|
444
|
+
"""Returns the tensor network data type."""
|
445
|
+
return self._c_dtype
|
446
|
+
|
447
|
+
@property
|
448
|
+
def device_name(self):
|
449
|
+
"""Returns the tensor network device name."""
|
450
|
+
return self._device_name
|
451
|
+
|
452
|
+
@property
|
453
|
+
def num_wires(self):
|
454
|
+
"""Returns the number of wires addressed on this device"""
|
455
|
+
return self._num_wires
|
456
|
+
|
457
|
+
@property
|
458
|
+
def method(self):
|
459
|
+
"""Returns the method (mps or tn) for evaluating the tensor network."""
|
460
|
+
return self._method
|
461
|
+
|
462
|
+
@property
|
463
|
+
def tensornet(self):
|
464
|
+
"""Returns a handle to the tensor network."""
|
465
|
+
return self._tensornet
|
466
|
+
|
467
|
+
@property
|
468
|
+
def state(self):
|
469
|
+
"""Copy the state vector data to a numpy array."""
|
470
|
+
state = np.zeros(2**self._num_wires, dtype=self.dtype)
|
471
|
+
self._tensornet.getState(state)
|
472
|
+
return state
|
473
|
+
|
474
|
+
def _tensornet_dtype(self):
|
475
|
+
"""Binding to Lightning Managed tensor network C++ class.
|
476
|
+
|
477
|
+
Returns: the tensor network class
|
478
|
+
"""
|
479
|
+
if self.method == "tn": # Using "tn" method
|
480
|
+
return exactTensorNetC128 if self.dtype == np.complex128 else exactTensorNetC64
|
481
|
+
# Using "mps" method
|
482
|
+
return mpsTensorNetC128 if self.dtype == np.complex128 else mpsTensorNetC64
|
483
|
+
|
484
|
+
def reset_state(self):
|
485
|
+
"""Reset the device's initial quantum state"""
|
486
|
+
# init the quantum state to |00..0>
|
487
|
+
self._tensornet.reset()
|
488
|
+
|
489
|
+
def _preprocess_state_vector(self, state, device_wires):
|
490
|
+
"""Convert a specified state to a full internal state vector.
|
491
|
+
|
492
|
+
Args:
|
493
|
+
state (array[complex]): normalized input state of length ``2**len(device_wires)``
|
494
|
+
device_wires (Wires): wires that get initialized in the state
|
495
|
+
|
496
|
+
Returns:
|
497
|
+
array[complex]: normalized input state of length ``2**len(device_wires)``
|
498
|
+
"""
|
499
|
+
output_shape = [2] * self._num_wires
|
500
|
+
# special case for integral types
|
501
|
+
if state.dtype.kind == "i":
|
502
|
+
state = np.array(state, dtype=self.dtype)
|
503
|
+
|
504
|
+
if len(device_wires) == self._num_wires and Wires(sorted(device_wires)) == device_wires:
|
505
|
+
return np.reshape(state, output_shape).ravel(order="C")
|
506
|
+
|
507
|
+
local_dev_wires = device_wires.tolist().copy()
|
508
|
+
local_dev_wires = local_dev_wires[::-1]
|
509
|
+
|
510
|
+
# generate basis states on subset of qubits via broadcasting as substitute of cartesian product.
|
511
|
+
|
512
|
+
# Allocate a single row as a base to avoid a large array allocation with
|
513
|
+
# the cartesian product algorithm.
|
514
|
+
# Initialize the base with the pattern [0 1 0 1 ...].
|
515
|
+
base = np.tile([0, 1], 2 ** (len(local_dev_wires) - 1)).astype(dtype=np.int64)
|
516
|
+
# Allocate the array where it will accumulate the value of the indexes depending on
|
517
|
+
# the value of the basis.
|
518
|
+
indexes = np.zeros(2 ** (len(local_dev_wires)), dtype=np.int64)
|
519
|
+
|
520
|
+
max_dev_wire = self._num_wires - 1
|
521
|
+
|
522
|
+
# Iterate over all device wires.
|
523
|
+
for i, wire in enumerate(local_dev_wires):
|
524
|
+
|
525
|
+
# Accumulate indexes from the basis.
|
526
|
+
indexes += base * 2 ** (max_dev_wire - wire)
|
527
|
+
|
528
|
+
if i == len(local_dev_wires) - 1:
|
529
|
+
continue
|
530
|
+
|
531
|
+
two_n = 2 ** (i + 1) # Compute the value of the base.
|
532
|
+
|
533
|
+
# Update the value of the base without reallocating a new array.
|
534
|
+
# Reshape the basis to swap the internal columns.
|
535
|
+
base = base.reshape(-1, two_n * 2)
|
536
|
+
swapper_A = two_n // 2
|
537
|
+
swapper_B = swapper_A + two_n
|
538
|
+
|
539
|
+
base[:, swapper_A:swapper_B] = base[:, swapper_A:swapper_B][:, ::-1]
|
540
|
+
# Flatten the base array
|
541
|
+
base = base.reshape(-1)
|
542
|
+
|
543
|
+
# get full state vector to be factorized into MPS
|
544
|
+
full_state = np.zeros(2**self._num_wires, dtype=self.dtype)
|
545
|
+
for i, value in enumerate(state):
|
546
|
+
full_state[indexes[i]] = value
|
547
|
+
return np.reshape(full_state, output_shape).ravel(order="C")
|
548
|
+
|
549
|
+
def _apply_state_vector(self, state, device_wires: Wires):
|
550
|
+
"""Convert a specified state to MPS state.
|
551
|
+
|
552
|
+
Args:
|
553
|
+
state (array[complex]): normalized input state of length ``2**len(device_wires)``
|
554
|
+
or broadcasted state of shape ``(batch_size, 2**len(device_wires))``
|
555
|
+
device_wires (Wires): wires that get initialized in the state
|
556
|
+
"""
|
557
|
+
if self.method == "tn":
|
558
|
+
raise DeviceError("Exact Tensor Network does not support StatePrep")
|
559
|
+
|
560
|
+
if self.method == "mps":
|
561
|
+
state = self._preprocess_state_vector(state, device_wires)
|
562
|
+
mps_site_shape = [2]
|
563
|
+
M = decompose_dense(state, self._num_wires, mps_site_shape, self._max_bond_dim)
|
564
|
+
self._tensornet.updateMPSSitesData(M)
|
565
|
+
|
566
|
+
def _apply_mps_state(self, mps: tuple[np.ndarray], target_wires: Wires) -> None:
|
567
|
+
|
568
|
+
if len(target_wires) == self._num_wires and Wires(sorted(target_wires)) == target_wires:
|
569
|
+
self._tensornet.updateMPSSitesData(mps)
|
570
|
+
return
|
571
|
+
|
572
|
+
trgt_wires = target_wires.tolist()
|
573
|
+
|
574
|
+
# Sort wires in ascending order
|
575
|
+
trgt_wires.sort()
|
576
|
+
|
577
|
+
# check if 0 is present in trgt_wires and the number of wires to be appended is more than 1
|
578
|
+
if not 0 in trgt_wires and (self._num_wires - len(trgt_wires) > 1):
|
579
|
+
raise DeviceError(
|
580
|
+
"MPSPrep only support to append a single wire at the beginning of the MPS."
|
581
|
+
)
|
582
|
+
|
583
|
+
mps = list(mps)
|
584
|
+
|
585
|
+
if len(mps[0].shape) != 3:
|
586
|
+
mps[0] = mps[0].reshape(1, 2, 2)
|
587
|
+
|
588
|
+
if len(mps[-1].shape) != 3:
|
589
|
+
mps[-1] = mps[-1].reshape(2, 2, 1)
|
590
|
+
|
591
|
+
# Check the canonical form of the MPS
|
592
|
+
if check_canonical_form(mps, is_right=False):
|
593
|
+
# Expand and restore the canonical form for the current MPS to match the size of the target wires
|
594
|
+
new_mps = expand_mps_first_site(mps, self._max_bond_dim)
|
595
|
+
new_mps = restore_left_canonical_form(new_mps, [2])
|
596
|
+
|
597
|
+
elif check_canonical_form(mps, is_right=True):
|
598
|
+
# Expand and restore the canonical form for the current MPS to match the size of the target wires
|
599
|
+
new_mps = expand_mps_first_site(mps, self._max_bond_dim)
|
600
|
+
new_mps = restore_right_canonical_form(new_mps, [2])
|
601
|
+
|
602
|
+
else: # No canonical form
|
603
|
+
new_mps = expand_mps_first_site(mps, self._max_bond_dim)
|
604
|
+
|
605
|
+
# Restore dimension of first and last sites
|
606
|
+
new_mps[0] = new_mps[0].reshape(2, 2)
|
607
|
+
new_mps[-1] = new_mps[-1].reshape(2, 2)
|
608
|
+
|
609
|
+
# Update the MPS sites in the tensornet
|
610
|
+
self._tensornet.updateMPSSitesData(new_mps)
|
611
|
+
|
612
|
+
def _apply_basis_state(self, state, wires):
|
613
|
+
"""Initialize the quantum state in a specified computational basis state.
|
614
|
+
|
615
|
+
Args:
|
616
|
+
state (array[int]): computational basis state of shape ``(wires,)``
|
617
|
+
consisting of 0s and 1s.
|
618
|
+
wires (Wires): wires that the provided computational state should be
|
619
|
+
initialized on
|
620
|
+
|
621
|
+
Note: This function does not support broadcasted inputs yet.
|
622
|
+
"""
|
623
|
+
# length of basis state parameter
|
624
|
+
n_basis_state = len(state)
|
625
|
+
|
626
|
+
if not set(state.tolist()).issubset({0, 1}):
|
627
|
+
raise ValueError("BasisState parameter must consist of 0 or 1 integers.")
|
628
|
+
|
629
|
+
if n_basis_state != len(wires):
|
630
|
+
raise ValueError("BasisState parameter and wires must be of equal length.")
|
631
|
+
|
632
|
+
self._tensornet.setBasisState(state)
|
633
|
+
|
634
|
+
def _apply_MPO(self, gate_matrix, wires):
|
635
|
+
"""Apply a matrix product operator to the quantum state (MPS method only).
|
636
|
+
|
637
|
+
Args:
|
638
|
+
gate_matrix (array[complex/float]): matrix representation of the MPO
|
639
|
+
wires (Wires): wires that the MPO should be applied to
|
640
|
+
Returns:
|
641
|
+
None
|
642
|
+
"""
|
643
|
+
# TODO: Discuss if public interface for max_mpo_bond_dim argument
|
644
|
+
max_mpo_bond_dim = self._max_bond_dim
|
645
|
+
|
646
|
+
# Get sorted wires and MPO site tensor
|
647
|
+
mpos, sorted_wires = gate_matrix_decompose(
|
648
|
+
gate_matrix, wires, max_mpo_bond_dim, self._c_dtype
|
649
|
+
)
|
650
|
+
|
651
|
+
self._tensornet.applyMPOOperation(mpos, sorted_wires, max_mpo_bond_dim)
|
652
|
+
|
653
|
+
# pylint: disable=too-many-branches
|
654
|
+
def _apply_lightning_controlled(self, operation):
|
655
|
+
"""Apply an arbitrary controlled operation to the state tensor. Note that `cutensornet` only supports controlled gates with a single wire target.
|
656
|
+
|
657
|
+
Args:
|
658
|
+
operation (~pennylane.operation.Operation): controlled operation to apply
|
659
|
+
|
660
|
+
Returns:
|
661
|
+
None
|
662
|
+
"""
|
663
|
+
tensornet = self._tensornet
|
664
|
+
|
665
|
+
basename = operation.base.name
|
666
|
+
method = getattr(tensornet, f"{basename}", None)
|
667
|
+
control_wires = list(operation.control_wires)
|
668
|
+
control_values = operation.control_values
|
669
|
+
target_wires = list(operation.target_wires)
|
670
|
+
|
671
|
+
if method is not None and basename not in ("GlobalPhase", "MultiRZ"):
|
672
|
+
inv = False
|
673
|
+
param = operation.parameters
|
674
|
+
method(control_wires, control_values, target_wires, inv, param)
|
675
|
+
else: # apply gate as an n-controlled matrix
|
676
|
+
method = getattr(tensornet, "applyControlledMatrix")
|
677
|
+
method(qml.matrix(operation.base), control_wires, control_values, target_wires, False)
|
678
|
+
|
679
|
+
# pylint: disable=too-many-statements
|
680
|
+
def _apply_lightning(self, operations):
|
681
|
+
"""Apply a list of operations to the quantum state.
|
682
|
+
|
683
|
+
Args:
|
684
|
+
operations (list[~pennylane.operation.Operation]): operations to apply
|
685
|
+
|
686
|
+
Returns:
|
687
|
+
None
|
688
|
+
"""
|
689
|
+
tensornet = self._tensornet
|
690
|
+
|
691
|
+
# Skip over identity operations instead of performing
|
692
|
+
# matrix multiplication with it.
|
693
|
+
for operation in operations:
|
694
|
+
if isinstance(operation, qml.Identity):
|
695
|
+
continue
|
696
|
+
if isinstance(operation, Adjoint):
|
697
|
+
name = operation.base.name
|
698
|
+
invert_param = True
|
699
|
+
else:
|
700
|
+
name = operation.name
|
701
|
+
invert_param = False
|
702
|
+
method = getattr(tensornet, name, None)
|
703
|
+
wires = list(operation.wires)
|
704
|
+
|
705
|
+
if (
|
706
|
+
isinstance(operation, qml.ops.Controlled)
|
707
|
+
and len(list(operation.target_wires)) == 1
|
708
|
+
and len(set(operation.control_values)) == 1
|
709
|
+
):
|
710
|
+
self._apply_lightning_controlled(operation)
|
711
|
+
elif isinstance(operation, qml.GlobalPhase):
|
712
|
+
matrix = np.eye(2) * operation.matrix().flatten()[0]
|
713
|
+
method = getattr(tensornet, "applyMatrix")
|
714
|
+
# GlobalPhase is always applied to the first wire in the tensor network
|
715
|
+
method(matrix, [0], False)
|
716
|
+
elif len(wires) <= 2:
|
717
|
+
if method is not None:
|
718
|
+
param = operation.parameters
|
719
|
+
method(wires, invert_param, param)
|
720
|
+
else:
|
721
|
+
# Inverse can be set to False since qml.matrix(operation) is already in
|
722
|
+
# inverted form
|
723
|
+
method = getattr(tensornet, "applyMatrix")
|
724
|
+
try:
|
725
|
+
method(qml.matrix(operation), wires, False)
|
726
|
+
except AttributeError: # pragma: no cover
|
727
|
+
# To support older versions of PL
|
728
|
+
method(operation.matrix(), wires, False)
|
729
|
+
else:
|
730
|
+
try:
|
731
|
+
gate_ops_matrix = qml.matrix(operation)
|
732
|
+
except AttributeError: # pragma: no cover
|
733
|
+
# To support older versions of PL
|
734
|
+
gate_ops_matrix = operation.matrix()
|
735
|
+
|
736
|
+
if self.method == "mps":
|
737
|
+
self._apply_MPO(gate_ops_matrix, wires)
|
738
|
+
if self.method == "tn":
|
739
|
+
method = getattr(tensornet, "applyMatrix")
|
740
|
+
method(gate_ops_matrix, wires, False)
|
741
|
+
|
742
|
+
def apply_operations(self, operations):
|
743
|
+
"""Append operations to the tensor network graph."""
|
744
|
+
# State preparation is currently done in Python
|
745
|
+
if operations: # make sure operations[0] exists
|
746
|
+
if isinstance(operations[0], StatePrep):
|
747
|
+
if self.method == "mps":
|
748
|
+
self._apply_state_vector(
|
749
|
+
operations[0].parameters[0].copy(), operations[0].wires
|
750
|
+
)
|
751
|
+
operations = operations[1:]
|
752
|
+
if self.method == "tn":
|
753
|
+
raise DeviceError("Exact Tensor Network does not support StatePrep")
|
754
|
+
elif isinstance(operations[0], BasisState):
|
755
|
+
self._apply_basis_state(operations[0].parameters[0], operations[0].wires)
|
756
|
+
operations = operations[1:]
|
757
|
+
elif isinstance(operations[0], MPSPrep):
|
758
|
+
if self.method == "mps":
|
759
|
+
self._apply_mps_state(operations[0].mps, operations[0].wires)
|
760
|
+
|
761
|
+
operations = operations[1:]
|
762
|
+
|
763
|
+
if self.method == "tn":
|
764
|
+
raise DeviceError("Exact Tensor Network does not support MPSPrep")
|
765
|
+
|
766
|
+
self._apply_lightning(operations)
|
767
|
+
|
768
|
+
def set_tensor_network(self, circuit: QuantumScript):
|
769
|
+
"""
|
770
|
+
Set the tensor network that results from executing the given quantum script.
|
771
|
+
|
772
|
+
This is an internal function that will be called by the successor to ``lightning.tensor``.
|
773
|
+
|
774
|
+
Args:
|
775
|
+
circuit (QuantumScript): The single circuit to simulate
|
776
|
+
"""
|
777
|
+
self.apply_operations(circuit.operations)
|
778
|
+
self.appendFinalState()
|
779
|
+
|
780
|
+
return self
|
781
|
+
|
782
|
+
def appendFinalState(self):
|
783
|
+
"""
|
784
|
+
Append the final state to the tensor network. This function should be called once when apply_operations is called. It only applies to the MPS method and is an empty call for the Exact Tensor Network method.
|
785
|
+
"""
|
786
|
+
if self.method == "mps":
|
787
|
+
self._tensornet.appendMPSFinalState(self._cutoff, self._cutoff_mode)
|