首页 文章

在MPI中实现Cannons算法

提问于
浏览
2

我正在尝试使用MPI实现Cannons算法,我正在使用此示例代码:

http://siber.cankaya.edu.tr/ozdogan/GraduateParallelComputing.old/ceng505/node133.html

有一节我不理解 . 这是示例代码 .

37    /* Perform the initial matrix alignment. First for A and then for B */ 
38    MPI_Cart_shift(comm_2d, 0, -mycoords[0], &shiftsource, &shiftdest); 
39    MPI_Sendrecv_replace(a, nlocal*nlocal, MPI_DOUBLE, shiftdest, 
40        1, shiftsource, 1, comm_2d, &status); 
41 
42    MPI_Cart_shift(comm_2d, 1, -mycoords[1], &shiftsource, &shiftdest); 
43    MPI_Sendrecv_replace(b, nlocal*nlocal, MPI_DOUBLE, 
44        shiftdest, 1, shiftsource, 1, comm_2d, &status);

这是我目前的代码 .

MPI_Comm_size(comm, &size); 
MPI_Comm_rank(comm, &rank); 
MPI_Cart_coords(comm, rank, 2, coordinates); 

MPI_Cart_shift(comm, 0, -1, &rightrank, &leftrank);
MPI_Cart_shift(comm, 1, -1, &downrank, &uprank); 

MPI_Cart_shift(comm, 0, -coordinates[0], &shiftsource, &shiftdest); 
printf("coordinates[0] = %d for a shiftsource = %d, shiftdest = %d\n", coordinates[0], shiftsource, shiftdest);
//MPI_Sendrecv_replace(a, a->rowNum * a->colNum, MPI_INT, shiftdest, 
    //1, shiftsource, 1, comm, &status); 

MPI_Cart_shift(comm, 1, -coordinates[1], &shiftsource, &shiftdest); 
printf("coordinates[1] = %d for b shiftsource = %d, shiftdest = %d\n", coordinates[1], shiftsource, shiftdest);
//MPI_Sendrecv_replace(b, b->rowNum * b->colNum, MPI_INT, 
  //  shiftdest, 1, shiftsource, 1, comm, &status);

我在另一个函数中调用MPI_Cart_create,但它与示例代码中的基本调用相同 .

MPI_Comm_size (MPI_COMM_WORLD, &size);  /* get number of processes */
    .
    .
    .
if(is_perfect_square(size))  dim_size[0] = dim_size[1] = (int) sqrt(size);
else
{ //if size = 2 then dims = 2, 1; size = 4 then 2,2; 8 = 4, 2...
    dim_size[0] = (int) sqrt(size + size);
    dim_size[1] = dim_size[0] / 2;
}
MPI_Cart_create(MPI_COMM_WORLD, 2, dim_size, periods, 1, &CannonsCart);

现在我只想了解shiftource和shiftdest的重点 . 我假设它是为了初始转移但是当我运行这个代码时,我的printf语句说这个 .

coordinates[0] = 0 for a shiftsource = 0, shiftdest = 0
coordinates[1] = 0 for b shiftsource = 0, shiftdest = 0

coordinates[0] = 1 for a shiftsource = 1, shiftdest = 1
coordinates[1] = 1 for b shiftsource = 2, shiftdest = 2

coordinates[0] = 1 for a shiftsource = 0, shiftdest = 0
coordinates[1] = 0 for b shiftsource = 2, shiftdest = 2

coordinates[0] = 0 for a shiftsource = 1, shiftdest = 1
coordinates[1] = 1 for b shiftsource = 0, shiftdest = 0

我不明白为什么shiftource和shiftdest是相同的 . 对于矩阵a和b,它应该是一个向左,一个向上 .

对于此测试用例,此调用的进程数(I.E. size)为4 . 如果我需要,我将只托管我的所有代码 .

1 回答

  • 2

    MPI_Cart_shift 的第三个参数是沿第二个参数指定的维度(方向)的位移 . 对于沿指定维度具有坐标 0 的所有进程,位移也将是 0 (因为它被指定为 -coordinate[i] ),因此源和目标排名将匹配调用进程的排名 .

    当位移为 1 时,您也会得到相同的 shiftsourceshiftdest ,因为您的拓扑结构是2x2,并且沿两个维度都有周期性边界条件 . 沿着先前等级的所选维度的坐标将是 (coordinates[i] - 1 + 2) % 2 (这里 (a - m + k) % k 计算 a - m modulo k ) . 但这等于 (coordinate[i] + 1) % 2 ,这正是下一个等级的坐标 . 因此,前一个和下一个过程的坐标是一致的,因此等级最终是相同的 .

相关问题