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 all commits
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
30 changes: 25 additions & 5 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 @@ -187,8 +195,9 @@ def _run_coupling_map(self, dag, wire_map, edges=None):
dag.substitute_node_with_dag(node, self._rzz_dag(*node.op.params))
else:
raise TranspilerError(
f"Flipping of gate direction is only supported "
f"for {list(self._static_replacements)} at this time, not '{node.name}'."
f"'{node.name}' would be supported on '{qargs}' if the direction were"
f" swapped, but no rules are known to do that."
f" {list(self._KNOWN_REPLACEMENTS)} can be automatically flipped."
)
return dag

Expand Down Expand Up @@ -281,11 +290,22 @@ def _run_target(self, dag, wire_map):
f"The circuit requires a connection between physical qubits {qargs}"
f" for {node.name}"
)
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"'{node.name}' would be supported on '{qargs}' if the direction were"
f" swapped, but no rules are known to do that."
f" {list(self._KNOWN_REPLACEMENTS)} can be automatically flipped."
)
else:
raise TranspilerError(
f"Flipping of gate direction is only supported "
f"for {list(self._static_replacements)} at this time, not '{node.name}'."
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
43 changes: 43 additions & 0 deletions test/python/transpiler/test_gate_direction.py
Original file line number Diff line number Diff line change
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, "'my_2q_gate' would be supported.*"):
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, "'my_2q_gate' would be supported.*"):
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)

def test_allows_calibrated_gates_coupling_map(self):
"""Test that the gate direction pass allows a gate that's got a calibration to pass through
without error."""
Expand Down