Skip to content

torch_sci_solver.torch_impl.qiskit_adapter

Adapter exposing this package's torch matvec + Davidson + RDM machinery as a sci_solver for qiskit_addon_sqd.fermion.diagonalize_fermionic_hamiltonian.

Why use this instead of the in-house sqd_loop?

The qiskit_addon_sqd loop provides several production features that the package's standalone sqd_loop doesn't (and shouldn't reinvent):

  • max_dim — basis-size cap per spin sector. The right primary knob for fitting large bases on bounded device RAM. (Far more principled than tuning --num-block.)
  • num_batches — ensemble averaging across subsampled batches; tends to improve SQD convergence.
  • include_configurations — pin anchor configs (HF, important determinants).
  • carryover_threshold — keep high-weight CI strings across iterations.
  • callback — per-iteration introspection hook.
  • Standard BitArray input — what Qiskit primitives produce.

The torch path (matvec, Davidson, 2-RDM, energy reconstruction) stays identical; we just plug into qiskit's outer loop instead of running our own.

Typical use::

from qiskit_addon_sqd.fermion import diagonalize_fermionic_hamiltonian
from torch_sci_solver.torch_impl.qiskit_adapter import make_torch_sci_solver

solver = make_torch_sci_solver(device='cuda', chunk_size=2_000_000)

result = diagonalize_fermionic_hamiltonian(
    one_body_tensor=h1_spatial,
    two_body_tensor=eri_spatial,
    bit_array=bit_array,
    samples_per_batch=samples_per_batch,
    norb=L, nelec=(n_a, n_b),
    max_iterations=10,
    sci_solver=solver,
    max_dim=10000,           # per-spin-sector basis cap
    num_batches=1,           # raise for ensemble averaging
)
print(result.energy)         # converged SQD energy
occ_a, occ_b = result.orbital_occupancies

TorchSCISolver [source]

TorchSCISolver(*, device: 'str | torch.device' = 'cpu', devices: 'Optional[list[str | torch.device]]' = None, dtype: dtype = float64, chunk_size: int = 2000000, davidson_block_size: Optional[int] = None, max_davidson_iters: int = 20, davidson_tolerance: float = 1e-07, davidson_de_tolerance: Optional[float] = None, compute_full_rdm: bool = False, compute_spin_squared: bool = False, verbose: bool = False, budget_fraction: float = 0.65, gdb_kwargs: 'Optional[dict[str, Any]]' = None, seed_strategy: str = 'smallest_int', apply_ab_projection: bool = True, matvec_impl: str = 'auto', mode: Literal['tpb', 'gdb'] = 'tpb', n_roots: int = 1, davidson_dtype: Optional[dtype] = None, davidson_fp32_shift: "Literal['hf'] | float | None" = 'hf', davidson_fp32_energy: Literal['auto', 'rq64', 'ritz'] = 'auto', davidson_correction: Literal['davidson', 'olsen'] = 'davidson', davidson_restart: Literal['recompute', 'reuse', 'thick'] = 'recompute', davidson_missed_root_check: "Literal['auto'] | bool" = 'auto', distributed: 'bool | dict[str, Any] | None' = None, unknown_call_kwargs: Literal['ignore', 'warn', 'error'] = 'ignore', memory_budget_bytes: Optional[int] = None, table_dtype: Literal['auto', 'int32', 'int64'] = 'auto', compact_eri: Literal['auto', 'on', 'off'] = 'auto', triton_block: Optional[int] = None, diagnostics: 'Optional[dict[str, Any]]' = None, deterministic: bool = False, ab_factorization: Literal['off', 'cholesky'] = 'off', ab_factorization_tol: float = 1e-10)

Diagonalize selected CI subspaces on CPU, GPU or distributed GPU ranks.

The callable engine returns one EigenStates container per input subspace, with the lowest n_roots eigenpairs in ascending energy order. mode="tpb" uses Cartesian alpha/beta products; mode="gdb" uses explicit determinant pairs. A scalar particle count selects spinless bases.

devices=[...] assigns independent batches to GPUs, while distributed=... partitions a single subspace across ranks. config, capabilities and preflight expose the resolved settings and supported inputs. stats and format_perf_summary report timings.

For the ground-state callback used by the SQD recovery loop, use the factory in torch_sci_solver.qiskit.

Build a sci_solver callable matching the qiskit_addon_sqd contract.

Parameters:

Name Type Description Default
device 'str | torch.device'

torch device for the diag (typically 'cuda').

'cpu'
dtype dtype

float dtype (float64 recommended for stability).

float64
chunk_size int

matvec batch size; lower on matvec OOM.

2000000
davidson_block_size Optional[int]

Davidson subspace size. If None, auto-tune per subspace from the free memory remaining after helpers+integrals are on device — far more accurate than scaling from total device RAM, especially at 100M+ basis sizes where helpers are non-trivial.

None
max_davidson_iters int

Outer Davidson restart count per diagonalization (default 20). Total matvec work scales as max_davidson_iters * davidson_block_size. Used when a per-call max_davidson_iters override is not supplied.

20
davidson_tolerance float

Davidson ‖R‖ convergence threshold. An absolute residual, not scaled to the energy. On device="mps" (float32, no float64 support) a value below MPS_DAVIDSON_TOLERANCE_FLOOR (1e-5) is unlikely to ever be reached for typical quantum chemistry energy scales, so it is overridden to that floor (per call, and at construction) with a RuntimeWarning — not just warned about — so a run on this device stays meaningful without the caller having to scale the tolerance to their own energy.

1e-07
davidson_de_tolerance Optional[float]

Opt-in eigenvalue-stability check. None (default) disables it: convergence is residual-only (davidson_tolerance). Pass a value to additionally require that a root's Ritz value has also stopped changing by more than sqrt(davidson_de_tolerance) before it is declared converged (pyscf-style two-condition stopping criterion; recommended value: davidson_de_tolerance=davidson_tolerance; see :func:~torch_sci_solver.torch_impl.davidson.davidson_torch).

None
compute_full_rdm bool

also build and return spin-summed 1- and 2-RDMs.

False
compute_spin_squared bool

also build the αβ 2-RDM block and compute ⟨S²⟩ via the s_squared_from_rdm formula. Validated against PySCF's spin_square0 to machine precision on singlet / triplet / quintet small systems. Cost: one Γαβ build per subspace (a few seconds on A100 at 50M-config basis). Printed in the [sci_solver] verbose line and exposed on solver.stats['spin_squared'] (list, one entry per subspace across the whole run).

False
verbose bool

per-subspace memory + Davidson prints.

False
budget_fraction float

fraction of free memory the Davidson subspace is allowed to consume (default 0.80; raise if you want to push closer to the limit, lower if stability matters more than throughput).

0.65
gdb_kwargs 'Optional[dict[str, Any]]'

options that only apply to the GDB (pair) basis, i.e. mode="gdb". Bundled here rather than flattened into this signature so the basis-specific knobs stay in one place. Unknown keys raise, so a typo is not silently ignored. Passing this under mode="tpb" also raises. Recognized keys (see :data:GDB_KWARG_DEFAULTS):

          ``budget_bytes`` — peak workspace for one
          excitation-enumeration chunk. GDB re-derives the
          excitation rows on every matvec instead of storing
          them (a stored table is O(nnz(H)); see
          :mod:`~torch_sci_solver.torch_impl.pair_helpers`),
          so this sets how much it materializes at a time,
          and therefore how many chunks — and kernel
          launches — each matvec costs. ``None`` (default)
          uses a flat 8192 MB on every device — measured
          fastest on an A100 across dimensions; a "biggest
          chunk that fits free VRAM" auto-sizer was tried
          and was up to 4.7x slower. Lower it if VRAM is
          tight. Unrelated to ``budget_fraction``, which
          sizes the persistent Davidson subspace.

          ``block_matvec`` — ``"auto"`` (default),
          ``"on"`` or ``"off"``: use the exact
          Cartesian-block matvec when the pair basis
          decomposes into disjoint ``α_uids × β_uids``
          groups. ``"auto"`` applies the size and group
          gates; ``"on"`` skips them (tests, A/B runs);
          ``"off"`` always streams the pair-keyed
          tables. A failed structural check falls back
          to the streamed tables.

          ``block_table_bytes`` — optional cap on the
          block decomposition's byte footprint (the two
          pair-index maps plus uid lists); the build is
          gated out when the estimate exceeds it.
          ``None`` leaves it uncapped.
None
seed_strategy str

which determinant to place at index 0 of the basis — i.e., which determinant Davidson seeds its initial vector W = [1, 0, ..., 0] on. One of: * 'smallest_int' (default; also spelled 'lowest_diagonal') — sort the basis by integer value. A single-root solve seeds at the lowest entry of the diagonal Davidson sees (argmin of diag H, spin penalty included); a multi-root seed block starts at the smallest-integer determinant and adds the lowest-diagonal ones. For closed-shell chemistry the lowest diagonal is the HF-like determinant, which is in the singlet-ground-state Krylov basin. Empirically gives clean singlets up through N_BITS=7000 on a 36-orbital benchmark when combined with αβ-swap projection (auto-enabled for symmetric bases) and the post-recovery dedup (always on). * 'connected' — pick the determinant with the most single/double-excitation neighbors in the basis. Matches SBD/TPB's behavior. Mostly an SBD-comparison opt-in now that we have a better default; on this benchmark it returns higher-energy singlets at small basis and occasionally steers Davidson onto a quintet at intermediate basis. O(N²) bit-popcount, sub-second at N=14k; cost goes to stats['t_seed']. Either way, when the basis splits into blocks of H that no single or double excitation connects, a single-root solve then solves each other block from its own lowest diagonal entry (at most 8 of them, with a warning for the rest) and returns the lowest energy, since Davidson does not leave its start's block. On one device a product-mode block is solved on its own strings, at the cost of its size. Each subspace entry of stats['per_call_log'] records n_blocks and the block_solves.

'smallest_int'
apply_ab_projection bool
          When True (default), apply the αβ-swap projection
          to Davidson on αβ-symmetric bases (auto-detected).
          Set False to skip it even on symmetric bases.

          The projection restricts Davidson to the physical
          α↔β-swap eigenspace of H that contains the closed-
          shell singlet subspace. Because the matvec stores
          the wavefunction in the interleaved-Wick basis
          (see ``rdm.py`` "Convention"), the projector
          carries a per-(iₐ, i_b) sign — it is
          ``P(v)[i,j] = (v[i,j] + τ[i,j] · v[j,i]) / 2``
          with ``τ = σ · σᵀ`` and σ the interleaved-Wick →
          spin-block sign matrix. This makes Davidson track
          the true singlet ground state at all basis sizes:
          at small scale it reproduces PySCF's exact FCI on
          the closed-shell CI space; at large scale it
          suppresses spurious triplet contamination from
          round-off in the chunked matvec, which without
          the projection can steer Davidson onto a wrong
          eigenstate. Set ``apply_ab_projection=False``
          only for SBD/TPB parity comparison (SBD has no
          equivalent projection) or when you want the bare
          variational minimum on the *unrestricted* CI
          basis (which for closed-shell singlets may not
          be the singlet minimum on truncated subspaces —
          enforce the singlet with ``spin_sq=0.0`` if you
          need that instead).
True

Returns:

Name Type Description
None

A callable matching qiskit_addon_sqd.fermion.solve_sci_batch::

sci_solver(ci_strings, one_body, two_body, norb, nelec, *, spin_sq=None, **kwargs) -> list[SCIResult]

None

suitable as the sci_solver=... argument of

None

qiskit_addon_sqd.fermion.diagonalize_fermionic_hamiltonian.

None

Notes on the kwargs surface: - spin_sq=None (default) — no penalty. Bit-identical to the v0.10.18 code path: no S² operator built, no augmented matvec, no extra memory. Use this for the unmodified variational answer. - spin_sq=<float> — augmented Davidson solves H + λ · (S² − spin_sq) with λ = 1.0 by default. spin_sq is the target value of ⟨S²⟩ (e.g., 0.0 for a singlet, 2.0 for a triplet, 6.0 for a quintet). The penalty strength λ can be overridden by passing spin_penalty_lambda=<float> as a kwarg to this call; otherwise λ defaults to 1.0, which puts the lowest triplet 2 Ha above the lowest singlet — sufficient when the chemistry singlet–triplet gap is sub-eV. S² is built via the scatter-based SpinSqOperator with O(M_a · n_a · (L − n_a)) precompute and ~O(L² + N_off) per matvec, where N_off is the count of nonzero off-diagonal elements of S² in the basis — typically a small multiple of N. No N² memory cost.

The reported energy is the physical ⟨ψ|H|ψ⟩ of the converged eigenstate — the penalty contribution λ(⟨S²⟩ − target) is subtracted before returning, so the penalty is invisible to the caller. The eigenvector's ⟨S²⟩ is exposed as solver.stats['spin_sq_final'] for verification. - max_davidson_iters and tol are forwarded to the underlying Davidson as outer restart count and ‖R‖ threshold respectively. (max_cycle is rejected: it was a misleading pyscf-style alias for max_davidson_iters, and nothing here calls pyscf.) - Other pyscf-only kwargs (nroots, max_space, …) are silently ignored.

matvec_impl None

Matvec and preparation backend. "auto" (default) uses "torch" on CPU and supported Triton kernels on NVIDIA CUDA. Real FP32/FP64 GDB selects Triton when available, otherwise batched with a terminal warning about substantially slower solves. Complex GDB defaults to batched. TPB and spinless automatic CUDA selection require working Triton; their kernels support real and complex operands. "torch" is the vectorized Torch implementation and disables all custom Triton kernels, including CUDA move discovery and connectivity. "triton" explicitly selects supported CUDA kernels, retaining existing portable fallbacks for unsupported channels and layouts. Complex GDB uses its supported doubles kernels and portable singles arithmetic. The resolved value is stored on self.matvec_impl and recorded in benchmark metadata. "batched" is a deprecated alias for "torch" and logs a future-removal warning. Use "torch" for identical behavior; prefer "auto" for available Triton acceleration.

mode None

Basis-space mode, "tpb" (default) or "gdb".

          ``"tpb"`` — *tensor product basis*, the historical
          behaviour. Stores the wavefunction over the
          Cartesian product ``{(α_i, β_j) : i, j}`` of dim
          ``M_α · M_β``: the two spin sectors are
          deduplicated independently and every α-string
          couples with every β-string.

          ``"gdb"`` — *general determinant basis*. The caller
          supplies an explicit list of ``(α_i, β_i)`` pairs
          and the wavefunction has dim ``N`` = number of
          distinct pairs. In GDB mode input arrays
          ``(strings_a, strings_b)`` are treated as parallel
          length-N lists (index ``i`` defines pair ``i``,
          duplicates collapsed by ``(α, β)``) rather than as
          two independent sets crossed via product. Use GDB
          when the sampler already produced meaningful
          (α, β) pairings you want to preserve — e.g., raw
          measurement bitstrings — instead of blowing them up
          through the product.

          **GDB is not a drop-in for qiskit_addon_sqd's outer loop.**
          ``qiskit_addon_sqd.fermion.diagonalize_fermionic_hamiltonian``
          dedups its bitstring matrix independently per spin
          (via ``bitstring_matrix_to_ci_strs``) and passes
          the resulting per-spin-unique arrays to the
          ``sci_solver`` callable as if forming their
          Cartesian product. Feeding that flow to a
          ``mode="gdb"`` solver would silently
          misinterpret the per-spin-unique arrays as
          parallel pairs — an entirely different (and
          usually wrong) subspace. The correct pair-mode
          SQD workflow is: raw bit_array → extract α/β
          halves per row → call
          ``solve_fermion((alpha, beta), mode="gdb")``
          directly, bypassing
          ``diagonalize_fermionic_hamiltonian``. If you need
          an SQD outer loop, wrap your own.
n_roots None

number of lowest eigenpairs to find per subspace (default 1 — backward-compatible, returns the ground state only). When > 1, Davidson extracts the n_roots lowest Ritz pairs; each root produces its own occupancies, energy, and SCIResult. All roots are accessible via the return value of __call__: each element of the returned list[EigenStates] holds states[0] (ground state) through states[n_roots-1] (highest solved root). n_roots must not exceed davidson_block_size (auto-tuned or user-supplied). It must also fit in the CI space (or projected sector). Full RDMs, spin diagnostics and warm-start snapshots are computed for root 0 only.

davidson_dtype None

storage dtype of Davidson's subspace (C, HC, the Ritz problem). None (default) keeps it in dtype. The narrow subspace — torch.float32 over a real fp64 dtype, or torch.complex64 over complex128 — halves the subspace memory (C/HC dominate the peak at 10⁸ determinants) while the matvec still applies H in full precision: its first op, hii * T, promotes the narrow input, so only the vector read is narrow. Buys capacity, not speed. Any other combination raises.

davidson_fp32_shift None

only with an fp32 davidson_dtype: Davidson sees H − shift·I so its fp32 Ritz values are correlation-sized rather than total energies (fp32 resolves ~1e-7 relative). "hf" (default) uses min(hii), the HF-like diagonal; a float sets it. None disables it — unsafe: measured to stall at ~1e-5 residual, 0.3 mHa off.

davidson_fp32_energy None

with an fp32 davidson_dtype, or on device="mps" (where the whole solve is float32): how the returned energy is formed. "rq64": an fp64 Rayleigh quotient of the returned vector, one extra matvec per root, exact. "ritz": Davidson's fp32 Ritz value plus the shift, no extra matvec; its error is that of an fp32-rounded wavefunction, does not shrink with tol and grows with the basis (3.5e-7 Ha at 400 determinants, 1.4e-6 Ha at 14,400 on N2 2.2 Å). "auto" (default) picks "ritz" when the call's tol >= 1e-3 and "rq64" otherwise: at that residual the energy is already uncertain by more than the Ritz error (1.8e-5–1.8e-4 Ha on N2 in fp64), so the matvec is saved where it is free, e.g. the SQD warm loop at 3e-3, and kept where it matters. On MPS the fp64 quotient uses CPU copies of the integrals, tables and basis (MPS has no float64), one CPU matvec per root, and also replaces the penalty-stripped energy under spin_sq; "ritz" keeps the float32 Ritz value, biased by about |E| eps(float32).

davidson_correction None

"davidson" (default): the diagonal-preconditioned correction (theta - D)^-1 r. "olsen": Olsen's correction, orthogonal to the Ritz vector (see davidson_torch). Every mode and root count.

davidson_restart None

what single-root Davidson keeps across a restart. "recompute" (default): the Ritz vector, whose H x costs one matvec per restart. "reuse": also its H x, formed from stored products. "thick": "reuse" plus the previous Ritz vector (GD+1). Both confirm convergence after a restart with one fresh matvec. Multi-root already restarts from stored products.

davidson_missed_root_check None

n_roots > 1 only: after convergence, search for a root the solve missed and re-solve with it (see davidson_torch). "auto" (default): on exactly when the solve starts from init_vectors, where it is needed for correctness: a warm multi-root start, even from the exact ground state, can converge without a lower excited root (N2 SQD batch: root 1 off by 0.45 Ha). True also checks cold solves, which can miss a root at a loose tolerance; False never checks.

distributed None

Opt-in distributed-memory solve of each subspace. None/False (default) keeps the existing single-process / batch-parallel devices= path byte for byte. True uses all visible CUDA devices (NCCL) when there are at least two, else the launcher's WORLD_SIZE. A dict selects the launch explicitly: world_size, backend ("gloo" or "nccl"), device_ids, master_addr, master_port, init_method and timeout (seconds). The state vector and the Davidson subspace are partitioned across ranks; C/HC projections and residual norms are all-reduced. Supported: TPB, GDB and spinless bases, real and complex, single- or multi-root. matvec selects the owner-computes local operator ("local", the default) or the replicated fallback; tile selects a 2-D grid ("auto", "force" or (p_alpha, p_beta)), exchange_bytes bands large αβ corners, and hand_back_dir names a shared directory for the memmapped hand-back on multi-node runs. Mutually exclusive with devices=. See docs/distributed_state_vector.md.

unknown_call_kwargs None

policy for per-call keywords this engine does not recognize: "ignore" (default, the historical behaviour), "warn" (emit a UserWarning naming them) or "error" (raise TypeError). The recognized set is :data:CALL_KWARG_NAMES; note that max_cycle is recognized only to raise its own targeted error, and pyscf-only names such as nroots are unknown here.

memory_budget_bytes None

optional per-rank byte cap. It bounds the auto-tile policy, the default GDB/spinless enumeration workspace (when gdb_kwargs["budget_bytes"] is unset) and the automatic Davidson block sizing. None (default) keeps the current free-memory behaviour. A distributed={"budget_bytes": ...} cap is combined with it by taking the smaller.

table_dtype None

index-payload dtype of the TPB excitation tables, "auto" (default: int64, the reference build), "int32" (halves the table memory; rejects indices above :data:INT32_MAX) or "int64". The GDB and spinless tables are always int64, and the Triton kernels require int64 payloads.

compact_eri None

"auto" (default), "on" or "off" — whether the spatial ERI is stored in the 16x-smaller compact spin-adapted form. "auto" keeps the historical heuristic (compact when the Triton kernels do not need the dense tensor and the spin-orbital ERI is at least 64^4). The spinless path has no compact store.

triton_block None

optional Triton launch block (a positive multiple of 16), or None (default) for the kernels' own choice. It drives the distributed TPB tile operator, whose block constant is read per launch; the single-process Triton entry/doubles kernels keep their built-in block.

diagnostics None

optional dict of diagnostic switches: dump_dir (per-call basis dump directory, same as TORCH_SCI_DUMP_DIR), matvec_profile (enable the TORCH_SCI_MATVEC_PROFILE phase timers) and profile_blocks (enable the SCIS_PROFILE_BLOCKS channel timers). Explicit environment variables are still honoured.

deterministic None

True runs every call under torch's deterministic algorithms: CUDA index_add/scatter_add take their deterministic implementations, the atomic Triton entry kernels (spinless, streamed GDB) and the cuSPARSE products of the factorized αβ pass fall back to them, and CUBLAS_WORKSPACE_CONFIG defaults to ":4096:8" when CUDA is not yet initialized. A CPU or CUDA run is then bitwise reproducible for a fixed device set, backend, rank count and NCCL algorithm choice (pin NCCL_ALGO across runs); a different rank count still reorders the global reductions, and MPS has no deterministic accumulating index_put (warned). The switch is process-wide for the duration of a call, so do not run solvers with different settings concurrently in threads of one process. Slower on CUDA; a debugging aid.

ab_factorization None

"off" (default) or "cholesky". With "cholesky" the TPB αβ doubles pass runs in factorized form, Σ_P A^α_P C (A^β_P)^T, from a pivoted Cholesky decomposition of the spatial ERI (computed once per Hamiltonian; no auxiliary basis). Exact to ab_factorization_tol; faster when the ERI is low rank against the singles per string. Real TPB solves only, not with distributed=.

ab_factorization_tol None

largest residual diagonal of the pivoted Cholesky (an indefinite ERI supermatrix, e.g. synthetic integrals, takes a signed eigendecomposition with this cutoff).

config property

config: dict[str, Any]

JSON-friendly view of the requested and resolved solver setup.

requested is the normalized constructor input (every keyword, with gdb_kwargs defaults filled); resolved is what the engine will actually use: the mode, resolved and requested matvec_impl, dtype names, effective device(s), the distributed launch config (or None), the per-path probe_state_types and the new interface knobs. json.dumps(solver.config) works.

Returns:

Type Description
dict[str, Any]

{"requested": {...}, "resolved": {...}}.

capabilities

capabilities() -> dict[str, Any]

Per-mode support map for discovery and workflow gating.

The result is JSON-friendly and answers what a mode/basis supports without constructing a solve: layouts, dtypes, spinless and multi-root support, warm start / init_vectors (including the cached state type and whether HF augmentation applies), full RDMs, <S^2>, the spin penalty, distributed matvec/tile layouts, the GDB block matvec / structural basis / move cache, Triton pass coverage, the accepted per-call keywords and the unknown-keyword policy. Unsupported physics is reported with a reason, not just a False: the spinless entry carries spin_squared_unsupported_reason and spin_penalty_unsupported_reason because S^2 needs an alpha/beta partition that a flat spin-orbital basis does not have.

Returns:

Type Description
dict[str, Any]

A dict with one entry per mode under "modes" plus a

dict[str, Any]

"spinless" entry (a call-time layout selected from a scalar

dict[str, Any]

nelec, not a mode= value), "accepted_call_kwargs" and

dict[str, Any]

the configured "unknown_call_kwargs" policy.

preflight

preflight(ci_strings: Any, nelec: Any, *, norb: 'Optional[int]' = None, one_body_tensor: Any = None, two_body_tensor: Any = None, **call_kwargs: Any) -> dict[str, Any]

Run every call-time gate without solving and return the resolved plan.

The same validation the next solve would perform runs first: unknown per-call keywords (according to :attr:unknown_call_kwargs), the max_cycle rejection, Davidson overrides, probe/init_vectors normalization, basis deduplication/popcount checks, pair-shape and structural-basis gates, n_roots vs basis dimension, the distributed matvec/backend gates and the mode-specific feature gates. No Davidson iteration, process group, operator or device allocation is started.

Parameters:

Name Type Description Default
ci_strings Any

The same per-subspace input the solve would receive.

required
nelec Any

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

required
norb 'Optional[int]'

Number of spatial orbitals (spin-orbitals on the spinless path). When omitted it is inferred from the highest set bit; pass it explicitly for wide/limb strings.

None
one_body_tensor Any

Optional integrals, used only to validate a warm start's cached integral fingerprint.

None
two_body_tensor Any

Optional two-electron integrals for the same fingerprint check.

None
**call_kwargs Any

The per-call keywords the solve would receive, including spin_sq, tol, init_vectors, ...

{}

Returns:

Type Description
dict[str, Any]

A JSON-friendly plan: the effective mode/basis, particle sector,

dict[str, Any]

per-subspace dimensions and layouts, resolved matvec_impl, tile

dict[str, Any]

grid and its source, warm/cold start, and the RDM path. The

dict[str, Any]

rdm_path key reports whether a full RDM was requested; the

dict[str, Any]

rdm_accumulation key (also per subspace) reports whether it is

dict[str, Any]

accumulated "partitioned" or "replicated". The

dict[str, Any]

subspaces entries also report each subspace's replicated vs

dict[str, Any]

owner-computes path. Without an explicit memory_budget_bytes /

dict[str, Any]

distributed budget_bytes cap, an "auto" tile decision uses

dict[str, Any]

the current free-memory estimate rather than the post-setup budget

dict[str, Any]

the real call sees; pass a cap for a deterministic plan.

Raises:

Type Description
ValueError

Invalid settings or incompatible basis inputs.

TypeError

Input types do not match the selected solver configuration.

NotImplementedError

The requested mode or feature is unsupported.

close

close() -> None

Tear down the multi-GPU worker pool or distributed session, if any.

Idempotent and safe to call on a single-device solver (no-op). The distributed session is also closed by a weakref.finalize guard.

__call__

__call__(ci_strings, one_body_tensor, two_body_tensor, norb, nelec, spin_sq: Optional[float] = None, **kwargs)

Diagonalize each input subspace and return its lowest eigenpairs.

Parameters:

Name Type Description Default
ci_strings list

Per-subspace inputs: (strings_a, strings_b) arrays for TPB/GDB, or flat string arrays for spinless systems. Structural GDB bases are also accepted where supported.

required
one_body_tensor ndarray

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

required
two_body_tensor ndarray

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

required
norb int

Spatial orbital count, or spin-orbital count for spinless inputs.

required
nelec tuple[int, int] | int

Alpha/beta particle counts, or a scalar particle count for spinless inputs.

required
spin_sq Optional[float]

target S² value. None (default) → no penalty. A float → enable the S² penalty biasing Davidson toward the ⟨S²⟩ = spin_sq sector. The reported energy is the physical ⟨ψ|H|ψ⟩, with the penalty contribution stripped before return. See the factory docstring for details.

None
**kwargs Any

Per-call overrides. Recognized: - max_davidson_iters → Davidson outer restart count (overrides this solver's self.max_davidson_iters for this call) - tol → Davidson ‖R‖ convergence threshold (overrides this solver's self.davidson_tolerance for this call) - de_tol → opt-in Davidson eigenvalue-stability check (overrides this solver's self.davidson_de_tolerance for this call); None disables it, a value's effective threshold is its sqrt (recommended: tol's value) - spin_penalty_lambda → penalty strength λ (default 1.0) - init_vectors → per-subspace Davidson start vector: a list with one entry per ci_strings subspace, each None (cold start) or a 1-D array laid out like the sci_state.amplitudes this mode returns, indexed by the strings passed in this call — product mode: flattened (len(strings_a), len(strings_b)), spin-block signs; GDB: one entry per (strings_a[i], strings_b[i]) pair, interleaved-Wick signs; spinless: one entry per string. Strings dropped from the previous basis are simply absent; strings the caller did not pass start at 0. The vector is reordered to the engine's internal order, projected and normalized; one with less than 1e-8 of its own norm left after projection falls back to the cold start (its overall scale does not matter). stats["per_call_log"] records warm per subspace. Mutually exclusive with probe_state. - probe_method='warm_start' / probe_state / probe_kwargs → cache and reuse the converged ground-state eigenvector on a superset basis. The cached state type depends on the path: TorchSCIState (TPB), TorchPairSCIState (GDB) or TorchSpinlessSCIState (a scalar nelec); the types are not interchangeable. A cold call with probe_method returns (results, states); a warm extension returns (results, states) only when probe_kwargs={'build_output_state': True}. The spinless path has no alpha/beta split and therefore no HF augmentation (include_hf_in_core is ignored with a warning); its spin_sq/compute_spin_squared refusals are physics limitations reported by preflight and capabilities(). Unknown names follow unknown_call_kwargs (ignore, warn or error). Unsupported PySCF iteration controls such as max_cycle raise.

{}

Returns:

Name Type Description
results list[EigenStates]

One container per input subspace, with root 0 the ground state and electronic energies excluding nuclear repulsion. Probe calls that request output states return (results, output_states) instead.

format_perf_summary

format_perf_summary() -> str

Return a multi-line string summarizing per-call performance.

Useful at the end of an SQD run to see whether per-iteration cost is growing (and which component is the culprit). Call as::

print(solver.self.format_perf_summary())

The columns to watch when diagnosing slowdown: - N_max — largest subspace this call saw. If this grows faster than overall time, scaling is sublinear (good). - setup, davidson, occ — per-component time. Track which one grows fastest across calls. - gap — time spent OUTSIDE our solver (in qiskit's outer loop). Growth here is not our problem. - mem_peak — peak GPU memory. Sudden jumps indicate allocation pattern changes; steady growth indicates a leak.

EigenStates [source] dataclass

EigenStates(states: List[SCIResultWithConvergence])

Container for all solved roots of one CI subspace.

Mirrors sci_solvers.eigen_states.EigenStates from the parent package without depending on it (the torch package is standalone). Each element of states is one :class:SCIResultWithConvergence, sorted ascending in energy. states[0] is the ground state; states[1:] are excited states. Single-root solves produce an EigenStates of length one.

This is the return type of :meth:TorchSCISolver.__call__ so that all roots are directly accessible from the call return value, matching the pattern used by sci_solvers.MultirootSCISolver.

SCIResultWithConvergence [source] dataclass

SCIResultWithConvergence(state: str | None = None)

Bases: SCIResult

SCIResultWithConvergence.