4

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.

ryanhill1
  • 2,623
  • 1
  • 11
  • 39

1 Answers1

5

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

Michael
  • 393
  • 1
  • 5