MPI Scatter, Gather, and Allgather

In the previous lesson, we went over the essentials of collective communication. We covered the most basic collective communication routine – MPI_Bcast. In this lesson, we are going to expand on collective communication routines by going over two very important routines – MPI_Scatter and MPI_Gather. We will also cover a variant of MPI_Gather, known as MPI_Allgather. The code for this tutorial is available here.

An Introduction to MPI_Scatter

MPI_Scatter is a collective routine that is very similar to MPI_Bcast (If you are unfamiliar with these terms, please read the previous lesson). MPI_Scatter involves a designated root process sending data to all processes in a communicator. The primary difference between MPI_Bcast and MPI_Scatter is small but important. MPI_Bcast sends the same piece of data to all processes while MPI_Scatter sends chunks of an array to different processes. Check out the illustration below for further clarification.

MPI_Bcast vs MPI_Scatter

In the illustration, MPI_Bcast takes a single data element at the root process (the red box) and copies it to all other processes. MPI_Scatter takes an array of elements and distributes the elements in the order of process rank. The first element (in red) goes to process zero, the second element (in green) goes to process one, and so on. Although the root process (process zero) contains the entire array of data, MPI_Scatter will copy the appropriate element into the receiving buffer of the process. Here is what the function prototype of MPI_Scatter looks like.

  • MPI_Scatter(void* send_data, int send_count, MPI_Datatype send_datatype, void* recv_data, int recv_count, MPI_Datatype recv_datatype, int root, MPI_Comm communicator)

Yes, the function looks big and scary, but let’s examine it in more detail. The first parameter, send_data, is an array of data that resides on the root process. The second and third parameters, send_count and send_datatype, dictate how many elements of a specific MPI Datatype will be sent to each process. If send_count is one and send_datatype is MPI_INT, then process zero gets the first integer of the array, process one gets the second integer, and so on. If send_count is two, then process zero gets the first and second integers, process one gets the third and fourth, and so on. In practice, send_count is often equal to the number of elements in the array divided by the number of processes. What’s that you say? The number of elements isn’t divisible by the number of processes? Don’t worry, we will cover that in a later lesson :)

The receiving parameters of the function prototype are nearly identical in respect to the sending parameters. The recv_data parameter is a buffer of data that can hold recv_count elements that have a datatype of recv_datatype. The last parameters, root and communicator, indicate the root process that is scattering the array of data and the communicator in which the processes reside.

An Introduction to MPI_Gather

MPI_Gather is the inverse of MPI_Scatter. Instead of spreading elements from one process to many processes, MPI_Gather takes elements from many processes and gathers them to one single process. This routine is highly useful to many parallel algorithms, such as parallel sorting and searching. Below is a simple illustration of this algorithm.

MPI_Gather

Similar to MPI_Scatter, MPI_Gather takes elements from each process and gathers them to the root process. The elements are ordered by the rank of the process from which they were received. The function prototype for MPI_Gather is identical to that of MPI_Scatter.

  • MPI_Gather(void* send_data, int send_count, MPI_Datatype send_datatype, void* recv_data, int recv_count, MPI_Datatype recv_datatype, int root, MPI_Comm communicator)

In MPI_Gather, only the root process needs to have a valid receive buffer. All other calling processes can pass NULL for recv_data. Also, don’t forget that the recv_count parameter is the count of elements received per process, not the total summation of counts from all processes. This can often confuse beginning MPI programmers.

Computing Average of Numbers with MPI_Scatter and MPI_Gather

In the code for this lesson, I have provided an example program that computes the average across all numbers in an array. The program is in avg.c. Although the program is quite simple, it demonstrates how one can use MPI to divide work across processes, perform computation on subsets of data, and then aggregate the smaller pieces into the final answer. The program takes the following steps:

  1. Generate a random array of numbers on the root process (process 0).
  2. Scatter the numbers to all processes, giving each process an equal amount of numbers.
  3. Each process computes the average of their subset of the numbers.
  4. Gather all averages to the root process. The root process then computes the average of these numbers to get the final average.

The main part of the code with the MPI calls looks like this:

if (world_rank == 0) {
  rand_nums = create_rand_nums(elements_per_proc * world_size);
}
 
// Create a buffer that will hold a subset of the random numbers
float *sub_rand_nums = malloc(sizeof(float) * elements_per_proc);
 
// Scatter the random numbers to all processes
MPI_Scatter(rand_nums, elements_per_proc, MPI_FLOAT, sub_rand_nums,
            elements_per_proc, MPI_FLOAT, 0, MPI_COMM_WORLD);
 
// Compute the average of your subset
float sub_avg = compute_avg(sub_rand_nums, elements_per_proc);
// Gather all partial averages down to the root process
float *sub_avgs = NULL;
if (world_rank == 0) {
  sub_avgs = malloc(sizeof(float) * world_size);
}
MPI_Gather(&sub_avg, 1, MPI_FLOAT, sub_avgs, 1, MPI_FLOAT, 0,
           MPI_COMM_WORLD);
 
// Compute the total average of all numbers.
if (world_rank == 0) {
  float avg = compute_avg(sub_avgs, world_size);
}

At the beginning of the code, the root process creates an array of random numbers. When MPI_Scatter is called, each process now contains elements_per_proc elements of the original data. Each process computes the average of their subset of data and then the root process gathers each individual average. The total average is computed on this much smaller array of numbers.

Using the run script included in the code for this lesson, the output of your program should be similar to the following. Note that the numbers are randomly generated, so your final result might be different from mine.

Running MPI Average Program

MPI_Allgather and Modification of Average Program

So far, we have covered two MPI routines that perform many-to-one or one-to-many communication patterns, which simply means that many processes send/receive to one process. Oftentimes it is useful to be able to send many elements to many processes (i.e. a many-to-many communication pattern). MPI_Allgather has this characteristic.

Given a set of elements distributed across all processes, MPI_Allgather will gather all of the elements to all the processes. In the most basic sense, MPI_Allgather is an MPI_Gather followed by an MPI_Bcast. The illustration below shows how data is distributed after a call to MPI_Allgather.

MPI_Gather

Just like MPI_Gather, the elements from each process are gathered in order of their rank, except this time the elements are gathered to all processes. Pretty easy, right? The function declaration for MPI_Allgather is almost identical to MPI_Gather with the difference that there is no root process in MPI_Allgather.

  • MPI_Allgather(void* send_data, int send_count, MPI_Datatype send_datatype, void* recv_data, int recv_count, MPI_Datatype recv_datatype, MPI_Comm communicator)

I have modified the average computation code to use MPI_Allgather. You can view the source in all_avg.c from the lesson code. The main difference in the code is shown below.

// Gather all partial averages down to all the processes
float *sub_avgs = (float *)malloc(sizeof(float) * world_size);
MPI_Allgather(&sub_avg, 1, MPI_FLOAT, sub_avgs, 1, MPI_FLOAT,
              MPI_COMM_WORLD);
 
// Compute the total average of all numbers.
float avg = compute_avg(sub_avgs, world_size);

The partial averages are now gathered to everyone using MPI_Allgather. The averages are now printed off from all of the processes. Example output of the program should look like the following:

Running MPI Average Program with MPI_Allgather

As you may have noticed, the only difference between all_avg.c and avg.c is that all_avg.c prints the average across all processes with MPI_Allgather.

Up Next

In the next lesson, I will cover some of the more complex collective communication algorithms. Stay tuned! Feel free to leave any comments or questions about the lesson.

For all beginner lessons, go the the beginner MPI tutorial.

HAS MPITUTORIAL.COM HELPED YOU?

Donate a small sum of 5 dollars today to help me out with my hosting costs. Thank you!


Related posts:

  1. Dynamic Receiving with MPI Probe (and MPI Status)
  2. MPI Broadcast and Collective Communication
  3. MPI Introduction
  4. MPI Send and Receive
  5. Point-to-Point Communication Application – Random Walk
Wes tagged this post with: , , Read 8 articles by

6 Comments

  1. Eduardo says:

    Very nice article and good news that this tutorials serie is not dead.

    Thanks a lot.

    • Wes says:

      Thanks for the feedback. I hope I can find some more time to provide some more content on this site. It’s a shame there isn’t more information out there on MPI

  2. yy says:

    Pretty good tutorial! I think a little change of the output in the random walk example would be better.

  3. Neil says:

    Hello! Your tutorials really benefit me a lot! Just want to say thanks!
    I am looking forward to learning the “later lesson” about the case that number of elements isn’t divisible by the number of processes… LOL

    Leave a Reply

    Your email address will not be published. Required fields are marked *

    *

    You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

    RECOMMENDED BOOKS

    My recommendations for great books on MPI.
    Click here for more info

    BEGINNER TUTORIAL

    A step-by-step tutorial on beginner MPI topics.
    Click here for more info

    buy cheap viagra
    buy viagra cheapest
    buy discount soma
    buy real viagra pharmacy online
    buy viagra online no prescription
    buy cialis now
    buy viagra onli
    cheap soft tab viagra
    cialis super active review
    india viagra cialis vicodin
    buy cheap levitra
    cialis no perscription
    female use of viagra
    viagra and cialis
    buy generic viagra pharmacy online
    cheap discount viagra
    viagra dosage
    viagra oral jelly
    buy duscount viagra online
    cheap no prescription viagra
    cheap viagra viagra
    buy viagra online in australia
    buy viagra cialis
    cipro 20
    lowest price viagra
    buy cialis no prescription
    cheap inexpensive viagra
    buy cialis from india
    buy viagra online without prescription
    buy viagra online at cheap price
    viagra without prescription
    buy online online pill viagra viagra
    levitra 100mg uk
    buy discount viagra
    buy internet viagra
    buying viagra online
    buy real viagra online
    viagra super active
    buy viagra and cilas
    levitra online
    buy viagra cheaply
    buy viagra pharmacy online
    buy now levitra
    cheap meltabs viagra
    ordering cialias
    free viagra in the uk
    buy viagra online paypal vipps
    buy cialis online
    buy low price viagra
    buy now viagra
    viagra rrp australia
    cialis no prescription
    cialis replacement
    buy viagra online alternative viagra
    cheap genric viagra online
    buy levitra now
    viagra oral
    buy viagra on the internet
    generic cialis
    viagra for sale
    buy viagra online in uk
    buy online online viagra viagra
    buy female viagra
    buy viagra using paypal
    key buy-viagra
    buy viagra online at
    buy generic viagra
    cheap generic viagra
    amazon viagra
    cost of viagra
    which is better cialis or viagra
    is viagra safe for women
    buy viagra over the counter us
    buy discounted viagra
    real viagra
    cheap viagra generic
    cheap generic viagra no prescription
    cheap pharmaceutical viagra
    natural viagra
    alternative to viagra
    cheap levitra online
    buying viagra in uk
    cheap discount cialis
    buy sale viagra
    viagra over the counter walgreens
    cheap free viagra viagra
    cheap viagra in the uk
    buy cheap tamiflu
    free viagra without prescription
    buy viagra online
    buy cialis canada
    viagra online uk
    female viagra
    cheap generic viagra online
    cheap prescription viagra without
    buy 100 mg viagra
    generic levitra
    cheap discount viagra viagra
    buy viagra online au
    cheap free price viagra
    buy get online prescription viagra
    buy viagra order viagra
    cheap generic 50 mg viagra
    buy no online prescription viagra
    buy generic viagra online pharmacy online
    cheap pill pill sale viagra
    buy nexium
    viagra and cialis cheap
    buy cheap viagra online
    cheap free viagra
    buy viagra online get prescription
    buy viagra online
    homemade viagra
    buy viagra online cheapest
    buy viagra pill
    buy viagra online u
    buy viagra overnight
    cialis overnight shipping
    buy line viagra where
    ordering viagra onl
    buy cheap viagra online uk
    buy lexapro
    buy online order viagra
    cheap viagra canada
    buy cymbalta
    walmart cialis price
    viagra generic
    cheap viagra fast shipping
    cheap mexico viagra
    buy prescription viagra
    buy viagra cialis levitra
    free viagra
    buy viagra online at lowest price
    free viagra sample
    cheap generic substitute viagra
    cheap viagra
    buy viagra online online pharmacy
    guaranteed cheapest viagra
    cheap herbal viagra
    cheap phizer viagra
    buying viagra
    viagra professional
    generic viagra from india
    buy viagra alternative
    cheap discount levitra online
    buy viagra online discount
    buy kamagra viagra india
    buy prescription viagra without
    viagra price in india
    marijuana and viagra
    buy in spain viagra
    shipping viagra to australia
    Viagra Oklahoma city
    where to buy viagra in beijing
    buy generic viagra img
    buy sildenafil viagra
    generic vs brand name viagra
    brand cialis 20
    cheap kamagra viagra
    cheap generic viagra no script
    buy viagra usa
    buy site viagra
    cheap cialis online
    cheapest uk supplier viagra
    cheap generic viagra uk
    cheap pharmacy viagra
    buy in online uk viagra
    online overnight viagra
    cheap deal viagra
    buy viagra pill online
    cheap prescription viagra
    uninsured cost of cialis
    cheap sale viagra
    buy viagra powered by phpbb
    cheap pill viagra
    viagra and cialis and
    cheap kamagra uk viagra
    buy viagra online pharmacy
    non prescription viagra
    buy viagra 50mg
    purchase viagra online
    cialis vs viagra
    buy viagra online canadapurchase cialis
    buy viagra online off pharmacy prices
    viagra uk
    buy locally viagra
    viagra pro online
    buy viagra prescription america
    buy viagra cheapest best prices online
    buy in online usa viagra
    buy generic viagra viagra
    buy internet viagra
    viagra sample
    cheap price viagra
    cheap india viagra
    cheap generic overnight viagra
    cheap viagra india
    buy real viagra
    cheap generic viagra from usa
    buy now online viagra
    buy viagra online australia
    cheap generic online viagra
    buy discount cialis
    where can I buy cialis 20mg
    buy online levitra cialis viagra
    buy viagra onlines
    buy generic viagra buy
    discount viagra
    buy later now pay viagra
    cheap viagra without a prescription
    accutane for sale online
    buy price viagra
    buy viagra online order generic viagra
    buy viagra online and get prescription
    buy viagra montreal
    over the counter viagra
    buy viagra now
    cheap viagra tablets
    ed. trusted medstore in cialis
    watermelon viagra
    buy viagra online in the uk
    buy viagra online web meds
    buy viagra
    buy viagra internet
    cheap generic viagra overnight delivery
    buy viagra online in
    Viagra for sale
    does watermelon have viagra effect
    ebay + cialis
    buy viagra prescription
    viagra coupons and discounts
    buy levitra viagra online
    purchase levitra online
    generic viagra
    cialis coupons
    buy viagra online india
    cialis voucher
    ed pro trial pack
    brand cialis
    buy prescription vaniqa viagra
    generic-viagra
    viagra uk cheap purchase buy
    viagra alternatives
    cheap site viagra
    buy viagra online uk
    buy viagra online ireland
    q buy viagra online
    canadian levitra vs usa levitra
    price of viagra
    buy viagra online a href
    cheap viagra online canada
    cheap herbal viagra viagra
    buy viagra per pill
    buy kamagra viagra
    cheap generic india viagra
    viagra free trial offer
    buy online drug viagra pharmacy
    buy generic viagra usa
    cheap molde ticket viagra
    buy real viagra online pharmacy
    buy cheap cialis
    cheap generic viagra substitutes
    cheap man viagra
    buy in uk viagra
    viagra and hearing loss
    buy viagra online
    how can i buy viagra online in canada
    buy generic viagra
    buy viagra online order
    buy levitra canada
    buy generic viagra online
    cheap viagra in uk
    buy line viagra
    uk viagra sales
    viagra pfizer
    cheap generic viagra substitute
    viagrafree samples
    buy viagra other drug onlinea