geqie-qml API¶
All public objects are importable directly from the geqie_qml package.
Layers¶
GEQIELayer
¶
GEQIELayer(
geqie_encoding: str | ModuleType = "frqi",
encoding_params: dict | None = None,
finite_difference_epsilon: float = 0.001,
grad_mode: str = FULL,
)
Bases: Module
PyTorch layer that encodes a batch of images into quantum statevectors on-the-fly.
Applies geqie.encode to each image and returns the resulting statevector
U|ψ_init⟩ (where |ψ_init⟩ is the encoding's initial state, typically |0⟩).
There are no trainable parameters; input gradients are propagated so that any
preceding classical layers can be trained end-to-end.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
geqie_encoding
|
str or ModuleType
|
Encoding to use. Pass a name string (e.g. |
'frqi'
|
encoding_params
|
dict
|
Extra keyword arguments forwarded verbatim to the encoding functions. |
None
|
finite_difference_epsilon
|
float
|
Step size for central finite-difference gradient estimation. |
0.001
|
grad_mode
|
str
|
How input gradients are produced in the backward pass:
|
FULL
|
Source code in geqie-qml/src/geqie_qml/layers/geqie_layer.py
forward
¶
Encode a batch of images into quantum statevectors.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
images
|
torch.Tensor, shape ``(batch_size, H, W)``, real
|
Batch of images to encode. Each image is encoded independently. |
required |
Returns:
| Type | Description |
|---|---|
torch.Tensor, shape ``(batch_size, 2**n_qubits)``, complex64
|
Statevector |
Source code in geqie-qml/src/geqie_qml/layers/geqie_layer.py
UnitaryInputLayer
¶
Bases: Module
Converts a pre-computed image unitary U into the encoded statevector
U|0⟩ by extracting the first column.
No trainable parameters. Output is a complex statevector ready to be
passed to, e.g., :class:SamplerAnsatzLayer or any other quantum layer.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
n_qubits
|
int
|
|
required |
Input / Output
Input : (B, 2**n_qubits, 2**n_qubits) complex — pre-computed unitary matrices from the
data-loader.
Output : (B, 2**n_qubits) complex — encoded statevectors U|0⟩.
Source code in geqie-qml/src/geqie_qml/layers/unitary_input_layer.py
SamplerAnsatzLayer
¶
SamplerAnsatzLayer(
n_qubits: int,
ansatz: QuantumCircuit,
weight_init: Tensor | None = None,
seed: int | None = None,
)
Bases: Module
Trainable ansatz layer with analytic parameter-shift gradients.
Designed to be placed after :class:UnitaryInputLayer in an nn.Sequential
pipeline, mirroring the original pqc.compose(geqie_layer).compose(ansatz)
pattern with SamplerQNN.
Accepts any Qiskit QuantumCircuit as the ansatz. The circuit is parsed
once at construction into a plain Python gate list; no Qiskit objects are
retained. All forward and backward computations are pure NumPy statevector
operations, bypassing Qiskit's parameter-binding machinery entirely.
Gradients are computed with the parameter-shift rule and prefix-state
caching: the statevector before each parametric gate is saved during the
forward pass so that the backward pass only re-runs the circuit suffix,
saving ≈50 % of compute vs. a full re-evaluation per parameter. This
avoids the assign_parameters_mapping bottleneck that makes backward
passes prohibitively slow for large image encodings.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
n_qubits
|
int
|
|
required |
ansatz
|
QuantumCircuit
|
Parameterized ansatz. Any single-qubit Pauli-axis rotation
( |
required |
weight_init
|
Tensor | None
|
Initial weights of shape |
None
|
seed
|
int | None
|
Random seed for default weight initialization. |
None
|
Input / Output
Input : (B, 2**n_qubits) complex — statevectors (e.g. from :class:UnitaryInputLayer).
Output : (B, 2**n_qubits) float — measurement probability distributions
|A(θ)|input⟩|².
Example
from qiskit.circuit.library import real_amplitudes ansatz = real_amplitudes(7, reps=4) model = nn.Sequential( ... UnitaryInputLayer(7), ... SamplerAnsatzLayer(7, ansatz), ... nn.Linear(128, 10), ... nn.LogSoftmax(dim=-1), ... )
Source code in geqie-qml/src/geqie_qml/layers/sampler_ansatz_layer.py
Precomputation¶
compute_and_save_circuits
¶
compute_and_save_circuits(
data,
labels,
save_dir: str = "circuits",
file_prefix: str = "matrix",
number_of_workers: int | None = None,
geqie_encoding: str | ModuleType = "frqi",
encoding_params: dict[str, Any] = {},
)
Encode a dataset of images into unitary matrices and save them as .npz files.
Each output file contains matrix (complex128 unitary) and label
(integer). Files are named {prefix}_{index}_label_{label}.npz and can
be loaded at training time via :class:ZipUnitaryDataset.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
(array - like, shape(N, H, W))
|
Images to encode. |
required |
labels
|
(array - like, shape(N))
|
Integer class labels, one per image. |
required |
save_dir
|
str
|
Directory where .npz files are written. Created if absent. |
'circuits'
|
file_prefix
|
str
|
Filename prefix; files are named |
'matrix'
|
number_of_workers
|
int | None
|
Number of worker processes. Defaults to |
None
|
geqie_encoding
|
str
|
GEQIE encoding name, e.g. |
'frqi'
|
encoding_params
|
dict
|
Additional keyword arguments forwarded to the encoding function. |
{}
|
Source code in geqie-qml/src/geqie_qml/precompute.py
Datasets¶
load_precomputed_zip_matrices
¶
load_precomputed_zip_matrices(
zip_path: str,
split_names: List[str] = ["train", "test"],
cache_size: int = 0,
) -> tuple[ZipUnitaryDataset, ...]
Load train and test splits from a .precomputed.zip archive.
The function searches the zip tree for split_names folders at
any nesting depth and returns lazy :class:ZipUnitaryDataset objects for each split.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
zip_path
|
str
|
Path to the zip archive produced by :func: |
required |
cache_size
|
int
|
Maximum number of decoded items each split may keep in its in-memory
LRU cache. |
0
|
Returns:
| Name | Type | Description |
|---|---|---|
datasets |
tuple[ZipUnitaryDataset, ...]
|
Lazy datasets for each split. |
Source code in geqie-qml/src/geqie_qml/dataset/zip_unitary_dataset.py
ZipUnitaryDataset
¶
Bases: Dataset
PyTorch Dataset that lazily reads pre-computed unitary matrices from .npz files stored inside a zip archive.
The archive may nest train and test folders at any depth; the
loader searches the zip tree automatically to locate them.
Expected zip layout::
archive.precomputed.zip
├── train/
│ ├── matrix_0_label_7.npz
│ └── ...
└── test/
├── matrix_0_label_2.npz
└── ...
Each .npz file must contain:
matrix: complex128 array of shape(2**n, 2**n)label: class label (can be string)
A thread-local ZipFile handle is cached per worker so that the zip
central directory is parsed only once per process/thread, making the
dataset safe and efficient with multi-worker DataLoader usage.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
zip_path
|
str
|
Path to the |
required |
split_name
|
str
|
Dataset split name from zip to load (e.g. |
'train'
|
cache_size
|
int
|
Maximum number of decoded |
0
|