Skip to content

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") or an already-imported geqie.encodings.* module.

'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" (default): exact per-image Jacobian estimated via central finite differences. Correct for any encoding, but evaluates 2 * batch_size * H * W extra circuits per backward pass.
  • "first_batch_average": the pixel Jacobian dψ/dx is computed once (lazily, on the first backward pass) by averaging the per-image Jacobians over all images in that first batch, then cached and reused for all subsequent batches. No circuits are evaluated after the first backward pass. Exact only when the encoding's Jacobian is input-independent; otherwise it is a biased approximation traded for speed.
  • "none": no input gradient is produced (returns None). Valid only when nothing trainable precedes this layer.
FULL
Source code in geqie-qml/src/geqie_qml/layers/geqie_layer.py
def __init__(
    self,
    geqie_encoding: str | ModuleType = "frqi",
    encoding_params: dict | None = None,
    finite_difference_epsilon: float = 1e-3,
    grad_mode: str = GRADIENT_MODES.FULL,
) -> None:
    super().__init__()
    self.encoding_module: ModuleType = resolve_encoding_module(geqie_encoding)
    self.encoding_name: str = self.encoding_module.__name__.split(".")[-1]
    self.encoding_params: dict = encoding_params or {}
    self.finite_difference_epsilon: float = finite_difference_epsilon
    self.grad_mode: str = validate_grad_mode(grad_mode)
    self.frozen_jacobian_cache: dict = {}

forward

forward(images: Tensor) -> Tensor

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 U|ψ_init⟩ for each image.

Source code in geqie-qml/src/geqie_qml/layers/geqie_layer.py
def forward(self, images: torch.Tensor) -> torch.Tensor:
    """
    Encode a batch of images into quantum statevectors.

    Parameters
    ----------
    images : torch.Tensor, shape ``(batch_size, H, W)``, real
        Batch of images to encode.  Each image is encoded independently.

    Returns
    -------
    torch.Tensor, shape ``(batch_size, 2**n_qubits)``, complex64
        Statevector ``U|ψ_init⟩`` for each image.
    """
    return GEQIEEncodeGrad.apply(
        images,
        self.encoding_name,
        self.encoding_params,
        self.finite_difference_epsilon,
        self.grad_mode,
        self.frozen_jacobian_cache,
    )

UnitaryInputLayer

UnitaryInputLayer(n_qubits: int)

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
def __init__(self, n_qubits: int):
    super().__init__()
    self.n_qubits = n_qubits
    self.dim = 2 ** n_qubits

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 (rx/ry/rz and equivalents) may be parameterized; any fixed gate (cx, cz, swap, h, ...) is accepted.

required
weight_init Tensor | None

Initial weights of shape (ansatz.num_parameters,). Defaults to Uniform(0, 2π).

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
def __init__(
    self,
    n_qubits: int,
    ansatz: qiskit.QuantumCircuit,
    weight_init: torch.Tensor | None = None,
    seed: int | None = None,
):
    super().__init__()
    if ansatz.num_qubits != n_qubits:
        raise ValueError(
            f"ansatz acts on {ansatz.num_qubits} qubits, expected {n_qubits}."
        )
    self.n_qubits = n_qubits
    self.dim = 2 ** n_qubits
    self.ops = parse_circuit(ansatz)        # parsed once; no live Qiskit objects

    n_w = ansatz.num_parameters
    if weight_init is None:
        rng = torch.Generator().manual_seed(seed) if seed is not None else None
        weight_init = (2.0 * np.pi * torch.rand(n_w, generator=rng)).float()
    else:
        weight_init = torch.as_tensor(weight_init, dtype=torch.float32).reshape(-1)
        if weight_init.numel() != n_w:
            raise ValueError(
                f"weight_init has {weight_init.numel()} elements, expected {n_w}."
            )

    self.weights = nn.Parameter(weight_init)

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 {prefix}_{index}_label_{label}.npz.

'matrix'
number_of_workers int | None

Number of worker processes. Defaults to cpu_count - 1, minimum 1.

None
geqie_encoding str

GEQIE encoding name, e.g. "frqi".

'frqi'
encoding_params dict

Additional keyword arguments forwarded to the encoding function.

{}
Source code in geqie-qml/src/geqie_qml/precompute.py
def 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
    ----------
    data : array-like, shape (N, H, W)
        Images to encode.
    labels : array-like, shape (N,)
        Integer class labels, one per image.
    save_dir : str
        Directory where .npz files are written.  Created if absent.
    file_prefix : str
        Filename prefix; files are named ``{prefix}_{index}_label_{label}.npz``.
    number_of_workers : int | None
        Number of worker processes.  Defaults to ``cpu_count - 1``, minimum 1.
    geqie_encoding : str
        GEQIE encoding name, e.g. ``"frqi"``.
    encoding_params : dict
        Additional keyword arguments forwarded to the encoding function.
    """
    if number_of_workers is None:
        number_of_workers = max(1, cpu_count() - 1)

    os.makedirs(save_dir, exist_ok=True)
    encoding_name = _normalize_encoding_name(geqie_encoding)

    logger.debug(f"Starting precompute with {number_of_workers} workers for encoding '{encoding_name}'")
    if number_of_workers == 1:
        for i in tqdm(range(len(data)), total=len(data)):
            _compute_save_single(
                image=data[i],
                label=labels[i],
                sample_index=i,
                save_dir=save_dir,
                file_prefix=file_prefix,
                geqie_encoding=encoding_name,
                encoding_params=encoding_params
            )
    else:
        with futures.ProcessPoolExecutor(max_workers=number_of_workers) as executor:
            precompute_futures = [
                executor.submit(
                    _compute_save_single,
                    image=data[i],
                    label=labels[i],
                    sample_index=i,
                    save_dir=save_dir,
                    file_prefix=file_prefix,
                    geqie_encoding=encoding_name,
                    encoding_params=encoding_params,
                ) for i in tqdm(range(len(data)), total=len(data), desc="Submitting tasks")
            ]

            for future in tqdm(futures.as_completed(precompute_futures), total=len(precompute_futures), desc="Processing tasks"):
                future.result()

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:compute_and_save_circuits.

required
cache_size int

Maximum number of decoded items each split may keep in its in-memory LRU cache. 0 (the default) disables caching to keep memory bounded for large matrices.

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
def 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
    ----------
    zip_path : str
        Path to the zip archive produced by :func:`compute_and_save_circuits`.
    cache_size : int
        Maximum number of decoded items each split may keep in its in-memory
        LRU cache. ``0`` (the default) disables caching to keep memory bounded
        for large matrices.

    Returns
    -------
    datasets : tuple[ZipUnitaryDataset, ...]
        Lazy datasets for each split.
    """
    datasets = []
    for split_name in split_names:
        datasets.append(
            ZipUnitaryDataset(zip_path, split_name=split_name, cache_size=cache_size)
        )
    return tuple(datasets)

ZipUnitaryDataset

ZipUnitaryDataset(
    zip_path: str,
    split_name: str = "train",
    cache_size: int = 0,
)

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 .precomputed.zip archive.

required
split_name str

Dataset split name from zip to load (e.g. "train", "test").

'train'
cache_size int

Maximum number of decoded (matrix, label) items to keep in an in-memory LRU cache. 0 (the default) disables caching, which keeps memory bounded and predictable for large matrices. A positive value trades memory for speed by retaining the most recently used items; note the cache lives per DataLoader worker process.

0
Source code in geqie-qml/src/geqie_qml/dataset/zip_unitary_dataset.py
def __init__(self, zip_path: str, split_name: str = "train", cache_size: int = 0):
    """
    Parameters
    ----------
    zip_path : str
        Path to the ``.precomputed.zip`` archive.
    split_name : str
        Dataset split name from zip to load (e.g. ``"train"``, ``"test"``).
    cache_size : int
        Maximum number of decoded ``(matrix, label)`` items to keep in an
        in-memory LRU cache. ``0`` (the default) disables caching, which
        keeps memory bounded and predictable for large matrices. A positive
        value trades memory for speed by retaining the most recently used
        items; note the cache lives *per DataLoader worker process*.
    """
    self._zip_path = zip_path
    self._split_name = split_name
    self._cache_size = max(0, int(cache_size))
    self._entry_index = self._index_zip(zip_path, split_name)
    # LRU cache of loaded matrices; empty/unused when cache_size == 0.
    self._cache: OrderedDict[int, tuple] = OrderedDict()
    self._cache_lock = threading.Lock()
    self._local = threading.local()  # per-thread ZipFile handle
    self._open_handles: list[zipfile.ZipFile] = []
    self._handles_lock = threading.Lock()
    # Fires on GC and at interpreter exit via atexit — covers normal
    # shutdown and KeyboardInterrupt.  Hard kills (SIGKILL) cannot be
    # caught at the Python level; the OS reclaims the file descriptors.
    weakref.finalize(self, ZipUnitaryDataset._close_handles,
                     self._open_handles, self._handles_lock)