Home > Mobile >  MPI C, Allreduce struct based on a value
MPI C, Allreduce struct based on a value

Time:11-24

I'm trying to find the max absolute value of some local sub arrays. The problem comes when trying to share the original value to the other processesors because this value must conserve their original sign (positive or negative)

So I have this struct:

struct max_data
{
    int index;
    double real_value, absolute_value;
};

Function to find the max absolute:

struct max_data find_max_absolute(double vec[], int size)
{
    double max = absolute(vec[0]), current = 0;
    int position = 0;
    struct max_data a;
    for (int i = 1; i < size; i  )
    {
        current = absolute(vec[i]);
        if (current > max)
        {
            position = i;
            max = current;
        }
    }
    a.index = position;
    a.real_value = vec[position];
    a.absolute_value = max;
    return a;
}

And inside the main, I used this code:

// ...

struct max_data local_max_data = find_max_data(local_result, size);
local_max_value = local_max_data.absolute_value;

MPI_Allreduce(&local_max_value, &max_value, 1, MPI_DOUBLE, MPI_MAX, MPI_COMM_WORLD);

Can I approach it creating a custom operation or datatype?

CodePudding user response:

You need to define a custom reduction operator.

void abs_max(void *in,void *inout,int *len,MPI_Datatype *type) {
  // r is the already reduced value, n is the new value
  float n = *(float*)in, r = *(float*)inout;
  float m;

  if (fabs(n)>fabs(r))
    m = n;
  else m = r;
#ifdef DEBUG
  printf("combine %e %e : %d\n",r,n,m);
#endif
  *(float*)inout = m;
}

which you then use as:

  MPI_Op calc_absmax;
  MPI_Op_create(abs_max,1,&calc_absmax);
  MPI_Allreduce(&data,&data_abs_max,1,MPI_FLOAT,calc_absmax,comm);
  MPI_Op_free(&calc_absmax);
  • Related