CQCL / tket

Source code for the TKET quantum compiler, Python bindings and utilities
https://docs.quantinuum.com/tket/
Apache License 2.0
261 stars 47 forks source link

Runtime error when using `KAKDecomposition` on Circboxes #1553

Open Bennybenassius opened 3 months ago

Bennybenassius commented 3 months ago

Ilan and I have found this issue during random testing:

When running:

from pytket import Circuit, Qubit
from pytket.circuit import CircBox
from pytket.passes import *

subcirc_0 = Circuit(0, "subcirc_0")
qbit_0 = Qubit("qbit_0", 0)
subcirc_0.add_qubit(qbit_0)
qbit_1 = Qubit("qbit_1", 0)
subcirc_0.add_qubit(qbit_1)
subcirc_0.X(qbit_0)
circbox_subcirc_0 = CircBox(subcirc_0)

subcirc_1 = Circuit(0, "subcirc_1")

qreg_0 = subcirc_1.add_q_register("qreg_0",1)
qreg_1 = subcirc_1.add_q_register("qreg_1",1)
subcirc_1.CZ(qreg_0[0], qreg_1[0])
circbox_subcirc_1 = CircBox(subcirc_1)

main_circ = Circuit(4, 2, "main_circ")

# Applying gates 
main_circ.add_gate(circbox_subcirc_0,[0, 1])
# main_circ.CX(0, 2).X(0)
main_circ.add_gate(circbox_subcirc_1,[0, 1])
main_circ.CX(1, 2)

KAKDecomposition().apply(main_circ)

Throws a runtime error:

 RuntimeError: Cannot obtain matrix from op: CircBox 

This error seems to only occur when the Circboxes are right next to each other. Upon uncommenting the line # main_circ.CX(0, 2).X(0), the code runs without an issue and simply leaves the Circboxes untouched. This bug also disappears when DecomposeBoxes is used on the Circuit first.

CalMacCQ commented 2 months ago

Hmm I find this surprising that the error only manifests when the two CircBox(es) are next to one another. As you pointed out if we put gates in between then the KAKDecomposition pass can be applied without issue.

The subcircuits here are pure quantum so the subcircuit unitary is well defined.

We can do

circbox_subcirc_0.get_unitary()

and

circbox_subcirc_1.get_unitary()

without issue.

In the default_compilation_pass for the different backends we always call DecomposeBoxes prior to doing local rewrites like KAKDecomposition or FullPeepholeOptimise. However its understandable that the beahviour exhibited above is confusing. If indeed DecomposeBoxes is needed then this should ideally be clear from the error message.

Any ideas @cqc-alec ?

cqc-alec commented 2 months ago

I would expect KAKDecomposition to leave all CircBoxes alone and optimize around them; this is clearly a bug.