qrunch.chemistry.qrackle.matrix_modules.cupy_matrix_module

CuPy (CUDA GPU) implementation of the MatrixModuleProtocol.

Classes

CuPyMatrix

CuPy GPU implementation of MatrixProtocol.

CuPyMatrixModule

CuPy (CUDA GPU) implementation of MatrixModuleProtocol.

CuPyVector

CuPy GPU implementation of VectorProtocol.

class CuPyMatrix

Bases: MatrixProtocol

CuPy GPU implementation of MatrixProtocol.

Requirements:
  • Qrunch install requirements: qrunch[cuda] (or qrunch[all]).

  • A working cuda (cupy) installation.

__init__(_host_data: NDArray[float64], _device_data: NDArray[float64 | float32] | None = None, _host_synced: bool = True) → None
Parameters:
  • _host_data (NDArray[float64])

  • _device_data (NDArray[float64 | float32] | None)

  • _host_synced (bool)

Return type:

None

property device_data: Any

Device array if currently resident on GPU, else None.

fill_from_raw_numpy_array(array: NDArray[float64]) → None

Fill the matrix with data from a raw numpy array.

Parameters:

array (NDArray[float64]) – Two-dimensional numpy array with the correct shape.

Return type:

None

property shape: tuple[int, int]

Shape of the matrix.

to_raw_numpy_array() → NDArray[float64]

Get the contents of the matrix as a dense raw numpy array.

Return type:

NDArray[float64]

class CuPyMatrixModule

Bases: MatrixModuleProtocol[CuPyMatrix, CuPyVector]

CuPy (CUDA GPU) implementation of MatrixModuleProtocol.

Device memory management

Arrays are allocated on the host and immediately transferred to the GPU device. The module tracks device memory usage against a configurable budget and evicts the least-recently-used (LRU) device-resident arrays when the budget would be exceeded. When an operation requires device data that has been evicted, the module transparently re-uploads the host copy.

Explicit free_matrix() / free_vector() calls release the device buffer immediately.

Lazy host synchronisation

Results of GPU operations (matrix_multiply, add, commutator, linear_combination; etc.) are kept device-only: a host buffer is allocated but left uninitialised. The expensive device-to-host (D2H) copy is deferred until one of the following occurs:

  • CuPyMatrix.to_raw_numpy_array() (or the vector equivalent) is called — the host buffer is filled on demand.

  • The matrix/vector is evicted from device — the host buffer is filled before the device buffer is released, so that the data can be re-uploaded later if needed.

This means chains of GPU operations (e.g. commutator feeding into linear_combination) never touch host memory at all, which can significantly reduce wall-clock time for large matrices.

Requirements:
  • Qrunch install requirements: qrunch[cuda] (or qrunch[all]).

  • A working cuda (cupy) installation.

__init__(*, device_memory_limit_bytes: int | None = None, device_precision: Literal['float32', 'float64'] = 'float64', track_allocation_stack: bool = True, stack_capture_depth: int = 12) → None

Initialise the module and its allocation tracker.

Parameters:
  • device_memory_limit_bytes (int | None) – Maximum number of bytes to use on device. If None, queries the device for total memory and uses 90% of it as the limit.

  • device_precision (Literal['float32', 'float64']) – Floating-point precision used for device arrays. "float64" (default) uses double precision; "float32" uses single precision, halving device memory usage at the cost of numerical accuracy. Host arrays are always kept in float64.

  • track_allocation_stack (bool) – When True (default) capture a Python call-stack snapshot at every allocation.

  • stack_capture_depth (int) – Maximum number of stack frames captured per allocation when track_allocation_stack is enabled.

Return type:

None

add(left: CuPyMatrix, right: CuPyMatrix) → CuPyMatrix

Calculate the element-wise sum \(L + R\).

Parameters:
Return type:

CuPyMatrix

allocation_report() → str

Human-readable, multi-line summary of all live allocations.

Includes host and device memory usage and per-object details.

Return type:

str

antisymmetrize(matrix: CuPyMatrix) → CuPyMatrix

Calculate the antisymmetric projection \(\tfrac{1}{2}(M - M^{T})\).

Parameters:

matrix (CuPyMatrix) – Square matrix to be antisymmetrized.

Return type:

CuPyMatrix

commutator(left: CuPyMatrix, right: CuPyMatrix) → CuPyMatrix

Calculate the commutator \([L, R] = L R - R L\).

Parameters:
Return type:

CuPyMatrix

copy_matrix(matrix: CuPyMatrix) → CuPyMatrix

Create an independent copy of matrix.

Parameters:

matrix (CuPyMatrix) – Matrix to copy.

Return type:

CuPyMatrix

property device_dtype: dtype[floating[Any]]

Numpy dtype used for device arrays.

property device_memory_limit_bytes: int

Device memory budget in bytes.

property device_memory_used_bytes: int

Number of bytes currently used on the GPU device.

diagonalize(matrix: CuPyMatrix) → EigenvalueSolution[CuPyMatrix, CuPyVector]

Solve \(A v = \lambda v\) for a symmetric matrix.

Parameters:

matrix (CuPyMatrix) – Symmetric square matrix.

Return type:

EigenvalueSolution[CuPyMatrix, CuPyVector]

free_matrix(matrix: CuPyMatrix) → None

Release device and tracking resources for matrix.

Parameters:

matrix (CuPyMatrix) – Matrix previously returned by this module.

Return type:

None

free_vector(vector: CuPyVector) → None

Release device and tracking resources for vector.

Parameters:

vector (CuPyVector) – Vector previously returned by this module.

Return type:

None

frobenius_inner_product(left: CuPyMatrix, right: CuPyMatrix) → float

Calculate the Frobenius inner product \(\sum_{i,j} L_{i,j} R_{i,j}\).

Parameters:
Return type:

float

frobenius_norm(matrix: CuPyMatrix) → float

Calculate the Frobenius norm \(\| M \|_{F} = \sqrt{\sum_{i,j} M_{i,j}^{2}}\).

Parameters:

matrix (CuPyMatrix) – Matrix whose Frobenius norm is requested.

Return type:

float

generalized_eigenvalue_solver(a_matrix: CuPyMatrix, b_matrix: CuPyMatrix) → EigenvalueSolution[CuPyMatrix, CuPyVector]

Solve \(A v = \lambda B v\) for symmetric \(A\) and SPD \(B\).

Falls back to host scipy for the generalized eigenproblem since CuPy does not natively support generalised symmetric eigenproblems.

Parameters:
  • a_matrix (CuPyMatrix) – Symmetric square matrix \(A\).

  • b_matrix (CuPyMatrix) – Symmetric positive-definite square matrix \(B\).

Return type:

EigenvalueSolution[CuPyMatrix, CuPyVector]

identity(dimension: int) → CuPyMatrix

Get the square identity matrix of the given dimension.

Parameters:

dimension (int) – Number of rows and columns.

Return type:

CuPyMatrix

init_matrix(shape: tuple[int, int], *, zeroes: bool) → CuPyMatrix

Allocate a new dense matrix on GPU.

Parameters:
  • shape (tuple[int, int]) – Desired (number_of_rows, number_of_columns).

  • zeroes (bool) – If True the matrix is initialized to zero.

Return type:

CuPyMatrix

init_vector(length: int, *, zeroes: bool) → CuPyVector

Allocate a new dense vector on GPU.

Parameters:
  • length (int) – Desired number of elements.

  • zeroes (bool) – If True the vector is initialized to zero.

Return type:

CuPyVector

inverse(matrix: CuPyMatrix) → CuPyMatrix

Calculate the inverse \(M^{-1}\).

Parameters:

matrix (CuPyMatrix) – Square non-singular matrix.

Return type:

CuPyMatrix

linear_combination(coefficients: list[float], matrices: list[CuPyMatrix]) → CuPyMatrix

Calculate the linear combination \(\sum_i c_i M_i\).

Parameters:
  • coefficients (list[float]) – Real coefficients.

  • matrices (list[CuPyMatrix]) – Matrices of identical shape; must be non-empty and of the same length as coefficients.

Return type:

CuPyMatrix

lowdin_orthogonalizer(overlap: CuPyMatrix, threshold: float = 1e-09) → CuPyMatrix

Construct the symmetric (Lowdin) orthogonalizer \(X = S^{-1/2}\).

Eigenvectors whose overlap eigenvalue is below threshold are dropped, projecting out near-linear-dependent directions.

Parameters:
  • overlap (CuPyMatrix) – Symmetric positive-definite overlap matrix \(S\).

  • threshold (float) – Eigenvalue cutoff for near-linear-dependence removal.

Return type:

CuPyMatrix

matrix_exponential(matrix: CuPyMatrix) → CuPyMatrix

Calculate the matrix exponential \(\exp(M)\) on device using CuPyX.

Parameters:

matrix (CuPyMatrix) – Square matrix.

Return type:

CuPyMatrix

matrix_multiply(left: CuPyMatrix, right: CuPyMatrix) → CuPyMatrix

Calculate the matrix product \(L R\).

Parameters:
  • left (CuPyMatrix) – Left factor of shape (m, k).

  • right (CuPyMatrix) – Right factor of shape (k, n).

Return type:

CuPyMatrix

metadata_hash(matrix: CuPyMatrix) → str

Calculate a stable metadata hash for a matrix.

Parameters:

matrix (CuPyMatrix) – Matrix whose contents should be hashed.

Return type:

str

new_matrix(array: NDArray[float64]) → CuPyMatrix

Allocate an independently owned matrix containing a copy of the input array.

Parameters:

array (NDArray[float64]) – Two-dimensional numpy array whose shape and contents are copied.

Return type:

CuPyMatrix

property number_of_live_allocations: int

Number of currently tracked (not yet freed) objects.

resized_copy(matrix: CuPyMatrix, *, shape: tuple[int, int]) → CuPyMatrix

Create a new matrix of the given shape holding the overlapping top-left block of matrix.

The result preserves the source device array’s dtype.

Parameters:
  • matrix (CuPyMatrix) – Source matrix.

  • shape (tuple[int, int]) – Shape of the result as (rows, columns).

Return type:

CuPyMatrix

scale(matrix: CuPyMatrix, scalar: float) → CuPyMatrix

Scale the matrix by a scalar \(cM\).

Parameters:
  • matrix (CuPyMatrix) – Matrix to scale.

  • scalar (float) – Real scaling factor.

Return type:

CuPyMatrix

shifted_floored_divide(numerator: CuPyMatrix, denominator: CuPyMatrix, *, shift: float, denominator_floor: float) → CuPyMatrix

Divide by shifted, sign-preserving floored denominators on device.

Parameters:
  • numerator (CuPyMatrix) – Numerator matrix.

  • denominator (CuPyMatrix) – Denominator matrix of identical shape.

  • shift (float) – Finite scalar subtracted from every denominator.

  • denominator_floor (float) – Finite positive minimum denominator magnitude.

Return type:

CuPyMatrix

slice_columns(matrix: CuPyMatrix, start_column: int, end_column: int) → CuPyMatrix

Create a new matrix containing columns start_column to end_column (exclusive).

Parameters:
  • matrix (CuPyMatrix) – Source matrix.

  • start_column (int) – First column index (inclusive).

  • end_column (int) – Last column index (exclusive).

Return type:

CuPyMatrix

solve_linear_system(lhs_matrix: CuPyMatrix, rhs_matrix: CuPyMatrix) → CuPyMatrix

Solve \(A X = B\) for \(X\).

Parameters:
  • lhs_matrix (CuPyMatrix) – Square non-singular matrix \(A\).

  • rhs_matrix (CuPyMatrix) – Right-hand-side matrix \(B\).

Return type:

CuPyMatrix

subtract(left: CuPyMatrix, right: CuPyMatrix) → CuPyMatrix

Calculate the element-wise difference \(L - R\).

Parameters:
Return type:

CuPyMatrix

symmetrize(matrix: CuPyMatrix) → CuPyMatrix

Calculate the symmetric projection \(\tfrac{1}{2}(M + M^{T})\).

Parameters:

matrix (CuPyMatrix) – Square matrix to be symmetrized.

Return type:

CuPyMatrix

property total_allocated_bytes: int

The total number of bytes used by currently tracked objects (host + device).

trace(matrix: CuPyMatrix) → float

Calculate the trace \(\mathrm{Tr}(M) = \sum_{i} M_{i,i}\).

Parameters:

matrix (CuPyMatrix) – Square matrix.

Return type:

float

trace_of_product(left: CuPyMatrix, right: CuPyMatrix) → float

Calculate the trace \(\mathrm{Tr}(L R) = \sum_{i,k} L_{i,k} R_{k,i}\).

Parameters:
  • left (CuPyMatrix) – Left factor of shape (m, n).

  • right (CuPyMatrix) – Right factor of shape (n, m).

Return type:

float

transpose(matrix: CuPyMatrix) → CuPyMatrix

Calculate the transpose \(M^{T}\).

Parameters:

matrix (CuPyMatrix) – Matrix to transpose.

Return type:

CuPyMatrix

vector_outer_difference(left: CuPyVector, right: CuPyVector) → CuPyMatrix

Create the matrix with elements \(L_i - R_j\) on device.

Parameters:
  • left (CuPyVector) – Vector determining the rows.

  • right (CuPyVector) – Vector determining the columns.

Return type:

CuPyMatrix

class CuPyVector

Bases: VectorProtocol

CuPy GPU implementation of VectorProtocol.

Requirements:
  • Qrunch install requirements: qrunch[cuda] (or qrunch[all]).

  • A working cuda (cupy) installation.

__init__(_host_data: NDArray[float64], _device_data: NDArray[float64 | float32] | None = None, _host_synced: bool = True) → None
Parameters:
  • _host_data (NDArray[float64])

  • _device_data (NDArray[float64 | float32] | None)

  • _host_synced (bool)

Return type:

None

property device_data: Any

Device array if currently resident on GPU, else None.

fill_from_raw_numpy_array(array: NDArray[float64]) → None

Fill the vector with data from a raw numpy array.

Parameters:

array (NDArray[float64]) – One-dimensional numpy array with length elements.

Return type:

None

property length: int

Number of elements of the vector.

to_raw_numpy_array() → NDArray[float64]

Get the contents of the vector as a raw numpy array.

Return type:

NDArray[float64]