Skip to content

sci_solvers.energy_solvers.torch_sci_solver

torch_sci_solver-based sci_solver implementation.

Wraps torch_sci_solver's matvec + Davidson + RDM stack (via make_torch_sci_solver) in this package's :class:EnergyCalculatorBase contract. Runs on GPU by default (device="cuda") and falls back to CPU; suited to large active spaces where the torch batched matvec is fastest.

TorchSCISolver [source]

TorchSCISolver(*, symmetrize_spin: bool, hamiltonian: HamiltonianData | str | PathLike[str] | None = None, device: device | str = 'cuda', devices: Optional[List[device | str]] = None, dtype: dtype = float64, verbose: bool = False, chunk_size: int = 2000000, davidson_block_size: Optional[int] = 20, max_davidson_iters: int = 20, davidson_tolerance: float = 0.0001, apply_ab_projection: bool = False, nroots: int = 1, n_roots: int = 1, **solver_kwargs: Any)

Bases: EnergyCalculatorBase

torch_sci based - a torch implementation of SCI, uses GPU by default

Multi-root support: pass n_roots > 1 to solve for excited states in addition to the ground state. Each per-batch :class:~sci_solvers.eigen_states.EigenStates then holds states[0] (ground state) through states[n_roots - 1] (highest solved root), ascending in energy — read excited states from states[1:]. The qiskit-addon-sqd recovery loop (driven via :meth:~sci_solvers.energy_calculation_base.EnergyCalculatorBase.sci_solver_callable) still consumes only the ground state, so raising n_roots is free for the hot loop and surfaces excited states only to callers that read them. This mirrors the general-algebra solvers' nroots (named n_roots here to match the underlying torch_sci_solver package).

Initialize the TorchSCISolver.

Default parameters are set to match exact energy as sbd tpb app (https://github.com/r-ccs-cms/sbd/tree/main/apps/chemistry_tpb_selected_basis_diagonalization)

Parameters:

Name Type Description Default
device device | str

Single torch device for the diagonalization (default "cuda"). Ignored when devices is given.

'cuda'
devices Optional[List[device | str]]

Opt into single-node, multi-GPU batch-parallel dispatch by passing a list of CUDA devices, e.g. ["cuda:0", "cuda:1"]. Each SQD subspace (batch) is then diagonalized on its own GPU via a persistent process pool. Speedup is bounded by min(num_batches, len(devices)): it is near- linear only when num_batches >= len(devices) and roughly divisible by it (an awkward remainder leaves GPUs idle in the final wave). None (default) keeps single-device behaviour. When set, devices[0] becomes the primary device and the device argument is not forwarded.

None
dtype dtype

Numeric dtype for the diagonalization (default torch.float64). Pass torch.complex128 (or complex64) to solve a complex Hermitian Hamiltonian — opt-in only: passing complex hcore/eri to :meth:sci_solver_callable_eigen_states while this stays at its real default raises rather than silently dropping the imaginary part. The underlying engine selects the supported arithmetic for the dtype, basis and device; see torch_sci_solver.torch_impl.qiskit_adapter.TorchSCISolver's matvec_impl docs.

float64
davidson_block_size Optional[int]

Davidson subspace size — vectors accumulated before a restart (default 20). Total matvec work is roughly max_davidson_iters * davidson_block_size, since this solver's Davidson is genuinely nested (an outer restart loop over an inner subspace-expansion loop). Must be >= n_roots; None auto-tunes it.

20
max_davidson_iters int

Outer Davidson restart count per diagonalization (default 20). Note this is a restart count, not the flat per-matvec budget that max_cycle denotes on the PySCF-family solvers — the two are not interchangeable, which is why this solver does not accept max_cycle. Override per call via :meth:sci_solver_callable_eigen_states's own max_davidson_iters.

20
davidson_tolerance float

Davidson residual (‖R‖) convergence threshold (default 1e-4).

0.0001
nroots int

Number of lowest eigenpairs (roots) to solve for per batch (canonical spelling, matching the general-algebra solvers). Default 1 (ground state only).

1
n_roots int

Backward-compatible alias for nroots. Pass one or the other, not both (a non-default value on each raises). When > 1, Davidson extracts the nroots lowest Ritz pairs and each solved batch's :class:~sci_solvers.eigen_states.EigenStates holds one :class:SCIResult per root, ascending in energy — read excited states from states[1:]. Must not exceed davidson_block_size (auto-tuned when that is None).

1

config property

config: dict[str, Any]

JSON-friendly requested/resolved engine configuration.

Delegates to the underlying torch_sci_solver engine so workflows do not need to reach into self._solver for the mode, device, dtype, distributed launch config or gdb_kwargs.

sci_solver_callable_eigen_states

sci_solver_callable_eigen_states(ci_strs_batches: List[Tuple[ndarray, ndarray]] | List[ndarray], hcore: ndarray, eri: ndarray, norb: int, nelec: Tuple[int, int] | int, *, spin_sq: float | None = None, max_davidson_iters: int | None = None, init_vectors: List[ndarray | None] | None = None, **kwargs: Any) -> List[EigenStates]

Diagonalize each batch via our homegrown torch_sci implementation.

Positional signature matches qiskit_addon_sqd.fermion.solve_sci_batch (ci_strings, one_body, two_body, norb, nelec plus spin_sq); the remaining keyword knobs are this solver's own and are not PySCF's — the torch engine runs its own Davidson, nothing routes to kernel_fixed_space.

Two reduction paths are dispatched on nelec's type, mirroring GeneralAlgebraSolverBase:

  • spatial — nelec an (n_a, n_b) tuple: ci_strs_batches is a list of (strs_a, strs_b) tuples over separate alpha/beta determinant lists.
  • spinless (flat spin-orbital, no alpha/beta split) — nelec a scalar total particle number N: ci_strs_batches is a list of flat strs arrays. Complex-only (mirrors sci_solvers.spinless_ci_problem). Multi-root (n_roots > 1 at construction) works at the same level as the spatial path (davidson_torch is basis-shape-agnostic); spin_sq is rejected (no alpha/beta split to target a spin sector).

Parameters:

Name Type Description Default
ci_strs_batches List[Tuple[ndarray, ndarray]] | List[ndarray]

List of (strs_a, strs_b) int64-array tuples (spatial), or a list of flat strs int64 arrays (spinless — see above).

required
hcore ndarray

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

required
eri ndarray

Two-electron repulsion integrals, shape (norb,)*4.

required
norb int

Number of spatial orbitals (spin-orbitals nmo on the spinless path).

required
nelec Tuple[int, int] | int

(n_alpha, n_beta) (spatial), or a scalar total N (spinless — see above).

required
spin_sq float | None

Target value for total spin squared (S²). Spatial path only; rejected on the spinless path.

None
max_davidson_iters int | None

Outer Davidson restart count for this call. Defaults to the solver's own max_davidson_iters (set at construction) when omitted — pass it only to override for a single call. This solver deliberately does not accept max_cycle: that name denotes a flat total-matvec budget on the PySCF-family solvers, whereas this Davidson is nested (total work ~ max_davidson_iters * davidson_block_size), so the same value would buy very different amounts of work.

None
init_vectors List[ndarray | None] | None

Davidson start vector per batch, to warm start an iteration from the previous one's state projected onto the new strings (the projection is the caller's job). One entry per batch, each None (cold start) or a 1-D array laid out like the sci_state.amplitudes this solver returns in that mode and indexed by the strings passed in this call:

  • TPB: (len(strs_a) * len(strs_b),), ia * len(strs_b) + ib, spin-block signs;
  • GDB (mode="gdb"): (len(strs_a),), one entry per (strs_a[i], strs_b[i]) pair, interleaved-Wick signs;
  • spinless: (len(strs),).

The solver reorders it to its internal basis (strings are sorted and deduplicated; a duplicate takes its first occurrence's amplitude, a string not passed starts at 0), applies the αβ projection, and normalizes it. If less than 1e-8 of its own norm is left after that, it falls back to the cold start (so its overall scale does not matter). Whether each batch was warm started is reported as warm by :meth:last_call_subspace_stats (TPB and GDB). Raises ValueError on a length mismatch or together with probe_state.

None
**kwargs Any

Additional kwargs forwarded to the underlying torch_sci_solver engine — e.g. tol (per-call Davidson residual threshold, overriding davidson_tolerance), spin_penalty_lambda.

{}

Returns:

Name Type Description
One List[EigenStates]

class:~sci_solvers.eigen_states.EigenStates per batch, in

List[EigenStates]

input order, each holding one :class:SCIResult per solved root,

List[EigenStates]

ascending in energy: states[0] is the ground state and

List[EigenStates]

states[1:] are the excited states (present only when the solver

List[EigenStates]

was constructed with n_roots > 1; a default n_roots == 1

List[EigenStates]

solver returns an EigenStates of length one). Energies are

List[EigenStates]

electronic only.

capabilities

capabilities() -> dict[str, Any]

Per-mode engine support map (layouts, dtypes, RDM/S², distributed, ...).

preflight

preflight(ci_strings: List[Tuple[ndarray, ndarray]] | List[ndarray], nelec: Tuple[int, int] | int, **call_kwargs: Any) -> dict[str, Any]

Run the engine's call-time gates and return the resolved plan, without solving.

Parameters:

Name Type Description Default
ci_strings List[Tuple[ndarray, ndarray]] | List[ndarray]

The per-batch CI strings (same shapes as :meth:sci_solver_callable_eigen_states).

required
nelec Tuple[int, int] | int

(n_alpha, n_beta) or a scalar total particle number.

required
**call_kwargs Any

The per-call keywords the solve would receive. norb= is strongly recommended (otherwise it is inferred from the highest set bit).

{}

Returns:

Type Description
dict[str, Any]

The engine's JSON-friendly plan: effective basis/mode, per-subspace

dict[str, Any]

dimensions, matvec_impl, tile grid/source, particle sector,

dict[str, Any]

warm/cold start and RDM path.

last_call_subspace_stats

last_call_subspace_stats() -> List[dict[str, Any]]

Per-batch diagnostics of the most recent solve, one dict per batch, in order.

The public way to confirm what a call actually did, without reaching into the engine: warm (whether that batch started from its init_vectors entry, False when it fell back to the cold start), n_matvecs, davidson_dtype, davidson_fp32_shift, the resolved davidson_fp32_energy, and the timings (t_setup, t_davidson, t_occ) and mem_peak_gb. Empty before the first call, after a spinless call (that path keeps no per-batch log) and after a call that raised: never an earlier call's stats.

compute_energy

compute_energy(ci_strs_batches: List[Tuple[ndarray, ndarray]] | None = None, bitstring_matrix_batches: List[ndarray] | None = None, sort_ci_strs: bool = True, **solver_call_kwargs: Any) -> List[SCIResult]

Compute energies for each batch of CI strs.

Note - to get from bitstrings into ci_strs you can use:

from qiskit_addon_sqd.fermion import bitstring_matrix_to_ci_strs
ci_strs = bitstring_matrix_to_ci_strs(bitstrings_to_use, open_shell=False) #or open_shell==True, depending on your case

Parameters:

Name Type Description Default
ci_strs_batches List[Tuple[ndarray, ndarray]] | None

List of (strs_a, strs_b) int64-array tuples. Provide exactly one of this argument or bitstring_matrix_batches.

None
bitstring_matrix_batches List[ndarray] | None

List of boolean NumPy matrices, one per batch. Provide exactly one of this argument or ci_strs_batches.

None
sort_ci_strs bool

Sort and deduplicate each batch's alpha/beta CI strings with np.unique before solving. Defaults to True so solvers that require strictly ascending strings (the general-algebra family) work out of the box; the bitstring path is already sorted, so this is a no-op there. Pair-mode (mode="gdb") solvers are exempt: their (strs_a, strs_b) are parallel (alpha_i, beta_i) lists, so sorting each one independently would break the pairing (they dedup/sort the pair list themselves). Pass False to forward the strings exactly as given.

True
**solver_call_kwargs Any

Additional kwargs forwarded to sci_solver_callable.

{}

sci_solver_callable

sci_solver_callable(ci_strs_batches: 'List[Tuple[np.ndarray, np.ndarray]] | List[np.ndarray]', hcore: ndarray, eri: ndarray, norb: int, nelec: 'Tuple[int, int] | int', **kwargs: Any) -> List[SCIResult]

Diagonalize each batch's CI-string subspace, returning ground states.

The qiskit-addon-sqd entry point: matches the sci_solver signature expected by qiskit_addon_sqd.fermion.diagonalize_fermionic_hamiltonian. Thin wrapper over :meth:sci_solver_callable_eigen_states that keeps each batch's ground state (root 0) and discards the excited states, since the SQD recovery loop consumes only the ground state. To access excited states, call :meth:sci_solver_callable_eigen_states directly.

Note - to get from bitstrings into ci_strs you can use:

from qiskit_addon_sqd.fermion import bitstring_matrix_to_ci_strs
ci_strs = bitstring_matrix_to_ci_strs(bitstrings_to_use, open_shell=False) #or open_shell==True, depending on your case

Parameters:

Name Type Description Default
ci_strs_batches 'List[Tuple[np.ndarray, np.ndarray]] | List[np.ndarray]'

List of (strs_a, strs_b) tuples (spatial), or a list of flat strs arrays (spinless — a scalar nelec; see :meth:sci_solver_callable_eigen_states). Each spatial tuple defines a subspace via the outer product of unique alpha and beta CI strings (int64 arrays where bit i of each integer indicates occupancy of orbital i).

required
hcore ndarray

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

required
eri ndarray

Two-electron repulsion integrals. Either full 4-D (norb,)*4 or a packed form (4-fold / 8-fold) — what's accepted depends on the concrete solver.

required
norb int

Number of spatial orbitals.

required
nelec 'Tuple[int, int] | int'

(n_alpha, n_beta) (spatial), or a scalar total N (spinless — not every solver implements this; see :meth:sci_solver_callable_eigen_states).

required
**kwargs Any

Solver-specific optional arguments. See each concrete solver for the accepted set.

{}

Returns:

Name Type Description
One List[SCIResult]

class:SCIResult (the ground state) per input batch, in input

List[SCIResult]

order. energy fields are electronic only; callers add e_nuc

List[SCIResult]

themselves to obtain chemical totals.