Swap test using different registers

Hi @Thomas,

Welcome to the forum and thank you so much for your question! :slight_smile:

There is no way, unfortunately, to perform operations between quantum functions that are being executed on separate devices. The concept of a QNode necessitates that it takes classical inputs and provides classical outputs, so every quantum operation is applied within the QNode itself. Therefore the best approach might be to use a single device and a single QNode.

The following could be an approach for performing the swap test using a single device and a single QNode:

import pennylane as qml
from pennylane import numpy as np
from pennylane.templates import AmplitudeEmbedding

# define two random input vectors
inp1 = np.array([1,2,0,0])
inp2 = np.array([0,1,0,0])

qubit_number = int(np.ceil(np.log2(len(inp1))))

dev = qml.device('default.qubit', wires=3 * qubit_number)

@qml.qnode(dev)
def prepare_reg1(inp):
    AmplitudeEmbedding(features=inp, wires=range(qubit_number, 3 * qubit_number), normalize=True, pad_with=0.)
    
    ancillea = []
    for i in range(qubit_number):

        anc = i
        ancillea.append(anc)
        first_state = i+qubit_number
        second_state = i+ 2*qubit_number
        qml.CSWAP(wires=[anc, first_state, second_state])

    return qml.expval(qml.operation.Tensor(*[qml.PauliZ(i) for i in ancillea]))

input_state = np.concatenate([inp1, inp2])
prepare_reg1(input_state)

print(prepare_reg1.draw())
 0: ─────────────────────────────────╭C─────╭┤ ⟨Z ⊗ Z⟩ 
 1: ──────────────────────────╭C─────│──────╰┤ ⟨Z ⊗ Z⟩ 
 2: ──╭QubitStateVector(M0)──│──────├SWAP───┤         
 3: ──├QubitStateVector(M0)──├SWAP──│───────┤         
 4: ──├QubitStateVector(M0)──│──────╰SWAP───┤         
 5: ──╰QubitStateVector(M0)──╰SWAP──────────┤         
M0 =
[0.40824829 0.81649658 0.         0.         0.         0.40824829
 0.         0.         0.         0.         0.         0.
 0.         0.         0.         0.        ]

Note that you may want to update the type of statistics obtained on the ancillae qubits.

Let us know if this would be something that works for you or if you’d have any further questions!

1 Like