Skip to content
userchbaPublic

About

Library of General Distributed Linear Algorithms for MPI-based matrix operations and tensor contractions on CPUs and GPUs.

Resources

Stars

1 star

Watchers

0 watching

Forks

Latest commit

 

History

27 Commits

Folders and files

Repository files navigation

LibGDLA

LibGDLA is a C++17 distributed matrix library built on MPI, LibDDLA, and LibRI. Its matrix interface supports real and complex single and double precision. A LibDDLA handle selects CPU or GPU execution. Use a CUDA-enabled or HIP-enabled LibDDLA installation for the corresponding device backend.

Matrix interface

Include <gdla/gdla.hpp> for initialization, matrix multiplication, Cholesky, and no-pivot LU. Initialize MPI with at least MPI_THREAD_FUNNELED before creating a LibGDLA context. All ranks share the configured grid and agree on axis definitions, operations, and coefficients. Destroy matrices and their context before MPI_Finalize. Existing callers may continue to pass a configured LibDDLA handle to gdla::Grid. Each matrix selects storage at construction from the grid’s DDLA handle. A CPU handle allocates host storage. A GPU handle allocates device storage for the local dense buffer or each present sparse tile. A, B and C can also be constructed directly from the same configured handle.

// All ranks have initialized MPI and selected their rank-local device.
auto context = gdla::init(MPI_COMM_WORLD, gdla::Backend::GPU);
auto grid = context.grid();
auto rows = gdla::Axis::fixed(5, 4);
auto inner = gdla::Axis::fixed(7, 4);
auto cols = gdla::Axis::fixed(6, 4);
gdla::Matrix<double> a(grid, gdla::Format::Tiled, rows, inner);
gdla::Matrix<double> b(grid, gdla::Format::Tiled, inner, cols);
gdla::Matrix<double> c(grid, gdla::Format::Tiled, rows, cols);

// Each rank supplies the nonzero tiles that it owns.
if (a.owner(0, 0) == grid.rank()) {
    auto tile = gdla::make_tile<double>(4, 4);
    tile(0, 0) = 2.0;
    a.set_tile(0, 0, tile);
}
if (b.owner(0, 0) == grid.rank()) {
    auto tile = gdla::make_tile<double>(4, 4);
    tile(0, 0) = 3.0;
    b.set_tile(0, 0, tile);
}
gdla::gemm('N', 'N', 1.0, a, b, 0.0, c);    // C(0,0) = 6
gdla::gemm('N', 'N', 1.0, a, b, 0.5, c);    // C(0,0) = 9
Format Local storage Axis definition
Dense Distributed column-major buffer with a LibDDLA descriptor Fixed blocks
Tiled Present tiles have the full physical block size. Logical boundary padding is zero. Fixed blocks
AtomPair Present atom pairs own variable-size row-major tiles Ordered widths and optional physical atom IDs

Use Axis::atom({4,7,3}, {10,42,19}) to define atom widths and IDs in logical order. Fixed axes may also carry IDs. Omitted IDs default to zero-based block ordinals. The process coordinates for block ordinals (i,j) are (i % nprows, j % npcols). Ordinary tile access takes ordinals. set_tile_by_id accepts the corresponding IDs. local_tile returns an independent physical tile. set_tile imports a host LibRI tensor and clears boundary padding. On a GPU matrix, local_tile explicitly downloads one tile. For direct backend access use dense_data() with dense_size() and descriptor(), or allocate_tile(i,j) and tile_data(i,j) for a rank-owned sparse block. Raw sparse writes must maintain zero padding and the diagonal tile’s UPLO convention. Use the handle’s stream or order external writes before GEMM. local_dense() and local_tiles() expose host storage on CPU matrices. A host read after an asynchronous backend operation requires synchronization. Rebuild consumers and relink against the matching library because the matrix layout has changed.

For half storage, pass Structure::Hermitian or Structure::Triangular and Uplo::Upper or Uplo::Lower to a Tiled or AtomPair matrix. Both axes must have the same cuts. Supply only tiles on the selected side. A diagonal tile has its full physical size. Import reconstructs the Hermitian half, including a real scalar diagonal, or zeros the unused triangular half.

The N, T, and C operations apply before alignment is checked. Contracted logical boundaries must match. Two fixed-format operands must also have the same nominal contracted block size. Matching is by logical position in the supplied axis order. Dense × Dense produces Dense. Every other product preserves the outer axis IDs and produces Tiled when both outer axes are regular, allowing a short final logical block. Otherwise it produces AtomPair. These format rules apply to the allocating convenience function multiply. For gemm and pgemm, the caller chooses C’s format and supplies matching outer axes. Existing dense buffers and surviving sparse tile addresses stay valid across the call. New sparse fill-in is allocated on C’s backend. An input aliased with C is snapshotted on the same backend. GPU dense GEMM passes the three local backend pointers directly to LibDDLA. GPU tiled GEMM packs only rank-local panels. Each panel moves once to its process row or column and is broadcast there. A HostStagedMPI handle broadcasts with MPI through host buffers. MPI and CCL handles keep LibDDLA’s device-to-device distributed copy. LibGDLA allocates its panel buffers, pointer arrays, partial sums and C fill-in before C changes. An allocation failure there throws on every rank and leaves C unchanged. With MPI or CCL, LibDDLA’s copy also allocates transfer scratch while the product runs, so a failure there can leave C partially updated. Dense C blocks are updated in place by batched GEMM. A caller-supplied triangular or Hermitian C selects the triangle to update. With nonzero beta, existing output tiles survive. With zero alpha, the result is beta times C.

Triangular updates and factorizations

All operations below are collective. gemm and pgemm have the same interface. For an upper or lower triangular or Hermitian output, they compute the selected entries of alpha * op(A) * op(B) + beta * C. A triangular output reads as zero on the other side. A Hermitian output reads as the conjugate mirror of the selected side and has a real diagonal, even if the full product would be non-Hermitian. To update a triangle of a general square matrix and preserve its other entries, call gdla::gemmt(gdla::Uplo::Upper, op_a, op_b, alpha, a, b, beta, c) or gdla::pgemmt. Selection includes the scalar entries inside diagonal and boundary tiles.

Call Result
int info = gdla::potrf(uplo, A) Cholesky factorization of a positive-definite matrix. Lower gives A = L Lᴴ, upper gives A = Uᴴ U. A Hermitian input becomes a triangular factor. A general input retains the opposite triangle.
int info = gdla::potrs(uplo, factor, B) Solve A X = B from a successful Cholesky factorization. One or several right-hand sides are overwritten by their solutions.
int info = gdla::pgetrf_nopiv(A) Square or rectangular LU without pivoting. The output packs the strict lower part of unit-diagonal L below the diagonal and U on and above it.

Use Uplo::Lower or Uplo::Upper for Cholesky. An info of zero indicates success. A positive factorization info identifies the first failing one-based scalar pivot. A numerical failure leaves the input matrix intact. A result is written into the existing storage of A or B: the dense buffer and retained sparse tiles keep their addresses. For potrs, supply a factor that completed with info == 0. General storage does not record which triangle holds the factor, so pass potrs the uplo given to potrf, as in LAPACK. Hermitian and triangular storage check it. A missing or zero factor diagonal is reported before the solution is published.

Dense operations use the corresponding distributed LibDDLA routines. Aligned tiled and atom-pair factorizations keep tiles distributed, create fill-in as needed, and apply batched trailing updates. The current GPU factorization adapters use temporary rank-local host workspaces and copy the result back into the original device storage. Diagonal blocks must be square, and LibGDLA never reblocks: Dense storage needs equal row and column block sizes, and tiled or atom-pair storage needs row and column cuts that agree up to the last pivot, such as the same atom partition on both axes. potrs also needs B’s rows cut like the factor’s. Other layouts throw std::invalid_argument before any change. All operations return results in the original matrix or RHS format with its existing axis IDs. See the numerical tests for real and complex examples.

LibRPA contraction interfaces

Include <gdla/contractions.hpp>. The Gamma-point ports support real FP64 and unrestricted output sectors. CPU GW also supports image-resolved multi-k contractions. gdla::contractions::Native stores each rank's contributions under an atom, partner atom, and relative cell. Inputs use LibRI tensors. Redistribution combines additive contributions before threshold screening.

  • GW takes set_Cs, set_Ws, and set_Gs. Call cal_Sigmas and read the locally owned blocks in Sigmas.
  • Polarizability takes set_Cs, set_Gs_pos, and set_Gs_neg. Call cal_chi0s and read chi0s.
  • raw_exchange reuses the GW solver with bare Coulomb and density inputs. Its caller applies the exchange sign.

Select the atom-pair or scalar block-cyclic layout and CPU or GPU execution before collective setup. See the LibRPA-compatible example and reference test for both layouts, basis dimensions, suffixes, and MPI ownership.

For Gamma calculations, call use_gpu() before set_parallel. In the GPU atom-pair layout, CUDA and HIP share the MPI panel schedule and contraction kernels. Each rank keeps its accumulated response or self-energy and the intermediate fields on its device. A finished field is copied to host once when MPI needs its panels. Both layouts batch the direct and crossed polarizability contractions on the device. The scalar block-cyclic GW route also batches the local Coulomb weighting and keeps intermediate products of chained GEMMs on the device. Its SUMMA multiplication broadcasts through reusable pinned host panels. Each rank can refill a panel once its upload completes while the GPU executes the preceding GEMM.

For HIP builds, configure with -DGDLA_ENABLE_RCCL=ON to broadcast Gamma atom-pair self-energy panels directly between devices. This option requires RCCL headers and the RCCL library. With a distinct device per MPI rank, the panel owner gathers resident intermediate tiles on its device, and ranks exchange offsets for up to 64 inner atoms at once. The default build, single-rank calls, and configurations with ranks sharing a device use the MPI panel path.

Periodic CWCG on CPU and GPU

For real FP64, call GW::use_atom_pairs(ao, aux) and pass the actual positive three-component period to set_parallel. A non-Gamma period selects the image-resolved solver. For complex FP64, or to select the panel size, construct gdla::contractions::PeriodicGW<T> gw(ao, aux, panel_terms) directly and use the same public setters, suffixes and cal_Sigmas. Call gw.use_gpu() before set_parallel for a GPU-enabled LibDDLA build. CPU and host-staged GPU panels default to 32 and 256 terms across the communicator. Resident GPU panels default to 256 terms per rank and can grow to 1,024 when the estimated temporary and partial products fit in 64 MiB. The estimate uses the largest orbital and auxiliary basis sizes and the scalar type. An explicit panel size overrides these defaults. All ranks supply identical basis definitions, periods, thresholds, suffixes and call order. Inputs are real-space tensors already transformed by the caller. This path covers the four unrestricted GW attachments. Periodic scalar-tile GW is outside its scope.

A persistent numerical block has one owner for its oriented atom pair and centered relative translation. Setters sum additive rank contributions and periodic aliases before strict max-norm screening, then balance surviving blocks by bytes. Each output owner computes and keeps its entire block. The calculation forms one distributed pair intermediate at a time and transfers requested operand blocks directly from their owners for each batch. Sparse key directories are replicated. PeriodicGW::local_input_bytes() counts numerical payload in all live input fields on this rank. Callers that keep their input maps must budget that additional memory separately.

On GPU, the output owner batches equal shapes with gemmBatched and mixed shapes with gemmVbatched. Each term writes its own partial product. A reduction on the same device queue accumulates terms for each output block. MPI moves requested real-space blocks through host memory. A local failure on one rank, such as a device allocation, is agreed before the next exchange and thrown on every rank. In staged mode, at each stage the owner uploads its local input blocks, packs the right-hand C in the required order when needed, and downloads the completed local stage results. Scratch buffers are reused until solver destruction or a new parallel setup. The maximum number of simultaneous three-atom term products on any rank is bounded by the panel size.

Periodic GPU device residency

Calling gw.use_gpu() on every rank before set_parallel selects device residency by default for both CUDA and HIP. This keeps one DDLA context for the solver and counts the panel limit per rank. Set LIBGDLA_PERIODIC_DEVICE_RESIDENCY=0 on all ranks to select the staged mode. An explicit use_device_residency(true/false) overrides the environment, and true also selects the GPU. Unchanged C, W and G values needed on that rank stay on its device across calls. C is packed in three layouts for the four GW attachments. Setting or freeing a field invalidates that field's cache. A change in the screened key directories rebuilds the routing plan. Each output block still has one owner. The extra cached operand blocks and C layouts can increase per-rank device memory for dense connectivity. local_input_bytes() measures the owned host input payload only.

The owner keeps its current pair intermediate and accumulating Sigma on the device. Ranks exchange each required block once per peer for each new field or new intermediate. MPI uses host buffers, so an owner with outgoing intermediate blocks stages its local intermediate through host memory. The GEMM panel bounds numerical term scratch. The solver caches up to 65,536 local terms per stage and traverses larger stages from the sparse directories.

The existing cal_Sigmas() returns the completed host map and leaves a device copy. Direct GPU consumers of PeriodicGW<T> can skip that final download:

gw.cal_Sigmas_device(); // Or pass the usual array of field suffixes.
gw.for_each_device_sigma([&](int a, int b, auto cell, const auto& dims, const auto* device_ptr) {
    consume_device_tile(a, b, cell, dims, device_ptr);
});

The callback visits only the current rank's row-major tiles. The pointers are read-only and valid until the next calculation, parallel setup, or solver destruction. Complete work on any external queue before that point. Call gw.download_Sigmas() when the host map is needed.

The periodic MPI tests compare real and complex results with original LibRI and check rank ownership on an eight-by-eight-by-eight mesh. See the test and the periodic products.

Periodic polarizability

For an unrestricted periodic cell, construct gdla::contractions::PeriodicPolarizability<T> chi(ao, aux). Real and complex FP64 use the same interface. Select chi.use_gpu() before parallel setup for a GPU build of LibDDLA. Each rank supplies its additive real-space blocks through the ordinary setters.

chi.set_parallel(comm, positions, lattice, period);
chi.set_Cs(C, threshold_C);
for (auto tau : times) {
    chi.set_Gs_pos(Gplus(tau), threshold_G);
    chi.set_Gs_neg(Gminus(tau), threshold_G);
    chi.cal_chi0s();
    consume(chi.chi0s);
}

The solver folds relative cells and screens the combined input. For each sign order it contracts C with the translated Green function in panels of up to 256 target orbital columns (a single wider atom stays intact). It uses the resulting pair intermediates in the direct and crossed terms. The crossed term uses a plain transpose, including for complex inputs. Each output atom-pair and cell has one MPI owner. The direct term uses scratch for one output at a time. The GPU keeps the right-hand coefficient panels across time points and the intermediate between its two direct GEMMs on the device. Replacing or freeing C clears the cached panels.

This implementation targets small primitive cells with several translations. It replicates screened inputs on each rank and stores two host coefficient layouts. The output ownership distributes work and result memory. The replicated inputs and half contractions can limit large-cell or fine-mesh memory scaling. Irreducible output sectors require a different solver.

Build and test

Supply a LibDDLA installation exposing the handle-based distributed and batched GEMM APIs, LibRI and cereal headers, MPI, and BLAS. The reference tests additionally use LibComm and OpenMP. CMake builds a static LibGDLA library by default. Set -DBUILD_SHARED_LIBS=ON for a shared library. GEMM, Cholesky and no-pivot LU are compiled for float, double and their complex counterparts. The GPU implementations dispatch through the selected LibDDLA backend. Use the C++ compiler and MPI ABI of the selected LibDDLA build.

cmake -S . -B build -DCMAKE_PREFIX_PATH=/path/to/libddla \
  -DLIBRI_INCLUDE_DIR=/path/to/LibRI/include \
  -DCEREAL_INCLUDE_DIR=/path/to/cereal/include \
  -DLIBCOMM_INCLUDE_DIR=/path/to/LibComm/include
cmake --build build -j
ctest --test-dir build --output-on-failure
cmake --install build --prefix /path/to/libgdla

Use -DGDLA_TEST_GPU=ON with a GPU-enabled dependency and a GPU allocation. The matrix, triangular-update, and factorization suites use 1, 4, and 6 CPU ranks and 1 and 4 GPU ranks. A two-rank failure-injection test verifies that all ranks can catch a panel allocation or decoding failure, preserve the previous output, and retry the multiplication. GPU contraction tests require one visible device per node-local rank. Use -DBUILD_TESTING=OFF to build and install the library, headers and CMake package without building reference tests.

An installed consumer can use find_package(LibGDLA CONFIG REQUIRED) and link gdla::gdla. Make LibDDLA, LibRI, and cereal discoverable to the consumer. The license notice for the ported LibRI code is in licenses/LibRI-NOTICE.md.

About

Library of General Distributed Linear Algorithms for MPI-based matrix operations and tensor contractions on CPUs and GPUs.

Resources

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages