I have the following MWE using comm.Scatterv
and comm.Gatherv
to distribute a 4D array across a given number of cores (size
)
import numpy as np
from mpi4py import MPI
import matplotlib.pyplot as plt
comm = MPI.COMM_WORLD
size = comm.Get_size()
rank = comm.Get_rank()
if rank == 0:
test = np.random.rand(411,48,52,40) #Create array of random numbers
outputData = np.zeros(np.shape(test))
split = np.array_split(test,size,axis = 0) #Split input array by the number of available cores
split_sizes = []
for i in range(0,len(split),1):
split_sizes = np.append(split_sizes, len(split[i]))
displacements = np.insert(np.cumsum(split_sizes),0,0)[0:-1]
plt.imshow(test[0,0,:,:])
plt.show()
else:
#Create variables on other cores
split_sizes = None
displacements = None
split = None
test = None
outputData = None
#Broadcast variables to other cores
test = comm.bcast(test, root = 0)
split = comm.bcast(split, root=0)
split_sizes = comm.bcast(split_sizes, root = 0)
displacements = comm.bcast(displacements, root = 0)
output_chunk = np.zeros(np.shape(split[rank])) #Create array to receive subset of data on each core, where rank specifies the core
print("Rank %d with output_chunk shape %s" %(rank,output_chunk.shape))
comm.Scatterv([test,split_sizes, displacements,MPI.DOUBLE],output_chunk,root=0) #Scatter data from test across cores and receive in output_chunk
output = output_chunk
plt.imshow(output_chunk[0,0,:,:])
plt.show()
print("Output shape %s for rank %d" %(output.shape,rank))
comm.Barrier()
comm.Gatherv(output,[outputData,split_sizes,displacements,MPI.DOUBLE], root=0) #Gather output data together
if rank == 0:
print("Final data shape %s" %(outputData.shape,))
plt.imshow(outputData[0,0,:,:])
plt.show()
This creates a 4D array of random numbers and in principle should divide it across size
cores before recombining. I expected Scatterv
to divide along axis 0 (length 411) according to the starting integers and displacements in the vectors split_sizes
and displacements
. However, I get an error when recombining with Gatherv
(mpi4py.MPI.Exception: MPI_ERR_TRUNCATE: message truncated
) and the plot of output_chunk on each core shows that most of the input data has been lost, so it appears that the split has not occurred along the first axis.
My questions are: Why doesn't the split occur along the first axis, how do I know which axis the split occurs along, and is it possible to change/specify which axis this occurs along?