-
Notifications
You must be signed in to change notification settings - Fork 42
/
Copy pathtest_adjoint_jacobian.py
1484 lines (1185 loc) · 51.5 KB
/
test_adjoint_jacobian.py
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
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright 2018-2023 Xanadu Quantum Technologies Inc.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
Unit tests for the :mod:`pennylane_lightning_gpu.LightningGPU` device (MPI).
"""
# pylint: disable=protected-access,cell-var-from-loop,c-extension-no-member
import itertools
import math
from mpi4py import MPI
import pytest
from conftest import device_name, LightningDevice as ld
from scipy.stats import unitary_group
import pennylane as qml
from pennylane import numpy as np
from pennylane import QNode, qnode
I, X, Y, Z = (
np.eye(2),
qml.PauliX.compute_matrix(),
qml.PauliY.compute_matrix(),
qml.PauliZ.compute_matrix(),
)
# Tuple passed to distributed device ctor
# np.complex for data type and True or False
# for enabling batched_obs.
fixture_params = itertools.product(
[np.complex64, np.complex128],
[True, False],
)
def Rx(theta):
r"""One-qubit rotation about the x axis.
Args:
theta (float): rotation angle
Returns:
array: unitary 2x2 rotation matrix :math:`e^{-i \sigma_x \theta/2}`
"""
return math.cos(theta / 2) * I + 1j * math.sin(-theta / 2) * X
def Ry(theta):
r"""One-qubit rotation about the y axis.
Args:
theta (float): rotation angle
Returns:
array: unitary 2x2 rotation matrix :math:`e^{-i \sigma_y \theta/2}`
"""
return math.cos(theta / 2) * I + 1j * math.sin(-theta / 2) * Y
def Rz(theta):
r"""One-qubit rotation about the z axis.
Args:
theta (float): rotation angle
Returns:
array: unitary 2x2 rotation matrix :math:`e^{-i \sigma_z \theta/2}`
"""
return math.cos(theta / 2) * I + 1j * math.sin(-theta / 2) * Z
class TestAdjointJacobian: # pylint: disable=too-many-public-methods
"""Tests for the adjoint_jacobian method"""
@pytest.fixture(params=fixture_params)
def dev(self, request):
"""Returns a PennyLane device."""
return qml.device(
device_name,
wires=8,
mpi=True,
c_dtype=request.param[0],
batch_obs=request.param[1],
)
def test_not_expval(self, dev):
"""Test if a QuantumFunctionError is raised for a tape with measurements that are not
expectation values"""
with qml.tape.QuantumTape() as tape:
qml.RX(0.1, wires=0)
qml.var(qml.PauliZ(0))
with pytest.raises(
qml.QuantumFunctionError, match="Adjoint differentiation method does not"
):
dev.adjoint_jacobian(tape)
with qml.tape.QuantumTape() as tape:
qml.RX(0.1, wires=0)
qml.state()
if device_name == "lightning.gpu" and ld._CPP_BINARY_AVAILABLE:
message = "Adjoint differentiation does not support State measurements."
elif ld._CPP_BINARY_AVAILABLE:
message = "This method does not support statevector return type."
else:
message = "Adjoint differentiation method does not support measurement StateMP"
with pytest.raises(
qml.QuantumFunctionError,
match=message,
):
dev.adjoint_jacobian(tape)
def test_finite_shots_warns(self):
"""Tests warning raised when finite shots specified"""
dev = qml.device(device_name, wires=8, mpi=True, shots=1)
with qml.tape.QuantumTape() as tape:
qml.expval(qml.PauliZ(0))
with pytest.warns(
UserWarning,
match="Requested adjoint differentiation to be computed with finite shots.",
):
dev.adjoint_jacobian(tape)
def test_empty_measurements(self, dev):
"""Tests if an empty array is returned when the measurements of the tape is empty."""
with qml.tape.QuantumTape() as tape:
qml.RX(0.4, wires=[0])
jac = dev.adjoint_jacobian(tape)
assert len(jac) == 0
@pytest.mark.skipif(not ld._CPP_BINARY_AVAILABLE, reason="Lightning binary required")
def test_unsupported_op(self, dev):
"""Test if a QuantumFunctionError is raised for an unsupported operation, i.e.,
multi-parameter operations that are not qml.Rot"""
with qml.tape.QuantumTape() as tape:
qml.CRot(0.1, 0.2, 0.3, wires=[0, 1])
qml.expval(qml.PauliZ(0))
with pytest.raises(
qml.QuantumFunctionError,
match="The CRot operation is not supported using the",
):
dev.adjoint_jacobian(tape)
@pytest.mark.skipif(not ld._CPP_BINARY_AVAILABLE, reason="Lightning binary required")
def test_proj_unsupported(self, dev):
"""Test if a QuantumFunctionError is raised for a Projector observable"""
with qml.tape.QuantumTape() as tape:
qml.CRX(0.1, wires=[0, 1])
qml.expval(qml.Projector([0, 1], wires=[0, 1]))
with pytest.raises(
qml.QuantumFunctionError,
match="differentiation method does not support the Projector",
):
dev.adjoint_jacobian(tape)
with qml.tape.QuantumTape() as tape:
qml.CRX(0.1, wires=[0, 1])
qml.expval(qml.Projector([0], wires=[0]) @ qml.PauliZ(0))
with pytest.raises(
qml.QuantumFunctionError,
match="differentiation method does not support the Projector",
):
dev.adjoint_jacobian(tape)
@pytest.mark.parametrize("theta", np.linspace(-2 * np.pi, 2 * np.pi, 7))
@pytest.mark.parametrize("G", [qml.RX, qml.RY, qml.RZ])
@pytest.mark.parametrize("stateprep", [qml.QubitStateVector, qml.StatePrep])
def test_pauli_rotation_gradient(self, stateprep, G, theta, dev):
"""Tests that the automatic gradients of Pauli rotations are correct."""
random_state = np.array(
[0.43593284 - 0.02945156j, 0.40812291 + 0.80158023j], requires_grad=False
)
tape = qml.tape.QuantumScript(
[stateprep(random_state, 0), G(theta, 0)], [qml.expval(qml.PauliZ(0))]
)
tape.trainable_params = {1}
calculated_val = dev.adjoint_jacobian(tape)
tol = 1e-3 if dev.R_DTYPE == np.float32 else 1e-7
# compare to finite differences
tapes, fn = qml.gradients.param_shift(tape)
numeric_val = fn(qml.execute(tapes, dev, None))
assert np.allclose(calculated_val, numeric_val, atol=tol, rtol=0)
@pytest.mark.parametrize("theta", np.linspace(-2 * np.pi, 2 * np.pi, 7))
@pytest.mark.parametrize("stateprep", [qml.QubitStateVector, qml.StatePrep])
def test_Rot_gradient(self, stateprep, theta, dev):
"""Tests that the device gradient of an arbitrary Euler-angle-parameterized gate is
correct."""
params = np.array([theta, theta**3, np.sqrt(2) * theta])
with qml.tape.QuantumTape() as tape:
stateprep(np.array([1.0, -1.0], requires_grad=False) / np.sqrt(2), wires=0)
qml.Rot(*params, wires=[0])
qml.expval(qml.PauliZ(0))
tape.trainable_params = {1, 2, 3}
calculated_val = dev.adjoint_jacobian(tape)
tol = 1e-3 if dev.R_DTYPE == np.float32 else 1e-7
# compare to finite differences
tapes, fn = qml.gradients.param_shift(tape)
numeric_val = fn(qml.execute(tapes, dev, None))
assert np.allclose(calculated_val, numeric_val, atol=tol, rtol=0)
@pytest.mark.parametrize("par", [1, -2, 1.623, -0.051, 0]) # integers, floats, zero
def test_ry_gradient(self, par, tol, dev):
"""Test that the gradient of the RY gate matches the exact analytic formula."""
with qml.tape.QuantumTape() as tape:
qml.RY(par, wires=[0])
qml.expval(qml.PauliX(0))
tape.trainable_params = {0}
# gradients
exact = np.cos(par)
grad_A = dev.adjoint_jacobian(tape)
# different methods must agree
assert np.allclose(grad_A, exact, atol=tol, rtol=0)
def test_rx_gradient(self, tol, dev):
"""Test that the gradient of the RX gate matches the known formula."""
a = 0.7418
with qml.tape.QuantumTape() as tape:
qml.RX(a, wires=0)
qml.expval(qml.PauliZ(0))
# circuit jacobians
dev_jacobian = dev.adjoint_jacobian(tape)
expected_jacobian = -np.sin(a)
assert np.allclose(dev_jacobian, expected_jacobian, atol=tol, rtol=0)
def test_multiple_rx_gradient_pauliz(self, tol, dev):
"""Tests that the gradient of multiple RX gates in a circuit yields the correct result."""
params = np.array([np.pi, np.pi / 2, np.pi / 3])
with qml.tape.QuantumTape() as tape:
qml.RX(params[0], wires=0)
qml.RX(params[1], wires=1)
qml.RX(params[2], wires=2)
for idx in range(3):
qml.expval(qml.PauliZ(idx))
# circuit jacobians
dev_jacobian = dev.adjoint_jacobian(tape)
expected_jacobian = -np.diag(np.sin(params))
assert np.allclose(dev_jacobian, expected_jacobian, atol=tol, rtol=0)
def test_multiple_rx_gradient_hermitian(self, tol, dev):
"""Tests that the gradient of multiple RX gates in a circuit yields the correct result
with Hermitian observable
"""
params = np.array([np.pi, np.pi / 2, np.pi / 3])
with qml.tape.QuantumTape() as tape:
qml.RX(params[0], wires=0)
qml.RX(params[1], wires=1)
qml.RX(params[2], wires=2)
for idx in range(3):
qml.expval(qml.Hermitian([[1, 0], [0, -1]], wires=[idx]))
tape.trainable_params = {0, 1, 2}
# circuit jacobians
dev_jacobian = dev.adjoint_jacobian(tape)
expected_jacobian = -np.diag(np.sin(params))
assert np.allclose(dev_jacobian, expected_jacobian, atol=tol, rtol=0)
qubit_ops = [getattr(qml, name) for name in qml.ops._qubit__ops__] # pylint: disable=no-member
ops = {qml.RX, qml.RY, qml.RZ, qml.PhaseShift, qml.CRX, qml.CRY, qml.CRZ, qml.Rot}
def test_multiple_rx_gradient_expval_hermitian(self, tol, dev):
"""Tests that the gradient of multiple RX gates in a circuit yields the correct result
with Hermitian observable
"""
params = np.array([np.pi / 3, np.pi / 4, np.pi / 5])
with qml.tape.QuantumTape() as tape:
qml.RX(params[0], wires=0)
qml.RX(params[1], wires=1)
qml.RX(params[2], wires=2)
qml.expval(
qml.Hermitian(
[[1, 0, 0, 0], [0, -1, 0, 0], [0, 0, -1, 0], [0, 0, 0, 1]],
wires=[0, 2],
)
)
tape.trainable_params = {0, 1, 2}
dev_jacobian = dev.adjoint_jacobian(tape)
expected_jacobian = np.array(
[
-np.sin(params[0]) * np.cos(params[2]),
0,
-np.cos(params[0]) * np.sin(params[2]),
]
)
assert np.allclose(dev_jacobian, expected_jacobian, atol=tol, rtol=0)
qubit_ops = [getattr(qml, name) for name in qml.ops._qubit__ops__] # pylint: disable=no-member
ops = {qml.RX, qml.RY, qml.RZ, qml.PhaseShift, qml.CRX, qml.CRY, qml.CRZ, qml.Rot}
@pytest.mark.skipif(not ld._CPP_BINARY_AVAILABLE, reason="Lightning binary required")
def test_multiple_rx_gradient_expval_hamiltonian(self, tol, dev):
"""Tests that the gradient of multiple RX gates in a circuit yields the correct result
with Hermitian observable
"""
params = np.array([np.pi / 3, np.pi / 4, np.pi / 5])
ham = qml.Hamiltonian(
[1.0, 0.3, 0.3, 0.4],
[
qml.PauliX(0) @ qml.PauliX(1),
qml.PauliZ(0),
qml.PauliZ(1),
qml.Hermitian(
[[1, 0, 0, 0], [0, -1, 0, 0], [0, 0, -1, 0], [0, 0, 0, 1]],
wires=[0, 2],
),
],
)
with qml.tape.QuantumTape() as tape:
qml.RX(params[0], wires=0)
qml.RX(params[1], wires=1)
qml.RX(params[2], wires=2)
qml.expval(ham)
tape.trainable_params = {0, 1, 2}
dev_jacobian = dev.adjoint_jacobian(tape)
expected_jacobian = (
0.3 * np.array([-np.sin(params[0]), 0, 0])
+ 0.3 * np.array([0, -np.sin(params[1]), 0])
+ 0.4
* np.array(
[
-np.sin(params[0]) * np.cos(params[2]),
0,
-np.cos(params[0]) * np.sin(params[2]),
]
)
)
assert np.allclose(dev_jacobian, expected_jacobian, atol=tol, rtol=0)
qubit_ops = [getattr(qml, name) for name in qml.ops._qubit__ops__] # pylint: disable=no-member
ops = {qml.RX, qml.RY, qml.RZ, qml.PhaseShift, qml.CRX, qml.CRY, qml.CRZ, qml.Rot}
@pytest.mark.parametrize("obs", [qml.PauliX, qml.PauliY])
@pytest.mark.parametrize(
"op",
[
qml.RX(0.4, wires=0),
qml.RY(0.6, wires=0),
qml.RZ(0.8, wires=0),
qml.CRX(1.0, wires=[0, 1]),
qml.CRY(2.0, wires=[0, 1]),
qml.CRZ(3.0, wires=[0, 1]),
qml.Rot(0.2, -0.1, 0.2, wires=0),
],
)
def test_gradients_pauliz(self, op, obs, dev):
"""Tests that the gradients of circuits match between the finite difference and device
methods."""
# op.num_wires and op.num_params must be initialized a priori
with qml.tape.QuantumTape() as tape:
qml.Hadamard(wires=0)
qml.RX(0.543, wires=0)
qml.CNOT(wires=[0, 1])
op # pylint: disable=pointless-statement
qml.Rot(1.3, -2.3, 0.5, wires=[0])
qml.RZ(-0.5, wires=0)
qml.adjoint(qml.RY(0.5, wires=1), lazy=False)
qml.CNOT(wires=[0, 1])
qml.expval(obs(wires=0))
qml.expval(qml.PauliZ(wires=1))
tape.trainable_params = set(range(1, 1 + op.num_params))
tol = 1e-3 if dev.R_DTYPE == np.float32 else 1e-7
# pylint: disable=unnecessary-direct-lambda-call
grad_F = (lambda t, fn: fn(qml.execute(t, dev, None)))(*qml.gradients.param_shift(tape))
grad_D = dev.adjoint_jacobian(tape)
assert np.allclose(grad_D, grad_F, atol=tol, rtol=0)
@pytest.mark.parametrize(
"op",
[
qml.RX(0.4, wires=0),
qml.RY(0.6, wires=0),
qml.RZ(0.8, wires=0),
qml.CRX(1.0, wires=[0, 1]),
qml.CRY(2.0, wires=[0, 1]),
qml.CRZ(3.0, wires=[0, 1]),
qml.Rot(0.2, -0.1, 0.2, wires=0),
],
)
def test_gradients_hermitian(self, op, dev):
"""Tests that the gradients of circuits match between the finite difference and device
methods."""
# op.num_wires and op.num_params must be initialized a priori
with qml.tape.QuantumTape() as tape:
qml.Hadamard(wires=0)
qml.RX(0.543, wires=0)
qml.CNOT(wires=[0, 1])
op.queue()
qml.Rot(1.3, -2.3, 0.5, wires=[0])
qml.RZ(-0.5, wires=0)
qml.adjoint(qml.RY(0.5, wires=1), lazy=False)
qml.CNOT(wires=[0, 1])
qml.expval(
qml.Hermitian(
[[0, 0, 1, 1], [0, 1, 2, 1], [1, 2, 1, 0], [1, 1, 0, 0]],
wires=[0, 1],
)
)
tape.trainable_params = set(range(1, 1 + op.num_params))
tol = 1e-3 if dev.R_DTYPE == np.float32 else 1e-7
# pylint: disable=unnecessary-direct-lambda-call
grad_F = (lambda t, fn: fn(qml.execute(t, dev, None)))(*qml.gradients.param_shift(tape))
grad_D = dev.adjoint_jacobian(tape)
assert np.allclose(grad_D, grad_F, atol=tol, rtol=0)
def test_gradient_gate_with_multiple_parameters_pauliz(self, dev):
"""Tests that gates with multiple free parameters yield correct gradients."""
x, y, z = [0.5, 0.3, -0.7]
tape = qml.tape.QuantumScript(
[
qml.RX(0.4, wires=[0]),
qml.Rot(x, y, z, wires=[0]),
qml.RY(-0.2, wires=[0]),
],
[qml.expval(qml.PauliZ(0))],
)
tape.trainable_params = {1, 2, 3}
tol = 1e-3 if dev.R_DTYPE == np.float32 else 1e-7
grad_D = dev.adjoint_jacobian(tape)
tapes, fn = qml.gradients.param_shift(tape)
grad_F = fn(qml.execute(tapes, dev, None))
# gradient has the correct shape and every element is nonzero
assert len(grad_D) == 3
assert all(isinstance(v, np.ndarray) for v in grad_D)
assert np.count_nonzero(grad_D) == 3
# the different methods agree
assert np.allclose(grad_D, grad_F, atol=tol, rtol=0)
def test_gradient_gate_with_multiple_parameters_hermitian(self, dev):
"""Tests that gates with multiple free parameters yield correct gradients."""
x, y, z = [0.5, 0.3, -0.7]
tape = qml.tape.QuantumScript(
[
qml.RX(0.4, wires=[0]),
qml.Rot(x, y, z, wires=[0]),
qml.RY(-0.2, wires=[0]),
],
[qml.expval(qml.Hermitian([[0, 1], [1, 1]], wires=0))],
)
tape.trainable_params = {1, 2, 3}
tol = 1e-3 if dev.R_DTYPE == np.float32 else 1e-7
grad_D = dev.adjoint_jacobian(tape)
tapes, fn = qml.gradients.param_shift(tape)
grad_F = fn(qml.execute(tapes, dev, None))
# gradient has the correct shape and every element is nonzero
assert len(grad_D) == 3
assert all(isinstance(v, np.ndarray) for v in grad_D)
assert np.count_nonzero(grad_D) == 3
# the different methods agree
assert np.allclose(grad_D, grad_F, atol=tol, rtol=0)
@pytest.mark.skipif(not ld._CPP_BINARY_AVAILABLE, reason="Lightning binary required")
def test_gradient_gate_with_multiple_parameters_hamiltonian(self, dev):
"""Tests that gates with multiple free parameters yield correct gradients."""
x, y, z = [0.5, 0.3, -0.7]
ham = qml.Hamiltonian(
[1.0, 0.3, 0.3],
[qml.PauliX(0) @ qml.PauliX(1), qml.PauliZ(0), qml.PauliZ(1)],
)
tape = qml.tape.QuantumScript(
[
qml.RX(0.4, wires=[0]),
qml.Rot(x, y, z, wires=[0]),
qml.RY(-0.2, wires=[0]),
],
[qml.expval(ham)],
)
tape.trainable_params = {1, 2, 3}
tol = 1e-3 if dev.R_DTYPE == np.float32 else 1e-7
grad_D = dev.adjoint_jacobian(tape)
tapes, fn = qml.gradients.param_shift(tape)
grad_F = fn(qml.execute(tapes, dev, None))
# gradient has the correct shape and every element is nonzero
assert len(grad_D) == 3
assert all(isinstance(v, np.ndarray) for v in grad_D)
assert np.count_nonzero(grad_D) == 3
# the different methods agree
assert np.allclose(grad_D, grad_F, atol=tol, rtol=0)
def test_use_device_state(self, tol, dev):
"""Tests that when using the device state, the correct answer is still returned."""
x, y, z = [0.5, 0.3, -0.7]
with qml.tape.QuantumTape() as tape:
qml.RX(0.4, wires=[0])
qml.Rot(x, y, z, wires=[0])
qml.RY(-0.2, wires=[0])
qml.expval(qml.PauliZ(0))
tape.trainable_params = {1, 2, 3}
dM1 = dev.adjoint_jacobian(tape)
qml.execute([tape], dev, None)
dM2 = dev.adjoint_jacobian(tape, use_device_state=True)
assert np.allclose(dM1, dM2, atol=tol, rtol=0)
def test_provide_starting_state(self, tol, dev):
"""Tests provides correct answer when provided starting state."""
comm = MPI.COMM_WORLD
x, y, z = [0.5, 0.3, -0.7]
with qml.tape.QuantumTape() as tape:
qml.RX(0.4, wires=[0])
qml.Rot(x, y, z, wires=[0])
qml.RY(-0.2, wires=[0])
qml.expval(qml.PauliZ(0))
tape.trainable_params = {1, 2, 3}
dM1 = dev.adjoint_jacobian(tape)
if device_name == "lightning.gpu":
local_state_vector = dev.state
complex_type = np.complex128 if dev.R_DTYPE == np.float64 else np.complex64
state_vector = np.zeros(1 << 8).astype(complex_type)
comm.Allgather(local_state_vector, state_vector)
qml.execute([tape], dev, None)
dM2 = dev.adjoint_jacobian(tape, starting_state=state_vector)
assert np.allclose(dM1, dM2, atol=tol, rtol=0)
@pytest.mark.skipif(not ld._CPP_BINARY_AVAILABLE, reason="Lightning binary required")
def test_provide_wrong_starting_state(self, dev):
"""Tests raise an exception when provided starting state mismatches."""
x, y, z = [0.5, 0.3, -0.7]
with qml.tape.QuantumTape() as tape:
qml.RX(0.4, wires=[0])
qml.Rot(x, y, z, wires=[0])
qml.RY(-0.2, wires=[0])
qml.expval(qml.PauliZ(0))
tape.trainable_params = {1, 2, 3}
with pytest.raises(
qml.QuantumFunctionError,
match="The number of qubits of starting_state must be the same as",
):
dev.adjoint_jacobian(tape, starting_state=np.ones(7))
@pytest.mark.skipif(
device_name == "lightning.gpu",
reason="Adjoint differentiation does not support State measurements.",
)
@pytest.mark.skipif(not ld._CPP_BINARY_AVAILABLE, reason="Lightning binary required")
def test_state_return_type(self, dev):
"""Tests raise an exception when the return type is State"""
with qml.tape.QuantumTape() as tape:
qml.RX(0.4, wires=[0])
qml.state()
tape.trainable_params = {0}
with pytest.raises(
qml.QuantumFunctionError,
match="This method does not support statevector return type.",
):
dev.adjoint_jacobian(tape)
class TestAdjointJacobianQNode:
"""Test QNode integration with the adjoint_jacobian method"""
@pytest.fixture(params=fixture_params)
def dev(self, request):
"""Returns a PennyLane device."""
return qml.device(
device_name,
wires=8,
mpi=True,
c_dtype=request.param[0],
batch_obs=request.param[1],
)
def test_finite_shots_warning(self):
"""Tests that a warning is raised when computing the adjoint diff on a device with finite shots"""
dev = qml.device(device_name, wires=8, mpi=True, shots=1)
with pytest.warns(
UserWarning,
match="Requested adjoint differentiation to be computed with finite shots.",
):
@qml.qnode(dev, diff_method="adjoint")
def circ(x):
qml.RX(x, wires=0)
return qml.expval(qml.PauliZ(0))
with pytest.warns(
UserWarning,
match="Requested adjoint differentiation to be computed with finite shots.",
):
qml.grad(circ)(0.1)
@pytest.mark.skipif(not ld._CPP_BINARY_AVAILABLE, reason="Lightning binary required")
def test_qnode(self, mocker, dev):
"""Test that specifying diff_method allows the adjoint method to be selected"""
args = np.array([0.54, 0.1, 0.5], requires_grad=True)
def circuit(x, y, z):
qml.Hadamard(wires=0)
qml.RX(0.543, wires=0)
qml.CNOT(wires=[0, 1])
qml.Rot(x, y, z, wires=0)
qml.Rot(1.3, -2.3, 0.5, wires=[0])
qml.RZ(-0.5, wires=0)
qml.RY(0.5, wires=1)
qml.CNOT(wires=[0, 1])
return qml.expval(qml.PauliX(0) @ qml.PauliZ(1))
qnode1 = QNode(circuit, dev, diff_method="adjoint")
spy = mocker.spy(dev, "adjoint_jacobian")
grad_fn = qml.grad(qnode1)
grad_A = grad_fn(*args)
spy.assert_called()
h = 1e-3 if dev.R_DTYPE == np.float32 else 1e-7
tol = 1e-3 if dev.R_DTYPE == np.float32 else 1e-7
qnode2 = QNode(circuit, dev, diff_method="finite-diff", h=h)
grad_fn = qml.grad(qnode2)
grad_F = grad_fn(*args)
assert np.allclose(grad_A, grad_F, atol=tol, rtol=0)
thetas = np.linspace(-2 * np.pi, 2 * np.pi, 8)
@pytest.mark.parametrize("reused_p", thetas**3 / 19)
@pytest.mark.parametrize("other_p", thetas**2 / 1)
def test_fanout_multiple_params(
self, reused_p, other_p, tol, mocker, dev
): # pylint: disable=too-many-arguments
"""Tests that the correct gradient is computed for qnodes which
use the same parameter in multiple gates."""
def expZ(state):
return np.abs(state[0]) ** 2 - np.abs(state[1]) ** 2
extra_param = np.array(0.31, requires_grad=False)
@qnode(dev, diff_method="adjoint")
def cost(p1, p2):
qml.RX(extra_param, wires=[0])
qml.RY(p1, wires=[0])
qml.RZ(p2, wires=[0])
qml.RX(p1, wires=[0])
return qml.expval(qml.PauliZ(0))
zero_state = np.array([1.0, 0.0])
cost(reused_p, other_p)
spy = mocker.spy(dev, "adjoint_jacobian")
# analytic gradient
grad_fn = qml.grad(cost)
grad_D = grad_fn(reused_p, other_p)
spy.assert_called_once()
# manual gradient
grad_true0 = (
expZ(
Rx(reused_p) @ Rz(other_p) @ Ry(reused_p + np.pi / 2) @ Rx(extra_param) @ zero_state
)
- expZ(
Rx(reused_p) @ Rz(other_p) @ Ry(reused_p - np.pi / 2) @ Rx(extra_param) @ zero_state
)
) / 2
grad_true1 = (
expZ(
Rx(reused_p + np.pi / 2) @ Rz(other_p) @ Ry(reused_p) @ Rx(extra_param) @ zero_state
)
- expZ(
Rx(reused_p - np.pi / 2) @ Rz(other_p) @ Ry(reused_p) @ Rx(extra_param) @ zero_state
)
) / 2
expected = grad_true0 + grad_true1 # product rule
assert np.allclose(grad_D[0], expected, atol=tol, rtol=0)
@pytest.mark.skipif(not ld._CPP_BINARY_AVAILABLE, reason="Lightning binary required")
def test_gradient_repeated_gate_parameters(self, mocker, dev):
"""Tests that repeated use of a free parameter in a multi-parameter gate yields correct
gradients."""
params = np.array([0.8, 1.3], requires_grad=True)
def circuit(params):
qml.RX(np.array(np.pi / 4, requires_grad=False), wires=[0])
qml.Rot(params[1], params[0], 2 * params[0], wires=[0])
return qml.expval(qml.PauliX(0))
spy_analytic = mocker.spy(dev, "adjoint_jacobian")
h = 1e-3 if dev.R_DTYPE == np.float32 else 1e-7
tol = 1e-3 if dev.R_DTYPE == np.float32 else 1e-7
cost = QNode(circuit, dev, diff_method="finite-diff", h=h)
grad_fn = qml.grad(cost)
grad_F = grad_fn(params)
spy_analytic.assert_not_called()
cost = QNode(circuit, dev, diff_method="adjoint")
grad_fn = qml.grad(cost)
grad_D = grad_fn(params)
spy_analytic.assert_called_once()
# the different methods agree
assert np.allclose(grad_D, grad_F, atol=tol, rtol=0)
def test_interface_tf(self, dev):
"""Test if gradients agree between the adjoint and finite-diff methods when using the
TensorFlow interface"""
tf = pytest.importorskip("tensorflow")
def f(params1, params2):
qml.RX(0.4, wires=[0])
qml.RZ(params1 * tf.sqrt(params2), wires=[0])
qml.RY(tf.cos(params2), wires=[0])
return qml.expval(qml.PauliZ(0))
if dev.R_DTYPE == np.float32:
tf_r_dtype = tf.float32
else:
tf_r_dtype = tf.float64
params1 = tf.Variable(0.3, dtype=tf_r_dtype)
params2 = tf.Variable(0.4, dtype=tf_r_dtype)
h = 2e-3 if dev.R_DTYPE == np.float32 else 1e-7
tol = 1e-3 if dev.R_DTYPE == np.float32 else 1e-7
qnode1 = QNode(f, dev, interface="tf", diff_method="adjoint")
qnode2 = QNode(f, dev, interface="tf", diff_method="finite-diff", h=h)
with tf.GradientTape() as tape:
res1 = qnode1(params1, params2)
g1 = tape.gradient(res1, [params1, params2])
with tf.GradientTape() as tape:
res2 = qnode2(params1, params2)
g2 = tape.gradient(res2, [params1, params2])
assert np.allclose(g1, g2, atol=tol)
def test_interface_torch(self, dev):
"""Test if gradients agree between the adjoint and finite-diff methods when using the
Torch interface"""
torch = pytest.importorskip("torch")
def f(params1, params2):
qml.RX(0.4, wires=[0])
qml.RZ(params1 * torch.sqrt(params2), wires=[0])
qml.RY(torch.cos(params2), wires=[0])
return qml.expval(qml.PauliZ(0))
params1 = torch.tensor(0.3, requires_grad=True)
params2 = torch.tensor(0.4, requires_grad=True)
h = 2e-3 if dev.R_DTYPE == np.float32 else 1e-7
qnode1 = QNode(f, dev, interface="torch", diff_method="adjoint")
qnode2 = QNode(f, dev, interface="torch", diff_method="finite-diff", h=h)
res1 = qnode1(params1, params2)
res1.backward()
grad_adjoint = params1.grad, params2.grad
res2 = qnode2(params1, params2)
res2.backward()
grad_fd = params1.grad, params2.grad
assert np.allclose(grad_adjoint, grad_fd)
def test_interface_jax(self, dev):
"""Test if the gradients agree between adjoint and finite-difference methods in the
jax interface"""
jax = pytest.importorskip("jax")
if dev.R_DTYPE == np.float64:
from jax.config import config # pylint: disable=import-outside-toplevel
config.update("jax_enable_x64", True)
def f(params1, params2):
qml.RX(0.4, wires=[0])
qml.RZ(params1 * jax.numpy.sqrt(params2), wires=[0])
qml.RY(jax.numpy.cos(params2), wires=[0])
return qml.expval(qml.PauliZ(0))
params1 = jax.numpy.array(0.3, dev.R_DTYPE)
params2 = jax.numpy.array(0.4, dev.R_DTYPE)
h = 2e-3 if dev.R_DTYPE == np.float32 else 1e-7
tol = 1e-3 if dev.R_DTYPE == np.float32 else 1e-7
qnode_adjoint = QNode(f, dev, interface="jax", diff_method="adjoint")
qnode_fd = QNode(f, dev, interface="jax", diff_method="finite-diff", h=h)
grad_adjoint = jax.grad(qnode_adjoint)(params1, params2)
grad_fd = jax.grad(qnode_fd)(params1, params2)
assert np.allclose(grad_adjoint, grad_fd, atol=tol)
def circuit_ansatz(params, wires):
"""Circuit ansatz containing all the parametrized gates"""
qml.QubitStateVector(unitary_group.rvs(2**8, random_state=0)[0], wires=wires)
qml.RX(params[0], wires=wires[0])
qml.RY(params[1], wires=wires[1])
qml.adjoint(qml.RX(params[2], wires=wires[2]))
qml.RZ(params[0], wires=wires[3])
qml.CRX(params[3], wires=[wires[3], wires[0]])
qml.PhaseShift(params[4], wires=wires[2])
qml.CRY(params[5], wires=[wires[2], wires[1]])
qml.adjoint(qml.CRZ(params[5], wires=[wires[0], wires[3]]))
qml.adjoint(qml.PhaseShift(params[6], wires=wires[0]))
qml.Rot(params[6], params[7], params[8], wires=wires[0])
qml.adjoint(qml.Rot(params[8], params[8], params[9], wires=wires[1]))
qml.MultiRZ(params[11], wires=[wires[0], wires[1]])
qml.PauliRot(params[12], "XXYZ", wires=[wires[0], wires[1], wires[2], wires[3]])
qml.CPhase(params[12], wires=[wires[3], wires[2]])
qml.IsingXX(params[13], wires=[wires[1], wires[0]])
qml.IsingXY(params[14], wires=[wires[3], wires[2]])
qml.IsingYY(params[14], wires=[wires[3], wires[2]])
qml.IsingZZ(params[14], wires=[wires[2], wires[1]])
qml.U1(params[15], wires=wires[0])
qml.U2(params[16], params[17], wires=wires[0])
qml.U3(params[18], params[19], params[20], wires=wires[1])
qml.adjoint(qml.CRot(params[21], params[22], params[23], wires=[wires[1], wires[2]]))
qml.SingleExcitation(params[24], wires=[wires[2], wires[0]])
qml.DoubleExcitation(params[25], wires=[wires[2], wires[0], wires[1], wires[3]])
qml.SingleExcitationPlus(params[26], wires=[wires[0], wires[2]])
qml.SingleExcitationMinus(params[27], wires=[wires[0], wires[2]])
qml.DoubleExcitationPlus(params[27], wires=[wires[2], wires[0], wires[1], wires[3]])
qml.DoubleExcitationMinus(params[27], wires=[wires[2], wires[0], wires[1], wires[3]])
qml.RX(params[28], wires=wires[0])
qml.RX(params[29], wires=wires[1])
@pytest.mark.parametrize(
"returns",
[
qml.PauliZ(0),
qml.PauliX(2),
qml.PauliZ(0) @ qml.PauliY(3),
qml.Hadamard(2),
qml.Hadamard(3) @ qml.PauliZ(2),
qml.PauliX(0) @ qml.PauliY(3),
qml.PauliY(0) @ qml.PauliY(2) @ qml.PauliY(3),
qml.Hermitian(
np.kron(qml.PauliY.compute_matrix(), qml.PauliZ.compute_matrix()),
wires=[3, 2],
),
qml.Hermitian(np.array([[0, 1], [1, 0]], requires_grad=False), wires=0),
qml.Hermitian(np.array([[0, 1], [1, 0]], requires_grad=False), wires=0) @ qml.PauliZ(2),
],
)
def test_integration(returns):
"""Integration tests that compare to default.qubit for a large circuit containing parametrized
operations"""
dev_def = qml.device("default.qubit", wires=range(8))
dev_lightning = qml.device(device_name, wires=range(8), mpi=True)
def circuit(params):
circuit_ansatz(params, wires=range(8))
return qml.expval(returns), qml.expval(qml.PauliY(1))
n_params = 30
params = np.linspace(0, 10, n_params)
qnode_def = qml.QNode(circuit, dev_def)
qnode_lightning = qml.QNode(circuit, dev_lightning, diff_method="adjoint")
def casted_to_array_def(params):
return np.array(qnode_def(params))
def casted_to_array_lightning(params):
return np.array(qnode_lightning(params))
j_def = qml.jacobian(casted_to_array_def)(params)
j_lightning = qml.jacobian(casted_to_array_lightning)(params)
assert np.allclose(j_def, j_lightning)
custom_wires = ["alice", 3.14, -1, 0, "bob", 1, "unit", "test"]
@pytest.mark.parametrize(
"returns",
[
qml.PauliZ(custom_wires[0]),
qml.PauliX(custom_wires[2]),
qml.PauliZ(custom_wires[0]) @ qml.PauliY(custom_wires[3]),
qml.Hadamard(custom_wires[2]),
qml.Hadamard(custom_wires[3]) @ qml.PauliZ(custom_wires[2]),
# qml.Projector([0, 1], wires=[custom_wires[0], custom_wires[2]]) @ qml.Hadamard(custom_wires[3])
# qml.Projector([0, 0], wires=[custom_wires[2], custom_wires[0]])
qml.PauliX(custom_wires[0]) @ qml.PauliY(custom_wires[3]),
qml.PauliY(custom_wires[0]) @ qml.PauliY(custom_wires[2]) @ qml.PauliY(custom_wires[3]),
qml.Hermitian(np.array([[0, 1], [1, 0]], requires_grad=False), wires=custom_wires[0]),
qml.Hermitian(
np.kron(qml.PauliY.compute_matrix(), qml.PauliZ.compute_matrix()),
wires=[custom_wires[3], custom_wires[2]],
),
qml.Hermitian(np.array([[0, 1], [1, 0]], requires_grad=False), wires=custom_wires[0])