Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Improve error messages in Target-based GateDirection pass #9787

Merged
merged 4 commits into from
Mar 14, 2023
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 22 additions & 4 deletions qiskit/transpiler/passes/utils/gate_direction.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@

from qiskit.converters import dag_to_circuit, circuit_to_dag
from qiskit.circuit import QuantumRegister, ControlFlowOp
from qiskit.dagcircuit import DAGCircuit
from qiskit.dagcircuit import DAGCircuit, DAGOpNode
from qiskit.circuit.library.standard_gates import (
RYGate,
HGate,
Expand All @@ -34,6 +34,10 @@
)


def _swap_node_qargs(node):
return DAGOpNode(node.op, node.qargs[::-1], node.cargs)


class GateDirection(TransformationPass):
"""Modify asymmetric gates to match the hardware coupling direction.

Expand All @@ -58,6 +62,8 @@ class GateDirection(TransformationPass):
└──────┘ └───┘└──────┘└───┘
"""

_KNOWN_REPLACEMENTS = frozenset(["cx", "cz", "ecr", "swap", "rzx", "rxx", "ryy", "rzz"])

def __init__(self, coupling_map, target=None):
"""GateDirection pass.

Expand Down Expand Up @@ -99,6 +105,8 @@ def __init__(self, coupling_map, target=None):
self._swap_dag.add_qreg(qr)
self._swap_dag.apply_operation_back(SwapGate(), [qr[1], qr[0]], [])

# If adding more replacements (either static or dynamic), also update the class variable
# `_KNOWN_REPLACMENTS` to include them in the error messages.
self._static_replacements = {
"cx": self._cx_dag,
"cz": self._cz_dag,
Expand Down Expand Up @@ -186,7 +194,7 @@ def _run_coupling_map(self, dag, wire_map, edges=None):
else:
raise TranspilerError(
f"Flipping of gate direction is only supported "
f"for {list(self._static_replacements)} at this time, not '{node.name}'."
f"for {list(self._KNOWN_REPLACEMENTS)} at this time, not '{node.name}'."
)
return dag

Expand Down Expand Up @@ -277,11 +285,21 @@ def _run_target(self, dag, wire_map):
f"The circuit requires a connection between physical qubits {qargs}"
f" for {node.name}"
)
else:
elif self.target.instruction_supported(node.name, qargs):
continue
elif self.target.instruction_supported(node.name, swapped) or dag.has_calibration_for(
_swap_node_qargs(node)
):
raise TranspilerError(
f"Flipping of gate direction is only supported "
f"for {list(self._static_replacements)} at this time, not '{node.name}'."
f"for {list(self._KNOWN_REPLACEMENTS)} at this time, not '{node.name}'."
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's worth also mentioning only opposite direction is defined?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think that's kind of implied by the running pass?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pulse level user might be lazy for managing order matching of virtual and logical qubits. So one might hit this error with some typo. Saying having calibration of another direction might help the user to find what's wrong in his code. Otherwise one might start investigating how to implement gate flipping.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

How is the new message in 607914e for you?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks. I like new one.

)
else:
raise TranspilerError(
f"'{node.name}' with parameters '{node.op.params}' is not supported on qubits"
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This message could seem bit weird when parameter is empty.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I guess marginally weird, but still perfectly understandable, right? It'll just say something like

'cx' with parameters '[]' is not supported

which still looks pretty sensible and easy to parse.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I can change it if you'd prefer, though.

Copy link
Contributor

@nkanazawa1989 nkanazawa1989 Mar 13, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm not sure how much parameters are important for gate direction. If the user tries slightly different parameter, I don't think he will succeed in transpile.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The point is that a Target can allow a gate with certain parameters on certain qubit pairs, but not other parameter values or qubits. I put the parameters in because I didn't want people to be confused if their target supports (say) my_rotation with a specific angle of $\pi/2$ but not other angles, and the error just says "my_rotation isn't supported".

I think it's a bit beyond scope for us to try and pull out all "similar" instructions from the target and try and guess which of those the user might have meant, though.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fair enough.

f" '{qargs}' in either direction."
)

return dag

def run(self, dag):
Expand Down
47 changes: 45 additions & 2 deletions test/python/transpiler/test_gate_direction.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,8 @@

import ddt

from qiskit import ClassicalRegister, QuantumRegister, QuantumCircuit
from qiskit.circuit import Parameter
from qiskit import ClassicalRegister, QuantumRegister, QuantumCircuit, pulse
from qiskit.circuit import Parameter, Gate
from qiskit.circuit.library import (
CXGate,
CZGate,
Expand Down Expand Up @@ -439,6 +439,49 @@ def test_target_control_flow(self):
pass_ = GateDirection(None, target)
self.assertEqual(pass_(circuit), expected)

def test_target_cannot_flip_message(self):
"""A suitable error message should be emitted if the gate would be supported if it were
flipped."""
gate = Gate("my_2q_gate", 2, [])
target = Target(num_qubits=2)
target.add_instruction(gate, properties={(0, 1): None})

circuit = QuantumCircuit(2)
circuit.append(gate, (1, 0))

pass_ = GateDirection(None, target)
with self.assertRaisesRegex(TranspilerError, "Flipping of gate direction.*"):
pass_(circuit)

def test_target_cannot_flip_message_calibrated(self):
"""A suitable error message should be emitted if the gate would be supported if it were
flipped."""
target = Target(num_qubits=2)
target.add_instruction(CXGate(), properties={(0, 1): None})

gate = Gate("my_2q_gate", 2, [])
circuit = QuantumCircuit(2)
circuit.append(gate, (1, 0))
circuit.add_calibration(gate, (0, 1), pulse.ScheduleBlock())

pass_ = GateDirection(None, target)
with self.assertRaisesRegex(TranspilerError, "Flipping of gate direction.*"):
pass_(circuit)

def test_target_unknown_gate_message(self):
"""A suitable error message should be emitted if the gate isn't valid in either direction on
the target."""
gate = Gate("my_2q_gate", 2, [])
target = Target(num_qubits=2)
target.add_instruction(CXGate(), properties={(0, 1): None})

circuit = QuantumCircuit(2)
circuit.append(gate, (0, 1))

pass_ = GateDirection(None, target)
with self.assertRaisesRegex(TranspilerError, "'my_2q_gate'.*not supported on qubits .*"):
pass_(circuit)


if __name__ == "__main__":
unittest.main()