torchquantum icon indicating copy to clipboard operation
torchquantum copied to clipboard

`tq2qiskit` fails when the `QuantumModule` contains a `nn.ModuleList()` of gates

Open teaguetomesh opened this issue 1 year ago • 1 comments

I wanted to visualize the model I had built to check whether I had correctly implemented it. However, the conversion to qiskit fails when the quantum model contains a nn.ModuleList

Minimal example:

class ExampleQNN(tq.QuantumModule):
    def __init__(self):
        super().__init__()
        
        self.gates = torch.nn.ModuleList()
        for _ in range(3):
            self.gates.append(tq.U3(has_params=True, trainable=True))

    @tq.static_support
    def forward(self, q_device: tq.QuantumDevice):
        self.q_device = q_device

        for gate in self.gates:
            gate(self.q_device, wires=0)
        
        pauli_Z_expval = tq.expval(self.q_device, wires=0, observables=tq.PauliZ())
        
        return pauli_Z_expval


model = ExampleQNN()
circ = tq2qiskit(tq.QuantumDevice(n_wires=1), model, draw=True)

This fails with the following error message: Screenshot 2023-08-17 at 2 41 31 PM

Looking online, I believe that calling Module.modules() instead, could fix the issue.

teaguetomesh avatar Aug 17 '23 19:08 teaguetomesh

Hi! Thanks for opening the issue! We’re currently working on expanding the tq2qiskit and qiskit2tq functionalities and will definitely make sure to cover this case!