Repository navigation
Conversation
Retain borrowed BLACS contexts for derived distributed matrices, reject the unused raw-descriptor view path, and route serial frozen layouts through the local linear algebra backend. Add lifetime and serial-layout coverage.
Name borrowed BLACS-context factories separately from communicator-owned factories because Intel MPI defines MPI_Comm as int. Update Matrix2d and tests to use the explicit borrowed-distribution API.
ABACUS-PR-BOT
left a comment
There was a problem hiding this comment.
The factory rename resolves the integer-communicator overload collision in source. Please address the three implementation issues below.
Static source review of 25fec99: git diff --check passed. No builds or tests were run, and CI was not verified.
Address the blocking findings: preserve serial view layout, support tall/skinny matrix storage, and remove INT_MIN negation UB. Also address non-blocking findings: clarify API contracts, use named locals in conditional call arguments, make matmul tests fail on internal errors instead of passing falsely, and document view overlap constraints.
ABACUS-PR-BOT
left a comment
There was a problem hiding this comment.
The three implementation issues from my previous review are addressed in 5db95a7. One earlier cleanup remains, noted in its original thread; the additional nonblocking comment concerns an existing gather error path.
Static source review only; the full-PR and incremental git diff --check checks passed. No builds or tests were run, and CI was not verified.
| const MPI_Comm comm) | ||
| { | ||
| const std::vector<unsigned char> local_payload = make_local_payload(matrix); | ||
| const int local_count = checked_mpi_count(local_payload.size()); |
There was a problem hiding this comment.
Non-blocking: Please agree across ranks on oversized payloads before throwing here, including the equivalent path in gather_on_root(). With enough memory for packing, a 32769 x 8192 double matrix on a 2 x 1 grid with block size 32768 exceeds INT_MAX on only one rank. That rank throws instead of joining the count-exchange collective, so the peer may remain blocked if the caller catches the exception instead of aborting the job.
kirk0830
left a comment
There was a problem hiding this comment.
This PR is made by the agentic programmer since the workload is quite high for this refactor task. I also review the PR.
Presently, I have only reviewed parts of the whole PR, comments are left inline, waiting for the agent to fix and reply.
| const std::shared_ptr<const Parallel_Blkcyclic> distrib | ||
| = matrix.distribution(); | ||
| std::vector<int> metadata; | ||
| metadata.reserve(LOCAL_METADATA_SIZE + matrix.nrloc() |
There was a problem hiding this comment.
these syntax looks misleading. Create the memory space for std::vector at first, then do the element assignment would be more straightforward and still insist the concept of avoiding memory fragments and performance issue by the push-back
There was a problem hiding this comment.
Changed this helper to allocate the exact-sized metadata vector first and fill it by index in fbaf69833. The single-allocation behavior is preserved without mixing reserve and push_back, and touched vectors with known final sizes follow the same pattern.
| } | ||
|
|
||
| template <typename T> | ||
| std::vector<unsigned char> make_local_matrix_buffer(const Matrix2d<T>& matrix) |
There was a problem hiding this comment.
we are already in the context of matrix, no need to mention the matrix explicitly again. make_local_buffer, even make_locbuf would be clear enough
There was a problem hiding this comment.
Renamed this to make_local_buffer and updated all call sites in fbaf69833. The enclosing matrix context already makes the buffer kind clear.
| { | ||
| const std::vector<int> metadata = make_local_metadata(matrix); | ||
| const std::size_t nmeta = metadata.size(); | ||
| const std::size_t nmeta_bytes = nmeta * sizeof(int); |
There was a problem hiding this comment.
Renamed nmeta_bytes to nbytes_meta in fbaf69833, so the n prefix denotes a count and the unit follows it consistently.
| const std::vector<int> metadata = make_local_metadata(matrix); | ||
| const std::size_t nmeta = metadata.size(); | ||
| const std::size_t nmeta_bytes = nmeta * sizeof(int); | ||
| const std::size_t data_elements = static_cast<std::size_t>(matrix.nrloc()) |
There was a problem hiding this comment.
the size of data, not the element. element is a too high level concept here
There was a problem hiding this comment.
Renamed data_elements to ndata and documented it as the number of stored T values, explicitly distinct from a byte count (fbaf69833).
| const std::size_t nmeta_bytes = nmeta * sizeof(int); | ||
| const std::size_t data_elements = static_cast<std::size_t>(matrix.nrloc()) | ||
| * static_cast<std::size_t>(matrix.ncloc()); | ||
| const std::size_t data_bytes = data_elements * sizeof(T); |
There was a problem hiding this comment.
then the nbyte of data from the size
There was a problem hiding this comment.
The data byte count is now nbytes_data = ndata * sizeof(T) in fbaf69833, making the unit transition explicit at the definition.
| const Matrix2d<T>& matrix, | ||
| const MPI_Comm comm) | ||
| { | ||
| const std::vector<unsigned char> local_buffer |
There was a problem hiding this comment.
Renamed the serialized local payload to locbuf, with recvbuf/rxbuf for receive storage, in fbaf69833. This keeps short local names while functions and types retain descriptive names.
| int mpi_count(const std::size_t nbytes) | ||
| { | ||
| return static_cast<int>(nbytes); | ||
| } |
There was a problem hiding this comment.
the function has its name mismatching its behavior. Only a casting from size_t to int, why it is named the mpi_count?
There was a problem hiding this comment.
Merged validation and conversion into checked_mpi_count(std::size_t), which checks the native int limit and then narrows, in 0ac210ae3. Collective and reduction code now share this helper.
| std::vector<int> make_byte_displs(const std::vector<int>& nbytes) | ||
| { | ||
| std::vector<int> displs(nbytes.size(), 0); | ||
| int offset = 0; | ||
| for (std::size_t ip = 0; ip < nbytes.size(); ++ip) | ||
| { | ||
| displs[ip] = offset; | ||
| if (nbytes[ip] > std::numeric_limits<int>::max() - offset) | ||
| { | ||
| throw std::invalid_argument( | ||
| "Matrix2d collective matrix buffer size overflow"); | ||
| } | ||
| offset += nbytes[ip]; | ||
| } | ||
| return displs; | ||
| } |
There was a problem hiding this comment.
can a scan with the std::accumulate solve the same problem? this will make the codes lighter. but, the function name is not satisfying. make_byte_displs but what actually does is a kind of accumulation. Consider a better name, such as make_byte_offsets instead of the displacement
There was a problem hiding this comment.
Renamed this to make_byte_offsets and kept the explicit scan in 0ac210ae3. std::accumulate returns only a total, while std::partial_sum would still require a widened accumulator and a checked conversion before every MPI count.
| std::vector<int> allgather_nbytes(const int nbytes_local, const MPI_Comm comm) | ||
| { | ||
| const int nproc = Parallel_Common::comm_size(comm); | ||
| const int nbytes_int = static_cast<int>(sizeof(int)); | ||
| std::vector<int> recvcounts(static_cast<std::size_t>(nproc), nbytes_int); | ||
| const std::vector<int> rdispls | ||
| = make_byte_displs(recvcounts); | ||
| std::vector<int> nbytes(static_cast<std::size_t>(nproc), 0); | ||
|
|
||
| Parallel_Common::allgatherv_bytes(&nbytes_local, | ||
| nbytes_int, | ||
| nbytes.data(), | ||
| recvcounts.data(), | ||
| rdispls.data(), | ||
| comm); | ||
| return nbytes; | ||
| } |
There was a problem hiding this comment.
very confusing: is this function really needed? don't any the parallelization mechanism have this support? tuning and moving with respect to the byte is quite dangerous and confusing
There was a problem hiding this comment.
Kept the two-phase exchange because Allgatherv requires receive counts and displacements before payload transfer. The first phase now reuses the existing Parallel::allgather_int through ParaWorld, and the payload phase uses allgatherv_bytes; no MPI routine is called directly (0ac210ae3).
kirk0830
left a comment
There was a problem hiding this comment.
I have made my second review, this is also the first thorough review on the whole PR. The naming of variables/functions/namespaces are not quite satisfying, which would be risks for future devel. I will fix them soon.
| = make_byte_displs(metacounts); | ||
| const int metadata_total_bytes | ||
| = metadispls.back() + metacounts.back(); | ||
| const int nbytes_int = static_cast<int>(sizeof(int)); |
There was a problem hiding this comment.
seems this amount is always used in this file. Considering a const int W_INT = static_cast(sizeof(int)); at the head of this cpp file, which might be better.
There was a problem hiding this comment.
Promoted the repeated width to a file-level constexpr int W_INT = sizeof(int) in both the collective and reduction implementations (fbaf69833).
| } | ||
|
|
||
| template <typename U> | ||
| void assert_compatible_layout(const NDArray<U, 2>& other) const |
There was a problem hiding this comment.
why its implementation is not placed in the cpp file?
There was a problem hiding this comment.
Moved the non-template assert_compatible_layout implementation into matrix2d.cpp in 0ac210ae3. The storage initializer remains in the class definition because the templated constructors instantiate it for all supported scalar types.
| @@ -0,0 +1,129 @@ | |||
| #ifndef ABACUS_SOURCE_SOURCE_BASE_MATRIX2D_VIEW_H | |||
There was a problem hiding this comment.
no leading documentations explaing about the design, purpose, usage of the implementation in this file, bad
There was a problem hiding this comment.
Added file-level Doxygen to matrix2d_view.h in fbaf69833, covering non-owning storage, row-major host versus column-major distributed addressing, distribution lifetime, and assert() bounds behavior.
| std::shared_ptr<const Parallel_Blkcyclic> distrib_; | ||
| }; | ||
|
|
||
| #endif |
There was a problem hiding this comment.
if this is the interface exposing to the external caller/user, make a complete documentation both inline and before any public functions
There was a problem hiding this comment.
Documented the public view constructors and accessors in fbaf69833, including ownership, layout, leading dimension, distribution lifetime, and non-throwing bounds contract.
| } | ||
|
|
||
| private: | ||
| T* data_; |
There was a problem hiding this comment.
cannot the std::weak_ptr of std::vector satisfy your need?
There was a problem hiding this comment.
I kept T* plus a shared distribution handle because views must also wrap external buffers and future subviews; weak_ptr<vector<T>> would restrict storage origins and still would not guarantee that individual elements remain alive. The lifetime contract is now explicit in the header (fbaf69833).
| } | ||
| } // namespace | ||
|
|
||
| void inv(Matrix2dView<double> matrix) |
There was a problem hiding this comment.
does this function twist the matrix inversion to the linear problem solving? I mean, converting the inversion to the AX=I equation solving? This is the twist of semantics, I think that is why the numpy, scipy and pytorch they still provide such an API. User should know to always use the inversion of matrix with much are on it own rather than delegating such a numerical programming sense by us
There was a problem hiding this comment.
I verified that this path uses P?GETRF + P?GETRI, so it retains explicit inversion rather than rewriting the API as AX = I. Added the same public @warning that prefers solve() unless the inverse itself is required (3bf1d7f7f).
| return static_cast<int>(value); | ||
| } | ||
|
|
||
| int queried_workspace_size(const std::complex<double>& value) |
There was a problem hiding this comment.
use ws to make consistent with the naming of blas/lapack
There was a problem hiding this comment.
Renamed the ScaLAPACK workspaces to ws, iws, lws, and liws in fbaf69833, matching BLAS/LAPACK terminology while keeping the descriptive query helper name.
ABACUS-PR-BOT
left a comment
There was a problem hiding this comment.
The current update needs __MPI retained on both Matrix2d test targets and wider or scaled intermediates for float norms. The additional API comment narrows the axpby overlap contract.
Static source review of fbbcadb540ee3baccbaf4f7a3a4040b6aa0e7af4, including the contributor delta, merge resolution, affected callers and build/test registration; no build, runtime test or numerical probe was run.
| AddTest( | ||
| TARGET MODULE_BASE_matrix2d | ||
| LIBS parameter base device container | ||
| SOURCES test_matrix2d.cpp |
There was a problem hiding this comment.
With ENABLE_MPI=ON, this directory disables __MPI, and neither Matrix2d target opts back in. That compiles out their distributed cases and MPI_Init, while linking base built with a different Parallel_Blkcyclic layout; the 2/4-rank CTest entries therefore do not validate the MPI implementation. Please add KEEP_FEATURE_DEFINITIONS __MPI to both AddTest calls and rerun the focused MPI tests.
There was a problem hiding this comment.
Both Matrix2d targets now retain __MPI, and the configure-time guard checks their retained feature property. This addresses the source mismatch described here. I checked the CMake trace statically; no configure, build or MPI tests were run.
There was a problem hiding this comment.
Thanks. This was fixed in 5085c5811 by adding KEEP_FEATURE_DEFINITIONS __MPI to both Matrix2d test targets, together with a configure-time assertion. On a clean ENABLE_MPI=ON build, all 6 focused CTest entries passed; the 2-rank and 4-rank runs each exercised the distributed cases with Matrix2d 30/30 and linalg 11/11 passing.
| real_type<T> abs2(const T& value) | ||
| { | ||
| const real_type<T> real_value = static_cast<real_type<T>>(value); | ||
| return real_value * real_value; |
There was a problem hiding this comment.
For float and complex<float>, real_type<T> also makes the intermediate squares single precision. A 1x1 matrix containing 1e20f now overflows before sqrt, and 1e-30f underflows to zero, although both Frobenius norms are representable; the previous double intermediates handled these cases. Please keep wider intermediates or use scaled sum-of-squares, then cast the final result to real_type<T> and add large/small float regressions.
There was a problem hiding this comment.
Thanks, this was a real precision bug. Fixed in 5ebd75f65: the Frobenius-norm square accumulation, max-abs magnitude calculation, OpenMP reductions, and MPI reductions now use double intermediates for float, double, complex, and integer inputs. The public result is cast back to real_type<T> only after the reduction completes. I added regressions in ReductionsUseTheMatrixRealType for 1e20f and 1e-30f, including the corresponding complex<float> values. Clean serial and MPI 2/4-rank Matrix2d tests pass.
There was a problem hiding this comment.
The reported float and complex range cases are addressed in 5ebd75f65. A remaining issue in this PR predates this fix: with binary64 intermediates, a 1x1 double matrix containing 1e200 still overflows on squaring and 1e-200 underflows to zero, although both norms are representable; complex<double> with zero imaginary part has the same issue. Please use scaled sum-of-squares and add the corresponding double/complex regressions.
| * | ||
| * All views must have the same global shape and compatible host or distributed | ||
| * layouts. The result may overlap either input because each element is read | ||
| * before it is written. |
There was a problem hiding this comment.
Non-blocking: Please restrict the overlap guarantee to views with identical element mapping. Shifted views such as left=buffer and result=buffer+1 pass the shape checks, but an early write overwrites a later input (and the OpenMP loop can race). Document other overlap as unsupported and add an exact in-place alias test.
There was a problem hiding this comment.
Updated in 5ebd75f65. The Doxygen contract now states that matmul supports no overlap, while axpby supports only views with the same logical element mapping, including an exact in-place alias; shifted and partial overlap are explicitly unsupported. I added exact in-place axpby(result=A, ..., left=A, ...) coverage to HostViewMatmulAndAxpby. It passes in the clean suites and separately with OMP_NUM_THREADS=4.
There was a problem hiding this comment.
The contract in 5ebd75f65 now permits only identical element mapping and explicitly excludes shifted/partial overlap. The new exact in-place axpby test computes its expected result from a saved pre-operation copy. This addresses the documented aliasing issue.
ABACUS-PR-BOT
left a comment
There was a problem hiding this comment.
The float-range, alias-contract and named-offset fixes are addressed in source. The remaining double-norm range issue is tracked in the original norm thread.
Non-blocking: Please add the exact configure/build/test commands, relevant options and observed outcomes to the Verification section. Your replies report serial, MPI 2-/4-rank and OMP_NUM_THREADS=4 results, but the commands needed to reproduce those runs are not recorded.
Static review of 5ebd75f65; no builds or tests were run, and CI was not verified.
| template <typename T> | ||
| void check_float_reduction_range(const T& value, const float expected) | ||
| { | ||
| Matrix2d<T> matrix(1, 1); |
There was a problem hiding this comment.
Non-blocking: Please exercise the float and complex range cases with an active distribution too. This helper always constructs a host matrix, so even the 2-/4-rank launches skip the collective path whose norm accumulator changes from float to double. A distributed 1x1 case would also cover ranks with no local entries.
ABACUS-PR-BOT
left a comment
There was a problem hiding this comment.
The new owning operations produce incompatible serial-frozen results in the case below. Two non-blocking comments cover the test and public type contract.
Non-blocking: the Verification section now records build/test commands and reported outcomes. Please also include the configure commands or relevant cache options for the serial, MPI and C++11 build directories so those runs can be reproduced.
Static incremental review of 664c8df94b051b71271941572f0edb08e218a14c; no builds or runtime tests were run, and CI was not verified.
| } | ||
| if (!source.is_active()) | ||
| { | ||
| return Matrix2d<T>(make_frozen_distribution(nrglb, ncglb)); |
There was a problem hiding this comment.
[P2] Please reuse the source distribution handle when the result shape is unchanged, including this serial-frozen branch. With a matrix constructed using make_frozen_distribution(2, 2), auto r = axpby(1.0, a, 0.0, a) gets a different handle, so r += a and r.dot(a) throw despite matching dimensions and indexing. Move the same-shape reuse check before this branch and cover composition of serial-frozen results with their inputs.
| const int nrblk) | ||
| { | ||
| const Matrix2d<T> expected = matrix2d_linalg::inv(host_matrix); | ||
| const Matrix2d<T> host_matrix_original = host_matrix; |
There was a problem hiding this comment.
Non-blocking: capture host_matrix_original before calling inv(host_matrix). The immediate equality check currently copies and compares the already-processed input, so it cannot detect mutation by that call. Other host tests have valid before-snapshots; this particular assertion should do the same.
| template <typename T> | ||
| Matrix2d<T> eye(const int n); | ||
|
|
||
| /** @brief Return the non-conjugate transpose of `matrix`. */ |
There was a problem hiding this comment.
Non-blocking: document or constrain the scalar types supported by transpose, dagger, and scale. Their declarations accept other Matrix2d types such as float, but the implementation exports only double and std::complex<double> instantiations, so other specializations fail at link time. Matching the explicit type notes on the other linalg functions would make this limit clear.
Matrix2d<T>is a small, self-contained value type for representing andoperating on a two-dimensional matrix in ABACUS. It is the rank-two
NDArray<T, 2>specialization: the object owns its local storage and carrieseither a host layout or a frozen block-cyclic distributed layout. Global and
local extents, ownership, leading dimension, process-grid coordinates, and the
BLACS/ScaLAPACK context therefore travel with the data instead of being passed
around as separate, easy-to-desynchronize pieces.
The same interface works for host matrices, serial frozen layouts, and active
MPI distributions. Matrix algorithms can take a
Matrix2d<T>(or anon-owning
Matrix2dView<T>) without reaching into an LCAO layout object orreconstructing pointer offsets themselves.
Quick start
Here is the MPI-build flow the API is designed to make routine: build complete
host inputs on every rank, create one distributed layout and scatter the host
values into it, run the linear algebra as collective value-returning
operations, then gather the result as an ordinary host matrix:
Value-returning calls such as
matmul(A, B),solve(A, B), andinv(A)return a complete
Matrix2d<T>by value. They do not mutate their inputs. Theresult inherits the relevant host or frozen distributed layout:
solveusesthe right-hand-side layout,
matmuluses the left-input process grid and BLACScontext, and
invpreserves the input layout. On active MPI distributions theseoperations remain collective, so every rank calls them in the same order.
The output-parameter forms
matmul(A, B, C),solve(A, B, X), andinv(A, AI)write the same complete result into an existing matrix. Callersthat deliberately need zero-copy mutation can use the separately named
low-level
_inplaceprimitives overMatrix2dView; for example,solve_inplace(A, B)documents that it overwritesAwith its LU factors andreplaces
Bwith the solution. Those primitives are escape hatches, not therecommended developer-facing entry points.
Every rank supplies the complete
a_hostandx_hostmatrices. Theblock-cyclic layout is created once when
ais constructed;xreusesa.distribution(), and value-returning results carry their own valid layoutcontext.
scatter()marks the host-to-distributed boundary andgather()marksthe distributed-to-host boundary. A root-only
gather_on_root()placeholder isnever fed back into a collective operation.
Problems this API is designed to remove
The existing LCAO two-dimensional matrix code commonly passes a raw buffer
together with a
Parallel_Orbitals, aParallel_2D-style layout, local row andcolumn counts, a leading dimension, and sometimes a BLACS context. Each caller
must remember which values belong together, which rank owns an entry, whether
the buffer is row-major or column-major, and whether padding is present. That
makes index arithmetic, copying, returning results, and preserving descriptor
context easy to get subtly wrong.
Matrix2dmoves those details behind one value:state are queryable from the same object;
to reconstruct offsets;
the required layout context;
Matrix2dView, while an owned value is explicit asMatrix2d.This PR does not yet migrate production LCAO call sites. It establishes the
value and interface that would let those call sites stop passing distribution
state implicitly or recomputing offsets. Until such migrations land, the
existing production paths are unchanged.
Compared with raw pointers
A raw
T*says nothing about who frees it, how many elements it contains,whether it is host row-major or distributed column-major, where column padding
starts, or which rank owns a global coordinate.
Matrix2downs its storage,carries its extents and layout, and provides checked local/global access plus
ownership queries. It is copyable and movable: copies have independent storage,
moves are
noexcept, and copies share only the immutable distribution handle.There is no hidden copy-on-write: copying a matrix copies its values.
The unsafe escape hatch remains available through
data()for BLACS, LAPACK,or existing kernels, but it is now an explicit boundary on an otherwise
self-describing object.
local_storage_size()is not assumed to equalnrloc() * ncloc()because the physical buffer may contain leading-dimensionpadding.
Compared with
Parallel_OrbitalsandParallel_2DThe legacy
Parallel_2Dobject describes a block-cyclic layout but does notown the matrix data. Callers still have to pair it with a buffer, local-size
values, offsets, and descriptor/context state. In this series that distribution
role is now represented by the frozen
Parallel_Blkcyclichandle used insideMatrix2d. The important interface change is that the matrix composes thathandle with its data: callers pass one matrix value, then query the layout from
it when needed.
Parallel_Orbitalsgoes further and is intentionally an LCAO coordinationobject. It mixes the Hamiltonian layout with wavefunction/MO layouts, band
sizes, atom traces, orbital index maps, and mutable bookkeeping. That is too
much state for a generic matrix routine and makes an omnibus object the
implicit context for otherwise independent math.
Matrix2dhas one job:represent matrix data and its layout. It can be constructed, copied, passed,
and tested without an LCAO basis, atom table, band distribution, or
GlobalV/PARAMdependency.This is a separation of responsibilities, not a claim that every
Parallel_Orbitalsresponsibility has disappeared. The PR does not introducea replacement omnibus object.
Scope and current coverage
This is a foundation-only feature PR. It adds:
Matrix2d<T>;Matrix2dView<T>for interop and explicitly named_inplaceprimitives whose mutation contract is documented;
reductions, diagonal extraction, gather/scatter, and layout queries;
solve,matmul,inv,axpby, andscale, pluseye,transpose, anddagger;doubleandstd::complex<double>;padding, collectives, input immutability, context preservation, and linear
algebra with real and complex matrices.
Not in this PR:
Matrix2d;Parallel_Orbitalsor block-cyclic layout object is removed or replaced;The public header documentation and this Quick start are the documentation update
for the new interface. No separate user manual page is added because this PR has
no production callers or user-facing workflow yet.
Verification
Local commands and fresh results for commit
664c8df94b051b71271941572f0edb08e218a14c:The local
pre-commitexecutable is not installed, so the underlying AgentGovernance checker was run directly. The GitHub checks remain the authoritative
current verification result for this revision.
Tests specifically verify value-returning and output-parameter forms, unchanged
inputs, output aliasing, real and complex scalars, host and serial layouts, and
2-/4-rank distributions with preserved process grids, block sizes, and BLACS
contexts. Return values are by value in C++11; no API returns
Matrix2d<T>&&.