Gate not supported in default.mixed device

I am using default.mixed device but getting the following error

pennylane._device.DeviceError: Gate C(CNOT) not supported on device default.mixed

Is there any way to tackle this?
My code is the following:

import pennylane as qml
from pennylane import numpy as np
import math

# Generate density matrices and arbitrary labels
density_matrix = []
labels = []
for i in range(20):
    state = np.random.randn(16,1) + 1j*np.random.randn(16, 1)
    state_normlized = np.array(state/np.linalg.norm(state))
    density_matrix.append(np.dot(state_normlized, state_normlized.conj().T))
    if state_normlized[0].real > 0:
        labels.append(1)
    else:
        labels.append(0)


def cross_entropy(labels, predictions):
    loss = 0
    for l, p in zip(labels, predictions):
        c_entropy = l * (anp.log(p[l])) + (1 - l) * anp.log(1 - p[1 - l])
        loss = loss + c_entropy
    return -1 * loss
    

def cost(params, X, Y, cost_fn):
    predictions = np.array([circuit(x, params) for x in X])
    if cost_fn == 'cross_entropy':
        loss = cross_entropy(Y, predictions)
    return loss
    

dev = qml.device('default.mixed', wires = 7)
@qml.qnode(dev)
def circuit(features, params):
    ancilla_state = [1/math.sqrt(6), 1/math.sqrt(6), 1/math.sqrt(6), 1/math.sqrt(6), 1/math.sqrt(6), 1/math.sqrt(6), 0, 0]
    # Embedding of data and initialization of control register
    qml.QubitDensityMatrix(features, wires = [0, 1, 2, 3])
    qml.AmplitudeEmbedding(ancilla_state, wires = [4, 5, 6])
    
    qml.ctrl(qml.IsingXX, control=(4,5,6), control_values = (0, 0, 0))(params[0], wires=(0,1))
    qml.ctrl(qml.IsingXX, control=(4,5,6), control_values = (0, 0, 1))(params[1], wires=(0,2))
    qml.ctrl(qml.IsingXX, control=(4,5,6), control_values = (0, 1, 0))(params[2], wires=(0,3))
    qml.ctrl(qml.IsingXX, control=(4,5,6), control_values = (0, 1, 1))(params[3], wires=(1,2))
    qml.ctrl(qml.IsingXX, control=(4,5,6), control_values = (1, 0, 0))(params[4], wires=(1,3))
    qml.ctrl(qml.IsingXX, control=(4,5,6), control_values = (1, 0, 1))(params[5], wires=(2,3))
       
    result = qml.probs(wires=0)
    return result
    
batch_size = 6
learning_rate = 0.005
total_params = 6  
params = np.random.randn(total_params, requires_grad=True)
opt = qml.NesterovMomentumOptimizer(stepsize=learning_rate)
cost_fn = "cross_entropy"

for it in range(10):
    batch_index = np.random.randint(0, len(density_matrix), (batch_size,))
    X_batch = [density_matrix[i] for i in batch_index]
    Y_batch = [labels[i] for i in batch_index]
    params, cost_new = opt.step_and_cost(lambda v: cost(v, X_batch, Y_batch, cost_fn), params)
    

I get the following error message:
File “/home/sreetamadas/anaconda3/lib/python3.10/site-packages/pennylane/qnode.py”, line 1027, in call
res = qml.execute(
File “/home/sreetamadas/anaconda3/lib/python3.10/site-packages/pennylane/interfaces/execution.py”, line 616, in execute
results = inner_execute(tapes)
File “/home/sreetamadas/anaconda3/lib/python3.10/site-packages/pennylane/interfaces/execution.py”, line 249, in inner_execute
return cached_device_execution(tapes)
File “/home/sreetamadas/anaconda3/lib/python3.10/site-packages/pennylane/interfaces/execution.py”, line 371, in wrapper
res = list(fn(tuple(execution_tapes.values()), **kwargs))
File “/home/sreetamadas/anaconda3/lib/python3.10/contextlib.py”, line 79, in inner
return func(*args, **kwds)
File “/home/sreetamadas/anaconda3/lib/python3.10/site-packages/pennylane/_qubit_device.py”, line 460, in batch_execute
res = self.execute(circuit)
File “/home/sreetamadas/anaconda3/lib/python3.10/site-packages/pennylane/devices/default_mixed.py”, line 685, in execute
return super().execute(circuit, **kwargs)
File “/home/sreetamadas/anaconda3/lib/python3.10/site-packages/pennylane/_qubit_device.py”, line 276, in execute
self.check_validity(circuit.operations, circuit.observables)
File “/home/sreetamadas/anaconda3/lib/python3.10/site-packages/pennylane/_device.py”, line 984, in check_validity
raise DeviceError(
pennylane._device.DeviceError: Gate C(CNOT) not supported on device default.mixed

Hi @sdas,

Thank you for your question!

We will release a new version of PennyLane tomorrow which should fix your problem. Please let us know if the problem persists after upgrading to PennyLane v0.35 :smiley:.

Hi @CatalinaAlbornoz , as suggested I upgraded pennylane. Now when I run the above code, I get the following error:

Traceback (most recent call last):
File “/home/sreetamadas/mixed_state_simulation.py”, line 62, in
params, cost_new = opt.step_and_cost(lambda v: cost(v, X_batch, Y_batch, cost_fn), params)
File “/home/sreetamadas/anaconda3/lib/python3.10/site-packages/pennylane/optimize/gradient_descent.py”, line 64, in step_and_cost
g, forward = self.compute_grad(objective_fn, args, kwargs, grad_fn=grad_fn)
File “/home/sreetamadas/anaconda3/lib/python3.10/site-packages/pennylane/optimize/nesterov_momentum.py”, line 76, in compute_grad
grad = g(*shifted_args, **kwargs)
File “/home/sreetamadas/anaconda3/lib/python3.10/site-packages/pennylane/_grad.py”, line 165, in call
grad_value, ans = grad_fn(*args, **kwargs) # pylint: disable=not-callable
File “/home/sreetamadas/.local/lib/python3.10/site-packages/autograd/wrap_util.py”, line 20, in nary_f
return unary_operator(unary_f, x, *nary_op_args, **nary_op_kwargs)
File “/home/sreetamadas/anaconda3/lib/python3.10/site-packages/pennylane/_grad.py”, line 183, in _grad_with_forward
vjp, ans = _make_vjp(fun, x) # pylint: disable=redefined-outer-name
File “/home/sreetamadas/.local/lib/python3.10/site-packages/autograd/core.py”, line 10, in make_vjp
end_value, end_node = trace(start_node, fun, x)
File “/home/sreetamadas/.local/lib/python3.10/site-packages/autograd/tracer.py”, line 10, in trace
end_box = fun(start_box)
File “/home/sreetamadas/.local/lib/python3.10/site-packages/autograd/wrap_util.py”, line 15, in unary_f
return fun(*subargs, **kwargs)
File “/home/sreetamadas/mixed_state_simulation.py”, line 62, in
params, cost_new = opt.step_and_cost(lambda v: cost(v, X_batch, Y_batch, cost_fn), params)
File “/home/sreetamadas/mixed_state_simulation.py”, line 27, in cost
predictions = np.array([circuit(x, params) for x in X])
File “/home/sreetamadas/mixed_state_simulation.py”, line 27, in
predictions = np.array([circuit(x, params) for x in X])
File “/home/sreetamadas/anaconda3/lib/python3.10/site-packages/pennylane/workflow/qnode.py”, line 1048, in call
res = qml.execute(
File “/home/sreetamadas/anaconda3/lib/python3.10/site-packages/pennylane/workflow/execution.py”, line 684, in execute
results = inner_execute(tapes)
File “/home/sreetamadas/anaconda3/lib/python3.10/site-packages/pennylane/workflow/execution.py”, line 283, in inner_execute
return cached_device_execution(tapes)
File “/home/sreetamadas/anaconda3/lib/python3.10/site-packages/pennylane/workflow/execution.py”, line 361, in wrapper
res = list(fn(tapes, **kwargs))
File “/home/sreetamadas/anaconda3/lib/python3.10/contextlib.py”, line 79, in inner
return func(*args, **kwds)
File “/home/sreetamadas/anaconda3/lib/python3.10/site-packages/pennylane/_qubit_device.py”, line 459, in batch_execute
res = self.execute(circuit)
File “/home/sreetamadas/anaconda3/lib/python3.10/site-packages/pennylane/devices/default_mixed.py”, line 685, in execute
return super().execute(circuit, **kwargs)
File “/home/sreetamadas/anaconda3/lib/python3.10/site-packages/pennylane/_qubit_device.py”, line 277, in execute
self.apply(circuit.operations, rotations=self._get_diagonalizing_gates(circuit), **kwargs)
File “/home/sreetamadas/anaconda3/lib/python3.10/site-packages/pennylane/devices/default_mixed.py”, line 693, in apply
raise DeviceError(
pennylane._device.DeviceError: Operation StatePrep cannot be used after other Operations have already been applied on a default.mixed device.

Hey @sdas!

The issue here is that you’re using two instances of state preparation (Operation StatePrep cannot be used after other Operations have already been applied on a default.mixed device.)

The way around this is to mush it all together into a 7-qubit density matrix. Mathematically, you want to do:

\rho \otimes \vert \psi \rangle \langle \psi \vert

and plug that into QubitDensityMatrix. The code would look like this:

state_as_density_matrix = np.outer(ancilla_state, np.conj(ancilla_state))
features = np.kron(features, state_as_density_matrix)

Let me know if that helps!

Hi @isaacdevlugt , thanks for the reply. Yes this indeed works.

1 Like