跳转到正文
Retep's
返回

[TIL] 线程块内的数据交换

编辑文章

本文由英文原文翻译。代码、公式与技术名称保留原文。

学习资料:rocPRIM 线程/值布局描述一个逻辑序列如何分布到线程上。例如,逻辑序列 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11] 可以分布到 4 个线程:

thread 0: [0, 1, 2]
thread 1: [3, 4, 5]
thread 2: [6, 7, 8]
thread 3: [9, 10, 11]

可以表示为 (4, 3):(3, 1):外层是 4 个线程、步长为 3;内层是 3 个寄存器、步长为 1。原文将全局索引写为 thread_id * 4 + local_id。

在 striped 布局中,连续元素分布到连续线程:

thread 0: [0, 4, 8]
thread 1: [1, 5, 9]
thread 2: [2, 6, 10]
thread 3: [3, 7, 11]

原文将其表示为 (4, 1):(3, 4)。注意,寄存器维度的步长变为线程总数。全局索引,也就是逻辑索引,为 thread_id + local_id * block_size。blocked_to_striped 在这两种归属方式之间重新分配值,不改变逻辑序列,即从第一种布局变换到第二种布局。

Warp 内的条带式布局

warp-striped 布局在每个 warp 或 wave 内独立进行条带式分配。以两个各含 4 个线程、每线程持有 2 个元素的 warp 为例:

warp 0:
thread 0: [0, 4]
thread 1: [1, 5]
thread 2: [2, 6]
thread 3: [3, 7]

warp 1:
thread 4: [8,  12]
thread 5: [9,  13]
thread 6: [10, 14]
thread 7: [11, 15]

blocked_to_warp_striped 不会在线程束之间移动值。因此通常可以使用高效的 wave 内指令,而不必借助共享内存和整个线程块的同步屏障。

Scatter 与 Gather

blocked-to-striped 这类固定变换有预先确定的排列,而 scatter 和 gather 接收显式 rank。对于 scatter_to_blocked,每个输入元素给出其目标 rank,即线性索引,由它决定最终的 blocked 位置:

destination_thread = rank // items_per_thread
destination_item   = rank % items_per_thread

对于 gather_from_striped,每个输出元素给出所需 striped 输入的 rank。

对于 striped 源布局:

source_thread = rank % block_size
source_item   = rank // block_size

一些例子:

initial:
thread 0: values [A, B], ranks [7, 0]
thread 1: values [C, D], ranks [6, 1]
thread 2: values [E, F], ranks [5, 2]
thread 3: values [G, H], ranks [4, 3]

match rank:
rank:   0  1  2  3  4  5  6  7
value:  B  D  F  H  G  E  C  A

After scatter:
thread 0: [B, D]   # ranks 0, 1
thread 1: [F, H]   # ranks 2, 3
thread 2: [G, E]   # ranks 4, 5
thread 3: [C, A]   # ranks 6, 7

Gather 则反过来:

initial:
thread 0: [A, E], ranks [7, 6]
thread 1: [B, F], ranks [5, 4]
thread 2: [C, G], ranks [3, 2]
thread 3: [D, H], ranks [1, 0]

After gather with the rank:

thread 0: [H, G]
thread 1: [F, E]
thread 2: [D, C]
thread 3: [B, A]

重新分布

不同 GPU 操作偏好不同的值分布。某种布局有利于合并访存,另一种可能匹配 MMA 指令或协作算法。重新分布通过在线程间移动寄存器中的值衔接这些阶段。根据源布局和目标布局,可以使用:

把这些交换视为布局变换,既能复用实现,也让编译器有机会选择代价最低的方式。


编辑文章
分享文章:

上一篇
[TIL] 布局计算小记
下一篇
[TIL] MLIR Toy 详解:第 7 章