-
Notifications
You must be signed in to change notification settings - Fork 2.5k
/
Copy pathtest_preset_passmanagers.py
1762 lines (1558 loc) · 65.7 KB
/
test_preset_passmanagers.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
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2024.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Tests preset pass manager API"""
import unittest
from test import combine
from ddt import ddt, data
import numpy as np
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister
from qiskit.circuit import Qubit, Gate, ControlFlowOp, ForLoopOp, Measure, library as lib, Parameter
from qiskit.compiler import transpile
from qiskit.transpiler import (
CouplingMap,
Layout,
PassManager,
TranspilerError,
Target,
InstructionProperties,
)
from qiskit.circuit.library import U2Gate, U3Gate, quantum_volume, CXGate, CZGate, XGate
from qiskit.transpiler.passes import (
ALAPScheduleAnalysis,
PadDynamicalDecoupling,
RemoveResetInZeroState,
)
from qiskit.providers.fake_provider import GenericBackendV2
from qiskit.converters import circuit_to_dag
from qiskit.circuit.library import GraphStateGate
from qiskit.quantum_info import random_unitary
from qiskit.transpiler.preset_passmanagers import generate_preset_pass_manager
from qiskit.transpiler.preset_passmanagers import level0, level1, level2, level3
from qiskit.transpiler.passes import ConsolidateBlocks, GatesInBasis
from qiskit.transpiler.preset_passmanagers.builtin_plugins import OptimizationPassManager
from test import QiskitTestCase # pylint: disable=wrong-import-order
from ..legacy_cmaps import MELBOURNE_CMAP, RUESCHLIKON_CMAP, LAGOS_CMAP, TOKYO_CMAP, BOGOTA_CMAP
def mock_get_passmanager_stage(
stage_name,
plugin_name,
pm_config,
optimization_level=None, # pylint: disable=unused-argument
) -> PassManager:
"""Mock function for get_passmanager_stage."""
if stage_name == "translation" and plugin_name == "custom_stage_for_test":
pm = PassManager([RemoveResetInZeroState()])
return pm
elif stage_name == "scheduling" and plugin_name == "custom_stage_for_test":
dd_sequence = [XGate(), XGate()]
pm = PassManager(
[
ALAPScheduleAnalysis(pm_config.instruction_durations),
PadDynamicalDecoupling(pm_config.instruction_durations, dd_sequence),
]
)
return pm
elif stage_name == "init":
return PassManager([])
elif stage_name == "routing":
return PassManager([])
elif stage_name == "optimization":
return OptimizationPassManager().pass_manager(pm_config, optimization_level)
elif stage_name == "layout":
return PassManager([])
else:
raise RuntimeError("Failure, unexpected stage plugin combo for test")
def emptycircuit():
"""Empty circuit"""
return QuantumCircuit()
def circuit_2532():
"""See https://github.com/Qiskit/qiskit-terra/issues/2532"""
circuit = QuantumCircuit(5)
circuit.cx(2, 4)
return circuit
@ddt
class TestPresetPassManager(QiskitTestCase):
"""Test preset passmanagers work as expected."""
@combine(level=[0, 1, 2, 3], name="level{level}")
def test_no_coupling_map_with_sabre(self, level):
"""Test that coupling_map can be None with Sabre (level={level})"""
q = QuantumRegister(2, name="q")
circuit = QuantumCircuit(q)
circuit.cz(q[0], q[1])
result = transpile(
circuit,
coupling_map=None,
layout_method="sabre",
routing_method="sabre",
optimization_level=level,
)
self.assertEqual(result, circuit)
@combine(level=[0, 1, 2, 3], name="level{level}")
def test_no_coupling_map(self, level):
"""Test that coupling_map can be None (level={level})"""
q = QuantumRegister(2, name="q")
circuit = QuantumCircuit(q)
circuit.cz(q[0], q[1])
result = transpile(circuit, basis_gates=["u1", "u2", "u3", "cx"], optimization_level=level)
self.assertIsInstance(result, QuantumCircuit)
self.assertEqual(result.num_qubits, circuit.num_qubits)
def test_layout_3239(self, level=3):
"""Test final layout after preset level3 passmanager does not include diagonal gates
See: https://github.com/Qiskit/qiskit-terra/issues/3239
"""
qc = QuantumCircuit(5, 5)
qc.h(0)
qc.cx(range(3), range(1, 4))
qc.z(range(4))
qc.measure(range(4), range(4))
result = transpile(
qc,
basis_gates=["u1", "u2", "u3", "cx"],
layout_method="trivial",
optimization_level=level,
)
dag = circuit_to_dag(result)
op_nodes = [node.name for node in dag.topological_op_nodes()]
self.assertNotIn("u1", op_nodes) # Check if the diagonal Z-Gates (u1) were removed
@combine(level=[0, 1, 2, 3], name="level{level}")
def test_no_basis_gates(self, level):
"""Test that basis_gates can be None (level={level})"""
q = QuantumRegister(2, name="q")
circuit = QuantumCircuit(q)
circuit.h(q[0])
circuit.cz(q[0], q[1])
result = transpile(circuit, basis_gates=None, optimization_level=level)
self.assertEqual(result, circuit)
def test_level0_keeps_reset(self):
"""Test level 0 should keep the reset instructions"""
q = QuantumRegister(2, name="q")
circuit = QuantumCircuit(q)
circuit.reset(q[0])
circuit.reset(q[0])
result = transpile(circuit, basis_gates=None, optimization_level=0)
self.assertEqual(result, circuit)
@combine(level=[0, 1, 2, 3], name="level{level}")
def test_unitary_is_preserved_if_in_basis(self, level):
"""Test that a unitary is not synthesized if in the basis."""
qc = QuantumCircuit(2)
qc.unitary(random_unitary(4, seed=42), [0, 1])
qc.measure_all()
with self.assertWarnsRegex(
DeprecationWarning,
"Providing non-standard gates \\(unitary\\) through the ``basis_gates`` argument",
):
result = transpile(qc, basis_gates=["cx", "u", "unitary"], optimization_level=level)
self.assertEqual(result, qc)
@combine(level=[0, 1, 2, 3], name="level{level}")
def test_unitary_is_preserved_if_basis_is_None(self, level):
"""Test that a unitary is not synthesized if basis is None."""
qc = QuantumCircuit(2)
qc.unitary(random_unitary(4, seed=4242), [0, 1])
qc.measure_all()
result = transpile(qc, basis_gates=None, optimization_level=level)
self.assertEqual(result, qc)
@combine(level=[0, 1, 2, 3], name="level{level}")
def test_unitary_is_preserved_if_in_basis_synthesis_translation(self, level):
"""Test that a unitary is not synthesized if in the basis with synthesis translation."""
qc = QuantumCircuit(2)
qc.unitary(random_unitary(4, seed=424242), [0, 1])
qc.measure_all()
with self.assertWarnsRegex(
DeprecationWarning,
"Providing non-standard gates \\(unitary\\) through the ``basis_gates`` argument",
):
result = transpile(
qc,
basis_gates=["cx", "u", "unitary"],
optimization_level=level,
translation_method="synthesis",
)
self.assertEqual(result, qc)
@combine(level=[0, 1, 2, 3], name="level{level}")
def test_unitary_is_preserved_if_basis_is_None_synthesis_transltion(self, level):
"""Test that a unitary is not synthesized if basis is None with synthesis translation."""
qc = QuantumCircuit(2)
qc.unitary(random_unitary(4, seed=42424242), [0, 1])
qc.measure_all()
result = transpile(
qc, basis_gates=None, optimization_level=level, translation_method="synthesis"
)
self.assertEqual(result, qc)
@combine(level=[0, 1, 2, 3], name="level{level}")
def test_respect_basis(self, level):
"""Test that all levels respect basis"""
qc = QuantumCircuit(3)
qc.h(0)
qc.h(1)
qc.cp(np.pi / 8, 0, 1)
qc.cp(np.pi / 4, 0, 2)
basis_gates = ["id", "rz", "sx", "x", "cx"]
result = transpile(
qc, basis_gates=basis_gates, coupling_map=[[0, 1], [2, 1]], optimization_level=level
)
dag = circuit_to_dag(result)
circuit_ops = {node.name for node in dag.topological_op_nodes()}
self.assertEqual(circuit_ops.union(set(basis_gates)), set(basis_gates))
@combine(level=[0, 1, 2, 3], name="level{level}")
def test_alignment_constraints_called_with_by_default(self, level):
"""Test that TimeUnitConversion is not called if there is no delay in the circuit."""
q = QuantumRegister(2, name="q")
circuit = QuantumCircuit(q)
circuit.h(q[0])
circuit.cz(q[0], q[1])
with unittest.mock.patch("qiskit.transpiler.passes.TimeUnitConversion.run") as mock:
backend = GenericBackendV2(
num_qubits=20,
coupling_map=TOKYO_CMAP,
basis_gates=["id", "u1", "u2", "u3", "cx"],
seed=42,
)
transpile(circuit, backend=backend, optimization_level=level)
mock.assert_not_called()
@combine(level=[0, 1, 2, 3], name="level{level}")
def test_alignment_constraints_called_with_delay_in_circuit(self, level):
"""Test that TimeUnitConversion is called if there is a delay in the circuit."""
q = QuantumRegister(2, name="q")
circuit = QuantumCircuit(q)
circuit.h(q[0])
circuit.cz(q[0], q[1])
circuit.delay(9.5, unit="ns")
with unittest.mock.patch(
"qiskit.transpiler.passes.TimeUnitConversion.run", return_value=circuit_to_dag(circuit)
) as mock:
backend = GenericBackendV2(
num_qubits=20,
coupling_map=TOKYO_CMAP,
basis_gates=["id", "u1", "u2", "u3", "cx"],
seed=42,
)
transpile(circuit, backend=backend, optimization_level=level)
mock.assert_called_once()
def test_unroll_only_if_not_gates_in_basis(self):
"""Test that the list of passes _unroll only runs if a gate is not in the basis."""
qcomp = GenericBackendV2(
num_qubits=5,
coupling_map=BOGOTA_CMAP,
basis_gates=["id", "u1", "u2", "u3", "cx"],
seed=42,
)
qv_circuit = quantum_volume(3)
gates_in_basis_true_count = 0
consolidate_blocks_count = 0
# pylint: disable=unused-argument
def counting_callback_func(pass_, dag, time, property_set, count):
nonlocal gates_in_basis_true_count
nonlocal consolidate_blocks_count
if isinstance(pass_, GatesInBasis) and property_set["all_gates_in_basis"]:
gates_in_basis_true_count += 1
if isinstance(pass_, ConsolidateBlocks):
consolidate_blocks_count += 1
transpile(
qv_circuit,
backend=qcomp,
optimization_level=3,
callback=counting_callback_func,
translation_method="synthesis",
)
self.assertEqual(gates_in_basis_true_count + 2, consolidate_blocks_count)
@ddt
class TestTranspileLevels(QiskitTestCase):
"""Test transpiler on fake backend"""
@combine(
circuit=[emptycircuit, circuit_2532],
level=[0, 1, 2, 3],
backend=[
GenericBackendV2(
num_qubits=5,
coupling_map=BOGOTA_CMAP,
basis_gates=["id", "u1", "u2", "u3", "cx"],
seed=42,
),
GenericBackendV2(
num_qubits=20,
coupling_map=TOKYO_CMAP,
basis_gates=["id", "u1", "u2", "u3", "cx"],
seed=42,
),
None,
],
dsc="Transpiler {circuit.__name__} on {backend} backend at level {level}",
name="{circuit.__name__}_{backend}_level{level}",
)
def test(self, circuit, level, backend):
"""All the levels with all the backends"""
result = transpile(circuit(), backend=backend, optimization_level=level, seed_transpiler=42)
self.assertIsInstance(result, QuantumCircuit)
@data(0, 1, 2, 3)
def test_quantum_volume_function_transpile(self, opt_level):
"""Test quantum_volume transpilation."""
qc = quantum_volume(10, 10, 12345)
backend = GenericBackendV2(
num_qubits=100,
basis_gates=["cz", "rz", "sx", "x", "id"],
coupling_map=CouplingMap.from_grid(10, 10),
)
pm = generate_preset_pass_manager(opt_level, backend)
res = pm.run(qc)
for inst in res.data:
self.assertTrue(
backend.target.instruction_supported(
inst.operation.name, qargs=tuple(res.find_bit(x).index for x in inst.qubits)
)
)
@ddt
class TestPassesInspection(QiskitTestCase):
"""Test run passes under different conditions"""
def setUp(self):
"""Sets self.callback to set self.passes with the passes that have been executed"""
super().setUp()
self.passes = []
def callback(**kwargs):
self.passes.append(kwargs["pass_"].__class__.__name__)
self.callback = callback
@data(0, 1, 2, 3)
def test_no_coupling_map(self, level):
"""Without coupling map, no layout selection nor swapper"""
qr = QuantumRegister(3, "q")
qc = QuantumCircuit(qr)
qc.cx(qr[2], qr[1])
qc.cx(qr[2], qr[0])
_ = transpile(qc, optimization_level=level, callback=self.callback)
self.assertNotIn("SetLayout", self.passes)
self.assertNotIn("TrivialLayout", self.passes)
self.assertNotIn("ApplyLayout", self.passes)
self.assertNotIn("StochasticSwap", self.passes)
self.assertNotIn("SabreSwap", self.passes)
self.assertNotIn("CheckGateDirection", self.passes)
@data(0, 1, 2, 3)
def test_backend(self, level):
"""With backend a layout and a swapper is run"""
qr = QuantumRegister(5, "q")
qc = QuantumCircuit(qr)
qc.cx(qr[2], qr[4])
backend = GenericBackendV2(num_qubits=14, coupling_map=MELBOURNE_CMAP, seed=42)
_ = transpile(qc, backend, optimization_level=level, callback=self.callback)
self.assertIn("SetLayout", self.passes)
self.assertIn("ApplyLayout", self.passes)
self.assertIn("CheckGateDirection", self.passes)
@data(0, 1, 2, 3)
def test_symmetric_coupling_map(self, level):
"""Symmetric coupling map does not run CheckGateDirection"""
qr = QuantumRegister(2, "q")
qc = QuantumCircuit(qr)
qc.cx(qr[0], qr[1])
coupling_map = [[0, 1], [1, 0]]
_ = transpile(
qc,
coupling_map=coupling_map,
initial_layout=[0, 1],
optimization_level=level,
callback=self.callback,
)
self.assertIn("SetLayout", self.passes)
self.assertIn("ApplyLayout", self.passes)
self.assertNotIn("CheckGateDirection", self.passes)
@data(0, 1, 2, 3)
def test_initial_layout_fully_connected_cm(self, level):
"""Honor initial_layout when coupling_map=None
See: https://github.com/Qiskit/qiskit-terra/issues/5345
"""
qr = QuantumRegister(2, "q")
qc = QuantumCircuit(qr)
qc.h(qr[0])
qc.cx(qr[0], qr[1])
transpiled = transpile(
qc, initial_layout=[0, 1], optimization_level=level, callback=self.callback
)
self.assertIn("SetLayout", self.passes)
self.assertIn("ApplyLayout", self.passes)
self.assertEqual(transpiled._layout.initial_layout, Layout.from_qubit_list([qr[0], qr[1]]))
@data(0, 1, 2, 3)
def test_partial_layout_fully_connected_cm(self, level):
"""Honor initial_layout (partially defined) when coupling_map=None
See: https://github.com/Qiskit/qiskit-terra/issues/5345
"""
qr = QuantumRegister(2, "q")
qc = QuantumCircuit(qr)
qc.h(qr[0])
qc.cx(qr[0], qr[1])
transpiled = transpile(
qc, initial_layout=[4, 2], optimization_level=level, callback=self.callback
)
self.assertIn("SetLayout", self.passes)
self.assertIn("ApplyLayout", self.passes)
ancilla = QuantumRegister(3, "ancilla")
self.assertEqual(
transpiled._layout.initial_layout,
Layout.from_qubit_list([ancilla[0], ancilla[1], qr[1], ancilla[2], qr[0]]),
)
@unittest.mock.patch.object(
level0.PassManagerStagePluginManager,
"get_passmanager_stage",
wraps=mock_get_passmanager_stage,
)
def test_backend_with_custom_stages(self, _plugin_manager_mock):
"""Test transpile() executes backend specific custom stage."""
optimization_level = 1
class TargetBackend(GenericBackendV2):
"""Fake lagos subclass with custom transpiler stages."""
def get_scheduling_stage_plugin(self):
"""Custom scheduling stage."""
return "custom_stage_for_test"
def get_translation_stage_plugin(self):
"""Custom post translation stage."""
return "custom_stage_for_test"
target = TargetBackend(num_qubits=7, seed=42)
qr = QuantumRegister(2, "q")
qc = QuantumCircuit(qr)
qc.h(qr[0])
qc.cx(qr[0], qr[1])
_ = transpile(qc, target, optimization_level=optimization_level, callback=self.callback)
self.assertIn("ALAPScheduleAnalysis", self.passes)
self.assertIn("PadDynamicalDecoupling", self.passes)
self.assertIn("RemoveResetInZeroState", self.passes)
def test_level1_runs_vf2post_layout_when_routing_required(self):
"""Test that if we run routing as part of sabre layout VF2PostLayout runs."""
target = GenericBackendV2(num_qubits=7, coupling_map=LAGOS_CMAP, seed=42)
qc = QuantumCircuit(5)
qc.h(0)
qc.cy(0, 1)
qc.cy(0, 2)
qc.cy(0, 3)
qc.cy(0, 4)
qc.measure_all()
_ = transpile(qc, target, optimization_level=1, callback=self.callback)
# Expected call path for layout and routing is:
# 1. TrivialLayout (no perfect match)
# 2. VF2Layout (no perfect match)
# 3. SabreLayout (heuristic layout and also runs routing)
# 4. VF2PostLayout (applies a better layout)
self.assertIn("TrivialLayout", self.passes)
self.assertIn("VF2Layout", self.passes)
self.assertIn("SabreLayout", self.passes)
self.assertIn("VF2PostLayout", self.passes)
# Assert we don't run standalone sabre swap
self.assertNotIn("SabreSwap", self.passes)
def test_level1_runs_vf2post_layout_when_routing_method_set_and_required(self):
"""Test that if we run routing as part of sabre layout then VF2PostLayout runs."""
target = GenericBackendV2(num_qubits=7, coupling_map=LAGOS_CMAP, seed=42)
qc = QuantumCircuit(5)
qc.h(0)
qc.cy(0, 1)
qc.cy(0, 2)
qc.cy(0, 3)
qc.cy(0, 4)
qc.measure_all()
_ = transpile(
qc, target, optimization_level=1, routing_method="sabre", callback=self.callback
)
# Expected call path for layout and routing is:
# 1. TrivialLayout (no perfect match)
# 2. VF2Layout (no perfect match)
# 3. SabreLayout (heuristic layout and also runs routing)
# 4. VF2PostLayout (applies a better layout)
self.assertIn("TrivialLayout", self.passes)
self.assertIn("VF2Layout", self.passes)
self.assertIn("SabreLayout", self.passes)
self.assertIn("VF2PostLayout", self.passes)
def test_level1_not_runs_vf2post_layout_when_layout_method_set(self):
"""Test that if we don't run VF2PostLayout with custom layout_method."""
target = GenericBackendV2(
num_qubits=7,
basis_gates=["cx", "id", "rz", "sx", "x"],
coupling_map=LAGOS_CMAP,
seed=42,
)
qc = QuantumCircuit(5)
qc.h(0)
qc.cy(0, 1)
qc.cy(0, 2)
qc.cy(0, 3)
qc.cy(0, 4)
qc.measure_all()
_ = transpile(
qc, target, optimization_level=1, layout_method="dense", callback=self.callback
)
self.assertNotIn("TrivialLayout", self.passes)
self.assertNotIn("VF2Layout", self.passes)
self.assertNotIn("SabreLayout", self.passes)
self.assertNotIn("VF2PostLayout", self.passes)
self.assertIn("DenseLayout", self.passes)
self.assertIn("SabreSwap", self.passes)
def test_level1_not_run_vf2post_layout_when_trivial_is_perfect(self):
"""Test that if we find a trivial perfect layout we don't run vf2post."""
target = GenericBackendV2(
num_qubits=7,
basis_gates=["cx", "id", "rz", "sx", "x"],
coupling_map=LAGOS_CMAP,
seed=42,
)
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0, 1)
qc.measure_all()
_ = transpile(qc, target, optimization_level=1, callback=self.callback)
self.assertIn("TrivialLayout", self.passes)
self.assertNotIn("VF2Layout", self.passes)
self.assertNotIn("SabreLayout", self.passes)
self.assertNotIn("VF2PostLayout", self.passes)
# Assert we don't run standalone sabre swap
self.assertNotIn("SabreSwap", self.passes)
def test_level1_not_run_vf2post_layout_when_vf2layout_is_perfect(self):
"""Test that if we find a vf2 perfect layout we don't run vf2post."""
target = GenericBackendV2(
num_qubits=7,
basis_gates=["cx", "id", "rz", "sx", "x"],
coupling_map=LAGOS_CMAP,
seed=42,
)
qc = QuantumCircuit(4)
qc.h(0)
qc.cx(0, 1)
qc.cx(0, 2)
qc.cx(0, 3)
qc.measure_all()
_ = transpile(qc, target, optimization_level=1, callback=self.callback)
self.assertIn("TrivialLayout", self.passes)
self.assertIn("VF2Layout", self.passes)
self.assertNotIn("SabreLayout", self.passes)
self.assertNotIn("VF2PostLayout", self.passes)
# Assert we don't run standalone sabre swap
self.assertNotIn("SabreSwap", self.passes)
def test_level1_runs_vf2post_layout_when_routing_required_control_flow(self):
"""Test that if we run routing as part of sabre layout VF2PostLayout runs."""
target = GenericBackendV2(
num_qubits=7,
basis_gates=["cx", "id", "rz", "sx", "x"],
coupling_map=LAGOS_CMAP,
seed=42,
)
_target = target.target
target._target.add_instruction(ForLoopOp, name="for_loop")
qc = QuantumCircuit(5)
qc.h(0)
qc.cy(0, 1)
qc.cy(0, 2)
qc.cy(0, 3)
qc.cy(0, 4)
with qc.for_loop((1,)):
qc.cx(0, 1)
qc.measure_all()
_ = transpile(qc, target, optimization_level=1, callback=self.callback)
# Expected call path for layout and routing is:
# 1. TrivialLayout (no perfect match)
# 2. VF2Layout (no perfect match)
# 3. SabreLayout (heuristic layout)
# 4. VF2PostLayout (applies a better layout)
self.assertIn("TrivialLayout", self.passes)
self.assertIn("VF2Layout", self.passes)
self.assertIn("SabreLayout", self.passes)
self.assertIn("VF2PostLayout", self.passes)
def test_level1_not_runs_vf2post_layout_when_layout_method_set_control_flow(self):
"""Test that if we don't run VF2PostLayout with custom layout_method."""
target = GenericBackendV2(
num_qubits=7,
basis_gates=["cx", "id", "rz", "sx", "x"],
coupling_map=LAGOS_CMAP,
seed=42,
)
_target = target.target
target._target.add_instruction(ForLoopOp, name="for_loop")
qc = QuantumCircuit(5)
qc.h(0)
qc.cy(0, 1)
qc.cy(0, 2)
qc.cy(0, 3)
qc.cy(0, 4)
with qc.for_loop((1,)):
qc.cx(0, 1)
qc.measure_all()
_ = transpile(
qc, target, optimization_level=1, layout_method="dense", callback=self.callback
)
self.assertNotIn("TrivialLayout", self.passes)
self.assertNotIn("VF2Layout", self.passes)
self.assertNotIn("SabreLayout", self.passes)
self.assertNotIn("VF2PostLayout", self.passes)
self.assertIn("DenseLayout", self.passes)
self.assertIn("SabreSwap", self.passes)
def test_level1_not_run_vf2post_layout_when_trivial_is_perfect_control_flow(self):
"""Test that if we find a trivial perfect layout we don't run vf2post."""
target = GenericBackendV2(
num_qubits=7,
basis_gates=["cx", "id", "rz", "sx", "x"],
coupling_map=LAGOS_CMAP,
seed=42,
)
_target = target.target
target._target.add_instruction(ForLoopOp, name="for_loop")
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0, 1)
with qc.for_loop((1,)):
qc.cx(0, 1)
qc.measure_all()
_ = transpile(qc, target, optimization_level=1, callback=self.callback)
self.assertIn("TrivialLayout", self.passes)
self.assertNotIn("VF2Layout", self.passes)
self.assertNotIn("SabreLayout", self.passes)
self.assertNotIn("SabreSwap", self.passes)
self.assertNotIn("VF2PostLayout", self.passes)
def test_level1_not_run_vf2post_layout_when_vf2layout_is_perfect_control_flow(self):
"""Test that if we find a vf2 perfect layout we don't run vf2post."""
target = GenericBackendV2(
num_qubits=7,
basis_gates=["cx", "id", "rz", "sx", "x"],
coupling_map=LAGOS_CMAP,
seed=42,
)
_target = target.target
target._target.add_instruction(ForLoopOp, name="for_loop")
qc = QuantumCircuit(4)
qc.h(0)
qc.cx(0, 1)
qc.cx(0, 2)
qc.cx(0, 3)
with qc.for_loop((1,)):
qc.cx(0, 1)
qc.measure_all()
_ = transpile(qc, target, optimization_level=1, callback=self.callback)
self.assertIn("TrivialLayout", self.passes)
self.assertIn("VF2Layout", self.passes)
self.assertNotIn("SabreLayout", self.passes)
self.assertNotIn("VF2PostLayout", self.passes)
self.assertNotIn("SabreSwap", self.passes)
@ddt
class TestInitialLayouts(QiskitTestCase):
"""Test transpiling with different layouts"""
@data(0, 1, 2, 3)
def test_layout_1711(self, level):
"""Test that a user-given initial layout is respected
in the qobj.
See: https://github.com/Qiskit/qiskit-terra/issues/1711
"""
# build a circuit which works as-is on the coupling map, using the initial layout
qr = QuantumRegister(3, "q")
cr = ClassicalRegister(3)
ancilla = QuantumRegister(13, "ancilla")
qc = QuantumCircuit(qr, cr)
qc.cx(qr[2], qr[1])
qc.cx(qr[2], qr[0])
initial_layout = {0: qr[1], 2: qr[0], 15: qr[2]}
final_layout = {
0: qr[1],
1: ancilla[0],
2: qr[0],
3: ancilla[1],
4: ancilla[2],
5: ancilla[3],
6: ancilla[4],
7: ancilla[5],
8: ancilla[6],
9: ancilla[7],
10: ancilla[8],
11: ancilla[9],
12: ancilla[10],
13: ancilla[11],
14: ancilla[12],
15: qr[2],
}
backend = GenericBackendV2(num_qubits=16, coupling_map=RUESCHLIKON_CMAP, seed=42)
qc_b = transpile(qc, backend, initial_layout=initial_layout, optimization_level=level)
self.assertEqual(qc_b._layout.initial_layout._p2v, final_layout)
for inst in qc_b.data:
if inst.operation.name == "cx":
self.assertIn(
tuple(qc_b.find_bit(bit).index for bit in inst.qubits), backend.coupling_map
)
self.assertIn([qc_b.find_bit(bit).index for bit in inst.qubits], [[15, 0], [15, 2]])
@data(0, 1, 2, 3)
def test_layout_2532(self, level):
"""Test that a user-given initial layout is respected,
in the transpiled circuit.
See: https://github.com/Qiskit/qiskit-terra/issues/2532
"""
# build a circuit which works as-is on the coupling map, using the initial layout
qr = QuantumRegister(5, "q")
cr = ClassicalRegister(2)
ancilla = QuantumRegister(9, "ancilla")
qc = QuantumCircuit(qr, cr)
qc.cx(qr[2], qr[4])
initial_layout = {
qr[2]: 11,
qr[4]: 3, # map to [11, 3] connection
qr[0]: 1,
qr[1]: 5,
qr[3]: 9,
}
final_layout = {
0: ancilla[0],
1: qr[0],
2: ancilla[1],
3: qr[4],
4: ancilla[2],
5: qr[1],
6: ancilla[3],
7: ancilla[4],
8: ancilla[5],
9: qr[3],
10: ancilla[6],
11: qr[2],
12: ancilla[7],
13: ancilla[8],
}
backend = GenericBackendV2(num_qubits=14, coupling_map=MELBOURNE_CMAP, seed=42)
qc_b = transpile(qc, backend, initial_layout=initial_layout, optimization_level=level)
self.assertEqual(qc_b._layout.initial_layout._p2v, final_layout)
output_qr = qc_b.qregs[0]
for instruction in qc_b:
if instruction.operation.name == "cx":
for qubit in instruction.qubits:
self.assertIn(qubit, [output_qr[11], output_qr[3]])
@data(0, 1, 2, 3)
def test_layout_2503(self, level):
"""Test that a user-given initial layout is respected,
even if cnots are not in the coupling map.
See: https://github.com/Qiskit/qiskit-terra/issues/2503
"""
# build a circuit which works as-is on the coupling map, using the initial layout
qr = QuantumRegister(3, "q")
cr = ClassicalRegister(2)
ancilla = QuantumRegister(17, "ancilla")
qc = QuantumCircuit(qr, cr)
qc.append(U3Gate(0.1, 0.2, 0.3), [qr[0]])
qc.append(U2Gate(0.4, 0.5), [qr[2]])
qc.barrier()
qc.cx(qr[0], qr[2])
initial_layout = [6, 7, 12]
final_layout = {
0: ancilla[0],
1: ancilla[1],
2: ancilla[2],
3: ancilla[3],
4: ancilla[4],
5: ancilla[5],
6: qr[0],
7: qr[1],
8: ancilla[6],
9: ancilla[7],
10: ancilla[8],
11: ancilla[9],
12: qr[2],
13: ancilla[10],
14: ancilla[11],
15: ancilla[12],
16: ancilla[13],
17: ancilla[14],
18: ancilla[15],
19: ancilla[16],
}
backend = GenericBackendV2(
num_qubits=20,
coupling_map=TOKYO_CMAP,
basis_gates=["id", "u1", "u2", "u3", "cx"],
seed=42,
)
qc_b = transpile(qc, backend, initial_layout=initial_layout, optimization_level=level)
self.assertEqual(qc_b._layout.initial_layout._p2v, final_layout)
output_qr = qc_b.qregs[0]
self.assertIsInstance(qc_b[0].operation, U3Gate)
self.assertEqual(qc_b[0].qubits[0], output_qr[6])
self.assertIsInstance(qc_b[1].operation, U2Gate)
self.assertEqual(qc_b[1].qubits[0], output_qr[12])
@ddt
class TestFinalLayouts(QiskitTestCase):
"""Test final layouts after preset transpilation"""
@data(0, 1, 2, 3)
def test_layout_tokyo_2845(self, level):
"""Test that final layout in a Tokyo-like device
is not the trivial layout for optimization level>0
See: https://github.com/Qiskit/qiskit-terra/issues/2845
"""
qr1 = QuantumRegister(3, "qr1")
qr2 = QuantumRegister(2, "qr2")
qc = QuantumCircuit(qr1, qr2)
qc.cx(qr1[0], qr1[1])
qc.cx(qr1[1], qr1[2])
qc.cx(qr1[2], qr2[0])
qc.cx(qr2[0], qr2[1])
ancilla = QuantumRegister(15, "ancilla")
trivial_layout = {
0: qr1[0],
1: qr1[1],
2: qr1[2],
3: qr2[0],
4: qr2[1],
5: ancilla[0],
6: ancilla[1],
7: ancilla[2],
8: ancilla[3],
9: ancilla[4],
10: ancilla[5],
11: ancilla[6],
12: ancilla[7],
13: ancilla[8],
14: ancilla[9],
15: ancilla[10],
16: ancilla[11],
17: ancilla[12],
18: ancilla[13],
19: ancilla[14],
}
vf2_layout = {
0: ancilla[0],
1: ancilla[1],
2: ancilla[2],
3: ancilla[3],
4: ancilla[4],
5: qr1[2],
6: qr2[0],
7: qr2[1],
8: ancilla[5],
9: ancilla[6],
10: qr1[1],
11: qr1[0],
12: ancilla[7],
13: ancilla[8],
14: ancilla[9],
15: ancilla[10],
16: ancilla[11],
17: ancilla[12],
18: ancilla[13],
19: ancilla[14],
}
# Trivial layout
expected_layout_level0 = trivial_layout
# Dense layout
expected_layout_level1 = vf2_layout
# CSP layout
expected_layout_level2 = vf2_layout
expected_layout_level3 = vf2_layout
expected_layouts = [
expected_layout_level0,
expected_layout_level1,
expected_layout_level2,
expected_layout_level3,
]
backend = GenericBackendV2(num_qubits=20, coupling_map=TOKYO_CMAP, seed=42)
result = transpile(qc, backend, optimization_level=level, seed_transpiler=42)
self.assertEqual(result._layout.initial_layout._p2v, expected_layouts[level])
@data(0, 1, 2, 3)
def test_layout_tokyo_fully_connected_cx(self, level):
"""Test that final layout in a Tokyo-like device
is a fully connected circuit
"""
qr = QuantumRegister(5, "qr")
qc = QuantumCircuit(qr)
for qubit_target in qr:
for qubit_control in qr:
if qubit_control != qubit_target:
qc.cx(qubit_control, qubit_target)
expected_layouts = [
[0, 1, 2, 3, 4],
[6, 5, 11, 10, 2],
[6, 5, 2, 11, 10],
[6, 5, 2, 11, 10],
]
backend = GenericBackendV2(num_qubits=20, coupling_map=TOKYO_CMAP, seed=42)
result = transpile(qc, backend, optimization_level=level, seed_transpiler=42)
self.assertEqual(
result.layout.initial_index_layout(filter_ancillas=True), expected_layouts[level]
)
@data(0, 1, 2, 3)
def test_all_levels_use_trivial_if_perfect(self, level):
"""Test that we always use trivial if it's a perfect match.
See: https://github.com/Qiskit/qiskit-terra/issues/5694 for more
details
"""
backend = GenericBackendV2(num_qubits=20, coupling_map=TOKYO_CMAP, seed=42)
rows = [x[0] for x in backend.coupling_map]
cols = [x[1] for x in backend.coupling_map]
adjacency_matrix = np.zeros((20, 20))
adjacency_matrix[rows, cols] = 1
qc = GraphStateGate(adjacency_matrix).definition
qc.measure_all()
expected = {
0: Qubit(QuantumRegister(20, "q"), 0),
1: Qubit(QuantumRegister(20, "q"), 1),
2: Qubit(QuantumRegister(20, "q"), 2),
3: Qubit(QuantumRegister(20, "q"), 3),
4: Qubit(QuantumRegister(20, "q"), 4),
5: Qubit(QuantumRegister(20, "q"), 5),
6: Qubit(QuantumRegister(20, "q"), 6),
7: Qubit(QuantumRegister(20, "q"), 7),
8: Qubit(QuantumRegister(20, "q"), 8),
9: Qubit(QuantumRegister(20, "q"), 9),
10: Qubit(QuantumRegister(20, "q"), 10),
11: Qubit(QuantumRegister(20, "q"), 11),
12: Qubit(QuantumRegister(20, "q"), 12),
13: Qubit(QuantumRegister(20, "q"), 13),
14: Qubit(QuantumRegister(20, "q"), 14),