MPI C,基于值的 Allreduce 结构

MPI C, Allreduce struct based on a value

我试图找到一些局部子数组的最大绝对值。尝试将原始值共享给其他处理器时出现问题,因为该值必须保留其原始符号(正或负)

所以我有这个结构:

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

查找最大值的函数:

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;
}

在主体中,我使用了这段代码:

// ...

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);

我可以创建自定义操作或数据类型吗?

您需要定义一个自定义归约运算符。

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;
}

然后您将其用作:

  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);