MPI wrapper contracts¶
Pointer-returning gather¶
Quick access
- Routines:
Needed modules
time_profiling(timing_uninitialized())f_precisions: Defines the portable Futile kind policy, undefined sentinels, precision conversion helpers, and low-level address inquiry helpers. Host codes should use these names instead of compiler-specific kindfmpi_types: renaming of the public constantsdictionaries(f_err_throw()): High-level dictionary API used throughout Futile and BigDFT. A dictionary is a pointer-based tree that can represent scalars, ordered mappings, and lists. It maps directly to YAML data and is manipulated with constructors
Subroutines and functions
- interface f_gather/fmpi_gather()¶
- interface f_gather/fmpi_gather_ptr()¶
Collect rank-2 real(f_double) buffers into a rank-1 allocation on root. Rank order and Fortran element order are preserved. Every rank owns its returned allocation and must call f_free_ptr: only root contains gathered data; other ranks receive a one-element scratch allocation. This explicit ownership contract amends MR !431 commit 05edce8f.
subroutine example_gather_ptr(root) integer, intent(in) :: root real(f_double), allocatable :: local(:,:) real(f_double), pointer :: collected(:) integer :: rank, nranks, source, offset, count rank=mpirank() nranks=mpisize() local=f_malloc([2,rank+1],id='gather_local') local=real(rank,f_double) collected => fmpi_gather_ptr(local,root=root) if (.not. associated(collected)) stop 1 if (rank == root) then if (size(collected) /= nranks*(nranks+1)) stop 2 offset=0 do source=0,nranks-1 count=2*(source+1) if (any(collected(offset+1:offset+count) /= real(source,f_double))) stop 3 offset=offset+count end do else ! This scratch allocation has no gathered payload. if (size(collected) /= 1) stop 4 end if ! Every rank frees its own result exactly once, including non-root ranks. call f_free_ptr(collected) call f_free(local) end subroutine example_gather_ptr
The runnable example tests unequal contributions and every possible root.
It runs through make check with run_parallel when MPI is enabled.
Only the root’s result contains gathered data. Every rank frees its returned
allocation, including the scratch allocation on a non-root rank.
Reductions and element counts¶
Quick access
- Routines:
Needed modules
time_profiling(timing_uninitialized())f_precisions: Defines the portable Futile kind policy, undefined sentinels, precision conversion helpers, and low-level address inquiry helpers. Host codes should use these names instead of compiler-specific kindf_enumsfmpi_types: renaming of the public constantsdictionaries(f_err_throw()): High-level dictionary API used throughout Futile and BigDFT. A dictionary is a pointer-based tree that can represent scalars, ordered mappings, and lists. It maps directly to YAML data and is manipulated with constructorsdynamic_memory
Subroutines and functions
- interface f_allreduce/fmpi_allreduce()¶
Reduce datatype elements collectively. The raw scalar/count form needs backing storage for count contiguous elements in both buffers. Array forms infer element count in the wide size kind. Scalar counts use integer(fmpi_count); native MPI transfers still require a nonnegative count representable in integer(fmpi_integer). Range checks are local and introduce no MPI communication. A caught error does not notify peers; recovery must be arranged by the caller. A zero count returns a null request.
subroutine check_count_boundaries() use dictionaries, only: dictionary,dict_free,f_err_open_try,f_err_close_try,f_err_check integer(fmpi_count) :: count,limit integer(f_long) :: long_value,long_diff integer(fmpi_integer) :: native,request integer(f_integer) :: send,recv type(dictionary), pointer :: errors logical :: ok,rejected limit=int(huge(0_fmpi_integer),fmpi_count) call require(fmpi_count_fits(0_fmpi_count),'zero count representable') call require(fmpi_count_fits(limit),'largest legacy count representable') call require(.not. fmpi_count_fits(-1_fmpi_count),'negative count rejected') call require(fmpi_displacement_fits(-limit),'signed displacement representable') ok=fmpi_count_to_mpi(limit,native) call require(ok .and. native == huge(native),'checked boundary conversion') call f_err_open_try() ok=fmpi_count_to_mpi(-1_fmpi_count,native) rejected=f_err_check(err_id=ERR_MPI_WRAPPERS) call f_err_close_try(errors) call require(.not. ok .and. rejected .and. native == 0,'negative conversion has defined failure') call dict_free(errors) if (limit < huge(count)) then count=limit+1_fmpi_count call require(.not. fmpi_count_fits(count),'wide count exceeds legacy range') call require(.not. fmpi_displacement_fits(count),'wide displacement exceeds legacy range') ! All ranks reject locally before any payload or temporary allocation. send=rank+1; recv=-7; request=-123 call f_err_open_try() call fmpi_allreduce(send,count,FMPI_SUM,recvbuf=recv,request=request) rejected=f_err_check(err_id=ERR_MPI_WRAPPERS) call f_err_close_try(errors) call require(rejected,'local count overflow rejected before payload') call require(send == rank+1 .and. recv == -7,'rejected transfer preserves buffers') call require(request == FMPI_REQUEST_NULL,'rejected transfer initializes request') call dict_free(errors) long_value=rank+1 call f_err_open_try() long_diff=fmpi_maxdiff(int(count,f_long),long_value) rejected=f_err_check(err_id=ERR_MPI_WRAPPERS) call f_err_close_try(errors) call require(rejected .and. f_is_undefined(long_diff),'maxdiff rejects before count narrowing') call require(long_value == rank+1,'rejected maxdiff preserves payload') call dict_free(errors) end if send=rank+1; recv=-7 call fmpi_allreduce(send,1_fmpi_count,FMPI_SUM,recvbuf=recv,request=request) call fmpi_wait(request) call require(recv == nranks*(nranks+1)/2,'wide count transfer and completion') call fmpi_allreduce(send,0_fmpi_count,FMPI_SUM,recvbuf=recv,request=request) call require(request == FMPI_REQUEST_NULL,'wide zero count request') call fmpi_wait(request) call require(recv == nranks*(nranks+1)/2,'wide zero count preserves buffer') end subroutine check_count_boundaries
Logical(f_byte) maps to MPI_BYTE, supporting bitwise BOR/BAND rather than logical LOR/LAND. Its scalar receive buffer has the same byte kind. Keep send and receive storage alive until fmpi_wait completes a request.
The multi-value scalar form accepts constant operands when irecvbuf is present; retrieval waits and releases the owned receive storage. Without irecvbuf it writes the operands, which must then be definable variables. Unspecified INTENT is deliberate and must not be changed to INOUT.
subroutine check_byte_reductions() integer, parameter :: n=7 ! More than the old four-byte receive declaration. logical(f_byte), asynchronous :: send(0:n+1), recv(0:n+1), saved(0:n+1) logical(f_byte) :: matrix(n,1), cube(n,1,1), scalar_received integer(fmpi_integer) :: bytes, ierr, request external :: MPI_TYPE_SIZE send=.false.; recv=.false. call require(mpitype(send(1)) == MPI_BYTE,'scalar byte datatype') call require(mpitype(send) == MPI_BYTE,'array byte datatype') call require(mpitype(matrix) == MPI_BYTE,'rank-two byte datatype') call require(mpitype(cube) == MPI_BYTE,'rank-three byte datatype') call MPI_TYPE_SIZE(mpitype(send(1)),bytes,ierr) call require(ierr == 0,'MPI_TYPE_SIZE status') call require(bytes*8 == storage_size(send(1)),'MPI datatype matches logical-byte storage') call byte_pattern(send(1:n)); saved=send ! Raw scalar/count form: both backing arrays have n elements plus guards. call fmpi_allreduce(send(1),int(n,fmpi_count),FMPI_BOR,recvbuf=recv(1)) call require(all(recv(1:n)),'byte scalar/count out-of-place result') call require(.not. recv(0) .and. .not. recv(n+1),'byte receive canaries') call require(all(send .eqv. saved),'byte send buffer unchanged') call fmpi_allreduce(send(1:n),op=FMPI_BOR) call require(all(send(1:n)),'byte array in-place result') call require(.not. send(0) .and. .not. send(n+1),'byte in-place canaries') send=saved; recv=.false. call fmpi_allreduce(send(1:n),op=FMPI_BOR,recvbuf=recv(1:n)) call require(all(recv(1:n)),'byte array out-of-place result') call require(all(send .eqv. saved),'array send buffer unchanged') call require(.not. recv(0) .and. .not. recv(n+1),'array receive canaries') recv=.false. call fmpi_allreduce(send(1),int(n,fmpi_count),FMPI_BOR,recvbuf=recv(1),request=request) call fmpi_wait(request) call require(all(recv(1:n)),'nonblocking byte result after wait') call require(.not. recv(0) .and. .not. recv(n+1),'nonblocking receive canaries') call require(all(send .eqv. saved),'nonblocking send buffer unchanged') call fmpi_allreduce(send(1:n),op=FMPI_BOR,request=request) call fmpi_wait(request) call require(all(send(1:n)),'nonblocking in-place byte result') call require(.not. send(0) .and. .not. send(n+1),'nonblocking in-place canaries') matrix(:,1)=saved(1:n) call fmpi_allreduce(matrix,op=FMPI_BOR) call require(all(matrix),'rank-two byte result') cube(:,1,1)=saved(1:n) call fmpi_allreduce(cube,op=FMPI_BOR) call require(all(cube),'rank-three byte result') send(1:n)=.not. saved(1:n) call fmpi_allreduce(send(1:n),op=FMPI_BAND) call require(.not. any(send(1:n)),'byte bitwise AND result') scalar_received=.false. call fmpi_allreduce(.true._f_byte,1_fmpi_count,FMPI_BOR,recvbuf=scalar_received) call require(scalar_received,'constant byte scalar with separate receive') end subroutine check_byte_reductions
mpi_contracts_check is an active contract driver, independent of the
historical disabled mpi_check regression. Its named reductions and
counts groups share kind-aware assertions and rank-aware failure reporting;
a failed assertion aborts the communicator so peers cannot hang in a later
collective. With no argument it runs all groups through make check and
run_parallel. Groups can also be selected directly:
mpirun -np 3 ./mpi_contracts_check reductions
mpirun -np 3 ./mpi_contracts_check counts
The reduction group verifies MPI byte type width, scalar/count and array
forms, in-place and separate receive storage, unchanged send buffers, canaries,
rank-two/rank-three arrays, and nonblocking completion. Bitwise operations on
MPI_BYTE are supported by the
MPI predefined reduction rules.
It also compiles and runs constant scalar operands with irecvbuf; their
unspecified intent is required by this valid separate-receive usage.
The count group exercises zero, one and seven elements, bounds canaries, blocking and nonblocking transfers, and null requests for empty operations. It also rejects counts above the native limit locally before any payload access. A timeout-bounded initiation test makes a peer wait for a token sent only after another rank returns from posting a nonblocking reduction; an implicit validation collective would deadlock this sequence. Separate local conversion tests run in serial builds too; no boundary test allocates a huge buffer.
Count kinds and legacy MPI boundaries¶
Description
renaming of the public constants
Quick access
- Routines:
fmpi_count_fits(),fmpi_count_to_address(),fmpi_count_to_mpi(),fmpi_displacement_fits(),fmpi_displacements_to_mpi()
Needed modules
mpif_module(mpi_in_place=>fmpi_in_place(),mpi_success=>fmpi_success(),mpi_request_null=>fmpi_request_null(),mpi_info_null=>fmpi_info_null(),mpi_win_null=>fmpi_win_null(),mpi_comm_null=>fmpi_comm_null(),mpi_group_null=>fmpi_group_null(),mpi_mode_noprecede=>fmpi_mode_noprecede(),mpi_bottom=>fmpi_bottom(),mpi_mode_nosucceed=>fmpi_mode_nosucceed(),mpi_mode_nostore=>fmpi_mode_nostore(),mpi_mode_noput=>fmpi_mode_noput(),mpi_statuses_ignore=>fmpi_statuses_ignore(),mpi_status_ignore=>fmpi_status_ignore(),mpi_status_size=>fmpi_status_size(),mpi_any_source=>fmpi_any_source(),mpi_any_tag=>fmpi_any_tag(),mpi_comm_world=>fmpi_comm_world()): do not put implicit none to avoid implicit declaration of datatypes in some MPI implementationsf_precisions: Defines the portable Futile kind policy, undefined sentinels, precision conversion helpers, and low-level address inquiry helpers. Host codes should use these names instead of compiler-specific kindf_enumsdictionaries(f_err_throw()): High-level dictionary API used throughout Futile and BigDFT. A dictionary is a pointer-based tree that can represent scalars, ordered mappings, and lists. It maps directly to YAML data and is manipulated with constructors
Subroutines and functions
- interface fmpi_types/fmpi_count_to_mpi()¶
Checked element-count narrowing for legacy mpif.h calls. The result is false and outputs are zero on error; return before any payload operation. These are local checks: no MPI operation, synchronization or peer notification.
- function fmpi_types/fmpi_count_fits(count)¶
True for nonnegative counts representable by legacy MPI integers. No communication.
- Parameters:
count [integer, in]
- Return:
ok [real]
- function fmpi_types/fmpi_displacement_fits(displacement)¶
Test signed datatype-extent offsets against the portable native integer range.
- Parameters:
displacement [integer, in]
- Return:
ok [real]
- Called from:
- function fmpi_types/fmpi_displacements_to_mpi(displacements, native)¶
Checked vector conversion; false/zero outputs and ERR_MPI_WRAPPERS on failure. Validation is local. Catching an error does not notify other ranks. Convert signed offsets in datatype extents, not MPI_ADDRESS_KIND bytes.
- Parameters:
displacements (*) [integer, in]
native (*) [integer, out]
- Return:
ok [logical]
- Call to:
- function fmpi_types/fmpi_count_to_address(count, unit, bytes)¶
Checked element-count times byte-unit conversion for MPI_WIN_CREATE. Window byte sizes use MPI_ADDRESS_KIND, not the legacy count limit.
- Parameters:
count [integer, in]
unit [integer, in]
bytes [integer, out]
- Return:
ok [logical]
fmpi_count is the public count kind. Configure selects a usable
MPI_COUNT_KIND from mpif.h when available and otherwise uses Futile’s
f_long. Missing support prints a notice rather than failing configuration.
Serial builds also use f_long. Selection is compile-only and works when
cross-compiling. The selected parameter is generated into a small Fortran
include; the broadcast, reduction, send/receive and one-sided modules remain
ordinary .f90 sources. This kind is not the MPI_COUNT datatype handle
and does not enable native large-count transfers by itself.
Explicit element counts and variable-collective count/displacement vectors
use integer(fmpi_count) throughout the public wrapper interfaces. There
are no parallel default-integer count overloads. Callers normalize a value
at the boundary if its integer kind differs; arithmetic must already have
been evaluated in a sufficiently wide kind before conversion. The separate
application-size audit records the future f_size_t producer/type review.
Array forms infer sizes through f_size before checked narrowing; byte
capacities use f_sizeof where appropriate. Character broadcasts count
characters, while maxdiff wrappers validate extents before allocation.
Rejected numeric maxdiff results use the undefined sentinel.
The legacy backend makes checked native-integer copies of vector metadata.
Blocking calls release them after the payload operation. Nonblocking variable
all-to-all calls retain their native vectors until fmpi_wait or
fmpi_waitall completes the request. Complete those requests through these
Futile wrappers so the retained metadata is released. The wide caller metadata
can be a temporary expression or be released after posting; the send/receive
payload buffers must remain alive and obey the usual MPI completion rules.
Legacy transfer counts must be nonnegative and at most
huge(0_fmpi_integer): usually 2,147,483,647 elements. That is just under
2 GiB for byte payloads, or 16 GiB for eight-byte payloads. Counts measure
elements, not bytes. Variable-collective displacements measure datatype
extents and may be negative when the operation/buffer permits it; conversion
uses the portable symmetric native integer range. Generated displacements
and communication totals accumulate in fmpi_count before narrowing.
Positive arithmetic products must remain representable in that kind; local
allocation capacities independently obey f_size_t.
A conversion failure raises ERR_MPI_WRAPPERS, returns false and zeros its
output. It must be followed by a return before communicating. All checks are
local integer comparisons: they perform no MPI calls and add no implicit
fence, collective or synchronization, including before nonblocking payloads.
A locally caught error does not notify other ranks and is not a collective
recovery protocol. Applications must arrange consistent recovery before peers
enter a payload collective, or use a fatal MPI-aware error handler. The wrapper
does not make successful transfers synchronize to support invalid input.
Zero-count reductions initialize an optional request to FMPI_REQUEST_NULL
and leave buffers unchanged.
MPI handles, ranks, requests and status remain native integers. RMA target
displacements and window byte sizes remain fmpi_address; file offsets
remain fmpi_offset. fmpi_count_to_address checks count-times-element-size
before multiplying or narrowing a window size, without imposing the smaller
legacy transfer-count limit on the window itself. No MPI-4 large-count backend
or mpi_f08 dependency is introduced.
ASCII character diagnostics and gathers¶
When fmpi_bcast is called with a character buffer and maxdiff, it saves
an explicit ASCII-code snapshot before broadcasting. The returned integer is
the global maximum absolute ASCII-code difference from that snapshot, rather
than a count of mismatched characters. Calls without maxdiff communicate
the original characters without this conversion.
Character-to-integer fmpi_gather overloads explicitly convert one character
to one ASCII integer code before communicating. Both f_integer and
f_long receive buffers are supported. These conversions do not use mixed
f_memcpy dispatch. The existing private character mpimaxdiff_c1 blueprint
also uses explicit ASCII conversion; it remains outside the public generic.
maxdiff_bcast_check exercises scalar strings, character arrays, embedded
NUL/control characters, zero-length cases and gathers into both integer kinds,
in addition to its numeric cases. It has been run with one, two and three MPI
ranks. No non-ASCII processor was available; encoding portability is expressed
by the IACHAR/ACHAR contract and by fixed ASCII expectations in the tests.
Collective algorithm selection¶
fmpi_allgather and fmpi_alltoall accept AUTOMATIC_ENUM,
NOT_VARIABLE_ENUM, VARIABLE_ENUM and ONESIDED_ENUM. Unknown selector
IDs raise ERR_MPI_WRAPPERS and return before communication. Initializing
an MPI status to success is insufficient: an unsupported selector must not
silently skip the transfer.
For all-to-all, an explicitly fixed algorithm requires uniform count arguments;
an explicitly variable or one-sided algorithm requires all four count and
displacement vectors. A caught incompatibility or insufficient buffer capacity
returns before payload communication. The receive buffer remains untouched and
an optional request is FMPI_REQUEST_NULL. Providing win selects the
one-sided path as before; its ordinary buffer/metadata requirements still apply.
Validation is local and does not add an MPI collective. Catching an error on one rank does not release peers already inside a collective; callers must arrange consistent recovery or use a fatal MPI-aware error handler.
The active algorithms regression checks invalid selectors, both directions
of incompatible all-to-all metadata, insufficient buffer capacity, preserved
receive canaries and null requests, then verifies fixed and nonblocking variable
all-to-all transfers. It is included in the default make check run:
mpirun -np 3 ./mpi_contracts_check algorithms
subroutine check_algorithms()
use f_enums, only: f_enumerator
use dictionaries, only: dictionary,dict_free,f_err_open_try,f_err_close_try,f_err_check
use dynamic_memory, only: f_malloc,f_free,assignment(=)
integer(f_integer), allocatable :: send(:),recv(:)
integer(fmpi_count), allocatable :: counts(:),displs(:)
integer(fmpi_integer) :: request
type(f_enumerator) :: invalid
type(dictionary), pointer :: errors
integer :: mode,j
logical :: rejected
integer, parameter :: guard=-7865432
send=f_malloc(nranks,id='algorithm_send')
recv=f_malloc(nranks,id='algorithm_receive')
counts=f_malloc(nranks,id='algorithm_counts')
displs=f_malloc(nranks,id='algorithm_displacements')
counts=1_fmpi_count
do j=1,nranks
send(j)=100*rank+j
displs(j)=int(j-1,fmpi_count)
end do
invalid=f_enumerator('UNSUPPORTED',-999,null())
! Every rank makes the same invalid calls. A caught error must return
! before touching payloads; no collective error-consensus fence is added.
recv=guard
call f_err_open_try()
call fmpi_allgather(sendbuf=send(1:1),recvbuf=recv,algorithm=invalid)
rejected=f_err_check(err_id=ERR_MPI_WRAPPERS)
call f_err_close_try(errors)
call require(rejected,'unknown allgather algorithm rejected')
call require(all(recv==guard),'rejected allgather preserves destination')
call dict_free(errors)
do mode=1,4
recv=guard
request=-999
call f_err_open_try()
select case(mode)
case(1)
call fmpi_alltoall(send,recv,algorithm=invalid,request=request)
case(2)
call fmpi_alltoall(send,recv,algorithm=VARIABLE_ENUM,request=request)
case(3)
call fmpi_alltoall(send,recv,sendcounts=counts,sdispls=displs, &
recvcounts=counts,rdispls=displs,algorithm=NOT_VARIABLE_ENUM,request=request)
case(4)
call fmpi_alltoall(send,recv,count=2_fmpi_count,request=request)
end select
rejected=f_err_check(err_id=ERR_MPI_WRAPPERS)
call f_err_close_try(errors)
call require(rejected,'invalid alltoall algorithm or buffer rejected')
call require(all(recv==guard),'rejected alltoall preserves destination')
call require(request==FMPI_REQUEST_NULL,'rejected alltoall request is null')
call dict_free(errors)
end do
! Only rank zero validates this invalid request. Peers enter a barrier,
! so any implicit validation collective would deadlock the bounded test.
if (rank == 0) then
recv=guard
call f_err_open_try()
call fmpi_alltoall(send,recv,algorithm=VARIABLE_ENUM,request=request)
rejected=f_err_check(err_id=ERR_MPI_WRAPPERS)
call f_err_close_try(errors)
call require(rejected,'algorithm rejection is local')
call require(all(recv==guard),'local rejection preserves destination')
call require(request==FMPI_REQUEST_NULL,'local rejection request is null')
call dict_free(errors)
end if
call fmpi_barrier()
! Supported fixed and variable choices must still transfer exact data.
call fmpi_alltoall(send,recv,algorithm=NOT_VARIABLE_ENUM)
do j=1,nranks
call require(recv(j)==100*(j-1)+rank+1,'fixed alltoall algorithm payload')
end do
call fmpi_alltoall(send,recv,sendcounts=counts,sdispls=displs, &
recvcounts=counts,rdispls=displs,algorithm=VARIABLE_ENUM,request=request)
call fmpi_wait(request)
do j=1,nranks
call require(recv(j)==100*(j-1)+rank+1,'variable alltoall algorithm payload')
end do
call f_free(send)
call f_free(recv)
call f_free(counts)
call f_free(displs)
end subroutine check_algorithms
Allgather source contract¶
With recvbuf present, fmpi_allgather preserves sendbuf; a read-only
variable or expression is permitted. The receive storage must not overlap
the source. Without recvbuf, sendbuf is the
writable full receive buffer. Its local contribution must already occupy the
range described by the receive count and displacement. Source intent is
therefore deliberately unspecified in the scalar and array overloads.
Counts and displacements retain their MPI element/datatype-extent semantics;
this contract introduces no extra synchronization.