-
Notifications
You must be signed in to change notification settings - Fork 558
/
test_parameter_shift.py
4616 lines (3625 loc) · 171 KB
/
test_parameter_shift.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 2022 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.
"""Tests for the gradients.parameter_shift module using the new return types."""
import pytest
import pennylane as qml
from pennylane import numpy as np
from pennylane.gradients import param_shift
from pennylane.gradients.parameter_shift import (
_get_operation_recipe,
_put_zeros_in_pdA2_involutory,
_make_zero_rep,
)
from pennylane.devices import DefaultQubit
from pennylane.operation import Observable, AnyWires
# pylint: disable=too-few-public-methods
class RY_with_F(qml.RY):
"""Custom variant of qml.RY with grad_method "F"."""
grad_method = "F"
# pylint: disable=too-few-public-methods
class RX_with_F(qml.RX):
"""Custom variant of qml.RX with grad_method "F"."""
grad_method = "F"
# pylint: disable=too-few-public-methods
class RX_par_dep_recipe(qml.RX):
"""RX operation with a parameter-dependent grad recipe."""
@property
def grad_recipe(self):
"""The gradient is given by [f(2x) - f(0)] / (2 sin(x)), by subsituting
shift = x into the two term parameter-shift rule."""
x = self.data[0]
c = 0.5 / np.sin(x)
return ([[c, 0.0, 2 * x], [-c, 0.0, 0.0]],)
class TestGetOperationRecipe:
"""Test the helper function `_get_operation_recipe` that obtains the
`grad_recipe` for a given operation in a tape."""
@pytest.mark.parametrize(
"orig_op, frequencies, shifts",
[
(qml.RX, (1.0,), None),
(qml.RX, (1.0,), (np.pi / 2,)),
(qml.CRY, (0.5, 1), None),
(qml.CRY, (0.5, 1), (0.4, 0.8)),
(qml.TRX, (0.5, 1), None),
(qml.TRX, (0.5, 1), (0.4, 0.8)),
],
)
def test_custom_recipe_first_order(self, orig_op, frequencies, shifts):
"""Test that a custom recipe is returned correctly for first-order derivatives."""
c, s = qml.gradients.generate_shift_rule(frequencies, shifts=shifts).T
recipe = list(zip(c, np.ones_like(c), s))
# pylint: disable=too-few-public-methods
class DummyOp(orig_op):
"""Custom version of original operation with different gradient recipe."""
grad_recipe = (recipe,)
with qml.queuing.AnnotatedQueue() as q:
DummyOp(0.2, wires=list(range(DummyOp.num_wires)))
tape = qml.tape.QuantumScript.from_queue(q)
out_recipe = _get_operation_recipe(tape, 0, shifts=shifts, order=1)
assert qml.math.allclose(out_recipe[:, 0], c)
assert qml.math.allclose(out_recipe[:, 1], np.ones_like(c))
if shifts is None:
assert qml.math.allclose(out_recipe[:, 2], s)
else:
exp_out_shifts = [-s for s in shifts[::-1]] + list(shifts)
assert qml.math.allclose(np.sort(s), exp_out_shifts)
assert qml.math.allclose(np.sort(out_recipe[:, 2]), np.sort(exp_out_shifts))
def test_qnode_custom_recipe(self):
"""Test a custom recipe using a QNode."""
dev = qml.device("default.qubit", wires=2)
x = np.array(0.4, requires_grad=True)
with qml.queuing.AnnotatedQueue() as q:
qml.RX(x, 0)
qml.expval(qml.PauliZ(0))
qml.expval(qml.PauliX(1))
tape = qml.tape.QuantumScript.from_queue(q)
# Incorrect gradient recipe, but this test only checks execution with an unshifted term.
recipes = ([[-1e7, 1, 0], [1e7, 1, 1e7]],)
tapes, fn = qml.gradients.param_shift(tape, gradient_recipes=recipes)
assert len(tapes) == 2
res = fn(qml.execute(tapes, dev, None))
assert len(res) == 2
assert isinstance(res, tuple)
@pytest.mark.parametrize(
"orig_op, frequencies, shifts",
[
(qml.RX, (1.0,), None),
(qml.RX, (1.0,), (np.pi / 2,)),
(qml.CRY, (0.5, 1), None),
(qml.CRY, (0.5, 1), (0.4, 0.8)),
(qml.TRX, (0.5, 1), None),
(qml.TRX, (0.5, 1), (0.4, 0.8)),
],
)
def test_custom_recipe_second_order(self, orig_op, frequencies, shifts):
"""Test that a custom recipe is returned correctly for second-order derivatives."""
c, s = qml.gradients.generate_shift_rule(frequencies, shifts=shifts).T
recipe = list(zip(c, np.ones_like(c), s))
# pylint: disable=too-few-public-methods
class DummyOp(orig_op):
"""Custom version of original operation with different gradient recipe."""
grad_recipe = (recipe,)
with qml.queuing.AnnotatedQueue() as q:
DummyOp(0.2, wires=list(range(DummyOp.num_wires)))
tape = qml.tape.QuantumScript.from_queue(q)
out_recipe = _get_operation_recipe(tape, 0, shifts=shifts, order=2)
c2, s2 = qml.gradients.generate_shift_rule(frequencies, shifts=shifts, order=2).T
assert qml.math.allclose(out_recipe[:, 0], c2)
assert qml.math.allclose(out_recipe[:, 1], np.ones_like(c2))
assert qml.math.allclose(out_recipe[:, 2], s2)
@pytest.mark.parametrize("order", [0, 3])
def test_error_wrong_order(self, order):
"""Test that get_operation_recipe raises an error for orders other than 1 and 2"""
with qml.queuing.AnnotatedQueue() as q:
qml.RX(0.2, wires=0)
tape = qml.tape.QuantumScript.from_queue(q)
with pytest.raises(NotImplementedError, match="only is implemented for orders 1 and 2."):
_get_operation_recipe(tape, 0, shifts=None, order=order)
class TestMakeZeroRep:
"""Test that producing a zero-gradient representative with ``_make_zero_rep`` works."""
# mimic an expectation value or variance, and a probs vector
@pytest.mark.parametrize("g", [np.array(0.6), np.array([0.6, 0.9])])
def test_single_measure_no_partitioned_shots(self, g):
"""Test the zero-gradient representative with a single measurement and single shots."""
rep = _make_zero_rep(g, single_measure=True, has_partitioned_shots=False)
assert isinstance(rep, np.ndarray) and rep.shape == g.shape
assert qml.math.allclose(rep, 0.0)
# mimic an expectation value or variance, and a probs vector
@pytest.mark.parametrize(
"g", [(np.array(0.6), np.array(0.4)) * 3, (np.array([0.3, 0.1]), np.array([0.6, 0.9]))]
)
def test_single_measure_partitioned_shots(self, g):
"""Test the zero-gradient representative with a single measurement and a shot vector."""
rep = _make_zero_rep(g, single_measure=True, has_partitioned_shots=True)
assert isinstance(rep, tuple) and len(rep) == len(g)
for r, _g in zip(rep, g):
assert isinstance(r, np.ndarray) and r.shape == _g.shape
assert qml.math.allclose(r, 0.0)
# mimic an expectation value, a probs vector, or a mixture of them
@pytest.mark.parametrize(
"g",
[
(np.array(0.6), np.array(0.4)) * 3,
(np.array([0.3, 0.1]), np.array([0.6, 0.9])),
(np.array(0.5), np.ones(4), np.array(0.2)),
],
)
def test_multi_measure_no_partitioned_shots(self, g):
"""Test the zero-gradient representative with multiple measurements and single shots."""
rep = _make_zero_rep(g, single_measure=False, has_partitioned_shots=False)
assert isinstance(rep, tuple) and len(rep) == len(g)
for r, _g in zip(rep, g):
assert isinstance(r, np.ndarray) and r.shape == _g.shape
assert qml.math.allclose(r, 0.0)
# mimic an expectation value, a probs vector, or a mixture of them
@pytest.mark.parametrize(
"g",
[
((np.array(0.6), np.array(0.4)),) * 3,
((np.array([0.3, 0.1]), np.array([0.6, 0.9])),) * 2,
((np.array(0.5), np.ones(4), np.array(0.2)),) * 4,
],
)
def test_multi_measure_partitioned_shots(self, g):
"""Test the zero-gradient representative with multiple measurements and a shot vector."""
rep = _make_zero_rep(g, single_measure=False, has_partitioned_shots=True)
assert isinstance(rep, tuple) and len(rep) == len(g)
for _rep, _g in zip(rep, g):
assert isinstance(_rep, tuple) and len(_rep) == len(_g)
for r, __g in zip(_rep, _g):
assert isinstance(r, np.ndarray) and r.shape == __g.shape
assert qml.math.allclose(r, 0.0)
# mimic an expectation value or variance, and a probs vector, but with 1d arguments
@pytest.mark.parametrize(
"g", [np.array([0.6, 0.2, 0.1]), np.outer([0.4, 0.2, 0.1], [0.6, 0.9])]
)
@pytest.mark.parametrize(
"par_shapes", [((), ()), ((), (2,)), ((), (3, 1)), ((3,), ()), ((3,), (3,)), ((3,), (4, 5))]
)
def test_single_measure_no_partitioned_shots_par_shapes(self, g, par_shapes):
"""Test the zero-gradient representative with a single measurement and single shots
as well as provided par_shapes."""
old_shape, new_shape = par_shapes
exp_shape = new_shape + g.shape[len(old_shape) :]
rep = _make_zero_rep(
g, single_measure=True, has_partitioned_shots=False, par_shapes=par_shapes
)
assert isinstance(rep, np.ndarray) and rep.shape == exp_shape
assert qml.math.allclose(rep, 0.0)
# mimic an expectation value or variance, and a probs vector, but with 1d arguments
@pytest.mark.parametrize(
"g", [(np.array(0.6), np.array(0.4)) * 3, (np.array([0.3, 0.1]), np.array([0.6, 0.9]))]
)
@pytest.mark.parametrize(
"par_shapes", [((), ()), ((), (2,)), ((), (3, 1)), ((3,), ()), ((3,), (3,)), ((3,), (4, 5))]
)
def test_single_measure_partitioned_shots_par_shapes(self, g, par_shapes):
"""Test the zero-gradient representative with a single measurement and a shot vector
as well as provided par_shapes."""
old_shape, new_shape = par_shapes
rep = _make_zero_rep(
g, single_measure=True, has_partitioned_shots=True, par_shapes=par_shapes
)
assert isinstance(rep, tuple) and len(rep) == len(g)
for r, _g in zip(rep, g):
exp_shape = new_shape + _g.shape[len(old_shape) :]
assert isinstance(r, np.ndarray) and r.shape == exp_shape
assert qml.math.allclose(r, 0.0)
# mimic an expectation value, a probs vector, or a mixture of them, but with 1d arguments
@pytest.mark.parametrize(
"g",
[
(np.array(0.6), np.array(0.4)) * 3,
(np.array([0.3, 0.1]), np.array([0.6, 0.9])),
(np.array(0.5), np.ones(4), np.array(0.2)),
],
)
@pytest.mark.parametrize(
"par_shapes", [((), ()), ((), (2,)), ((), (3, 1)), ((3,), ()), ((3,), (3,)), ((3,), (4, 5))]
)
def test_multi_measure_no_partitioned_shots_par_shapes(self, g, par_shapes):
"""Test the zero-gradient representative with multiple measurements and single shots
as well as provided par_shapes."""
old_shape, new_shape = par_shapes
rep = _make_zero_rep(
g, single_measure=False, has_partitioned_shots=False, par_shapes=par_shapes
)
assert isinstance(rep, tuple) and len(rep) == len(g)
for r, _g in zip(rep, g):
exp_shape = new_shape + _g.shape[len(old_shape) :]
assert isinstance(r, np.ndarray) and r.shape == exp_shape
assert qml.math.allclose(r, 0.0)
# mimic an expectation value, a probs vector, or a mixture of them, but with 1d arguments
@pytest.mark.parametrize(
"g",
[
((np.array(0.6), np.array(0.4)),) * 3,
((np.array([0.3, 0.1]), np.array([0.6, 0.9])),) * 2,
((np.array(0.5), np.ones(4), np.array(0.2)),) * 4,
],
)
@pytest.mark.parametrize(
"par_shapes", [((), ()), ((), (2,)), ((), (3, 1)), ((3,), ()), ((3,), (3,)), ((3,), (4, 5))]
)
def test_multi_measure_partitioned_shots_par_shapes(self, g, par_shapes):
"""Test the zero-gradient representative with multiple measurements and a shot vector
as well as provided par_shapes."""
old_shape, new_shape = par_shapes
rep = _make_zero_rep(
g, single_measure=False, has_partitioned_shots=True, par_shapes=par_shapes
)
assert isinstance(rep, tuple) and len(rep) == len(g)
for _rep, _g in zip(rep, g):
assert isinstance(_rep, tuple) and len(_rep) == len(_g)
for r, __g in zip(_rep, _g):
exp_shape = new_shape + __g.shape[len(old_shape) :]
assert isinstance(r, np.ndarray) and r.shape == exp_shape
assert qml.math.allclose(r, 0.0)
def grad_fn(tape, dev, fn=qml.gradients.param_shift, **kwargs):
"""Utility function to automate execution and processing of gradient tapes"""
tapes, fn = fn(tape, **kwargs)
return fn(dev.batch_execute(tapes))
class TestParamShift:
"""Unit tests for the param_shift function"""
def test_empty_circuit(self):
"""Test that an empty circuit works correctly"""
with qml.queuing.AnnotatedQueue() as q:
qml.expval(qml.PauliZ(0))
tape = qml.tape.QuantumScript.from_queue(q)
with pytest.warns(UserWarning, match="gradient of a tape with no trainable parameters"):
tapes, _ = qml.gradients.param_shift(tape)
assert not tapes
def test_all_parameters_independent(self):
"""Test that a circuit where all parameters do not affect the output"""
with qml.queuing.AnnotatedQueue() as q:
qml.RX(0.4, wires=0)
qml.expval(qml.PauliZ(1))
tape = qml.tape.QuantumScript.from_queue(q)
tapes, _ = qml.gradients.param_shift(tape)
assert not tapes
def test_state_non_differentiable_error(self):
"""Test error raised if attempting to differentiate with
respect to a state"""
with qml.queuing.AnnotatedQueue() as q:
qml.RX(0.543, wires=[0])
qml.RY(-0.654, wires=[1])
qml.state()
tape = qml.tape.QuantumScript.from_queue(q)
_match = r"return the state with the parameter-shift rule gradient transform"
with pytest.raises(ValueError, match=_match):
qml.gradients.param_shift(tape)
def test_independent_parameter(self, mocker):
"""Test that an independent parameter is skipped
during the Jacobian computation."""
spy = mocker.spy(qml.gradients.parameter_shift, "expval_param_shift")
with qml.queuing.AnnotatedQueue() as q:
qml.RX(0.543, wires=[0])
qml.RY(-0.654, wires=[1]) # does not have any impact on the expval
qml.expval(qml.PauliZ(0))
tape = qml.tape.QuantumScript.from_queue(q)
dev = qml.device("default.qubit", wires=2)
tapes, fn = qml.gradients.param_shift(tape)
assert len(tapes) == 2
assert tapes[0].batch_size == tapes[1].batch_size == None
res = fn(dev.batch_execute(tapes))
assert isinstance(res, tuple)
assert len(res) == 2
assert res[0].shape == ()
assert res[1].shape == ()
# only called for parameter 0
assert spy.call_args[0][0:2] == (tape, [0])
# TODO: uncomment when QNode decorator uses new qml.execute pipeline
# @pytest.mark.autograd
# def test_no_trainable_params_qnode_autograd(self, mocker):
# """Test that the correct ouput and warning is generated in the absence of any trainable
# parameters"""
# dev = qml.device("default.qubit", wires=2)
# spy = mocker.spy(dev, "expval")
# @qml.qnode(dev, interface="autograd")
# def circuit(weights):
# qml.RX(weights[0], wires=0)
# qml.RY(weights[1], wires=0)
# return qml.expval(qml.PauliZ(0) @ qml.PauliZ(1))
# weights = [0.1, 0.2]
# with pytest.warns(UserWarning, match="gradient of a QNode with no trainable parameters"):
# res = qml.gradients.param_shift(circuit)(weights)
# assert res == ()
# spy.assert_not_called()
# @pytest.mark.torch
# def test_no_trainable_params_qnode_torch(self, mocker):
# """Test that the correct ouput and warning is generated in the absence of any trainable
# parameters"""
# dev = qml.device("default.qubit", wires=2)
# spy = mocker.spy(dev, "expval")
# @qml.qnode(dev, interface="torch")
# def circuit(weights):
# qml.RX(weights[0], wires=0)
# qml.RY(weights[1], wires=0)
# return qml.expval(qml.PauliZ(0) @ qml.PauliZ(1))
# weights = [0.1, 0.2]
# with pytest.warns(UserWarning, match="gradient of a QNode with no trainable parameters"):
# res = qml.gradients.param_shift(circuit)(weights)
# assert res == ()
# spy.assert_not_called()
# @pytest.mark.tf
# def test_no_trainable_params_qnode_tf(self, mocker):
# """Test that the correct ouput and warning is generated in the absence of any trainable
# parameters"""
# dev = qml.device("default.qubit", wires=2)
# spy = mocker.spy(dev, "expval")
# @qml.qnode(dev, interface="tf")
# def circuit(weights):
# qml.RX(weights[0], wires=0)
# qml.RY(weights[1], wires=0)
# return qml.expval(qml.PauliZ(0) @ qml.PauliZ(1))
# weights = [0.1, 0.2]
# with pytest.warns(UserWarning, match="gradient of a QNode with no trainable parameters"):
# res = qml.gradients.param_shift(circuit)(weights)
# assert res == ()
# spy.assert_not_called()
# @pytest.mark.jax
# def test_no_trainable_params_qnode_jax(self, mocker):
# """Test that the correct ouput and warning is generated in the absence of any trainable
# parameters"""
# dev = qml.device("default.qubit", wires=2)
# spy = mocker.spy(dev, "expval")
# @qml.qnode(dev, interface="jax")
# def circuit(weights):
# qml.RX(weights[0], wires=0)
# qml.RY(weights[1], wires=0)
# return qml.expval(qml.PauliZ(0) @ qml.PauliZ(1))
# weights = [0.1, 0.2]
# with pytest.warns(UserWarning, match="gradient of a QNode with no trainable parameters"):
# res = qml.gradients.param_shift(circuit)(weights)
# assert res == ()
# spy.assert_not_called()
@pytest.mark.parametrize("broadcast", [True, False])
def test_no_trainable_params_tape(self, broadcast):
"""Test that the correct ouput and warning is generated in the absence of any trainable
parameters"""
dev = qml.device("default.qubit", wires=2)
weights = [0.1, 0.2]
with qml.queuing.AnnotatedQueue() as q:
qml.RX(weights[0], wires=0)
qml.RY(weights[1], wires=0)
qml.expval(qml.PauliZ(0) @ qml.PauliZ(1))
tape = qml.tape.QuantumScript.from_queue(q)
# TODO: remove once #2155 is resolved
tape.trainable_params = []
with pytest.warns(UserWarning, match="gradient of a tape with no trainable parameters"):
g_tapes, post_processing = qml.gradients.param_shift(tape, broadcast=broadcast)
res = post_processing(qml.execute(g_tapes, dev, None))
assert g_tapes == []
assert isinstance(res, np.ndarray)
assert res.shape == (0,)
def test_no_trainable_params_multiple_return_tape(self):
"""Test that the correct ouput and warning is generated in the absence of any trainable
parameters with multiple returns."""
dev = qml.device("default.qubit", wires=2)
weights = [0.1, 0.2]
with qml.queuing.AnnotatedQueue() as q:
qml.RX(weights[0], wires=0)
qml.RY(weights[1], wires=0)
qml.expval(qml.PauliZ(0) @ qml.PauliZ(1))
qml.probs(wires=[0, 1])
tape = qml.tape.QuantumScript.from_queue(q)
tape.trainable_params = []
with pytest.warns(UserWarning, match="gradient of a tape with no trainable parameters"):
g_tapes, post_processing = qml.gradients.param_shift(tape)
res = post_processing(qml.execute(g_tapes, dev, None))
assert g_tapes == []
assert isinstance(res, tuple)
for r in res:
assert isinstance(r, np.ndarray)
assert r.shape == (0,)
def test_all_zero_diff_methods_tape(self):
"""Test that the transform works correctly when the diff method for every parameter is
identified to be 0, and that no tapes were generated."""
dev = qml.device("default.qubit", wires=4)
params = np.array([0.5, 0.5, 0.5], requires_grad=True)
with qml.queuing.AnnotatedQueue() as q:
qml.Rot(*params, wires=0)
qml.probs([2, 3])
tape = qml.tape.QuantumScript.from_queue(q)
g_tapes, post_processing = qml.gradients.param_shift(tape)
assert g_tapes == []
result = post_processing(qml.execute(g_tapes, dev, None))
assert isinstance(result, tuple)
assert len(result) == 3
assert isinstance(result[0], np.ndarray)
assert result[0].shape == (4,)
assert np.allclose(result[0], 0)
assert isinstance(result[1], np.ndarray)
assert result[1].shape == (4,)
assert np.allclose(result[1], 0)
assert isinstance(result[2], np.ndarray)
assert result[2].shape == (4,)
assert np.allclose(result[2], 0)
def test_all_zero_diff_methods_multiple_returns_tape(self):
"""Test that the transform works correctly when the diff method for every parameter is
identified to be 0, and that no tapes were generated."""
dev = qml.device("default.qubit", wires=4)
params = np.array([0.5, 0.5, 0.5], requires_grad=True)
with qml.queuing.AnnotatedQueue() as q:
qml.Rot(*params, wires=0)
qml.expval(qml.PauliZ(wires=2))
qml.probs([2, 3])
tape = qml.tape.QuantumScript.from_queue(q)
g_tapes, post_processing = qml.gradients.param_shift(tape)
assert g_tapes == []
result = post_processing(qml.execute(g_tapes, dev, None))
assert isinstance(result, tuple)
assert len(result) == 2
# First elem
assert len(result[0]) == 3
assert isinstance(result[0][0], np.ndarray)
assert result[0][0].shape == ()
assert np.allclose(result[0][0], 0)
assert isinstance(result[0][1], np.ndarray)
assert result[0][1].shape == ()
assert np.allclose(result[0][1], 0)
assert isinstance(result[0][2], np.ndarray)
assert result[0][2].shape == ()
assert np.allclose(result[0][2], 0)
# Second elem
assert len(result[0]) == 3
assert isinstance(result[1][0], np.ndarray)
assert result[1][0].shape == (4,)
assert np.allclose(result[1][0], 0)
assert isinstance(result[1][1], np.ndarray)
assert result[1][1].shape == (4,)
assert np.allclose(result[1][1], 0)
assert isinstance(result[1][2], np.ndarray)
assert result[1][2].shape == (4,)
assert np.allclose(result[1][2], 0)
tapes, _ = qml.gradients.param_shift(tape)
assert tapes == []
# TODO: uncomment when QNode decorator uses new qml.execute pipeline
# @pytest.mark.parametrize("broadcast", [True, False])
# def test_all_zero_diff_methods(self, broadcast):
# """Test that the transform works correctly when the diff method for every parameter is
# identified to be 0, and that no tapes were generated."""
# dev = qml.device("default.qubit", wires=4)
# @qml.qnode(dev)
# def circuit(params):
# qml.Rot(*params, wires=0)
# return qml.probs([2, 3])
# params = np.array([0.5, 0.5, 0.5], requires_grad=True)
# result = qml.gradients.param_shift(circuit)(params)
# assert np.allclose(result, np.zeros((4, 3)), atol=0, rtol=0)
# tapes, _ = qml.gradients.param_shift(circuit.tape, broadcast=broadcast)
# assert tapes == []
def test_with_gradient_recipes(self):
"""Test that the function behaves as expected"""
with qml.queuing.AnnotatedQueue() as q:
qml.PauliZ(0)
qml.RX(1.0, wires=0)
qml.CNOT(wires=[0, 2])
qml.Rot(2.0, 3.0, 4.0, wires=0)
qml.expval(qml.PauliZ(0))
tape = qml.tape.QuantumScript.from_queue(q)
tape.trainable_params = {0, 2}
gradient_recipes = ([[0.1, 0.2, 0.3], [0.4, 0.5, 0.6]], [[1, 1, 1], [2, 2, 2], [3, 3, 3]])
tapes, _ = qml.gradients.param_shift(tape, gradient_recipes=gradient_recipes)
assert len(tapes) == 5
assert [t.batch_size for t in tapes] == [None] * 5
assert tapes[0].get_parameters(trainable_only=False) == [0.2 * 1.0 + 0.3, 2.0, 3.0, 4.0]
assert tapes[1].get_parameters(trainable_only=False) == [0.5 * 1.0 + 0.6, 2.0, 3.0, 4.0]
assert tapes[2].get_parameters(trainable_only=False) == [1.0, 2.0, 1 * 3.0 + 1, 4.0]
assert tapes[3].get_parameters(trainable_only=False) == [1.0, 2.0, 2 * 3.0 + 2, 4.0]
assert tapes[4].get_parameters(trainable_only=False) == [1.0, 2.0, 3 * 3.0 + 3, 4.0]
@pytest.mark.parametrize("ops_with_custom_recipe", [[0], [1], [0, 1]])
def test_recycled_unshifted_tape(self, ops_with_custom_recipe):
"""Test that if the gradient recipe has a zero-shift component, then
the tape is executed only once using the current parameter
values."""
dev = qml.device("default.qubit", wires=2)
x = [0.543, -0.654]
with qml.queuing.AnnotatedQueue() as q:
qml.RX(x[0], wires=[0])
qml.RX(x[1], wires=[0])
qml.expval(qml.PauliZ(0))
tape = qml.tape.QuantumScript.from_queue(q)
gradient_recipes = tuple(
[[-1e7, 1, 0], [1e7, 1, 1e-7]] if i in ops_with_custom_recipe else None
for i in range(2)
)
tapes, fn = qml.gradients.param_shift(tape, gradient_recipes=gradient_recipes)
# two tapes per parameter that doesn't use a custom recipe,
# one tape per parameter that uses custom recipe,
# plus one global call if at least one uses the custom recipe
num_ops_standard_recipe = tape.num_params - len(ops_with_custom_recipe)
assert len(tapes) == 2 * num_ops_standard_recipe + len(ops_with_custom_recipe) + 1
# Test that executing the tapes and the postprocessing function works
grad = fn(qml.execute(tapes, dev, None))
assert qml.math.allclose(grad, -np.sin(x[0] + x[1]), atol=1e-5)
@pytest.mark.parametrize("ops_with_custom_recipe", [[0], [1], [0, 1]])
@pytest.mark.parametrize("multi_measure", [False, True])
def test_custom_recipe_unshifted_only(self, ops_with_custom_recipe, multi_measure):
"""Test that if the gradient recipe has a zero-shift component, then
the tape is executed only once using the current parameter
values."""
dev = qml.device("default.qubit", wires=2)
x = [0.543, -0.654]
with qml.queuing.AnnotatedQueue() as q:
qml.RX(x[0], wires=[0])
qml.RX(x[1], wires=[0])
qml.expval(qml.PauliZ(0))
if multi_measure:
qml.expval(qml.PauliZ(1))
tape = qml.tape.QuantumScript.from_queue(q)
gradient_recipes = tuple(
[[-1e7, 1, 0], [1e7, 1, 0]] if i in ops_with_custom_recipe else None for i in range(2)
)
tapes, fn = qml.gradients.param_shift(tape, gradient_recipes=gradient_recipes)
# two tapes per parameter that doesn't use a custom recipe,
# plus one global (unshifted) call if at least one uses the custom recipe
num_ops_standard_recipe = tape.num_params - len(ops_with_custom_recipe)
assert len(tapes) == 2 * num_ops_standard_recipe + int(
tape.num_params != num_ops_standard_recipe
)
# Test that executing the tapes and the postprocessing function works
grad = fn(qml.execute(tapes, dev, None))
if multi_measure:
expected = np.array([[-np.sin(x[0] + x[1])] * 2, [0, 0]])
# The custom recipe estimates gradients to be 0
for i in ops_with_custom_recipe:
expected[0, i] = 0
else:
expected = [
-np.sin(x[0] + x[1]) if i not in ops_with_custom_recipe else 0 for i in range(2)
]
assert qml.math.allclose(grad, expected, atol=1e-5)
@pytest.mark.parametrize("ops_with_custom_recipe", [[0], [1], [0, 1]])
def test_custom_recipe_mixing_unshifted_shifted(self, ops_with_custom_recipe):
"""Test that if the gradient recipe has a zero-shift component, then
the tape is executed only once using the current parameter
values."""
dev = qml.device("default.qubit", wires=2)
x = [0.543, -0.654]
with qml.queuing.AnnotatedQueue() as q:
qml.RX(x[0], wires=[0])
qml.RX(x[1], wires=[0])
qml.expval(qml.PauliZ(0))
qml.expval(qml.PauliZ(1))
tape = qml.tape.QuantumScript.from_queue(q)
gradient_recipes = tuple(
[[-1e-7, 1, 0], [1e-7, 1, 0], [-1e5, 1, -5e-6], [1e5, 1, 5e-6]]
if i in ops_with_custom_recipe
else None
for i in range(2)
)
tapes, fn = qml.gradients.param_shift(tape, gradient_recipes=gradient_recipes)
# two tapes per parameter, independent of recipe
# plus one global (unshifted) call if at least one uses the custom recipe
assert len(tapes) == 2 * tape.num_params + int(len(ops_with_custom_recipe) > 0)
# Test that executing the tapes and the postprocessing function works
grad = fn(qml.execute(tapes, dev, None))
assert qml.math.allclose(grad[0], -np.sin(x[0] + x[1]), atol=1e-5)
assert qml.math.allclose(grad[1], 0, atol=1e-5)
@pytest.mark.parametrize("y_wire", [0, 1])
def test_f0_provided(self, y_wire):
"""Test that if the original tape output is provided, then
the tape is not executed additionally at the current parameter
values."""
dev = qml.device("default.qubit", wires=2)
with qml.queuing.AnnotatedQueue() as q:
qml.RX(0.543, wires=[0])
qml.RY(-0.654, wires=y_wire)
qml.expval(qml.PauliZ(0))
tape = qml.tape.QuantumScript.from_queue(q)
gradient_recipes = ([[-1e7, 1, 0], [1e7, 1, 1e7]],) * 2
f0 = dev.execute(tape)
tapes, fn = qml.gradients.param_shift(tape, gradient_recipes=gradient_recipes, f0=f0)
# one tape per parameter that impacts the expval
assert len(tapes) == 2 if y_wire == 0 else 1
fn(dev.batch_execute(tapes))
def test_op_with_custom_unshifted_term(self):
"""Test that an operation with a gradient recipe that depends on
its instantiated parameter values works correctly within the parameter
shift rule. Also tests that grad_recipes supersedes paramter_frequencies.
"""
s = np.pi / 2
# pylint: disable=too-few-public-methods
class RX(qml.RX):
"""RX operation with an additional term in the grad recipe.
The grad_recipe no longer yields the derivative, but we account for this.
For this test, the presence of the unshifted term (with non-vanishing coefficient)
is essential."""
grad_recipe = ([[0.5, 1, s], [-0.5, 1, -s], [0.2, 1, 0]],)
x = np.array([-0.361, 0.654], requires_grad=True)
dev = qml.device("default.qubit", wires=2)
with qml.queuing.AnnotatedQueue() as q:
qml.RX(x[0], wires=0)
RX(x[1], wires=0)
qml.expval(qml.PauliZ(0))
tape = qml.tape.QuantumScript.from_queue(q)
tapes, fn = qml.gradients.param_shift(tape)
# Unshifted tapes always are first within the tapes created for one operation;
# They are not batched together because we trust operation recipes to be condensed already
expected_shifts = [[0, 0], [s, 0], [-s, 0], [0, s], [0, -s]]
assert len(tapes) == 5
for tape, expected in zip(tapes, expected_shifts):
assert tape.operations[0].data[0] == x[0] + expected[0]
assert tape.operations[1].data[0] == x[1] + expected[1]
grad = fn(dev.batch_execute(tapes))
exp = np.stack([-np.sin(x[0] + x[1]), -np.sin(x[0] + x[1]) + 0.2 * np.cos(x[0] + x[1])])
assert len(grad) == len(exp)
for (
a,
b,
) in zip(grad, exp):
assert np.allclose(a, b)
def test_independent_parameters_analytic(self):
"""Test the case where expectation values are independent of some parameters. For those
parameters, the gradient should be evaluated to zero without executing the device."""
dev = qml.device("default.qubit", wires=2)
with qml.queuing.AnnotatedQueue() as q1:
qml.RX(1.0, wires=[0])
qml.RX(1.0, wires=[1])
qml.expval(qml.PauliZ(0))
tape1 = qml.tape.QuantumScript.from_queue(q1)
with qml.queuing.AnnotatedQueue() as q2:
qml.RX(1.0, wires=[0])
qml.RX(1.0, wires=[1])
qml.expval(qml.PauliZ(1))
tape2 = qml.tape.QuantumScript.from_queue(q2)
tapes, fn = qml.gradients.param_shift(tape1)
j1 = fn(dev.batch_execute(tapes))
# We should only be executing the device twice: Two shifted evaluations to differentiate
# one parameter overall, as the other parameter does not impact the returned measurement.
assert dev.num_executions == 2
tapes, fn = qml.gradients.param_shift(tape2)
j2 = fn(dev.batch_execute(tapes))
exp = -np.sin(1)
assert np.allclose(j1[0], exp)
assert np.allclose(j1[1], 0)
assert np.allclose(j2[0], 0)
assert np.allclose(j2[1], exp)
def test_grad_recipe_parameter_dependent(self):
"""Test that an operation with a gradient recipe that depends on
its instantiated parameter values works correctly within the parameter
shift rule. Also tests that `grad_recipe` supersedes `parameter_frequencies`.
"""
x = np.array(0.654, requires_grad=True)
dev = qml.device("default.qubit", wires=2)
with qml.queuing.AnnotatedQueue() as q:
RX_par_dep_recipe(x, wires=0)
qml.expval(qml.PauliZ(0))
tape = qml.tape.QuantumScript.from_queue(q)
tapes, fn = qml.gradients.param_shift(tape)
assert len(tapes) == 2
assert [t.batch_size for t in tapes] == [None, None]
assert qml.math.allclose(tapes[0].operations[0].data[0], 0)
assert qml.math.allclose(tapes[1].operations[0].data[0], 2 * x)
grad = fn(dev.batch_execute(tapes))
assert np.allclose(grad, -np.sin(x))
def test_error_no_diff_info(self):
"""Test that an error is raised if no grad_recipe, no parameter_frequencies
and no generator are found."""
# pylint: disable=too-few-public-methods
class RX(qml.RX):
"""This copy of RX overwrites parameter_frequencies to report
missing information, disabling its differentiation."""
@property
def parameter_frequencies(self):
"""Raise an error instead of returning frequencies."""
raise qml.operation.ParameterFrequenciesUndefinedError
# pylint: disable=too-few-public-methods
class NewOp(qml.operation.Operation):
"""This new operation does not overwrite parameter_frequencies
but does not have a generator, disabling its differentiation."""
num_params = 1
grad_method = "A"
num_wires = 1
x = np.array(0.654, requires_grad=True)
for op in [RX, NewOp]:
with qml.queuing.AnnotatedQueue() as q:
op(x, wires=0)
qml.expval(qml.PauliZ(0))
tape = qml.tape.QuantumScript.from_queue(q)
with pytest.raises(
qml.operation.OperatorPropertyUndefined, match="does not have a grad_recipe"
):
qml.gradients.param_shift(tape)
class TestParamShiftWithBroadcasted:
"""Tests for the `param_shift` transform on already broadcasted tapes.
The tests for `param_shift` using broadcasting itself can be found
further below."""
@pytest.mark.parametrize("dim", [1, 3])
@pytest.mark.parametrize("pos", [0, 1])
def test_with_single_parameter_broadcasted(self, dim, pos):
"""Test that the parameter-shift transform works with a tape that has
one of its parameters broadcasted already."""
x = np.array([0.23, 9.1, 2.3])
x = x[:dim]
y = -0.654
if pos == 1:
x, y = y, x
with qml.queuing.AnnotatedQueue() as q:
qml.RX(x, wires=[0])
qml.RY(y, wires=[0]) # does not have any impact on the expval
qml.expval(qml.PauliZ(0))
tape = qml.tape.QuantumScript.from_queue(q)
assert tape.batch_size == dim
tapes, fn = qml.gradients.param_shift(tape, argnum=[0, 1])
assert len(tapes) == 4
assert np.allclose([t.batch_size for t in tapes], dim)
dev = qml.device("default.qubit", wires=2)
res = fn(dev.batch_execute(tapes))
assert isinstance(res, tuple)
assert len(res) == 2
assert res[0].shape == (dim,)
assert res[1].shape == (dim,)
@pytest.mark.parametrize("argnum", [(0, 2), (0, 1), (1,), (2,)])
@pytest.mark.parametrize("dim", [1, 3])
def test_with_multiple_parameters_broadcasted(self, dim, argnum):
"""Test that the parameter-shift transform works with a tape that has
multiple of its parameters broadcasted already."""
x, y = np.array([[0.23, 9.1, 2.3], [0.2, 1.2, -0.6]])[:, :dim]
z = -0.654
with qml.queuing.AnnotatedQueue() as q:
qml.RX(x, wires=[0])
qml.RZ(z, wires=[0])
qml.RY(y, wires=[0]) # does not have any impact on the expval
qml.expval(qml.PauliZ(0))
tape = qml.tape.QuantumScript.from_queue(q)
assert tape.batch_size == dim
tapes, fn = qml.gradients.param_shift(tape, argnum=argnum)
assert len(tapes) == 2 * len(argnum)
assert np.allclose([t.batch_size for t in tapes], dim)
dev = qml.device("default.qubit", wires=2)
res = fn(dev.batch_execute(tapes))
assert isinstance(res, tuple)
assert len(res) == 3
assert res[0].shape == res[1].shape == res[2].shape == (dim,)
class TestParamShiftUsingBroadcasting:
"""Tests for the `param_shift` function using broadcasting.
The tests for `param_shift` on already broadcasted tapes can be found above."""
def test_independent_parameter(self, mocker):
"""Test that an independent parameter is skipped
during the Jacobian computation."""
spy = mocker.spy(qml.gradients.parameter_shift, "expval_param_shift")
with qml.queuing.AnnotatedQueue() as q:
qml.RX(0.543, wires=[0])
qml.RY(-0.654, wires=[1]) # does not have any impact on the expval
qml.expval(qml.PauliZ(0))
tape = qml.tape.QuantumScript.from_queue(q)
dev = qml.device("default.qubit", wires=2)
tapes, fn = qml.gradients.param_shift(tape, broadcast=True)
assert len(tapes) == 1
assert tapes[0].batch_size == 2
res = fn(dev.batch_execute(tapes))
assert len(res) == 2
assert res[0].shape == ()
assert res[1].shape == ()
# only called for parameter 0
assert spy.call_args[0][0:2] == (tape, [0])
def test_with_gradient_recipes(self):
"""Test that the function behaves as expected"""
x, z0, y, z1 = 1.0, 2.0, 3.0, 4.0
with qml.queuing.AnnotatedQueue() as q: