使用平铺

可以使用平铺来最大化应用的加速。 平铺将线程分成相等的矩形子集或平铺。 如果使用适当的平铺大小和平铺算法,则可以从 C++ AMP 代码中实现更好的加速。 平铺的基本组件为:

  • tile_static 变量。 平铺的主要好处是可以从 tile_static 访问中获得性能增益。 访问 tile_static 内存中的数据可能比访问全局空间(arrayarray_view 对象)中的数据要快得多。 为每个平铺创建 tile_static 变量的实例,平铺中的所有线程可以访问该变量。 在典型的平铺算法中,数据从全局内存复制到 tile_static 内存一次,然后从 tile_static 内存被访问多次。

  • tile_barrier::wait 方法tile_barrier::wait 调用会暂停当前线程的执行,直到同一平铺中的所有线程都到达 tile_barrier::wait 调用。 不能保证线程的运行顺序,只有在所有线程都到达 tile_barrier::wait 调用之后,平铺中的线程才越过该调用执行。 这意味着,使用 tile_barrier::wait 方法可以逐平铺而不是逐线程执行任务。 典型的平铺算法提供用于初始化整个平铺的 tile_static 内存,然后调用 tile_barrier::wait 的代码。 tile_barrier::wait 后面的代码包含需要访问所有 tile_static 值的计算。

  • 局部和全局索引。 可以访问相对于整个 array_viewarray 对象的索引以及相对于平铺的索引。 使用局部索引可使代码更易于阅读和调试。 通常,你会使用局部索引来访问 tile_static 变量,并使用全局索引来访问 arrayarray_view 变量。

  • tiled_extent 类tiled_index 类。 在 parallel_for_each 调用中使用 tiled_extent 对象而不是 extent 对象。 在 parallel_for_each 调用中使用 tiled_index 对象而不是 index 对象。

若要利用平铺,算法必须将计算域分区成平铺,然后将平铺数据复制到 tile_static 变量中以加快访问速度。

全局、平铺和局部索引的示例

注意

从 Visual Studio 2022 版本 17.0 开始,已弃用 C++ AMP 标头。 包含任何 AMP 标头都会导致生成错误。 应在包含任何 AMP 标头之前定义 _SILENCE_AMP_DEPRECATION_WARNINGS,以使警告静音。

下图显示了排列在 2x3 平铺中的 8x9 数据矩阵。

Diagram of an 8 by 9 matrix divided into 2 by 3 tiles.

以下示例显示了此平铺矩阵的全局、平铺和局部索引。 array_view 对象是使用 Description 类型的元素创建的。 Description 保存矩阵中元素的全局、平铺和局部索引。 parallel_for_each 调用中的代码设置每个元素的全局、平铺和局部索引值。 输出显示 Description 结构中的值。

#include <iostream>
#include <iomanip>
#include <Windows.h>
#include <amp.h>
using namespace concurrency;

const int ROWS = 8;
const int COLS = 9;

// tileRow and tileColumn specify the tile that each thread is in.
// globalRow and globalColumn specify the location of the thread in the array_view.
// localRow and localColumn specify the location of the thread relative to the tile.
struct Description {
    int value;
    int tileRow;
    int tileColumn;
    int globalRow;
    int globalColumn;
    int localRow;
    int localColumn;
};

// A helper function for formatting the output.
void SetConsoleColor(int color) {
    int colorValue = (color == 0)  4 : 2;
    SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), colorValue);
}

// A helper function for formatting the output.
void SetConsoleSize(int height, int width) {
    COORD coord;

    coord.X = width;
    coord.Y = height;
    SetConsoleScreenBufferSize(GetStdHandle(STD_OUTPUT_HANDLE), coord);

    SMALL_RECT* rect = new SMALL_RECT();
    rect->Left = 0;
    rect->Top = 0;
    rect->Right = width;
    rect->Bottom = height;
    SetConsoleWindowInfo(GetStdHandle(STD_OUTPUT_HANDLE), true, rect);
}

// This method creates an 8x9 matrix of Description structures.
// In the call to parallel_for_each, the structure is updated
// with tile, global, and local indices.
void TilingDescription() {
    // Create 72 (8x9) Description structures.
    std::vector<Description> descs;
    for (int i = 0; i < ROWS * COLS; i++) {
        Description d = {i, 0, 0, 0, 0, 0, 0};
        descs.push_back(d);
    }

    // Create an array_view from the Description structures.
    extent<2> matrix(ROWS, COLS);
    array_view<Description, 2> descriptions(matrix, descs);

    // Update each Description with the tile, global, and local indices.
    parallel_for_each(descriptions.extent.tile< 2, 3>(),
        [=] (tiled_index< 2, 3> t_idx) restrict(amp)
    {
        descriptions[t_idx].globalRow = t_idx.global[0];
        descriptions[t_idx].globalColumn = t_idx.global[1];
        descriptions[t_idx].tileRow = t_idx.tile[0];
        descriptions[t_idx].tileColumn = t_idx.tile[1];
        descriptions[t_idx].localRow = t_idx.local[0];
        descriptions[t_idx].localColumn= t_idx.local[1];
    });

    // Print out the Description structure for each element in the matrix.
    // Tiles are displayed in red and green to distinguish them from each other.
    SetConsoleSize(100, 150);
    for (int row = 0; row < ROWS; row++) {
        for (int column = 0; column < COLS; column++) {
            SetConsoleColor((descriptions(row, column).tileRow + descriptions(row, column).tileColumn) % 2);
            std::cout << "Value: " << std::setw(2) << descriptions(row, column).value << "      ";
        }
        std::cout << "\n";

        for (int column = 0; column < COLS; column++) {
            SetConsoleColor((descriptions(row, column).tileRow + descriptions(row, column).tileColumn) % 2);
            std::cout << "Tile:   " << "(" << descriptions(row, column).tileRow << "," << descriptions(row, column).tileColumn << ")  ";
        }
        std::cout << "\n";

        for (int column = 0; column < COLS; column++) {
            SetConsoleColor((descriptions(row, column).tileRow + descriptions(row, column).tileColumn) % 2);
            std::cout << "Global: " << "(" << descriptions(row, column).globalRow << "," << descriptions(row, column).globalColumn << ")  ";
        }
        std::cout << "\n";

        for (int column = 0; column < COLS; column++) {
            SetConsoleColor((descriptions(row, column).tileRow + descriptions(row, column).tileColumn) % 2);
            std::cout << "Local:  " << "(" << descriptions(row, column).localRow << "," << descriptions(row, column).localColumn << ")  ";
        }
        std::cout << "\n";
        std::cout << "\n";
    }
}

int main() {
    TilingDescription();
    char wait;
    std::cin >> wait;
}

该示例的主要工作是定义 array_view 对象和 parallel_for_each 调用。

  1. Description 结构的向量复制到 8x9 array_view 对象中。

  2. 使用 tiled_extent 对象作为计算域来调用 parallel_for_each 方法。 tiled_extent 对象是通过调用 descriptions 变量的 extent::tile() 方法创建的。 extent::tile() 调用的类型参数 <2,3> 指定创建 2x3 平铺。 因此,8x9 矩阵平铺成 12 个平铺图块(4 行 x 3列)。

  3. 使用 tiled_index<2,3> 对象 (t_idx) 作为索引来调用 parallel_for_each 方法。 索引 (t_idx) 的类型参数必须与计算域 (descriptions.extent.tile< 2, 3>()) 的类型参数匹配。

  4. 执行每个线程时,索引 t_idx 会返回有关线程所在平铺(tiled_index::tile 属性)以及线程在平铺中的位置(tiled_index::local 属性)的信息。

平铺同步 — tile_static 和 tile_barrier::wait

以上示例演示了平铺布局和索引,但这种结构本身并不是很有用。 当平铺是算法的一部分并利用 tile_static 变量时,平铺就很有用。 由于平铺中的所有线程都可以访问 tile_static 变量,因此 tile_barrier::wait 调用可用于同步对 tile_static 变量的访问。 尽管平铺中的所有线程都可以访问 tile_static 变量,但无法保证平铺中线程的执行顺序。 以下示例演示如何使用 tile_static 变量和 tile_barrier::wait 方法来计算每个平铺的平均值。 下面是理解该示例的关键所在:

  1. rawData 存储在 8x8 矩阵中。

  2. 平铺大小为 2x2。 这会创建一个 4x4 平铺网格,可以使用 array 对象将平均值存储在 4x4 矩阵中。 在受 AMP 限制的函数中,只能通过引用来捕获有限数量的类型。 array 类就是其中之一。

  3. 矩阵大小和样本大小是使用 #define 语句定义的,因为 arrayarray_viewextenttiled_index 的类型参数必须是常量值。 还可以使用 const int static 声明。 一个额外的好处是,可以轻而易举地通过更改样本大小来计算 4x4 平铺的平均值。

  4. 为每个平铺声明 tile_static 2x2 浮点值数组。 尽管声明位于每个线程的代码路径中,但只需为矩阵中的每个平铺创建一个数组。

  5. 有一行代码用于将每个平铺中的值复制到 tile_static 数组。 对于每个线程,在将值复制到该数组后,线程上的执行将因调用 tile_barrier::wait 而停止。

  6. 当平铺中的所有线程都到达屏障时,即可计算平均值。 因为代码针对每个线程执行,因此有一个 if 语句只计算一个线程上的平均值。 该平均值存储在 averages 变量中。 屏障在本质上是按平铺控制计算的构造,这非常类似于使用 for 循环。

  7. 由于 averages 变量中的数据是一个 array 对象,因此它必须复制回主机。 此示例使用向量转换运算符。

  8. 在完整示例中,可将 SAMPLESIZE 更改为 4,然后无需进行任何其他更改即可正常正确执行代码。

#include <iostream>
#include <amp.h>
using namespace concurrency;

#define SAMPLESIZE 2
#define MATRIXSIZE 8
void SamplingExample() {

    // Create data and array_view for the matrix.
    std::vector<float> rawData;
    for (int i = 0; i < MATRIXSIZE * MATRIXSIZE; i++) {
        rawData.push_back((float)i);
    }
    extent<2> dataExtent(MATRIXSIZE, MATRIXSIZE);
    array_view<float, 2> matrix(dataExtent, rawData);

    // Create the array for the averages.
    // There is one element in the output for each tile in the data.
    std::vector<float> outputData;
    int outputSize = MATRIXSIZE / SAMPLESIZE;
    for (int j = 0; j < outputSize * outputSize; j++) {
        outputData.push_back((float)0);
    }
    extent<2> outputExtent(MATRIXSIZE / SAMPLESIZE, MATRIXSIZE / SAMPLESIZE);
    array<float, 2> averages(outputExtent, outputData.begin(), outputData.end());

    // Use tiles that are SAMPLESIZE x SAMPLESIZE.
    // Find the average of the values in each tile.
    // The only reference-type variable you can pass into the parallel_for_each call
    // is a concurrency::array.
    parallel_for_each(matrix.extent.tile<SAMPLESIZE, SAMPLESIZE>(),
        [=, &averages] (tiled_index<SAMPLESIZE, SAMPLESIZE> t_idx) restrict(amp)
    {
        // Copy the values of the tile into a tile-sized array.
        tile_static float tileValues[SAMPLESIZE][SAMPLESIZE];
        tileValues[t_idx.local[0]][t_idx.local[1]] = matrix[t_idx];

        // Wait for the tile-sized array to load before you calculate the average.
        t_idx.barrier.wait();

        // If you remove the if statement, then the calculation executes for every
        // thread in the tile, and makes the same assignment to averages each time.
        if (t_idx.local[0] == 0 && t_idx.local[1] == 0) {
            for (int trow = 0; trow < SAMPLESIZE; trow++) {
                for (int tcol = 0; tcol < SAMPLESIZE; tcol++) {
                    averages(t_idx.tile[0],t_idx.tile[1]) += tileValues[trow][tcol];
                }
            }
            averages(t_idx.tile[0],t_idx.tile[1]) /= (float) (SAMPLESIZE * SAMPLESIZE);
        }
    });

    // Print out the results.
    // You cannot access the values in averages directly. You must copy them
    // back to a CPU variable.
    outputData = averages;
    for (int row = 0; row < outputSize; row++) {
        for (int col = 0; col < outputSize; col++) {
            std::cout << outputData[row*outputSize + col] << " ";
        }
        std::cout << "\n";
    }
    // Output for SAMPLESIZE = 2 is:
    //  4.5  6.5  8.5 10.5
    // 20.5 22.5 24.5 26.5
    // 36.5 38.5 40.5 42.5
    // 52.5 54.5 56.5 58.5

    // Output for SAMPLESIZE = 4 is:
    // 13.5 17.5
    // 45.5 49.5
}

int main() {
    SamplingExample();
}

争用条件

你可能会倾向于创建一个名为 totaltile_static 变量,并为每个线程递增该变量,如下所示:

// Do not do this.
tile_static float total;
total += matrix[t_idx];
t_idx.barrier.wait();

averages(t_idx.tile[0],t_idx.tile[1]) /= (float) (SAMPLESIZE* SAMPLESIZE);

这种方法的第一个问题是 tile_static 变量不能包含初始化表达式。 第二个问题是 total 赋值存在争用条件,因为平铺中的所有线程都可以不按特定顺序访问该变量。 可以编写一种算法以便仅允许一个线程访问每个屏障上的总计,如下所示。 但是,这种解决方法不可延伸。

// Do not do this.
tile_static float total;
if (t_idx.local[0] == 0&& t_idx.local[1] == 0) {
    total = matrix[t_idx];
}
t_idx.barrier.wait();

if (t_idx.local[0] == 0&& t_idx.local[1] == 1) {
    total += matrix[t_idx];
}
t_idx.barrier.wait();

// etc.

内存围栏

必须同步两种内存访问 — 全局内存访问和 tile_static 内存访问。 concurrency::array 对象仅分配全局内存。 concurrency::array_view 可以引用全局内存和/或 tile_static 内存,具体取决于它的构造方式。 必须同步两种内存:

  • 全局内存

  • tile_static

内存围栏确保线程平铺中的其他线程可以访问内存,并根据程序顺序执行内存访问。 为确保这一点,编译器和处理器不会在整个围栏中将读取和写入重新排序。 在 C++ AMP 中,内存围栏是通过调用以下方法之一创建的:

调用所需的特定围栏可以提高应用的性能。 屏障类型会影响编译器和硬件将语句重新排序的方式。 例如,如果使用全局内存围栏,则它仅适用于全局内存访问,因此,编译器和硬件可能会重新排序对围栏两侧的 tile_static 变量的读取和写入。

在以下示例中,屏障会将写入同步到 tileValues(一个 tile_static 变量)。 在此示例中,调用的是 tile_barrier::wait_with_tile_static_memory_fence 而不是 tile_barrier::wait

// Using a tile_static memory fence.
parallel_for_each(matrix.extent.tile<SAMPLESIZE, SAMPLESIZE>(),
    [=, &averages] (tiled_index<SAMPLESIZE, SAMPLESIZE> t_idx) restrict(amp)
{
    // Copy the values of the tile into a tile-sized array.
    tile_static float tileValues[SAMPLESIZE][SAMPLESIZE];
    tileValues[t_idx.local[0]][t_idx.local[1]] = matrix[t_idx];

    // Wait for the tile-sized array to load before calculating the average.
    t_idx.barrier.wait_with_tile_static_memory_fence();

    // If you remove the if statement, then the calculation executes
    // for every thread in the tile, and makes the same assignment to
    // averages each time.
    if (t_idx.local[0] == 0&& t_idx.local[1] == 0) {
        for (int trow = 0; trow <SAMPLESIZE; trow++) {
            for (int tcol = 0; tcol <SAMPLESIZE; tcol++) {
                averages(t_idx.tile[0],t_idx.tile[1]) += tileValues[trow][tcol];
            }
        }
    averages(t_idx.tile[0],t_idx.tile[1]) /= (float) (SAMPLESIZE* SAMPLESIZE);
    }
});

另请参阅

C++ AMP (C++ Accelerated Massive Parallelism)
tile_static 关键字