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
BitArrayinput — 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
|
davidson_tolerance
|
float
|
Davidson ‖R‖ convergence threshold.
An absolute residual, not scaled to the energy.
On |
1e-07
|
davidson_de_tolerance
|
Optional[float]
|
Opt-in eigenvalue-stability check.
|
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
|
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. |
None
|
seed_strategy
|
str
|
which determinant to place at index 0 of the
basis — i.e., which determinant Davidson seeds
its initial vector |
'smallest_int'
|
apply_ab_projection
|
bool
|
|
True
|
Returns:
| Name | Type | Description |
|---|---|---|
None
|
A callable matching sci_solver(ci_strings, one_body, two_body, norb, nelec, *, spin_sq=None, **kwargs) -> list[SCIResult] |
|
None
|
suitable as the |
|
None
|
|
|
None
|
Notes on the kwargs surface:
- The reported energy is the physical ⟨ψ|H|ψ⟩ of the converged
eigenstate — the penalty contribution |
|
matvec_impl |
None
|
Matvec and preparation backend. |
mode |
None
|
Basis-space mode, |
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 |
davidson_dtype |
None
|
storage dtype of Davidson's subspace ( |
davidson_fp32_shift |
None
|
only with an fp32 |
davidson_fp32_energy |
None
|
with an fp32 |
davidson_correction |
None
|
|
davidson_restart |
None
|
what single-root Davidson keeps across a restart.
|
davidson_missed_root_check |
None
|
|
distributed |
None
|
Opt-in distributed-memory solve of each subspace.
|
unknown_call_kwargs |
None
|
policy for per-call keywords this engine does
not recognize: |
memory_budget_bytes |
None
|
optional per-rank byte cap. It bounds the
auto-tile policy, the default GDB/spinless
enumeration workspace (when
|
table_dtype |
None
|
index-payload dtype of the TPB excitation tables,
|
compact_eri |
None
|
|
triton_block |
None
|
optional Triton launch block (a positive multiple of
16), or |
diagnostics |
None
|
optional dict of diagnostic switches:
|
deterministic |
None
|
|
ab_factorization |
None
|
|
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]
|
|
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 |
dict[str, Any]
|
|
dict[str, Any]
|
|
dict[str, Any]
|
the configured |
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
|
|
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 |
{}
|
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 |
dict[str, Any]
|
grid and its source, warm/cold start, and the RDM path. The |
dict[str, Any]
|
|
dict[str, Any]
|
|
dict[str, Any]
|
accumulated |
dict[str, Any]
|
|
dict[str, Any]
|
owner-computes path. Without an explicit |
dict[str, Any]
|
distributed |
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: |
required |
one_body_tensor
|
ndarray
|
One-electron integrals, shape |
required |
two_body_tensor
|
ndarray
|
Two-electron integrals, shape |
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
|
**kwargs
|
Any
|
Per-call overrides. Recognized:
- |
{}
|
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 |
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.