Pennylane-COBYLA integration

Hi! I am trying to minizime Ry Params of BasicEntanglerLayers with COBYLA optimizer. First, I used AmplitudeEmbedding which not allows gradient based optimizers as i infer from its warning.

This is the circuit:

def circuit(features, weights):
    qml.AmplitudeEmbedding(features=features, wires=range(0, NUM_LAT + NUM_TRASH), normalize=True, pad_with=features.flatten().shape[0])
    qml.Barrier(wires=range(0,WIRES), only_visual=True)
    qml.BasicEntanglerLayers(weights=weights, wires=range(0, NUM_LAT + NUM_TRASH), rotation=qml.RY)
    qml.Barrier(wires=range(0,WIRES), only_visual=True)
    for i in range(NUM_REF):
        qml.CSWAP(wires=[WIRES, NUM_LAT+i, NUM_LAT+NUM_TRASH+i])
    # Z Measure
    return qml.probs(WIRES)

This is the cost function:

def cost(weights):
    return np.mean(circuit(image, weights)[:,1])

This is the opt:

opt_res = minimize(cost, initial_weights, method='COBYLA')

This is the traceback:

ValueError: Weights tensor must be 2-dimensional or 3-dimensional if batching; got shape (10,)

Seems that COBYLA is flattening the weights tensor. BasicEntanglerLayers expects a weight tensor (layers, num_weights). In this example (1, 10).


Name: PennyLane
Version: 0.30.0
Summary: PennyLane is a Python quantum machine learning library by Xanadu Inc.
Home-page: GitHub - PennyLaneAI/pennylane: PennyLane is a cross-platform Python library for differentiable programming of quantum computers. Train a quantum computer the same way as a neural network.
License: Apache License 2.0
Location: /home/contepablod/.local/lib/python3.10/site-packages
Requires: appdirs, autograd, autoray, cachetools, networkx, numpy, pennylane-lightning, requests, rustworkx, scipy, semantic-version, toml
Required-by: PennyLane-Lightning, PennyLane-Lightning-GPU, PennyLane-qiskit

Platform info: Linux-
Python version: 3.10.6
Numpy version: 1.23.5
Scipy version: 1.10.1
Installed devices:

  • qiskit.aer (PennyLane-qiskit-0.30.1)
  • qiskit.basicaer (PennyLane-qiskit-0.30.1)
  • qiskit.ibmq (PennyLane-qiskit-0.30.1)
  • qiskit.ibmq.circuit_runner (PennyLane-qiskit-0.30.1)
  • qiskit.ibmq.sampler (PennyLane-qiskit-0.30.1)
  • default.gaussian (PennyLane-0.30.0)
  • default.mixed (PennyLane-0.30.0)
  • default.qubit (PennyLane-0.30.0)
  • default.qubit.autograd (PennyLane-0.30.0)
  • default.qubit.jax (PennyLane-0.30.0)
  • (PennyLane-0.30.0)
  • default.qubit.torch (PennyLane-0.30.0)
  • default.qutrit (PennyLane-0.30.0)
  • null.qubit (PennyLane-0.30.0)
  • lightning.qubit (PennyLane-Lightning-0.30.0)
  • lightning.gpu (PennyLane-Lightning-GPU-0.30.0)

Any insights?

Already solved, just passed to COBYLA initial_weights[0] and then reshaped inside the cost function to x = weights.reshape(1,10) being x the function parameters to allow the weights being processed by the circuit.

1 Like

Thanks @contepablod! Glad you solved your problem :slight_smile: