Q-Alchemy Python SDK
This is the Python-SDK for using the data cybernetics Q-Alchemy API which helps quantum computing researchers to put classical data into the quantum computer. This is all also called: the loading problem, encoding problem, or quantum state preparation. Some people also call it a form of QRAM, or quantum random-access memory.
Under the hood, Q-Alchemy runs on PineXQ, the hypermedia (Siren) API platform of data cybernetics. You do not need to know anything about it to use this SDK; if you want to work with the API directly, see the PineXQ documentation.
Installation
The SDK is published on PyPI, so you can install it with pip (or poetry, uv, pdm, ...):
pip install q-alchemy-sdk-py
# or
uv add q-alchemy-sdk-py
# or
pdm add q-alchemy-sdk-py
If you want to use the qiskit-integration, please use
pip install q-alchemy-sdk-py[qiskit]
And if you want the PennyLane-integration, please use
pip install q-alchemy-sdk-py[pennylane]
If you would like to run our examples, please use
pip install q-alchemy-sdk-py[examples]
We use uv and have tested this all with Python 3.11 through 3.14. So the way to install it after cloning is simply
uv sync --locked
Again, for qiskit- or PennyLane-integrations, please add the groups
uv sync --locked --extra qiskit --extra pennylane
And for running our examples,
uv sync --locked --extra examples
Usage
There are examples under the /examples folder, but for those that are eager to find out, here it is.
First, you will want to get an API key from the Q-Alchemy Portal. You
need to sign up for this, sorry, but this is necessary. Once you have the API key (free of charge of course)
you can test it!
Direct Example
import numpy as np
import os
from sklearn.datasets import fetch_openml
from q_alchemy.initialize import q_alchemy_as_qasm
mnist = fetch_openml('mnist_784', version=1, parser="auto")
zero: np.ndarray = mnist.data[mnist.target == "0"].iloc[0].to_numpy()
filler = np.empty(2 ** 10 - zero.shape[0])
filler.fill(0)
zero = np.hstack([zero, filler])
zero = zero / np.linalg.norm(zero)
qasm, summary = q_alchemy_as_qasm(zero, max_fidelity_loss=0.2,
api_key=os.environ["Q_ALCHEMY_API_KEY"], return_summary=True)
print(summary)
Qiskit Example
import numpy as np
from sklearn.datasets import fetch_openml
import os
from q_alchemy.qiskit_integration import QAlchemyInitialize, OptParams
mnist = fetch_openml('mnist_784', version=1, parser="auto")
zero: np.ndarray = mnist.data[mnist.target == "0"].iloc[0].to_numpy()
filler = np.empty(2 ** 10 - zero.shape[0])
filler.fill(0)
zero = np.hstack([zero, filler])
zero = zero / np.linalg.norm(zero)
instr = QAlchemyInitialize(
params=zero.tolist(),
opt_params=OptParams(
max_fidelity_loss=0.1,
basis_gates=["id", "rx", "ry", "rz", "cx"],
api_key=os.environ["Q_ALCHEMY_API_KEY"]
)
)
instr.definition.draw(fold=-1)
PennyLane Example
import numpy as np
import pennylane as qml
from sklearn.datasets import fetch_openml
import os
from q_alchemy.pennylane_integration import QAlchemyStatePreparation, OptParams
mnist = fetch_openml('mnist_784', version=1, parser="auto")
zero: np.ndarray = mnist.data[mnist.target == "0"].iloc[0].to_numpy()
filler = np.empty(2 ** 10 - zero.shape[0])
filler.fill(0)
zero = np.hstack([zero, filler])
zero = zero / np.linalg.norm(zero)
dev = qml.device('lightning.qubit', wires=10)
@qml.qnode(dev)
def circuit(state=None):
QAlchemyStatePreparation(
state,
wires=range(10),
opt_params=OptParams(
max_fidelity_loss=0.1,
basis_gates=["id", "rx", "ry", "rz", "cx"],
api_key=os.environ["Q_ALCHEMY_API_KEY"]
)
)
return qml.state()
print(qml.draw(circuit, level="device", max_length=100)(zero.tolist()))
Broadcasting with PennyLane
PennyLane provides native support for broadcasting, which allows quantum nodes to process batches of inputs efficiently. This is particularly useful in machine learning applications where inputs often come in batches. When broadcasting is used in conjunction with Q-Alchemy, each state in the batch is individually prepared using Q-Alchemy's circuit synthesis capabilities.
⚠️ Note: For simulators or backends that support native state initialization using the
StatePrepgate—such asdefault.qubit, andlightning.qubit—the state vector is injected directly without any decomposition into quantum gates. In this case, Q-Alchemy is not used. This behavior is ideal for rapid prototyping and testing. Switching to a hardware backend (or one without native state prep) will automatically invoke Q-Alchemy for state preparation.
Broadcasting Example
import numpy as np
import pennylane as qml
import os
import torch
from q_alchemy.pennylane_integration import AmplitudeEmbedding, OptParams
from sklearn.datasets import make_moons
# Sample data
X, _ = make_moons(n_samples=5, noise=0.1)
X = X / np.linalg.norm(X, axis=1, keepdims=True) # Normalize each row for amplitude embedding
# Create PennyLane device
dev = qml.device("qiskit.aer", wires=1)
@qml.qnode(dev, interface="torch")
def circuit(x):
AmplitudeEmbedding(
x,
wires=[0],
opt_params=OptParams(
max_fidelity_loss=0.0,
api_key=os.environ["Q_ALCHEMY_API_KEY"]
)
)
return qml.expval(qml.PauliZ(0))
# Run the circuit on a batch of inputs
X_tensor = torch.tensor(X, dtype=torch.float64)
print(qml.draw(circuit, level="device", max_length=100)(X_tensor))
This example demonstrates how batched data can be processed using broadcasting with AmplitudeEmbedding, and how Q-Alchemy is triggered on simulators like qiskit.aer. When moving to real hardware or gate-based backends that lack StatePrep gate, Q-Alchemy will transparently handle the state preparation.
Advanced options
Every entry point (q_alchemy_as_qasm, QAlchemyInitialize,
QAlchemyStatePreparation, AmplitudeEmbedding) takes its settings as an
OptParams object, or as a plain dict with the same keys. q_alchemy_as_qasm
also accepts them as keyword arguments. The state itself can be a list, a numpy
array, a scipy sparse array or, for Qiskit, a Statevector.
The fields you are most likely to touch:
| Field | Default | Meaning |
|---|---|---|
max_fidelity_loss |
0.0 |
How much fidelity you are willing to give up for a shallower circuit. 0.0 asks for an exact preparation. |
basis_gates |
["u", "cx"] |
Gate set the returned circuit is transpiled to. |
api_key |
$Q_ALCHEMY_API_KEY |
Your Q-Alchemy API key. Keep it safe! |
initialization_method |
InitializationMethods.AUTO |
Which algorithm builds the circuit (see below). |
extra_kwargs |
{} |
Method-specific options, as a dict (see below). |
use_qasm3 |
False |
Experimental: return OpenQASM 3 instead of OpenQASM 2. |
remove_data |
True |
Delete the job and its uploaded data once the result is fetched. |
job_completion_timeout_sec |
300 |
How long to wait for the job before giving up. |
InitializationMethods lives in q_alchemy.initialize:
AUTO(default) runs several Tucker candidates (iterative and hierarchical, as resources allow) at your fidelity budget and keeps the cheapest realized circuit. Trivial inputs such as single-qubit and single-basis states take an exact fast path.ITERATIVE_TUCKERandHIERARCHICAL_TUCKERpin one Tucker variant.SWAP_PIVOTis suited to very sparse states.BAA_LOW_RANKuses the BAA low-rank initializer; it is limited to 12 qubits.
Method-specific options (extra_kwargs)
extra_kwargs is passed through to the chosen method. Pass a dict, and the SDK
serializes it for you:
from q_alchemy.initialize import OptParams, InitializationMethods
opt_params = OptParams(
max_fidelity_loss=0.05,
initialization_method=InitializationMethods.ITERATIVE_TUCKER,
extra_kwargs={"max_iterations": 10, "factors_size": 4},
)
⚠️ Options are validated per method. A key that the chosen method does not accept fails the job with
Could not build the initialization circuit: ...instead of being silently ignored. In particular, the iterative-Tucker keys below are not valid underAUTO. Pin the method to use them.
| Method | Accepted extra_kwargs keys |
|---|---|
AUTO |
cost_function ("cx_then_depth" default, "depth_then_cx", "two_qubit_then_depth", "cx+depth", "cx", "depth"), basis_gates (gate set used to compare candidates, default ["u", "cx"]), transpile_optimization_level (1), seed_transpiler (0), dominant_basis_fast_path (True), fidelity_tolerance, geometric_entanglement, check_normalization (True) |
ITERATIVE_TUCKER |
max_iterations (≤ 0 picks one from the qubit count), factors_size (0 = automatic), max_stepup (0), fallback (True), perturbation (None), geometric_entanglement (0.0), check_normalization (True), barriers (False; debugging only, hurts transpilation) |
HIERARCHICAL_TUCKER |
geometric_entanglement, check_normalization |
SWAP_PIVOT |
aux |
BAA_LOW_RANK |
strategy ("greedy"), use_low_rank (True), max_combination_size, iso_scheme, unitary_scheme |
Two interactions worth knowing:
- Set the fidelity with
max_fidelity_lossonOptParams, not inextra_kwargs. Every method acceptsmax_fidelity_lossinextra_kwargstoo, but if you put it there it silently overrides the top-level value. - Under
AUTO,basis_gatesonOptParamsonly affects the final transpilation. Candidates are compared onu/cxcost unless you also passextra_kwargs={"basis_gates": [...]}.
Verifying preparation circuits with the sparse simulator
Q-Alchemy also hosts a sparse state-vector simulator so you can verify that a preparation circuit really produces your target state. The typical loop is prepare → simulate → verify:
from qiskit import QuantumCircuit
from qiskit.quantum_info import Statevector, state_fidelity
from q_alchemy import q_alchemy_as_qasm, SparseSimulator
qasm = q_alchemy_as_qasm(target, max_fidelity_loss=0.0) # prepare
prep = QuantumCircuit.from_qasm_str(qasm)
sim = SparseSimulator() # verify
sv = sim.sparse_statevector(prep)
print("fidelity:", state_fidelity(Statevector(sv.to_dense()), Statevector(target)))
SparseSimulator also exposes .counts(...) and .tomography(...), and it
auto-selects your resource tier from your plan (Standard/Medium for everyone,
XLarge for enterprise).
⚠️ The free plan is strongly limited — state preparation is capped (currently ~12 qubits, batches up to 100) and runs on the Medium simulator tier. Enterprise plans get larger circuits and the XLarge tier. See the limits table in the guide.
📖 Full guide: docs/initialize-and-verify.md · 🧪 Runnable notebook: examples/simulator_vs_initializer.ipynb
Using the simulator as a Qiskit backend
The hosted simulator is also exposed through Qiskit's standard BackendV2
interface — the same way IBM backends are used — so it drops straight into the
Qiskit ecosystem (transpiler, Sampler, etc.):
from qiskit import QuantumCircuit, transpile
from q_alchemy import QAlchemyBackend
backend = QAlchemyBackend() # reads Q_ALCHEMY_API_KEY from env
qc = QuantumCircuit(2, 2)
qc.h(0); qc.cx(0, 1); qc.measure([0, 1], [0, 1])
job = backend.run(transpile(qc, backend), shots=4096)
print(job.result().get_counts()) # {'00': ~2048, '11': ~2048}
backend.run(...) accepts Aer-style options (shots, seed_simulator,
save_sparse_statevector, save_statevector, sparse_index_format, ...), and
there's an IBM-style QAlchemyProvider().get_backend() for discovery. The
resource tier (Medium vs the enterprise XLarge) is selected automatically from
your plan — see the guide.
save_statevector vs save_sparse_statevector
Both ask for the state the circuit prepares, and both are served by the same remote call — the difference is what you get back, and how big it is.
save_statevector is the option you already know from Aer. It hands you the
familiar dense 2**n vector, so Statevector, state_fidelity and friends all
work unchanged:
qc = QuantumCircuit(2)
qc.h(0); qc.cx(0, 1) # no measurement: this is a state export
result = backend.run(qc, save_statevector=True).result()
print(result.data(0)["statevector"])
# [0.70710678+0.j 0. +0.j 0. +0.j 0.70710678+0.j] -> length 2**n
save_sparse_statevector is Q-Alchemy's own, and it is the one that scales. It
returns only the amplitudes the circuit actually populates, so nothing of
size 2**n is ever built:
result = backend.run(qc, save_sparse_statevector=True).result()
print(result.data(0)["sparse_statevector"])
# {'format': 'sparse_statevector_v1', 'num_qubits': 2, 'nnz': 2,
# 'index_format': 'hex', 'index_convention': 'little_endian',
# 'indices': ['0x0', '0x3'],
# 'amplitudes': [[0.7071067811865476, 0.0], [0.7071067811865476, 0.0]]}
Note the amplitudes are [real, imag] pairs: this entry is the simulator's own
JSON payload, passed through untouched. If you would rather have parsed
complex values — plus to_coo(), to_arrow() and amplitudes_dict() — go
through the client instead of the backend, which returns a typed
SparseStatevectorResult:
from q_alchemy import SparseSimulator
sv = SparseSimulator().sparse_statevector(qc)
print(sv.amplitudes) # [(0.7071067811865476+0j), (0.7071067811865476+0j)]
print(sv.amplitudes_dict()) # {'0x0': (0.707...+0j), '0x3': (0.707...+0j)}
indices and amplitudes line up element by element, and nnz is how many
were stored — two here, not four. That gap is the whole point, and it widens
fast: a 40-qubit state-preparation circuit populating a thousand basis states
returns a thousand amplitudes, while the dense form would need 2**40 complex
numbers, or roughly 17 TB. A dense export is impossible in that regime; a
sparse one is a few hundred kilobytes. Standard Qiskit backends offer no
equivalent.
That only helps if the state is sparse, and nothing forces it to be. By
default the simulator keeps every amplitude above 1e-10, so the result is
exact, but a circuit that populates most of its basis states needs as much
memory as the dense form and can exhaust the simulator. Pass max_nnz=N (to
backend.run or SparseSimulator.sparse_statevector) to cap it: after every
gate only the N largest amplitudes are kept and renormalised. The result is
then approximate, and nothing in it marks that it was truncated.
Ask for both together and you pay for one simulation:
result = backend.run(qc, save_statevector=True, save_sparse_statevector=True).result()
dense = result.data(0)["statevector"] # 2**n numpy array
sparse = result.data(0)["sparse_statevector"] # nnz entries
Use the dense form for small circuits you want to compare against Qiskit
directly; use the sparse form whenever 2**n would not fit — which is exactly
the regime this simulator exists for. Reach for sparse_index_format
(hex/bitstring) and sparse_index_convention
(little_endian/big_endian) to control how the indices are written, and see
the guide for feeding a sparse result straight
back into the loader via to_coo().
From PennyLane
Because it's a standard Qiskit backend, you can use it as a PennyLane device via the PennyLane–Qiskit plugin (whose original version was written by this SDK's author, Carsten Blank):
import pennylane as qml
from q_alchemy import QAlchemyBackend
dev = qml.device("qiskit.remote", wires=2, backend=QAlchemyBackend(), shots=4096)
@qml.qnode(dev)
def circuit():
qml.Hadamard(0)
qml.CNOT([0, 1])
return qml.counts()
Contributions
We welcome contributions - simply fork the repository of this plugin, and then make a pull request containing your contribution. All contributers to this plugin will be listed as authors on the releases.
We also encourage bug reports, suggestions for new features and enhancements!
Authors
Carsten Blank
License
The q-alchemy-sdk-py is free and open source, released under the Apache License, Version 2.0.
Metadata
Release files for q-alchemy-sdk-py 0.3.1
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | |
|---|---|---|---|---|
| q_alchemy_sdk_py-0.3.1.tar.gz | 80.1 kB | With provenance | Details |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Reset |
|---|---|---|---|---|
| q_alchemy_sdk_py-0.3.1-py3-none-any.whl | Python 3 | none | any | Details |
Total release size: 120.2 kB
Release files / q_alchemy_sdk_py-0.3.1.tar.gz
| Download URL | q_alchemy_sdk_py-0.3.1.tar.gz |
|---|---|
| Size | 80.1 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
0f3a22db8128c041a97cbb885f09e6bfd9146c83ee6f0fa6871fc29c07f7b956
|
|
BLAKE2b-256 checksum How to use checksums |
b71cd7c9733926f04fdb7f804982d9abd4bb2123348ed6148450ed220f9041dc
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.14
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Sep 23, 2026.
Transparency logRelease files / q_alchemy_sdk_py-0.3.1-py3-none-any.whl
| Download URL | q_alchemy_sdk_py-0.3.1-py3-none-any.whl |
|---|---|
| Size | 40.2 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
177d9a704e7dafaafd16bd434e86e755f6c7b714d3351b14f266aa707c77e446
|
|
BLAKE2b-256 checksum How to use checksums |
a394494bb2000de86032f13945c5b033da4567d555c60937b165465d6c26eea2
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.14
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Sep 23, 2026.
Transparency logSecurity for q-alchemy-sdk-py 0.3.1
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
Full provenance
All 2 files in this release have been uploaded with provenance metadata.
Attestation for q_alchemy_sdk_py-0.3.1.tar.gz
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Sep 23, 2026.
Transparency logA note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.