Skip to content

torch_sci_solver.qiskit

A GPU-capable (PyTorch) selected-CI eigensolver for SQD workflows.

This module provides two entry points, both designed as drop-in replacements for the corresponding functions in :mod:qiskit_addon_sqd.fermion:

  • :func:solve_fermion — the per-batch solver used inside a manual self-consistent configuration-recovery loop. Same call signature and return shape as qiskit_addon_sqd.fermion.solve_fermion.

  • :func:solve_sci_batch — the sci_solver callback consumed by qiskit_addon_sqd.fermion.diagonalize_fermionic_hamiltonian. Same call signature and return type (list[SCIResult]) as qiskit_addon_sqd.fermion.solve_sci_batch.

Both delegate to the vectorized PyTorch selected-CI engine in :mod:torch_sci_solver, which runs the matvec, Davidson diagonalization, and reduced-density-matrix construction on CPU or CUDA. The numerical core has been validated bit-for-bit against a scalar Python reference and, for the RDMs, against PySCF's FCI make_rdm1s / make_rdm12s to machine precision.

make_torch_sci_solver

make_torch_sci_solver(**kwargs) -> TorchSCISolver

Construct a :class:TorchSCISolver.

See :class:TorchSCISolver for the full list of accepted keyword arguments (device, devices, dtype, chunk_size, seed_strategy, ...). A constructed instance is callable with the :func:solve_sci_batch signature and is the recommended sci_solver to reuse across the iterations of an SQD run. Pass devices=["cuda:0","cuda:1",...] to spread each subspace batch across multiple GPUs on the same node.

.. note::

For drop-in compatibility with qiskit_addon_sqd.fermion, this factory defaults apply_ab_projection=False, so the solver returns the bare variational minimum in the subspace (matching PySCF's selected-CI, and reproducing FCI exactly on a complete basis). The engine's αβ-swap projection --- useful for suppressing triplet contamination from round-off on large noisy bases --- is available as an opt-in by passing apply_ab_projection=True, or enforce a spin sector explicitly with the spin_sq argument. Construct :class:TorchSCISolver directly to get the engine's native default (apply_ab_projection=True).

solve_fermion

solve_fermion(bitstring_matrix: ndarray | tuple[Sequence[int], Sequence[int]], /, hcore: ndarray, eri: ndarray, *, open_shell: bool = False, spin_sq: float | None = None, **kwargs) -> tuple[float, SCIState, tuple[ndarray, ndarray], float]

Approximate the ground state of a molecular Hamiltonian in a subspace.

This is a drop-in replacement for :func:qiskit_addon_sqd.fermion.solve_fermion backed by the PyTorch selected-CI engine. It projects the Hamiltonian onto the subspace spanned by the input configurations and diagonalizes it with a Davidson solver that runs on CPU or CUDA.

Parameters:

Name Type Description Default
bitstring_matrix ndarray | tuple[Sequence[int], Sequence[int]]

The configurations defining the subspace onto which the Hamiltonian is projected and diagonalized. Either a 2D numpy.ndarray of bool (one bitstring per row, spin-up in the left half and spin-down in the right half of each row) or a length-2 tuple ([a_str_0, ...], [b_str_0, ...]) of integer CI strings.

Interpretation depends on mode. With the default mode="tpb" the tuple's two arrays are treated as independent per-spin unique sets and their Cartesian product forms the basis. With mode="gdb" the two arrays are treated as parallel length-N pair lists (index i = pair i). These are different contracts — passing per-spin-unique arrays to mode="gdb" (as e.g. qiskit_addon_sqd's bitstring_matrix_to_ci_strs would produce them) silently re-interprets them as diagonal pairs. For pair mode extract the α and β halves per row of your bit_array yourself and pass those length-N arrays.

required
hcore ndarray

The core Hamiltonian (one-electron integrals), shape (N, N).

required
eri ndarray

The electron-repulsion (two-electron) integrals in chemist convention. Accepts the full (N, N, N, N) tensor or PySCF's 4-fold / 8-fold packed forms.

required
open_shell bool

If False, the spin-up and spin-down configurations are merged into a single set used for both sectors. Only meaningful when bitstring_matrix is a bitstring matrix.

False
spin_sq float | None

Target value of :math:\langle S^2 \rangle. None (default) applies no spin penalty and returns the bare variational minimum. A float biases the solver toward that spin sector via an augmented H + λ(S² − spin_sq) Davidson solve; the returned energy is the physical :math:\langle \psi | H | \psi \rangle with the penalty contribution removed.

None
**kwargs

Engine-construction options (device, devices, dtype, chunk_size, davidson_block_size, max_davidson_iters, davidson_tolerance, seed_strategy, budget_fraction, apply_ab_projection, compute_full_rdm, compute_spin_squared, verbose) are forwarded to the solver constructor. Any remaining kwargs (max_davidson_iters, tol, spin_penalty_lambda) are forwarded to the per-call diagonalization. Pass devices=["cuda:0","cuda:1",...] to fan the subspace batch across multiple GPUs on the same node (see :class:TorchSCISolver).

{}

Returns:

Type Description
float

A 4-tuple (energy, sci_state, occupancies, spin_sq):

SCIState
  • energy — minimum energy found in the subspace.
tuple[ndarray, ndarray]
  • sci_state — the approximate ground state as a :class:qiskit_addon_sqd.fermion.SCIState.
float
  • occupancies — (occ_a, occ_b) average spin-up / spin-down orbital occupancies, in the order expected by recover_configurations.
tuple[float, SCIState, tuple[ndarray, ndarray], float]
  • spin_sq — :math:\langle S^2 \rangle of the returned state when a spin penalty was applied, else 0.0.

solve_sci_batch

solve_sci_batch(ci_strings: list[tuple[ndarray, ndarray]], one_body_tensor: ndarray, two_body_tensor: ndarray, norb: int, nelec: tuple[int, int], *, spin_sq: float | None = None, **kwargs) -> list[SCIResult]

Diagonalize the Hamiltonian in a batch of subspaces.

This is a drop-in replacement for :func:qiskit_addon_sqd.fermion.solve_sci_batch, suitable as the sci_solver argument of :func:qiskit_addon_sqd.fermion.diagonalize_fermionic_hamiltonian. Each subspace is solved independently with the PyTorch Davidson engine.

.. note::

This convenience wrapper constructs a fresh :class:TorchSCISolver on every call, so it does not cache integrals or accumulate timing statistics across the iterations of an SQD run. For production runs --- especially on CUDA, where rebuilding the integral tensors every iteration is wasteful --- construct a single :class:TorchSCISolver once and pass it as sci_solver instead. The instance is callable with this exact signature and additionally exposes solver.stats and solver.format_perf_summary().

Parameters:

Name Type Description Default
ci_strings list[tuple[ndarray, ndarray]]

A list of (ci_strs_a, ci_strs_b) pairs, one per subspace (batch).

required
one_body_tensor ndarray

One-body integrals, shape (norb, norb).

required
two_body_tensor ndarray

Two-body integrals in chemist convention.

required
norb int

Number of spatial orbitals.

required
nelec tuple[int, int]

(n_alpha, n_beta) electron counts.

required
spin_sq float | None

Target :math:\langle S^2 \rangle value, or None for no spin penalty. See :func:solve_fermion.

None
**kwargs

Split between the solver constructor and the per-call diagonalization exactly as in :func:solve_fermion.

{}

Returns:

Type Description
list[SCIResult]

A list of :class:qiskit_addon_sqd.fermion.SCIResult, one per input

list[SCIResult]

subspace.

solve_fermion_from_bit_array_pairs

solve_fermion_from_bit_array_pairs(bit_array_or_matrix, /, hcore: ndarray, eri: ndarray, *, nelec: tuple[int, int], norb: int | None = None, spin_sq: float | None = None, max_pairs: int | None = None, seed: int | None = None, postselect: bool = True, **kwargs)

One-shot pair-mode SQD directly from a raw bit_array.

Pair-mode counterpart to :func:solve_fermion. The natural pair-mode input is a raw sampler output — one measurement row per (α, β) pair — which qiskit-addon-sqd's diagonalize_fermionic_hamiltonian normally consumes by (a) postselecting rows to the target particle count, (b) subsampling to control the subspace size, then (c) deduplicating independently per spin and forming the Cartesian product for Davidson. Step (c) is exactly the semantics pair mode is designed to replace: pair mode dedups by (α, β) row and diagonalizes over the resulting N-dim subspace, sidestepping the M_α × M_β blowup that motivated batching in the first place.

Because N ≤ n_shots and typical noisy-shot samples fit in memory comfortably (10k, 100k rows), the whole pair set is diagonalized in one Davidson call — no outer SQD loop, no per-batch carryover, no max_dim cap on per-spin sectors. If a future use case produces a pair set that's too large for one Davidson, a carryover-based outer loop can wrap this function; nothing here precludes it.

Parameters:

Name Type Description Default
bit_array_or_matrix

Either a Qiskit BitArray (one measurement row per shot) or an already-unpacked 2D numpy.ndarray of bool. Row layout: α occupancies in the left half (bits 0..norb-1), β occupancies in the right half (bits norb..2*norb-1) — matches qiskit_addon_sqd's convention.

required
hcore, eri

One- and two-electron integrals (chemist convention), same as :func:solve_fermion.

required
nelec tuple[int, int]

(n_α, n_β) — needed for both postselect (dropping rows with wrong particle counts) and the pair-mode solver.

required
norb int | None

Number of spatial orbitals. Defaults to hcore.shape[0].

None
spin_sq float | None

Target ⟨S²⟩ for the S² penalty; None (default) disables it. Passed through to :func:solve_fermion.

None
max_pairs int | None

Cap on the pair-set size after postselect. If the input yields more pairs, we subsample without replacement. None (default) keeps all rows. Set only when you know the solver can't hold the full pair set (rarely needed — pair mode memory is linear in N).

None
seed int | None

RNG seed for the max_pairs subsample. Ignored otherwise.

None
postselect bool

If True (default), drop rows whose α-popcount ≠ n_α or β-popcount ≠ n_β (noisy measurements outside the physical particle-count sector). Set False if the caller already applied a postselect or wants to include imperfect rows.

True
**kwargs

Forwarded to :func:solve_fermion. Common ones: device, chunk_size, davidson_block_size, compute_full_rdm, compute_spin_squared, max_davidson_iters, tol.

{}

Returns:

Type Description

The 4-tuple returned by :func:solve_fermion — ``(energy,

sci_state, occupancies, spin_sq). Thesci_state`` is a proper

class:qiskit_addon_sqd.fermion.SCIState with 2D

(M_α_unique, M_β_unique) amplitudes (sparse — zeros at

(α, β) positions that are not in the pair basis).

Raises:

Type Description
ValueError

if postselect=True drops every row (no rows match the target particle count).

diagonalize_fermionic_hamiltonian_pairs

diagonalize_fermionic_hamiltonian_pairs(one_body_tensor: ndarray, two_body_tensor: ndarray, bit_array, *, samples_per_batch: int | None = None, norb: int, nelec: tuple[int, int], max_iterations: int = 10, num_batches: int = 1, max_pairs_per_batch: int | None = None, energy_tol: float = 1e-08, occupancies_tol: float = 1e-05, carryover_threshold: float = 0.0001, initial_occupancies: tuple[ndarray, ndarray] | None = None, include_pairs: list[tuple[int, int]] | None = None, seed: int | None = None, solver=None, callback=None, use_full_recovered_pool: bool = False, add_hf_pair: bool = False, **solver_kwargs)

Pair-mode analog of :func:qiskit_addon_sqd.fermion.diagonalize_fermionic_hamiltonian.

Same iterative recovery loop over a noisy bit_array — postselect on iteration 0 (no prior occupancies yet), recover_configurations on iteration 1+ using the running RDM occupancies as prior, subsample into batches, diagonalize, aggregate best-of-batch, carry over the highest-amplitude configurations to the next iteration. The one difference: each batch's Davidson runs on the batch's row-deduped (α, β) pair set rather than the Cartesian product of independently dedup'd per-spin uniques.

Use this when the sampler output is a raw noisy BitArray from a quantum device — the recovery step is what makes the whole pipeline tolerate the fact that essentially no raw row has the exact target particle count. For a pre-recovered bit_array or a hand-curated pair list, prefer :func:solve_fermion_from_bit_array_pairs — it's a single Davidson call, no outer loop.

Parameters:

Name Type Description Default
one_body_tensor, two_body_tensor

Same integrals as :func:qiskit_addon_sqd.fermion.diagonalize_fermionic_hamiltonian.

required
bit_array

Qiskit BitArray of raw noisy measurement shots.

required
samples_per_batch int | None

Bitstrings drawn (with replacement) per batch. Ignored when use_full_recovered_pool=True.

None
norb int

Number of spatial orbitals.

required
nelec tuple[int, int]

(n_α, n_β) — targets for recovery and postselect.

required
max_iterations int

Outer-loop iteration cap.

10
num_batches int

Number of independent subsampled batches per iteration. The best-energy batch defines the iteration's result and carryover.

1
max_pairs_per_batch int | None

Optional cap on the pair-set size per batch (after row-dedup + carryover + include). None (default) keeps the full deduped set. Set only when a batch produces more pairs than Davidson can hold.

None
energy_tol, occupancies_tol

Convergence thresholds (same semantics as qiskit-addon-sqd).

required
carryover_threshold float

Amplitudes above this threshold are kept as carryover pairs for the next iteration.

0.0001
initial_occupancies tuple[ndarray, ndarray] | None

Optional (α, β) orbital-occupancy prior for iteration 0 (skips postselect-only fallback).

None
include_pairs list[tuple[int, int]] | None

Optional list of (α_int, β_int) tuples always included in every batch's pair set.

None
seed int | None

RNG seed for subsample + recovery.

None
solver

A prebuilt pair-mode TorchSCISolver (must have mode="gdb"). If None, one is constructed from solver_kwargs.

None
callback

Optional callable invoked with per-iteration list[SCIResult] (mirrors the qiskit-addon-sqd hook).

None
use_full_recovered_pool bool

If True (default False), skip the subsample step entirely and diagonalize the whole recovered bitstring array as one batch per iteration. samples_per_batch is ignored and num_batches is forced to 1. Use when you want deterministic coverage of the sample (no sampling variance) rather than a Monte Carlo subsample — pair mode's memory scales with the unique-pair count after row-dedup, which is bounded by bit_array.num_shots and typically much smaller.

False
add_hf_pair bool

If True (default False), inject the HF pair (HF_α, HF_β) into every batch's pair set if missing. HF has substantial ground-state overlap for closed-shell chemistry, and its presence gives Davidson a guaranteed non-zero component along a physically meaningful direction — otherwise a batch that samples zero configurations near HF (common on noisy hardware samples) yields a Davidson initial residual that fails to find the ground state.

False
**solver_kwargs

Forwarded to make_torch_sci_solver when solver is None.

{}

Returns:

Type Description

The lowest-energy SCIResult seen across all iterations —

matching the return contract of

func:qiskit_addon_sqd.fermion.diagonalize_fermionic_hamiltonian.