State preparation on qubits


I want to use AmplitudeEncoding to encode some features.

The following is the code:

The device I am using is: self.sim_dev = qml.device(‘default.qubit.torch’, wires = self.n_qubits)

→ construct rotation embeddings
self.amplitude_embedding(pos_embed, wires = range(1, 1+self.pos_qbs))
self.amplitude_embedding(view_embed, wires = range(1+self.pos_qbs, self.n_qubits))

And I get the following errors:
/usr/local/lib/python3.10/dist-packages/pennylane/devices/ in apply(self, operations, rotations, **kwargs)
275 for i, operation in enumerate(operations):
276 if i > 0 and isinstance(operation, (StatePrep, BasisState)):
→ 277 raise DeviceError(
278 f"Operation {} cannot be used after other Operations have already been applied "
279 f"on a {self.short_name} device."

DeviceError: Operation StatePrep cannot be used after other Operations have already been applied on a default.qubit.torch device.

My question is: If this can not be used or prohibited, what can I do with this?
The version of pennylane:
Name: PennyLane
Version: 0.33.1
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: /usr/local/lib/python3.10/dist-packages
Requires: appdirs, autograd, autoray, cachetools, networkx, numpy, pennylane-lightning, requests, rustworkx, scipy, semantic-version, toml, typing-extensions
Required-by: PennyLane-Lightning

Platform info: Linux-5.15.120±x86_64-with-glibc2.35
Python version: 3.10.12
Numpy version: 1.23.5
Scipy version: 1.11.3
Installed devices:

Thank you

Hey @Daniel_Wang!

PennyLane doesn’t allow you to use multiple state preparation operations at the moment. It’s sort of related to this github issue:

For now, the way around it is to manually do a tensor product and embed the full state in one go (see this comment: Allow using multiple QubitStateVector operations if acting on different wires · Issue #1150 · PennyLaneAI/pennylane · GitHub)

Hope this helps!

Quick update here:

If you use default.qubit, you can actually use AmplitudeEmbedding multiple times (on different sets of wires of course)

import pennylane as qml
from pennylane import numpy as np
dev = qml.device('default.qubit', wires=2)
def prepare_state():
    qml.AmplitudeEmbedding([1, 0], wires=0)
    qml.AmplitudeEmbedding([0, 1], wires=1)
    return qml.state()

So if you can get your code working by using default.qubit instead of default.qubit.torch then there’s a way around the original issue :slight_smile:

yes, thank you! I solved it.

1 Like

Awesome! Glad I could help :slight_smile: