-
Notifications
You must be signed in to change notification settings - Fork 558
/
test_default_qubit_2.py
2122 lines (1676 loc) · 80.1 KB
/
test_default_qubit_2.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 default qubit 2."""
# pylint: disable=import-outside-toplevel, no-member
import pytest
import numpy as np
import pennylane as qml
from pennylane.measurements import SampleMP, StateMP, ProbabilityMP
from pennylane.resource import Resources
from pennylane.devices import DefaultQubit, ExecutionConfig
from pennylane.devices.qubit.preprocess import validate_and_expand_adjoint
def test_name():
"""Tests the name of DefaultQubit."""
assert DefaultQubit().name == "default.qubit"
def test_shots():
"""Test the shots property of DefaultQubit."""
assert DefaultQubit().shots == qml.measurements.Shots(None)
assert DefaultQubit(shots=100).shots == qml.measurements.Shots(100)
with pytest.raises(AttributeError):
DefaultQubit().shots = 10
def test_wires():
"""Test that a device can be created with wires."""
assert DefaultQubit().wires is None
assert DefaultQubit(wires=2).wires == qml.wires.Wires([0, 1])
assert DefaultQubit(wires=[0, 2]).wires == qml.wires.Wires([0, 2])
with pytest.raises(AttributeError):
DefaultQubit().wires = [0, 1]
def test_debugger_attribute():
"""Test that DefaultQubit has a debugger attribute and that it is `None`"""
# pylint: disable=protected-access
dev = DefaultQubit()
assert hasattr(dev, "_debugger")
assert dev._debugger is None
class TestSnapshotMulti:
def test_snapshot_multiprocessing_execute(self):
"""DefaultQubit cannot execute tapes with Snapshot if `max_workers` is not `None`"""
dev = DefaultQubit(max_workers=2)
tape = qml.tape.QuantumScript(
[
qml.Snapshot(),
qml.Hadamard(wires=0),
qml.Snapshot("very_important_state"),
qml.CNOT(wires=[0, 1]),
qml.Snapshot(),
],
[qml.expval(qml.PauliX(0))],
)
with pytest.raises(
RuntimeError, match="ProcessPoolExecutor cannot execute a QuantumScript"
):
program, _ = dev.preprocess()
program([tape])
def test_snapshot_multiprocessing_qnode(self):
"""DefaultQubit cannot execute tapes with Snapshot if `max_workers` is not `None`"""
dev = DefaultQubit(max_workers=2)
@qml.qnode(dev)
def circuit():
qml.Snapshot("tag")
qml.Hadamard(wires=0)
qml.CNOT(wires=[0, 1])
qml.Snapshot()
return qml.expval(qml.PauliX(0) + qml.PauliY(0))
with pytest.raises(
qml.DeviceError,
match="Debugging with ``Snapshots`` is not available with multiprocessing.",
):
qml.snapshots(circuit)()
class TestTracking:
"""Testing the tracking capabilities of DefaultQubit."""
def test_tracker_set_upon_initialization(self):
"""Test that a new tracker is intialized with each device."""
assert DefaultQubit().tracker is not DefaultQubit().tracker
def test_tracker_not_updated_if_not_active(self):
"""Test that the tracker is not updated if not active."""
dev = DefaultQubit()
assert len(dev.tracker.totals) == 0
dev.execute(qml.tape.QuantumScript())
assert len(dev.tracker.totals) == 0
assert len(dev.tracker.history) == 0
def test_tracking_batch(self):
"""Test that the new default qubit integrates with the tracker."""
qs = qml.tape.QuantumScript([], [qml.expval(qml.PauliZ(0))])
dev = DefaultQubit()
config = ExecutionConfig(gradient_method="adjoint")
with qml.Tracker(dev) as tracker:
dev.execute(qs)
dev.compute_derivatives(qs, config)
dev.execute([qs, qs]) # and a second time
assert tracker.history == {
"batches": [1, 1],
"executions": [1, 2],
"resources": [Resources(num_wires=1), Resources(num_wires=1), Resources(num_wires=1)],
"derivative_batches": [1],
"derivatives": [1],
}
assert tracker.totals == {
"batches": 2,
"executions": 3,
"derivative_batches": 1,
"derivatives": 1,
}
assert tracker.latest == {"batches": 1, "executions": 2}
def test_tracking_execute_and_derivatives(self):
"""Test that the execute_and_compute_* calls are being tracked for the
new default qubit device"""
qs = qml.tape.QuantumScript([], [qml.expval(qml.PauliZ(0))])
dev = DefaultQubit()
config = ExecutionConfig(gradient_method="adjoint")
with qml.Tracker(dev) as tracker:
dev.compute_derivatives(qs, config)
dev.execute_and_compute_derivatives([qs] * 2, config)
dev.compute_jvp([qs] * 3, [(0,)] * 3, config)
dev.execute_and_compute_jvp([qs] * 4, [(0,)] * 4, config)
dev.compute_vjp([qs] * 5, [(0,)] * 5, config)
dev.execute_and_compute_vjp([qs] * 6, [(0,)] * 6, config)
assert tracker.history == {
"executions": [2, 4, 6],
"derivatives": [1, 2],
"derivative_batches": [1],
"execute_and_derivative_batches": [1],
"jvps": [3, 4],
"jvp_batches": [1],
"execute_and_jvp_batches": [1],
"vjps": [5, 6],
"vjp_batches": [1],
"execute_and_vjp_batches": [1],
"resources": [Resources(num_wires=1)] * 12,
}
def test_tracking_resources(self):
"""Test that resources are tracked for the new default qubit device."""
qs = qml.tape.QuantumScript(
[
qml.Hadamard(0),
qml.Hadamard(1),
qml.CNOT(wires=[0, 2]),
qml.RZ(1.23, 1),
qml.CNOT(wires=[1, 2]),
qml.Hadamard(0),
],
[qml.expval(qml.PauliZ(1)), qml.expval(qml.PauliY(2))],
)
expected_resources = Resources(
num_wires=3,
num_gates=6,
gate_types={"Hadamard": 3, "CNOT": 2, "RZ": 1},
gate_sizes={1: 4, 2: 2},
depth=3,
)
dev = DefaultQubit()
with qml.Tracker(dev) as tracker:
dev.execute(qs)
assert len(tracker.history["resources"]) == 1
assert tracker.history["resources"][0] == expected_resources
def test_tracking_batched_execution(self):
"""Test the number of times the device is executed over a QNode's
lifetime is tracked by the device's tracker."""
dev_1 = qml.device("default.qubit", wires=2)
def circuit_1(x, y):
qml.RX(x, wires=[0])
qml.RY(y, wires=[1])
qml.CNOT(wires=[0, 1])
return qml.expval(qml.PauliZ(0) @ qml.PauliX(1))
node_1 = qml.QNode(circuit_1, dev_1)
num_evals_1 = 10
with qml.Tracker(dev_1, persistent=True) as tracker1:
for _ in range(num_evals_1):
node_1(0.432, np.array([0.12, 0.5, 3.2]))
assert tracker1.totals["executions"] == num_evals_1
# test a second instance of a default qubit device
dev_2 = qml.device("default.qubit", wires=2)
def circuit_2(x):
qml.RX(x, wires=[0])
qml.CNOT(wires=[0, 1])
return qml.expval(qml.PauliZ(0) @ qml.PauliX(1))
node_2 = qml.QNode(circuit_2, dev_2)
num_evals_2 = 5
with qml.Tracker(dev_2) as tracker2:
for _ in range(num_evals_2):
node_2(np.array([0.432, 0.61, 8.2]))
assert tracker2.totals["executions"] == num_evals_2
# test a new circuit on an existing instance of a qubit device
def circuit_3(y):
qml.RY(y, wires=[1])
qml.CNOT(wires=[0, 1])
return qml.expval(qml.PauliZ(0) @ qml.PauliX(1))
node_3 = qml.QNode(circuit_3, dev_1)
num_evals_3 = 7
with tracker1:
for _ in range(num_evals_3):
node_3(np.array([0.12, 1.214]))
assert tracker1.totals["executions"] == num_evals_1 + num_evals_3
# pylint: disable=too-few-public-methods
class TestPreprocessing:
"""Unit tests for the preprocessing method."""
def test_chooses_best_gradient_method(self):
"""Test that preprocessing chooses backprop as the best gradient method."""
dev = DefaultQubit()
config = ExecutionConfig(
gradient_method="best", use_device_gradient=None, grad_on_execution=None
)
_, new_config = dev.preprocess(config)
assert new_config.gradient_method == "backprop"
assert new_config.use_device_gradient
assert not new_config.grad_on_execution
def test_config_choices_for_adjoint(self):
"""Test that preprocessing request grad on execution and says to use the device gradient if adjoint is requested."""
dev = DefaultQubit()
config = ExecutionConfig(
gradient_method="adjoint", use_device_gradient=None, grad_on_execution=None
)
_, new_config = dev.preprocess(config)
assert new_config.use_device_gradient
assert new_config.grad_on_execution
@pytest.mark.parametrize("max_workers", [None, 1, 2, 3])
def test_config_choices_for_threading(self, max_workers):
"""Test that preprocessing request grad on execution and says to use the device gradient if adjoint is requested."""
dev = DefaultQubit()
config = ExecutionConfig(device_options={"max_workers": max_workers})
_, new_config = dev.preprocess(config)
assert new_config.device_options["max_workers"] == max_workers
def test_circuit_wire_validation(self):
"""Test that preprocessing validates wires on the circuits being executed."""
dev = DefaultQubit(wires=3)
circuit_valid_0 = qml.tape.QuantumScript([qml.PauliX(0)])
program, _ = dev.preprocess()
circuits, _ = program([circuit_valid_0])
assert circuits == (circuit_valid_0,)
circuit_valid_1 = qml.tape.QuantumScript([qml.PauliX(1)])
program, _ = dev.preprocess()
circuits, _ = program([circuit_valid_0, circuit_valid_1])
assert circuits == tuple([circuit_valid_0, circuit_valid_1])
invalid_circuit = qml.tape.QuantumScript([qml.PauliX(4)])
with pytest.raises(qml.wires.WireError, match=r"Cannot run circuit\(s\) on"):
program, _ = dev.preprocess()
program(
[
invalid_circuit,
]
)
with pytest.raises(qml.wires.WireError, match=r"Cannot run circuit\(s\) on"):
program, _ = dev.preprocess()
program([circuit_valid_0, invalid_circuit])
@pytest.mark.parametrize(
"mp_fn,mp_cls,shots",
[
(qml.sample, SampleMP, 10),
(qml.state, StateMP, None),
(qml.probs, ProbabilityMP, None),
],
)
def test_measurement_is_swapped_out(self, mp_fn, mp_cls, shots):
"""Test that preprocessing swaps out any MP with no wires or obs"""
dev = DefaultQubit(wires=3)
original_mp = mp_fn()
exp_z = qml.expval(qml.PauliZ(0))
qs = qml.tape.QuantumScript([qml.Hadamard(0)], [original_mp, exp_z], shots=shots)
program, _ = dev.preprocess()
tapes, _ = program([qs])
assert len(tapes) == 1
tape = tapes[0]
assert tape.operations == qs.operations
assert tape.measurements != qs.measurements
assert qml.equal(tape.measurements[0], mp_cls(wires=[0, 1, 2]))
assert tape.measurements[1] is exp_z
class TestSupportsDerivatives:
"""Test that DefaultQubit states what kind of derivatives it supports."""
def test_supports_backprop(self):
"""Test that DefaultQubit says that it supports backpropagation."""
dev = DefaultQubit()
assert dev.supports_derivatives() is True
assert dev.supports_jvp() is True
assert dev.supports_vjp() is True
config = ExecutionConfig(gradient_method="backprop", interface="auto")
assert dev.supports_derivatives(config) is True
assert dev.supports_jvp(config) is True
assert dev.supports_vjp(config) is True
qs = qml.tape.QuantumScript([], [qml.state()])
assert dev.supports_derivatives(config, qs) is True
assert dev.supports_jvp(config, qs) is True
assert dev.supports_vjp(config, qs) is True
config = ExecutionConfig(gradient_method="backprop", device_options={"max_workers": 1})
assert dev.supports_derivatives(config) is False
assert dev.supports_jvp(config) is False
assert dev.supports_vjp(config) is False
config = ExecutionConfig(gradient_method="backprop", interface=None)
assert dev.supports_derivatives(config) is False
assert dev.supports_jvp(config) is False
assert dev.supports_vjp(config) is False
def test_supports_adjoint(self):
"""Test that DefaultQubit says that it supports adjoint differentiation."""
dev = DefaultQubit()
config = ExecutionConfig(gradient_method="adjoint", use_device_gradient=True)
assert dev.supports_derivatives(config) is True
assert dev.supports_jvp(config) is True
assert dev.supports_vjp(config) is True
qs = qml.tape.QuantumScript([], [qml.expval(qml.PauliZ(0))])
assert dev.supports_derivatives(config, qs) is True
assert dev.supports_jvp(config, qs) is True
assert dev.supports_vjp(config, qs) is True
config = ExecutionConfig(gradient_method="adjoint", use_device_gradient=False)
assert dev.supports_derivatives(config) is False
assert dev.supports_jvp(config) is False
assert dev.supports_vjp(config) is False
assert dev.supports_derivatives(config, qs) is False
assert dev.supports_jvp(config, qs) is False
assert dev.supports_vjp(config, qs) is False
def test_doesnt_support_adjoint_with_invalid_tape(self):
"""Tests that DefaultQubit does not support adjoint differentiation with invalid circuits."""
dev = DefaultQubit()
config = ExecutionConfig(gradient_method="adjoint")
circuit = qml.tape.QuantumScript([], [qml.probs()])
assert dev.supports_derivatives(config, circuit=circuit) is False
assert dev.supports_jvp(config, circuit=circuit) is False
assert dev.supports_vjp(config, circuit=circuit) is False
@pytest.mark.parametrize("gradient_method", ["parameter-shift", "finite-diff", "device"])
def test_doesnt_support_other_gradient_methods(self, gradient_method):
"""Test that DefaultQubit currently does not support other gradient methods natively."""
dev = DefaultQubit()
config = ExecutionConfig(gradient_method=gradient_method)
assert dev.supports_derivatives(config) is False
assert dev.supports_jvp(config) is False
assert dev.supports_vjp(config) is False
class TestBasicCircuit:
"""Tests a basic circuit with one RX gate and two simple expectation values."""
@pytest.mark.parametrize("max_workers", [None, 1, 2])
def test_basic_circuit_numpy(self, max_workers):
"""Test execution with a basic circuit."""
phi = np.array(0.397)
qs = qml.tape.QuantumScript(
[qml.RX(phi, wires=0)], [qml.expval(qml.PauliY(0)), qml.expval(qml.PauliZ(0))]
)
dev = DefaultQubit(max_workers=max_workers)
result = dev.execute(qs)
assert isinstance(result, tuple)
assert len(result) == 2
assert np.allclose(result[0], -np.sin(phi))
assert np.allclose(result[1], np.cos(phi))
@pytest.mark.parametrize("max_workers", [None, 1, 2])
def test_basic_circuit_numpy_with_config(self, max_workers):
"""Test execution with a basic circuit."""
phi = np.array(0.397)
qs = qml.tape.QuantumScript(
[qml.RX(phi, wires=0)], [qml.expval(qml.PauliY(0)), qml.expval(qml.PauliZ(0))]
)
dev = DefaultQubit(max_workers=max_workers)
config = ExecutionConfig(
device_options={"max_workers": dev._max_workers} # pylint: disable=protected-access
)
result = dev.execute(qs, execution_config=config)
assert isinstance(result, tuple)
assert len(result) == 2
assert np.allclose(result[0], -np.sin(phi))
assert np.allclose(result[1], np.cos(phi))
@pytest.mark.autograd
@pytest.mark.parametrize("max_workers", [None, 1, 2])
def test_autograd_results_and_backprop(self, max_workers):
"""Tests execution and gradients with autograd"""
phi = qml.numpy.array(-0.52)
dev = DefaultQubit(max_workers=max_workers)
def f(x):
qs = qml.tape.QuantumScript(
[qml.RX(x, wires=0)], [qml.expval(qml.PauliY(0)), qml.expval(qml.PauliZ(0))]
)
return qml.numpy.array(dev.execute(qs))
result = f(phi)
expected = np.array([-np.sin(phi), np.cos(phi)])
assert qml.math.allclose(result, expected)
if max_workers is not None:
return
g = qml.jacobian(f)(phi)
expected = np.array([-np.cos(phi), -np.sin(phi)])
assert qml.math.allclose(g, expected)
@pytest.mark.jax
@pytest.mark.parametrize("use_jit", (True, False))
@pytest.mark.parametrize("max_workers", [None, 1, 2])
def test_jax_results_and_backprop(self, use_jit, max_workers):
"""Tests execution and gradients with jax."""
import jax
phi = jax.numpy.array(0.678)
dev = DefaultQubit(max_workers=max_workers)
def f(x):
qs = qml.tape.QuantumScript(
[qml.RX(x, wires=0)], [qml.expval(qml.PauliY(0)), qml.expval(qml.PauliZ(0))]
)
return dev.execute(qs)
if use_jit:
if max_workers is not None:
return
f = jax.jit(f)
result = f(phi)
assert qml.math.allclose(result[0], -np.sin(phi))
assert qml.math.allclose(result[1], np.cos(phi))
if max_workers is not None:
return
g = jax.jacobian(f)(phi)
assert qml.math.allclose(g[0], -np.cos(phi))
assert qml.math.allclose(g[1], -np.sin(phi))
@pytest.mark.torch
@pytest.mark.parametrize("max_workers", [None, 1, 2])
def test_torch_results_and_backprop(self, max_workers):
"""Tests execution and gradients of a simple circuit with torch."""
import torch
phi = torch.tensor(-0.526, requires_grad=True)
dev = DefaultQubit(max_workers=max_workers)
def f(x):
qs = qml.tape.QuantumScript(
[qml.RX(x, wires=0)], [qml.expval(qml.PauliY(0)), qml.expval(qml.PauliZ(0))]
)
return dev.execute(qs)
result = f(phi)
assert qml.math.allclose(result[0], -torch.sin(phi))
assert qml.math.allclose(result[1], torch.cos(phi))
if max_workers is not None:
return
g = torch.autograd.functional.jacobian(f, phi + 0j)
assert qml.math.allclose(g[0], -torch.cos(phi))
assert qml.math.allclose(g[1], -torch.sin(phi))
# pylint: disable=invalid-unary-operand-type
@pytest.mark.tf
@pytest.mark.parametrize("max_workers", [None, 1, 2])
def test_tf_results_and_backprop(self, max_workers):
"""Tests execution and gradients of a simple circuit with tensorflow."""
import tensorflow as tf
phi = tf.Variable(4.873)
dev = DefaultQubit(max_workers=max_workers)
with tf.GradientTape(persistent=True) as grad_tape:
qs = qml.tape.QuantumScript(
[qml.RX(phi, wires=0)], [qml.expval(qml.PauliY(0)), qml.expval(qml.PauliZ(0))]
)
result = dev.execute(qs)
assert qml.math.allclose(result[0], -tf.sin(phi))
assert qml.math.allclose(result[1], tf.cos(phi))
if max_workers is not None:
return
grad0 = grad_tape.jacobian(result[0], [phi])
grad1 = grad_tape.jacobian(result[1], [phi])
assert qml.math.allclose(grad0[0], -tf.cos(phi))
assert qml.math.allclose(grad1[0], -tf.sin(phi))
@pytest.mark.tf
@pytest.mark.parametrize("op,param", [(qml.RX, np.pi), (qml.BasisState, [1])])
def test_qnode_returns_correct_interface(self, op, param):
"""Test that even if no interface parameters are given, result is correct."""
dev = DefaultQubit()
@qml.qnode(dev, interface="tf")
def circuit(p):
op(p, wires=[0])
return qml.expval(qml.PauliZ(0))
res = circuit(param)
assert qml.math.get_interface(res) == "tensorflow"
assert qml.math.allclose(res, -1)
class TestSampleMeasurements:
"""A copy of the `qubit.simulate` tests, but using the device"""
@pytest.mark.parametrize("max_workers", [None, 1, 2])
def test_single_expval(self, max_workers):
"""Test a simple circuit with a single expval measurement"""
x = np.array(0.732)
qs = qml.tape.QuantumScript([qml.RY(x, wires=0)], [qml.expval(qml.PauliZ(0))], shots=10000)
dev = DefaultQubit(max_workers=max_workers)
result = dev.execute(qs)
assert isinstance(result, (float, np.ndarray))
assert result.shape == ()
assert np.allclose(result, np.cos(x), atol=0.1)
@pytest.mark.parametrize("max_workers", [None, 1, 2])
def test_single_probs(self, max_workers):
"""Test a simple circuit with a single prob measurement"""
x = np.array(0.732)
qs = qml.tape.QuantumScript([qml.RY(x, wires=0)], [qml.probs(wires=0)], shots=10000)
dev = DefaultQubit(max_workers=max_workers)
result = dev.execute(qs)
assert isinstance(result, (float, np.ndarray))
assert result.shape == (2,)
assert np.allclose(result, [np.cos(x / 2) ** 2, np.sin(x / 2) ** 2], atol=0.1)
@pytest.mark.parametrize("max_workers", [None, 1, 2])
def test_single_sample(self, max_workers):
"""Test a simple circuit with a single sample measurement"""
x = np.array(0.732)
qs = qml.tape.QuantumScript([qml.RY(x, wires=0)], [qml.sample(wires=range(2))], shots=10000)
dev = DefaultQubit(max_workers=max_workers)
result = dev.execute(qs)
assert isinstance(result, (float, np.ndarray))
assert result.shape == (10000, 2)
assert np.allclose(
np.sum(result, axis=0).astype(np.float32) / 10000, [np.sin(x / 2) ** 2, 0], atol=0.1
)
@pytest.mark.parametrize("max_workers", [None, 1, 2])
def test_multi_measurements(self, max_workers):
"""Test a simple circuit containing multiple measurements"""
x, y = np.array(0.732), np.array(0.488)
qs = qml.tape.QuantumScript(
[qml.RX(x, wires=0), qml.CNOT(wires=[0, 1]), qml.RY(y, wires=1)],
[qml.expval(qml.Hadamard(0)), qml.probs(wires=range(2)), qml.sample(wires=range(2))],
shots=10000,
)
dev = DefaultQubit(max_workers=max_workers)
result = dev.execute(qs)
assert isinstance(result, tuple)
assert len(result) == 3
assert all(isinstance(res, (float, np.ndarray)) for res in result)
assert result[0].shape == ()
assert np.allclose(result[0], np.cos(x) / np.sqrt(2), atol=0.1)
assert result[1].shape == (4,)
assert np.allclose(
result[1],
[
np.cos(x / 2) ** 2 * np.cos(y / 2) ** 2,
np.cos(x / 2) ** 2 * np.sin(y / 2) ** 2,
np.sin(x / 2) ** 2 * np.sin(y / 2) ** 2,
np.sin(x / 2) ** 2 * np.cos(y / 2) ** 2,
],
atol=0.1,
)
assert result[2].shape == (10000, 2)
shots_data = [
[10000, 10000],
[(10000, 2)],
[10000, 20000],
[(10000, 2), 20000],
[(10000, 3), 20000, (30000, 2)],
]
@pytest.mark.parametrize("shots", shots_data)
@pytest.mark.parametrize("max_workers", [None, 1, 2])
def test_expval_shot_vector(self, max_workers, shots):
"""Test a simple circuit with a single expval measurement for shot vectors"""
x = np.array(0.732)
shots = qml.measurements.Shots(shots)
qs = qml.tape.QuantumScript([qml.RY(x, wires=0)], [qml.expval(qml.PauliZ(0))], shots=shots)
dev = DefaultQubit(max_workers=max_workers)
result = dev.execute(qs)
assert isinstance(result, tuple)
assert len(result) == len(list(shots))
assert all(isinstance(res, (float, np.ndarray)) for res in result)
assert all(res.shape == () for res in result)
assert all(np.allclose(res, np.cos(x), atol=0.1) for res in result)
@pytest.mark.parametrize("shots", shots_data)
@pytest.mark.parametrize("max_workers", [None, 1, 2])
def test_probs_shot_vector(self, max_workers, shots):
"""Test a simple circuit with a single prob measurement for shot vectors"""
x = np.array(0.732)
shots = qml.measurements.Shots(shots)
qs = qml.tape.QuantumScript([qml.RY(x, wires=0)], [qml.probs(wires=0)], shots=shots)
dev = DefaultQubit(max_workers=max_workers)
result = dev.execute(qs)
assert isinstance(result, tuple)
assert len(result) == len(list(shots))
assert all(isinstance(res, (float, np.ndarray)) for res in result)
assert all(res.shape == (2,) for res in result)
assert all(
np.allclose(res, [np.cos(x / 2) ** 2, np.sin(x / 2) ** 2], atol=0.1) for res in result
)
@pytest.mark.parametrize("shots", shots_data)
@pytest.mark.parametrize("max_workers", [None, 1, 2])
def test_sample_shot_vector(self, max_workers, shots):
"""Test a simple circuit with a single sample measurement for shot vectors"""
x = np.array(0.732)
shots = qml.measurements.Shots(shots)
qs = qml.tape.QuantumScript([qml.RY(x, wires=0)], [qml.sample(wires=range(2))], shots=shots)
dev = DefaultQubit(max_workers=max_workers)
result = dev.execute(qs)
assert isinstance(result, tuple)
assert len(result) == len(list(shots))
assert all(isinstance(res, (float, np.ndarray)) for res in result)
assert all(res.shape == (s, 2) for res, s in zip(result, shots))
assert all(
np.allclose(
np.sum(res, axis=0).astype(np.float32) / s, [np.sin(x / 2) ** 2, 0], atol=0.1
)
for res, s in zip(result, shots)
)
@pytest.mark.parametrize("shots", shots_data)
@pytest.mark.parametrize("max_workers", [None, 1, 2])
def test_multi_measurement_shot_vector(self, max_workers, shots):
"""Test a simple circuit containing multiple measurements for shot vectors"""
x, y = np.array(0.732), np.array(0.488)
shots = qml.measurements.Shots(shots)
qs = qml.tape.QuantumScript(
[qml.RX(x, wires=0), qml.CNOT(wires=[0, 1]), qml.RY(y, wires=1)],
[qml.expval(qml.Hadamard(0)), qml.probs(wires=range(2)), qml.sample(wires=range(2))],
shots=shots,
)
dev = DefaultQubit(max_workers=max_workers)
result = dev.execute(qs)
assert isinstance(result, tuple)
assert len(result) == len(list(shots))
for shot_res, s in zip(result, shots):
assert isinstance(shot_res, tuple)
assert len(shot_res) == 3
assert all(isinstance(meas_res, (float, np.ndarray)) for meas_res in shot_res)
assert shot_res[0].shape == ()
assert np.allclose(shot_res[0], np.cos(x) / np.sqrt(2), atol=0.1)
assert shot_res[1].shape == (4,)
assert np.allclose(
shot_res[1],
[
np.cos(x / 2) ** 2 * np.cos(y / 2) ** 2,
np.cos(x / 2) ** 2 * np.sin(y / 2) ** 2,
np.sin(x / 2) ** 2 * np.sin(y / 2) ** 2,
np.sin(x / 2) ** 2 * np.cos(y / 2) ** 2,
],
atol=0.1,
)
assert shot_res[2].shape == (s, 2)
@pytest.mark.parametrize("max_workers", [None, 1, 2])
def test_custom_wire_labels(self, max_workers):
"""Test that custom wire labels works as expected"""
x, y = np.array(0.732), np.array(0.488)
qs = qml.tape.QuantumScript(
[qml.RX(x, wires="b"), qml.CNOT(wires=["b", "a"]), qml.RY(y, wires="a")],
[
qml.expval(qml.PauliZ("b")),
qml.probs(wires=["a", "b"]),
qml.sample(wires=["b", "a"]),
],
shots=10000,
)
dev = DefaultQubit(max_workers=max_workers)
result = dev.execute(qs)
assert isinstance(result, tuple)
assert len(result) == 3
assert all(isinstance(res, (float, np.ndarray)) for res in result)
assert result[0].shape == ()
assert np.allclose(result[0], np.cos(x), atol=0.1)
assert result[1].shape == (4,)
assert np.allclose(
result[1],
[
np.cos(x / 2) ** 2 * np.cos(y / 2) ** 2,
np.sin(x / 2) ** 2 * np.sin(y / 2) ** 2,
np.cos(x / 2) ** 2 * np.sin(y / 2) ** 2,
np.sin(x / 2) ** 2 * np.cos(y / 2) ** 2,
],
atol=0.1,
)
assert result[2].shape == (10000, 2)
@pytest.mark.parametrize("max_workers", [None, 1, 2])
def test_batch_tapes(self, max_workers):
"""Test that a batch of tapes with sampling works as expected"""
x = np.array(0.732)
qs1 = qml.tape.QuantumScript([qml.RX(x, wires=0)], [qml.sample(wires=(0, 1))], shots=100)
qs2 = qml.tape.QuantumScript([qml.RX(x, wires=0)], [qml.sample(wires=1)], shots=50)
dev = DefaultQubit(max_workers=max_workers)
results = dev.execute((qs1, qs2))
assert isinstance(results, tuple)
assert len(results) == 2
assert all(isinstance(res, (float, np.ndarray)) for res in results)
assert results[0].shape == (100, 2)
assert results[1].shape == (50,)
@pytest.mark.parametrize("max_workers", [None, 1, 2])
def test_counts_wires(self, max_workers):
"""Test that a Counts measurement with wires works as expected"""
x = np.array(np.pi / 2)
qs = qml.tape.QuantumScript([qml.RY(x, wires=0)], [qml.counts(wires=[0, 1])], shots=10000)
dev = DefaultQubit(seed=123, max_workers=max_workers)
result = dev.execute(qs)
assert isinstance(result, dict)
assert set(result.keys()) == {"00", "10"}
# check that the count values match the expected
values = list(result.values())
assert np.allclose(values[0] / (values[0] + values[1]), 0.5, atol=0.01)
@pytest.mark.parametrize("max_workers", [None, 1, 2])
@pytest.mark.parametrize("all_outcomes", [False, True])
def test_counts_obs(self, all_outcomes, max_workers):
"""Test that a Counts measurement with an observable works as expected"""
x = np.array(np.pi / 2)
qs = qml.tape.QuantumScript(
[qml.RY(x, wires=0)],
[qml.counts(qml.PauliZ(0), all_outcomes=all_outcomes)],
shots=10000,
)
dev = DefaultQubit(seed=123, max_workers=max_workers)
result = dev.execute(qs)
assert isinstance(result, dict)
assert set(result.keys()) == {1, -1}
# check that the count values match the expected
values = list(result.values())
assert np.allclose(values[0] / (values[0] + values[1]), 0.5, atol=0.01)
class TestExecutingBatches:
"""Tests involving executing multiple circuits at the same time."""
@staticmethod
def f(dev, phi):
"""A function that executes a batch of scripts on DefaultQubit without preprocessing."""
ops = [
qml.PauliX("a"),
qml.PauliX("b"),
qml.ctrl(qml.RX(phi, "target"), ("a", "b", -3), control_values=[1, 1, 0]),
]
qs1 = qml.tape.QuantumScript(
ops,
[
qml.expval(qml.sum(qml.PauliY("target"), qml.PauliZ("b"))),
qml.expval(qml.s_prod(3, qml.PauliZ("target"))),
],
)
ops = [qml.Hadamard(0), qml.IsingXX(phi, wires=(0, 1))]
qs2 = qml.tape.QuantumScript(ops, [qml.probs(wires=(0, 1))])
return dev.execute((qs1, qs2))
@staticmethod
def f_hashable(phi):
"""A function that executes a batch of scripts on DefaultQubit without preprocessing."""
ops = [
qml.PauliX("a"),
qml.PauliX("b"),
qml.ctrl(qml.RX(phi, "target"), ("a", "b", -3), control_values=[1, 1, 0]),
]
qs1 = qml.tape.QuantumScript(
ops,
[
qml.expval(qml.sum(qml.PauliY("target"), qml.PauliZ("b"))),
qml.expval(qml.s_prod(3, qml.PauliZ("target"))),
],
)
ops = [qml.Hadamard(0), qml.IsingXX(phi, wires=(0, 1))]
qs2 = qml.tape.QuantumScript(ops, [qml.probs(wires=(0, 1))])
return DefaultQubit().execute((qs1, qs2))
@staticmethod
def expected(phi):
"""expected output of f."""
out1 = (-qml.math.sin(phi) - 1, 3 * qml.math.cos(phi))
x1 = qml.math.cos(phi / 2) ** 2 / 2
x2 = qml.math.sin(phi / 2) ** 2 / 2
out2 = x1 * np.array([1, 0, 1, 0]) + x2 * np.array([0, 1, 0, 1])
return (out1, out2)
@staticmethod
def nested_compare(x1, x2):
"""Assert two ragged lists are equal."""
assert len(x1) == len(x2)
assert len(x1[0]) == len(x2[0])
assert qml.math.allclose(x1[0][0], x2[0][0])
assert qml.math.allclose(x1[0][1], x2[0][1])
assert qml.math.allclose(x1[1], x2[1])
@pytest.mark.parametrize("max_workers", [None, 1, 2])
def test_numpy(self, max_workers):
"""Test that results are expected when the parameter does not have a parameter."""
dev = DefaultQubit(max_workers=max_workers)
phi = 0.892
results = self.f(dev, phi)
expected = self.expected(phi)
self.nested_compare(results, expected)
@pytest.mark.autograd
@pytest.mark.parametrize("max_workers", [None, 1, 2])
def test_autograd(self, max_workers):
"""Test batches can be executed and have backprop derivatives in autograd."""
dev = DefaultQubit(max_workers=max_workers)
phi = qml.numpy.array(-0.629)
results = self.f(dev, phi)
expected = self.expected(phi)
self.nested_compare(results, expected)
if max_workers is not None:
return
g0 = qml.jacobian(lambda x: qml.numpy.array(self.f(dev, x)[0]))(phi)
g0_expected = qml.jacobian(lambda x: qml.numpy.array(self.expected(x)[0]))(phi)
assert qml.math.allclose(g0, g0_expected)
g1 = qml.jacobian(lambda x: qml.numpy.array(self.expected(x)[1]))(phi)
g1_expected = qml.jacobian(lambda x: qml.numpy.array(self.expected(x)[1]))(phi)
assert qml.math.allclose(g1, g1_expected)
@pytest.mark.jax
@pytest.mark.parametrize("use_jit", (True, False))
def test_jax(self, use_jit):
"""Test batches can be executed and have backprop derivatives in jax."""
import jax
phi = jax.numpy.array(0.123)
f = jax.jit(self.f_hashable) if use_jit else self.f_hashable
results = f(phi)
expected = self.expected(phi)
self.nested_compare(results, expected)
g = jax.jacobian(f)(phi)
g_expected = jax.jacobian(self.expected)(phi)
self.nested_compare(g, g_expected)
@pytest.mark.torch
@pytest.mark.parametrize("max_workers", [None, 1, 2])
def test_torch(self, max_workers):
"""Test batches can be executed and have backprop derivatives in torch."""
import torch
dev = DefaultQubit(max_workers=max_workers)
x = torch.tensor(9.6243)
results = self.f(dev, x)
expected = self.expected(x)
self.nested_compare(results, expected)