-
Notifications
You must be signed in to change notification settings - Fork 551
/
test_default_qubit_tf.py
2315 lines (1839 loc) · 81.8 KB
/
test_default_qubit_tf.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-2020 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 and integration tests for the ``default.qubit.tf`` device.
"""
# pylint: disable=too-many-arguments,protected-access,too-many-public-methods
import numpy as np
import pytest
from gate_data import (
I,
X,
Y,
Z,
H,
S,
T,
CNOT,
CZ,
CCZ,
SWAP,
Toffoli,
CSWAP,
Rphi,
Rotx,
Roty,
Rotz,
Rot3,
CRotx,
CRoty,
CRotz,
CRot3,
MultiRZ1,
MultiRZ2,
ControlledPhaseShift,
OrbitalRotation,
FermionicSWAP,
)
import pennylane as qml
from pennylane import numpy as pnp
from pennylane import DeviceError
tf = pytest.importorskip("tensorflow", minversion="2.0")
from pennylane.devices.default_qubit_tf import ( # pylint: disable=wrong-import-position
DefaultQubitTF,
)
np.random.seed(42)
#####################################################
# Test matrices
#####################################################
U = np.array(
[
[0.83645892 - 0.40533293j, -0.20215326 + 0.30850569j],
[-0.23889780 - 0.28101519j, -0.88031770 - 0.29832709j],
]
)
U2 = np.array([[0, 1, 1, 1], [1, 0, 1, -1], [1, -1, 0, 1], [1, 1, -1, 0]]) / np.sqrt(3)
A = np.array([[1.02789352, 1.61296440 - 0.3498192j], [1.61296440 + 0.3498192j, 1.23920938 + 0j]])
#####################################################
# Define standard qubit operations
#####################################################
single_qubit = [
(qml.S, S),
(qml.T, T),
(qml.PauliX, X),
(qml.PauliY, Y),
(qml.PauliZ, Z),
(qml.Hadamard, H),
]
single_qubit_param = [
(qml.PhaseShift, Rphi),
(qml.RX, Rotx),
(qml.RY, Roty),
(qml.RZ, Rotz),
(qml.MultiRZ, MultiRZ1),
]
two_qubit = [(qml.CZ, CZ), (qml.CNOT, CNOT), (qml.SWAP, SWAP)]
two_qubit_param = [
(qml.CRX, CRotx),
(qml.CRY, CRoty),
(qml.CRZ, CRotz),
(qml.MultiRZ, MultiRZ2),
(qml.ControlledPhaseShift, ControlledPhaseShift),
(qml.FermionicSWAP, FermionicSWAP),
]
three_qubit = [(qml.Toffoli, Toffoli), (qml.CSWAP, CSWAP), (qml.CCZ, CCZ)]
four_qubit_param = [(qml.OrbitalRotation, OrbitalRotation)]
#####################################################
# Fixtures
#####################################################
# pylint: disable=unused-argument
@pytest.fixture(name="init_state")
def init_state_fixture(scope="session"):
"""Generates a random initial state"""
def _init_state(n):
"""random initial state"""
np.random.seed(4214152)
state = np.random.random([2**n]) + np.random.random([2**n]) * 1j
state /= np.linalg.norm(state)
return state
return _init_state
# pylint: disable=unused-argument
@pytest.fixture(name="broadcasted_init_state")
def broadcasted_init_state_fixture(scope="session"):
"""Generates a random initial state"""
def _broadcasted_init_state(n, batch_size):
"""random initial state"""
np.random.seed(4214152)
state = np.random.random([batch_size, 2**n]) + np.random.random([batch_size, 2**n]) * 1j
return state / np.linalg.norm(state, axis=1)[:, np.newaxis]
return _broadcasted_init_state
#####################################################
# Initialization test
#####################################################
@pytest.mark.tf
def test_analytic_deprecation():
"""Tests if the kwarg `analytic` is used and displays error message."""
msg = "The analytic argument has been replaced by shots=None. "
msg += "Please use shots=None instead of analytic=True."
with pytest.raises(
DeviceError,
match=msg,
):
qml.device("default.qubit.tf", wires=1, shots=1, analytic=True)
#####################################################
# Device-level matrix creation tests
#####################################################
@pytest.mark.tf
class TestTFMatrix:
"""Test special case of matrix construction in TensorFlow for
cases where variables must be casted to complex."""
@pytest.mark.parametrize(
"op,params,wires",
[
(qml.PhaseShift, [0.1], 0),
(qml.ControlledPhaseShift, [0.1], [0, 1]),
(qml.CRX, [0.1], [0, 1]),
(qml.CRY, [0.1], [0, 1]),
(qml.CRZ, [0.1], [0, 1]),
(qml.CRot, [0.1, 0.2, 0.3], [0, 1]),
(qml.U1, [0.1], 0),
(qml.U2, [0.1, 0.2], 0),
(qml.U3, [0.1, 0.2, 0.3], 0),
(qml.Rot, [0.1, 0.2, 0.3], 0),
],
)
def test_tf_matrix(self, op, params, wires):
tf_params = [tf.Variable(x) for x in params]
expected_mat = op(*params, wires=wires).matrix()
obtained_mat = op(*tf_params, wires=wires).matrix()
assert qml.math.get_interface(obtained_mat) == "tensorflow"
assert qml.math.allclose(qml.math.unwrap(obtained_mat), expected_mat)
@pytest.mark.parametrize(
"op,params,wires",
[
(qml.PhaseShift, ([0.1, 0.2, 0.5],), 0),
(qml.ControlledPhaseShift, ([0.1],), [0, 1]),
(qml.CRX, ([0.1, -0.6, 0.2],), [0, 1]),
(qml.CRY, ([0.1, -0.4, 6.3],), [0, 1]),
(qml.CRZ, ([0.1, -0.6, 0.2],), [0, 1]),
(qml.CRot, ([0.1, 0.2, 0.3], 0.6, [0.2, 1.2, 4.3]), [0, 1]),
(qml.U1, ([0.1, 0.2, 0.5],), 0),
(qml.U2, ([0.1, 0.2, 0.5], [0.6, 9.3, 2.1]), 0),
(qml.U3, ([0.1, 0.2, 0.3], 0.6, [0.2, 1.2, 4.3]), 0),
(qml.Rot, ([0.1, 0.2, 0.3], 0.6, [0.2, 1.2, 4.3]), 0),
],
)
def test_broadcasted_tf_matrix(self, op, params, wires):
params = [np.array(p) for p in params]
tf_params = [tf.Variable(x) for x in params]
expected_mat = op(*params, wires=wires).matrix()
obtained_mat = op(*tf_params, wires=wires).matrix()
assert qml.math.get_interface(obtained_mat) == "tensorflow"
assert qml.math.allclose(qml.math.unwrap(obtained_mat), expected_mat)
@pytest.mark.parametrize(
"param,pauli,wires",
[
(0.1, "I", "a"),
(0.2, "IX", ["a", "b"]),
(-0.3, "III", [0, 1, 2]),
(0.5, "ZXI", [0, 1, 2]),
# Broadcasted rotations
([0.1, 0.6], "I", "a"),
([0.2], "IX", ["a", "b"]),
([-0.3, 0.0, 0.2], "III", [0, 1, 2]),
([0.5, 0.2], "ZXI", [0, 1, 2]),
],
)
def test_pauli_rot_tf_(self, param, pauli, wires):
param = np.array(param)
op = qml.PauliRot(param, pauli, wires=wires)
expected_mat = op.matrix()
expected_eigvals = op.eigvals()
tf_op = qml.PauliRot(tf.Variable(param), pauli, wires=wires)
obtained_mat = tf_op.matrix()
obtained_eigvals = tf_op.eigvals()
assert qml.math.get_interface(obtained_mat) == "tensorflow"
assert qml.math.get_interface(obtained_eigvals) == "tensorflow"
assert qml.math.allclose(qml.math.unwrap(obtained_mat), expected_mat)
assert qml.math.allclose(qml.math.unwrap(obtained_eigvals), expected_eigvals)
@pytest.mark.parametrize(
"op,param,wires",
[
(qml.PhaseShift, 0.1, [1]),
(qml.ControlledPhaseShift, 0.1, [1, 2]),
(qml.CRZ, 0.1, [1, 2]),
(qml.U1, 0.1, [1]),
# broadcasted operation matrices
(qml.PhaseShift, np.array([0.1, 0.6]), [1]),
(qml.ControlledPhaseShift, np.array([0.1]), [1, 2]),
(qml.CRZ, np.array([0.1, 0.7, 8.3]), [1, 2]),
(qml.U1, np.array([0.1, 0.7, 8.3]), [1]),
],
)
def test_expand_tf_matrix(self, op, param, wires):
reg_mat = op(param, wires=wires).matrix()
if len(wires) == 1:
expected_mat = qml.math.kron(I, qml.math.kron(reg_mat, qml.math.kron(I, I)))
else:
expected_mat = qml.math.kron(I, qml.math.kron(reg_mat, I))
tf_mat = op(tf.Variable(param), wires=wires).matrix()
obtained_mat = qml.math.expand_matrix(tf_mat, wires, list(range(4)))
assert qml.math.get_interface(obtained_mat) == "tensorflow"
assert qml.math.allclose(qml.math.unwrap(obtained_mat), expected_mat)
#####################################################
# Device-level integration tests
#####################################################
@pytest.mark.tf
class TestApply:
"""Test application of PennyLane operations."""
def test_basis_state(self, tol):
"""Test basis state initialization"""
dev = DefaultQubitTF(wires=4)
state = np.array([0, 0, 1, 0])
dev.apply([qml.BasisState(state, wires=[0, 1, 2, 3])])
res = dev.state
expected = np.zeros([2**4])
expected[np.ravel_multi_index(state, [2] * 4)] = 1
assert isinstance(res, tf.Tensor)
assert np.allclose(res, expected, atol=tol, rtol=0)
def test_invalid_basis_state_length(self):
"""Test that an exception is raised if the basis state is the wrong size"""
dev = DefaultQubitTF(wires=4)
state = np.array([0, 0, 1, 0])
with pytest.raises(
ValueError, match=r"BasisState parameter and wires must be of equal length"
):
dev.apply([qml.BasisState(state, wires=[0, 1, 2])])
def test_invalid_basis_state(self):
"""Test that an exception is raised if the basis state is invalid"""
dev = DefaultQubitTF(wires=4)
state = np.array([0, 0, 1, 2])
with pytest.raises(
ValueError, match=r"BasisState parameter must consist of 0 or 1 integers"
):
dev.apply([qml.BasisState(state, wires=[0, 1, 2, 3])])
def test_state_prep(self, init_state, tol):
"""Test state prep application"""
dev = DefaultQubitTF(wires=1)
state = init_state(1)
dev.apply([qml.StatePrep(state, wires=[0])])
res = dev.state
expected = state
assert isinstance(res, tf.Tensor)
assert np.allclose(res, expected, atol=tol, rtol=0)
def test_full_subsystem_statevector(self, mocker):
"""Test applying a state vector to the full subsystem"""
dev = DefaultQubitTF(wires=["a", "b", "c"])
state = tf.constant([1, 0, 0, 0, 1, 0, 1, 1], dtype=tf.complex128) / 2.0
state_wires = qml.wires.Wires(["a", "b", "c"])
spy = mocker.spy(dev, "_scatter")
dev._apply_state_vector(state=state, device_wires=state_wires)
assert np.all(tf.reshape(dev._state, [-1]) == state)
spy.assert_not_called()
def test_partial_subsystem_statevector(self, mocker):
"""Test applying a state vector to a subset of wires of the full subsystem"""
dev = DefaultQubitTF(wires=["a", "b", "c"])
state = tf.constant([1, 0, 1, 0], dtype=tf.complex128) / np.sqrt(2.0)
state_wires = qml.wires.Wires(["a", "c"])
spy = mocker.spy(dev, "_scatter")
dev._apply_state_vector(state=state, device_wires=state_wires)
res = tf.reshape(tf.reduce_sum(dev._state, axis=(1,)), [-1])
assert np.all(res == state)
spy.assert_called()
def test_invalid_state_prep_size(self):
"""Test that an exception is raised if the state
vector is the wrong size"""
dev = DefaultQubitTF(wires=2)
state = np.array([0, 1])
with pytest.raises(ValueError, match=r"State vector must have shape \(2\*\*wires,\)"):
dev.apply([qml.StatePrep(state, wires=[0, 1])])
def test_invalid_state_prep_norm(self):
"""Test that an exception is raised if the state
vector is not normalized"""
dev = DefaultQubitTF(wires=2)
state = np.array([0, 12])
with pytest.raises(ValueError, match=r"Sum of amplitudes-squared does not equal one"):
dev.apply([qml.StatePrep(state, wires=[0])])
def test_invalid_state_prep(self):
"""Test that an exception is raised if a state preparation is not the
first operation in the circuit."""
dev = DefaultQubitTF(wires=2)
state = np.array([0, 1])
with pytest.raises(
qml.DeviceError,
match=r"cannot be used after other Operations have already been applied",
):
dev.apply([qml.PauliZ(0), qml.StatePrep(state, wires=[0])])
@pytest.mark.parametrize("op,mat", single_qubit)
def test_single_qubit_no_parameters(self, init_state, op, mat, tol):
"""Test non-parametrized single qubit operations"""
dev = DefaultQubitTF(wires=1)
state = init_state(1)
queue = [qml.StatePrep(state, wires=[0])]
queue += [op(wires=0)]
dev.apply(queue)
res = dev.state
expected = mat @ state
assert isinstance(res, tf.Tensor)
assert np.allclose(res, expected, atol=tol, rtol=0)
@pytest.mark.parametrize("theta", [0.5432, -0.232])
@pytest.mark.parametrize("op,func", single_qubit_param)
def test_single_qubit_parameters(self, init_state, op, func, theta, tol):
"""Test parametrized single qubit operations"""
dev = DefaultQubitTF(wires=1)
state = init_state(1)
queue = [qml.StatePrep(state, wires=[0])]
queue += [op(theta, wires=0)]
dev.apply(queue)
res = dev.state
expected = func(theta) @ state
assert np.allclose(res, expected, atol=tol, rtol=0)
def test_rotation(self, init_state, tol):
"""Test three axis rotation gate"""
dev = DefaultQubitTF(wires=1)
state = init_state(1)
a = 0.542
b = 1.3432
c = -0.654
queue = [qml.StatePrep(state, wires=[0])]
queue += [qml.Rot(a, b, c, wires=0)]
dev.apply(queue)
res = dev.state
expected = Rot3(a, b, c) @ state
assert np.allclose(res, expected, atol=tol, rtol=0)
def test_controlled_rotation(self, init_state, tol):
"""Test three axis controlled-rotation gate"""
dev = DefaultQubitTF(wires=2)
state = init_state(2)
a = 0.542
b = 1.3432
c = -0.654
queue = [qml.StatePrep(state, wires=[0, 1])]
queue += [qml.CRot(a, b, c, wires=[0, 1])]
dev.apply(queue)
res = dev.state
expected = CRot3(a, b, c) @ state
assert np.allclose(res, expected, atol=tol, rtol=0)
@pytest.mark.parametrize("op,mat", two_qubit)
def test_two_qubit_no_parameters(self, init_state, op, mat, tol):
"""Test non-parametrized two qubit operations"""
dev = DefaultQubitTF(wires=2)
state = init_state(2)
queue = [qml.StatePrep(state, wires=[0, 1])]
queue += [op(wires=[0, 1])]
dev.apply(queue)
res = dev.state
expected = mat @ state
assert np.allclose(res, expected, atol=tol, rtol=0)
@pytest.mark.parametrize("mat", [U, U2])
def test_qubit_unitary(self, init_state, mat, tol):
"""Test application of arbitrary qubit unitaries"""
N = int(np.log2(len(mat)))
dev = DefaultQubitTF(wires=N)
state = init_state(N)
queue = [qml.StatePrep(state, wires=range(N))]
queue += [qml.QubitUnitary(mat, wires=range(N))]
dev.apply(queue)
res = dev.state
expected = mat @ state
assert np.allclose(res, expected, atol=tol, rtol=0)
@pytest.mark.parametrize("op, mat", three_qubit)
def test_three_qubit_no_parameters(self, init_state, op, mat, tol):
"""Test non-parametrized three qubit operations"""
dev = DefaultQubitTF(wires=3)
state = init_state(3)
queue = [qml.StatePrep(state, wires=[0, 1, 2])]
queue += [op(wires=[0, 1, 2])]
dev.apply(queue)
res = dev.state
expected = mat @ state
assert np.allclose(res, expected, atol=tol, rtol=0)
@pytest.mark.parametrize("theta", [0.5432, -0.232])
@pytest.mark.parametrize("op,func", two_qubit_param)
def test_two_qubit_parameters(self, init_state, op, func, theta, tol):
"""Test two qubit parametrized operations"""
dev = DefaultQubitTF(wires=2)
state = init_state(2)
queue = [qml.StatePrep(state, wires=[0, 1])]
queue += [op(theta, wires=[0, 1])]
dev.apply(queue)
res = dev.state
expected = func(theta) @ state
assert np.allclose(res, expected, atol=tol, rtol=0)
@pytest.mark.parametrize("theta", [0.5432, -0.232])
@pytest.mark.parametrize("op,func", four_qubit_param)
def test_four_qubit_parameters(self, init_state, op, func, theta, tol):
"""Test four qubit parametrized operations"""
dev = DefaultQubitTF(wires=4)
state = init_state(4)
queue = [qml.StatePrep(state, wires=[0, 1, 2, 3])]
queue += [op(theta, wires=[0, 1, 2, 3])]
dev.apply(queue)
res = dev.state
expected = func(theta) @ state
assert np.allclose(res, expected, atol=tol, rtol=0)
def test_apply_ops_not_supported(self, mocker, monkeypatch):
"""Test that when a version of TensorFlow before 2.3.0 is used, the _apply_ops dictionary is
empty and application of a CNOT gate is performed using _apply_unitary_einsum"""
with monkeypatch.context() as m:
m.setattr("pennylane.devices.default_qubit_tf.SUPPORTS_APPLY_OPS", False)
dev = DefaultQubitTF(wires=3)
assert dev._apply_ops == {}
spy = mocker.spy(DefaultQubitTF, "_apply_unitary_einsum")
queue = [qml.CNOT(wires=[1, 2])]
dev.apply(queue)
spy.assert_called_once()
def test_apply_ops_above_8_wires(self, mocker):
"""Test that when 9 wires are used, the _apply_ops dictionary is empty and application of a
CNOT gate is performed using _apply_unitary_einsum"""
dev = DefaultQubitTF(wires=9)
assert dev._apply_ops == {}
spy = mocker.spy(DefaultQubitTF, "_apply_unitary_einsum")
queue = [qml.CNOT(wires=[1, 2])]
dev.apply(queue)
spy.assert_called_once()
@pytest.mark.xfail(
raises=tf.errors.UnimplementedError,
reason="Slicing is not supported for more than 8 wires",
strict=True,
)
def test_apply_ops_above_8_wires_using_special(self):
"""Test that special apply methods that involve slicing function correctly when using 9
wires"""
dev = DefaultQubitTF(wires=9)
dev._apply_ops = {"CNOT": dev._apply_cnot}
queue = [qml.CNOT(wires=[1, 2])]
dev.apply(queue)
def test_do_not_split_analytic_tf(self, mocker):
"""Tests that the Hamiltonian is not split for shots=None using the tf device."""
dev = qml.device("default.qubit.tf", wires=2)
ham = qml.Hamiltonian(tf.Variable([0.1, 0.2]), [qml.PauliX(0), qml.PauliZ(1)])
@qml.qnode(dev, diff_method="backprop", interface="tf")
def circuit():
return qml.expval(ham)
spy = mocker.spy(dev, "expval")
circuit()
# evaluated one expval altogether
assert spy.call_count == 1
@pytest.mark.tf
class TestApplyBroadcasted:
"""Test application of broadcasted PennyLane operations."""
@pytest.mark.skip("Applying a BasisState does not support broadcasting yet")
def test_basis_state_broadcasted(self, tol):
"""Test basis state initialization"""
dev = DefaultQubitTF(wires=4)
state = np.array([0, 0, 1, 0])
dev.apply([qml.BasisState(state, wires=[0, 1, 2, 3])])
res = dev.state
expected = np.zeros([2**4])
expected[np.ravel_multi_index(state, [2] * 4)] = 1
assert isinstance(res, tf.Tensor)
assert np.allclose(res, expected, atol=tol, rtol=0)
@pytest.mark.skip("Applying a BasisState does not support broadcasting yet")
def test_invalid_basis_state_length_broadcasted(self):
"""Test that an exception is raised if the basis state is the wrong size"""
dev = DefaultQubitTF(wires=4)
state = np.array([0, 0, 1, 0])
with pytest.raises(
ValueError, match=r"BasisState parameter and wires must be of equal length"
):
dev.apply([qml.BasisState(state, wires=[0, 1, 2])])
@pytest.mark.skip("Applying a BasisState does not support broadcasting yet")
def test_invalid_basis_state_broadcasted(self):
"""Test that an exception is raised if the basis state is invalid"""
dev = DefaultQubitTF(wires=4)
state = np.array([0, 0, 1, 2])
with pytest.raises(
ValueError, match=r"BasisState parameter must consist of 0 or 1 integers"
):
dev.apply([qml.BasisState(state, wires=[0, 1, 2, 3])])
@pytest.mark.parametrize("batch_size", [1, 3])
def test_qubit_state_vector_broadcasted(self, broadcasted_init_state, tol, batch_size):
"""Test broadcasted qubit state vector application"""
dev = DefaultQubitTF(wires=1)
state = broadcasted_init_state(1, batch_size=batch_size)
dev.apply([qml.StatePrep(state, wires=[0])])
res = dev.state
expected = state
assert isinstance(res, tf.Tensor)
assert np.allclose(res, expected, atol=tol, rtol=0)
def test_full_subsystem_statevector_broadcasted(self, mocker):
"""Test applying a broadcasted state vector to the full subsystem"""
dev = DefaultQubitTF(wires=["a", "b", "c"])
state = (
tf.constant(
[[1, 0, 0, 0, 1, 0, 1, 1], [1, 1, 1, 1, 0, 0, 0, 0], [0, 0, 1, 1, 0, 1, 0, 1]],
dtype=tf.complex128,
)
/ 2
)
state_wires = qml.wires.Wires(["a", "b", "c"])
spy = mocker.spy(dev, "_scatter")
dev._apply_state_vector(state=state, device_wires=state_wires)
assert np.all(tf.reshape(dev._state, [3, 8]) == state)
spy.assert_not_called()
def test_error_partial_subsystem_statevector_broadcasted(self):
"""Test applying a broadcasted state vector to a subset of wires of the full subsystem"""
dev = DefaultQubitTF(wires=["a", "b", "c"])
state = tf.constant(
[[1, 0, 1, 0], [1, 1, 0, 0], [0, 1, 1, 0]], dtype=tf.complex128
) / np.sqrt(2.0)
state_wires = qml.wires.Wires(["a", "c"])
with pytest.raises(NotImplementedError, match="Parameter broadcasting is not supported"):
dev._apply_state_vector(state=state, device_wires=state_wires)
def test_invalid_qubit_state_vector_size_broadcasted(self):
"""Test that an exception is raised if the broadcasted state
vector is the wrong size"""
dev = DefaultQubitTF(wires=2)
state = np.array([[0, 1], [1, 0], [1, 1], [0, 0]])
with pytest.raises(ValueError, match=r"State vector must have shape \(2\*\*wires,\)"):
dev.apply([qml.StatePrep(state, wires=[0, 1])])
def test_invalid_qubit_state_vector_norm_broadcasted(self):
"""Test that an exception is raised if the broadcasted state
vector is not normalized"""
dev = DefaultQubitTF(wires=2)
state = np.array([[1, 0], [0, 12], [1.3, 1]])
with pytest.raises(ValueError, match=r"Sum of amplitudes-squared does not equal one"):
dev.apply([qml.StatePrep(state, wires=[0])])
@pytest.mark.parametrize("op,mat", single_qubit)
def test_single_qubit_no_parameters_broadcasted(self, broadcasted_init_state, op, mat, tol):
"""Test non-parametrized single qubit operations"""
dev = DefaultQubitTF(wires=1)
state = broadcasted_init_state(1, 3)
queue = [qml.StatePrep(state, wires=[0])]
queue += [op(wires=0)]
dev.apply(queue)
res = dev.state
expected = np.einsum("ij,kj->ki", mat, state)
assert isinstance(res, tf.Tensor)
assert np.allclose(res, expected, atol=tol, rtol=0)
@pytest.mark.parametrize("theta", [0.5432, -0.232])
@pytest.mark.parametrize("op,func", single_qubit_param)
def test_single_qubit_parameters_broadcasted_state(
self, broadcasted_init_state, op, func, theta, tol
):
"""Test parametrized single qubit operations with broadcasted initial state"""
dev = DefaultQubitTF(wires=1)
state = broadcasted_init_state(1, 3)
queue = [qml.StatePrep(state, wires=[0])]
queue += [op(theta, wires=0)]
dev.apply(queue)
res = dev.state
expected = np.einsum("ij,kj->ki", func(theta), state)
assert np.allclose(res, expected, atol=tol, rtol=0)
@pytest.mark.parametrize("theta", [[np.pi / 3], [0.5432, -0.232, 0.1]])
@pytest.mark.parametrize("op,func", single_qubit_param)
def test_single_qubit_parameters_broadcasted_par(self, init_state, op, func, theta, tol):
"""Test parametrized single qubit operations with broadcasted parameters"""
theta = np.array(theta)
dev = DefaultQubitTF(wires=1)
state = init_state(1)
queue = [qml.StatePrep(state, wires=[0])]
queue += [op(theta, wires=0)]
dev.apply(queue)
res = dev.state
mat = np.array([func(t) for t in theta])
expected = np.einsum("lij,j->li", mat, state)
assert np.allclose(res, expected, atol=tol, rtol=0)
@pytest.mark.parametrize("theta", [[np.pi / 3], [0.5432, -0.232, 0.1]])
@pytest.mark.parametrize("op,func", single_qubit_param)
def test_single_qubit_parameters_broadcasted_both(
self, broadcasted_init_state, op, func, theta, tol
):
"""Test parametrized single qubit operations with broadcasted init state and parameters"""
theta = np.array(theta)
dev = DefaultQubitTF(wires=1)
state = broadcasted_init_state(1, batch_size=len(theta))
queue = [qml.StatePrep(state, wires=[0])]
queue += [op(theta, wires=0)]
dev.apply(queue)
res = dev.state
mat = np.array([func(t) for t in theta])
expected = np.einsum("lij,lj->li", mat, state)
assert np.allclose(res, expected, atol=tol, rtol=0)
def test_rotation_broadcasted_state(self, broadcasted_init_state, tol):
"""Test three axis rotation gate with broadcasted state"""
dev = DefaultQubitTF(wires=1)
state = broadcasted_init_state(1, 3)
a = 0.542
b = 1.3432
c = -0.654
queue = [qml.StatePrep(state, wires=[0])]
queue += [qml.Rot(a, b, c, wires=0)]
dev.apply(queue)
res = dev.state
expected = np.einsum("ij,lj->li", Rot3(a, b, c), state)
assert np.allclose(res, expected, atol=tol, rtol=0)
def test_rotation_broadcasted_par(self, init_state, tol):
"""Test three axis rotation gate with broadcasted parameters"""
dev = DefaultQubitTF(wires=1)
state = init_state(1)
a = np.array([0.542, 0.96, 0.213])
b = -0.654
c = np.array([1.3432, 0.6324, 6.32])
queue = [qml.StatePrep(state, wires=[0])]
queue += [qml.Rot(a, b, c, wires=0)]
dev.apply(queue)
res = dev.state
mat = np.array([Rot3(_a, b, _c) for _a, _c in zip(a, c)])
expected = np.einsum("lij,j->li", mat, state)
assert np.allclose(res, expected, atol=tol, rtol=0)
def test_rotation_broadcasted_both(self, broadcasted_init_state, tol):
"""Test three axis rotation gate with broadcasted state and parameters"""
dev = DefaultQubitTF(wires=1)
state = broadcasted_init_state(1, 3)
a = np.array([0.542, 0.96, 0.213])
b = np.array([1.3432, 0.6324, 6.32])
c = -0.654
queue = [qml.StatePrep(state, wires=[0])]
queue += [qml.Rot(a, b, c, wires=0)]
dev.apply(queue)
res = dev.state
mat = np.array([Rot3(_a, _b, c) for _a, _b in zip(a, b)])
expected = np.einsum("lij,lj->li", mat, state)
assert np.allclose(res, expected, atol=tol, rtol=0)
def test_controlled_rotation_broadcasted_state(self, broadcasted_init_state, tol):
"""Test controlled three axis rotation gate with broadcasted state"""
dev = DefaultQubitTF(wires=2)
state = broadcasted_init_state(2, 3)
a = 0.542
b = 1.3432
c = -0.654
queue = [qml.StatePrep(state, wires=[0, 1])]
queue += [qml.CRot(a, b, c, wires=[0, 1])]
dev.apply(queue)
res = dev.state
expected = np.einsum("ij,lj->li", CRot3(a, b, c), state)
assert np.allclose(res, expected, atol=tol, rtol=0)
def test_controlled_rotation_broadcasted_par(self, init_state, tol):
"""Test controlled three axis rotation gate with broadcasted parameters"""
dev = DefaultQubitTF(wires=2)
state = init_state(2)
a = np.array([0.542, 0.96, 0.213])
b = -0.654
c = np.array([1.3432, 0.6324, 6.32])
queue = [qml.StatePrep(state, wires=[0, 1])]
queue += [qml.CRot(a, b, c, wires=[0, 1])]
dev.apply(queue)
res = dev.state
mat = np.array([CRot3(_a, b, _c) for _a, _c in zip(a, c)])
expected = np.einsum("lij,j->li", mat, state)
assert np.allclose(res, expected, atol=tol, rtol=0)
def test_controlled_rotation_broadcasted_both(self, broadcasted_init_state, tol):
"""Test controlled three axis rotation gate with broadcasted state and parameters"""
dev = DefaultQubitTF(wires=2)
state = broadcasted_init_state(2, 3)
a = np.array([0.542, 0.96, 0.213])
b = np.array([1.3432, 0.6324, 6.32])
c = -0.654
queue = [qml.StatePrep(state, wires=[0, 1])]
queue += [qml.CRot(a, b, c, wires=[0, 1])]
dev.apply(queue)
res = dev.state
mat = np.array([CRot3(_a, _b, c) for _a, _b in zip(a, b)])
expected = np.einsum("lij,lj->li", mat, state)
assert np.allclose(res, expected, atol=tol, rtol=0)
@pytest.mark.parametrize("op,mat", two_qubit)
def test_two_qubit_no_parameters_broadcasted(self, broadcasted_init_state, op, mat, tol):
"""Test non-parametrized two qubit operations"""
dev = DefaultQubitTF(wires=2)
state = broadcasted_init_state(2, 3)
queue = [qml.StatePrep(state, wires=[0, 1])]
queue += [op(wires=[0, 1])]
dev.apply(queue)
res = dev.state
expected = np.einsum("ij,lj->li", mat, state)
assert np.allclose(res, expected, atol=tol, rtol=0)
@pytest.mark.parametrize("mat", [U, U2])
def test_qubit_unitary_broadcasted_state(self, broadcasted_init_state, mat, tol):
"""Test application of arbitrary qubit unitaries for broadcasted state"""
N = int(np.log2(len(mat)))
dev = DefaultQubitTF(wires=N)
state = broadcasted_init_state(N, 3)
queue = [qml.StatePrep(state, wires=range(N))]
queue += [qml.QubitUnitary(mat, wires=range(N))]
dev.apply(queue)
res = dev.state
expected = np.einsum("ij,lj->li", mat, state)
assert np.allclose(res, expected, atol=tol, rtol=0)
@pytest.mark.parametrize("mat", [U, U2])
def test_qubit_unitary_broadcasted_par(self, init_state, mat, tol):
"""Test application of broadcasted arbitrary qubit unitaries"""
mat = np.array([mat, mat, mat])
N = int(np.log2(mat.shape[-1]))
dev = DefaultQubitTF(wires=N)
state = init_state(N)
queue = [qml.StatePrep(state, wires=range(N))]
queue += [qml.QubitUnitary(mat, wires=range(N))]
dev.apply(queue)
res = dev.state
expected = np.einsum("lij,j->li", mat, state)
assert np.allclose(res, expected, atol=tol, rtol=0)
@pytest.mark.parametrize("mat", [U, U2])
def test_qubit_unitary_broadcasted_both(self, broadcasted_init_state, mat, tol):
"""Test application of arbitrary qubit unitaries for broadcasted state and parameters"""
mat = np.array([mat, mat, mat])
N = int(np.log2(mat.shape[-1]))
dev = DefaultQubitTF(wires=N)
state = broadcasted_init_state(N, 3)
queue = [qml.StatePrep(state, wires=range(N))]
queue += [qml.QubitUnitary(mat, wires=range(N))]
dev.apply(queue)
res = dev.state
expected = np.einsum("lij,lj->li", mat, state)
assert np.allclose(res, expected, atol=tol, rtol=0)
@pytest.mark.parametrize("op, mat", three_qubit)
def test_three_qubit_no_parameters_broadcasted(self, broadcasted_init_state, op, mat, tol):
"""Test broadcasted non-parametrized three qubit operations"""
dev = DefaultQubitTF(wires=3)
state = broadcasted_init_state(3, 2)
queue = [qml.StatePrep(state, wires=[0, 1, 2])]
queue += [op(wires=[0, 1, 2])]
dev.apply(queue)
res = dev.state
expected = np.einsum("ij,lj->li", mat, state)
assert np.allclose(res, expected, atol=tol, rtol=0)
def test_direct_eval_hamiltonian_broadcasted_error_tf(self):
"""Tests that an error is raised when attempting to evaluate a Hamiltonian with
broadcasting and shots=None directly via its sparse representation with TF."""
dev = qml.device("default.qubit.tf", wires=2)
ham = qml.Hamiltonian(tf.Variable([0.1, 0.2]), [qml.PauliX(0), qml.PauliZ(1)])
@qml.qnode(dev, diff_method="backprop", interface="tf")
def circuit():
qml.RX(np.zeros(5), 0) # Broadcast the state by applying a broadcasted identity
return qml.expval(ham)
with pytest.raises(NotImplementedError, match="Hamiltonians for interface!=None"):
circuit()
THETA = np.linspace(0.11, 1, 3)
PHI = np.linspace(0.32, 1, 3)
VARPHI = np.linspace(0.02, 1, 3)
scalar_angles = list(zip(THETA, PHI, VARPHI))
broadcasted_angles = [(THETA, PHI, VARPHI), (THETA[0], PHI, VARPHI)]
all_angles = scalar_angles + broadcasted_angles
# pylint: disable=unused-argument
@pytest.mark.tf
@pytest.mark.parametrize("theta, phi, varphi", all_angles)
class TestExpval:
"""Test expectation values"""
# test data; each tuple is of the form (GATE, OBSERVABLE, EXPECTED)
single_wire_expval_test_data = [
(
qml.RX,
qml.Identity,
lambda t, p: np.array(
[np.ones_like(t) * np.ones_like(p), np.ones_like(t) * np.ones_like(p)]
),
),
(
qml.RX,
qml.PauliZ,
lambda t, p: np.array([np.cos(t) * np.ones_like(p), np.cos(t) * np.cos(p)]),
),
(
qml.RY,
qml.PauliX,
lambda t, p: np.array([np.sin(t) * np.sin(p), np.sin(p) * np.ones_like(t)]),
),
(
qml.RX,
qml.PauliY,
lambda t, p: np.array([np.zeros_like(t) * np.zeros_like(p), -np.cos(t) * np.sin(p)]),
),
(
qml.RY,
qml.Hadamard,
lambda t, p: np.array(
[np.sin(t) * np.sin(p) + np.cos(t), np.cos(t) * np.cos(p) + np.sin(p)]
)
/ np.sqrt(2),
),
]
@pytest.mark.parametrize("gate,obs,expected", single_wire_expval_test_data)
def test_single_wire_expectation(self, gate, obs, expected, theta, phi, varphi, tol):
"""Test that identity expectation value (i.e. the trace) is 1"""
dev = DefaultQubitTF(wires=2)
with qml.queuing.AnnotatedQueue() as q:
_ = [gate(theta, wires=0), gate(phi, wires=1), qml.CNOT(wires=[0, 1])]