4
$\begingroup$

I'm trying to use Cirq with TensorFlow Quantum to simulate a variational quantum classifier. There's a tutorial on the TFQ website on building a quantum neural network to classify a simplified version of MNIST, which I've been using for reference.

The classifier that I'm building requires building my own custom gates.

After encoding the data as quantum circuits, the next step is to convert these Cirq circuits to tensors using tfq.convert_to_tensor.

I've found that this function works fine for any built-in Cirq gates, but when I pass my own custom gate as the argument, I get ValueError: Cannot serialize op <__main__.Custom_Gate object at...

Here's some watered down code that gives the gist of my attempts:

def simple_func(x):
    return x*cirq.z

class Custom_Gate(cirq.Gate):
    def __init__(self, x, n):
        self.x = x
        self.n = n
    def _unitary_(self):
        return simple_func(self.x)
    def _num_qubits_(self):
        return self.n
    def _circuit_diagram_info_(self, args: 'cirq.CircuitDiagramInfoArgs'):
        return ['U']

x = 3
n = 1
U = Custom_Gate(x, n)
q0 = cirq.GridQubit(0, 0)
test_circuit = cirq.Circuit()
test_circuit.append(U.on(q0))
SVGCircuit(test_circuit)

tfq.convert_to_tensor([test_circuit])

Am I making a mistake somewhere? Or does tfq.convert_to_tensor just not work for custom gates?

Thank you.

$\endgroup$
3
  • $\begingroup$ _unitary_ instead of __unitary__? Does cirq.unitary(gate) work on it? $\endgroup$ Dec 7, 2020 at 5:48
  • $\begingroup$ Thanks, that was a typo. Michael pointed out the larger problem below. $\endgroup$
    – ryanhill1
    Dec 7, 2020 at 21:57
  • $\begingroup$ @ Craig_Gidney Were you able to Serializing custom gates? $\endgroup$ Mar 31, 2021 at 15:03

1 Answer 1

5
$\begingroup$

I'm the engineer who looks after TensorFlow Quantum. Serializing custom gates is not supported. There is an active issue on the GitHub here: https://github.com/tensorflow/quantum/issues/354 . A quick workaround would be to try and determine the gate decomposition for your custom gate in terms of tfq.util.get_supported_gates gate instances. A good place to start might be the cirq.kak_decomposition.

Michael

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.