Merged
feat(pypto-pro): Support mxfp8/mxfp4 #5439
yzfAdd on Aug 13
feat(pypto-pro): Support mxfp8/mxfp4 #5439
Merged
Merged fromfafafafafa/pypto_cannmasterintocann/pyptomaster
Total: 41 files changed+3113-70
| @@ -34,6 +34,9 @@ | |||
| 34 | | `pypto_pro.language.DT_FP4` | 4 | 否 | 是 | — | IEEE浮点 | 低精度推理 | | 34 | | `pypto_pro.language.DT_FP4` | 4 | 否 | 是 | — | IEEE浮点 | 低精度推理 | |
| 35 | | `pypto_pro.language.DT_FP8E4M3FN` | 8 | 否 | 是 | `float8_e4m3_t` | IEEE浮点 | FP8推理(E4M3格式) | | 35 | | `pypto_pro.language.DT_FP8E4M3FN` | 8 | 否 | 是 | `float8_e4m3_t` | IEEE浮点 | FP8推理(E4M3格式) | |
| 36 | | `pypto_pro.language.DT_FP8E5M2` | 8 | 否 | 是 | `float8_e5m2_t` | IEEE浮点 | FP8推理(E5M2格式) | | 36 | | `pypto_pro.language.DT_FP8E5M2` | 8 | 否 | 是 | `float8_e5m2_t` | IEEE浮点 | FP8推理(E5M2格式) | |
| 37 | +| `pypto_pro.language.DT_FP8E8M0` | 8 | 否 | 是 | `float8_e8m0_t` | IEEE浮点 | MXFP8/MXFP4每组32个元素共享的scale | | ||
| 38 | +| `pypto_pro.language.DT_FP4E2M1` | 4 | 否 | 是 | `float4_e2m1x2_t` | IEEE浮点 | E2M1格式的4位浮点数据,GM中两个元素打包为1字节 | | ||
| 39 | +| `pypto_pro.language.DT_FP4E1M2` | 4 | 否 | 是 | `float4_e1m2x2_t` | IEEE浮点 | E1M2格式的4位浮点数据,GM中两个元素打包为1字节 | | ||
| 37 | | `pypto_pro.language.DT_FP16` | 16 | 否 | 是 | `half` | IEEE浮点 | 矩阵输入、向量计算(最常用) | | 40 | | `pypto_pro.language.DT_FP16` | 16 | 否 | 是 | `half` | IEEE浮点 | 矩阵输入、向量计算(最常用) | |
| 38 | | `pypto_pro.language.DT_FP32` | 32 | 否 | 是 | `float` | IEEE浮点 | 累加器、高精度计算 | | 41 | | `pypto_pro.language.DT_FP32` | 32 | 否 | 是 | `float` | IEEE浮点 | 累加器、高精度计算 | |
| 39 | | `pypto_pro.language.DT_BF16` | 16 | 否 | 是 | `bfloat16_t` | Brain浮点 | 矩阵输入(动态范围优于FP16) | | 42 | | `pypto_pro.language.DT_BF16` | 16 | 否 | 是 | `bfloat16_t` | Brain浮点 | 矩阵输入(动态范围优于FP16) | |
| @@ -56,6 +59,8 @@ | |||
| 56 | 59 | ||
| 57 | **默认类型常量**:裸整数常量(如`42`)默认为`pypto_pro.language.DT_INT64`,裸浮点常量(如`3.14`)默认为`pypto_pro.language.DT_FP32`。 | 60 | **默认类型常量**:裸整数常量(如`42`)默认为`pypto_pro.language.DT_INT64`,裸浮点常量(如`3.14`)默认为`pypto_pro.language.DT_FP32`。 |
| 58 | 61 | ||
| 62 | +**MX浮点类型**:MXFP8的数据元素使用`DT_FP8E4M3FN`或`DT_FP8E5M2`,MXFP4的数据元素可使用`DT_FP4E2M1`或`DT_FP4E1M2`;两者均使用`DT_FP8E8M0`保存分组缩放因子。E8M0编码值`e`对应缩放因子`2^(e-127)`。类型组合和分组规则见[`matmul_mx`](../operation/matrix_computation/matmul_mx.md)和[`matmul_mx_acc`](../operation/matrix_computation/matmul_mx_acc.md)。 | ||
| 63 | + | ||
| 59 | ## 调用示例 | 64 | ## 调用示例 |
| 60 | 65 | ||
| 61 | ```python | 66 | ```python |
| @@ -1,48 +1,68 @@ | |||
| 1 | # pypto_pro.language.MemorySpace | 1 | # pypto_pro.language.MemorySpace |
| 2 | 2 | ||
| 3 | -## 产品支持情况 | 3 | +## 产品支持情况 |
| 4 | - | 4 | + |
| 5 | -<!-- npu="950" id1 --> | 5 | +<!-- npu="950" id1 --> |
| 6 | -- Ascend 950PR/Ascend 950DT:支持 | 6 | +- Ascend 950PR/Ascend 950DT:支持 |
| 7 | -<!-- end id1 --> | 7 | +<!-- end id1 --> |
| 8 | -<!-- npu="A3" id2 --> | 8 | +<!-- npu="A3" id2 --> |
| 9 | -- Atlas A3 训练系列产品/Atlas A3 推理系列产品:不支持 | 9 | +- Atlas A3 训练系列产品/Atlas A3 推理系列产品:不支持 |
| 10 | -<!-- end id2 --> | 10 | +<!-- end id2 --> |
| 11 | -<!-- npu="910b" id3 --> | 11 | +<!-- npu="910b" id3 --> |
| 12 | -- Atlas A2 训练系列产品/Atlas A2 推理系列产品:不支持 | 12 | +- Atlas A2 训练系列产品/Atlas A2 推理系列产品:不支持 |
| 13 | -<!-- end id3 --> | 13 | +<!-- end id3 --> |
| 14 | - | 14 | + |
| 15 | ## 功能说明 | 15 | ## 功能说明 |
| 16 | 16 | ||
| 17 | -内存空间枚举,用于标记Tile所在的物理存储位置,是[`pypto_pro.language.TileType`](TileType.md)的关键属性。 | 17 | +内存空间枚举,用于标记Tile所在的物理存储位置,是[`pypto_pro.language.TileType`](TileType.md)的关键属性。 |
| 18 | 18 | ||
| 19 | -不同内存空间对应昇腾芯片上不同的物理存储区域,决定了Tile能参与哪些计算、需要哪条流水搬运。 | 19 | +不同内存空间对应昇腾芯片上不同的物理存储区域,决定了Tile能参与哪些计算、需要哪条流水搬运。 |
| 20 | 20 | ||
| 21 | ## 取值 | 21 | ## 取值 |
| 22 | 22 | ||
| 23 | | 取值 | 物理位置 | 说明 | 典型用途 | | 23 | | 取值 | 物理位置 | 说明 | 典型用途 | |
| 24 | |---|---|---|---| | 24 | |---|---|---|---| |
| 25 | -| `pypto_pro.language.MemorySpace.DDR` | 片外DDR | 全局内存,Tensor所在 | GM张量存储 | | 25 | +| `pypto_pro.language.MemorySpace.DDR` | 片外DDR | 全局内存,Tensor所在 | GM张量存储 | |
| 26 | -| `pypto_pro.language.MemorySpace.Vec` | 片上UB | 向量/统一缓冲区 | 向量计算(element-wise、reduce等)的输入输出 | | 26 | +| `pypto_pro.language.MemorySpace.Vec` | 片上UB | 向量/统一缓冲区 | 向量计算(element-wise、reduce等)的输入输出 | |
| 27 | -| `pypto_pro.language.MemorySpace.Mat` | 片上L1 | 矩阵缓冲区 | matmul的L1暂存(GM→L1→L0A/L0B两跳的中间站) | | 27 | +| `pypto_pro.language.MemorySpace.Mat` | 片上L1 | 矩阵缓冲区 | matmul的L1暂存(GM→L1→L0A/L0B两跳的中间站) | |
| 28 | -| `pypto_pro.language.MemorySpace.Left` | 片上L0A | 左操作数缓冲区 | matmul左矩阵输入 | | 28 | +| `pypto_pro.language.MemorySpace.Left` | 片上L0A | 左操作数缓冲区 | matmul左矩阵输入 | |
| 29 | -| `pypto_pro.language.MemorySpace.Right` | 片上L0B | 右操作数缓冲区 | matmul右矩阵输入 | | 29 | +| `pypto_pro.language.MemorySpace.Right` | 片上L0B | 右操作数缓冲区 | matmul右矩阵输入 | |
| 30 | -| `pypto_pro.language.MemorySpace.Acc` | 片上L0C | 累加器缓冲区 | matmul累加器输出 | | 30 | +| `pypto_pro.language.MemorySpace.Acc` | 片上L0C | 累加器缓冲区 | matmul累加器输出 | |
| 31 | -| `pypto_pro.language.MemorySpace.Scaling` | 片上 | 缩放/量化参数缓冲区 | quantization/反量化参数 | | 31 | +| `pypto_pro.language.MemorySpace.Scaling` | 片上 | 缩放/量化参数缓冲区 | quantization/反量化参数 | |
| 32 | -| `pypto_pro.language.MemorySpace.Bias` | Bias Buffer | 底层偏置缓冲区标识 | 当前CCE Tile codegen未实现该内存空间映射,不能用于`make_tile`或`make_tile_group`创建Tile | | 32 | +| `pypto_pro.language.MemorySpace.ScaleLeft` | 片上L0A(scale专用地址域) | A矩阵的E8M0 scale(分组缩放因子)缓冲区 | `matmul_mx`的`scale_a` | |
| 33 | +| `pypto_pro.language.MemorySpace.ScaleRight` | 片上L0B(scale专用地址域) | B矩阵的E8M0 scale(分组缩放因子)缓冲区 | `matmul_mx`的`scale_b` | | ||
| 34 | +| `pypto_pro.language.MemorySpace.Bias` | Bias Buffer | 底层偏置缓冲区标识 | 当前CCE Tile codegen未实现该内存空间映射,不能用于`make_tile`或`make_tile_group`创建Tile | | ||
| 33 | 35 | ||
| 34 | ## 补充说明 | 36 | ## 补充说明 |
| 35 | 37 | ||
| 36 | -不同内存空间的tile在构造[`pypto_pro.language.TileType`](TileType.md)时有不同的默认`layout`: | 38 | +不同内存空间的tile在构造[`pypto_pro.language.TileType`](TileType.md)时有不同的默认`layout`: |
| 37 | 39 | ||
| 38 | -| 内存空间 | A3默认`layout` | A5默认`layout` | 额外允许 | | 40 | +| 内存空间 | A3默认`layout` | A5默认`layout` | 额外允许 | |
| 39 | |---|---|---|---| | 41 | |---|---|---|---| |
| 40 | | `Vec` | 无约束 | 无约束 | — | | 42 | | `Vec` | 无约束 | 无约束 | — | |
| 41 | -| `Mat` | `pl.NZ` | `pl.NZ` | `pl.ZN`转置分形布局;UINT64/INT64还允许`pl.ND` | | 43 | +| `Mat` | `pl.NZ` | `pl.NZ` | `pl.ZN`转置分形布局;UINT64/INT64还允许`pl.ND` | |
| 42 | -| `Left` | `pl.ZZ` | `pl.NZ` | 同时允许`pl.ZZ`和`pl.NZ` | | 44 | +| `Left` | `pl.ZZ` | `pl.NZ` | 同时允许`pl.ZZ`和`pl.NZ` | |
| 43 | | `Right` | `pl.ZN` | `pl.ZN` | — | | 45 | | `Right` | `pl.ZN` | `pl.ZN` | — | |
| 44 | -| `Acc` | `pl.NZ` | `pl.NZ` | FP32/INT32自动`fractal=1024` | | 46 | +| `Acc` | `pl.NZ` | `pl.NZ` | FP32/INT32自动`fractal=1024` | |
| 45 | | `Scaling` | `pl.ND` | `pl.ND` | — | | 47 | | `Scaling` | `pl.ND` | `pl.ND` | — | |
| 48 | +| `ScaleLeft` | — | `pl.ZZ` | 仅用于A矩阵的`DT_FP8E8M0`分组缩放因子,32字节地址对齐 | | ||
| 49 | +| `ScaleRight` | — | `pl.NN` | 仅用于B矩阵的`DT_FP8E8M0`分组缩放因子,32字节地址对齐 | | ||
| 50 | + | ||
| 51 | +### MX scale(MX矩阵计算的E8M0分组缩放因子)配套缓冲区 | ||
| 52 | + | ||
| 53 | +`ScaleLeft`和`ScaleRight`分别是与L0A和L0B配套的MX scale缓冲区,在PTO-ISA中分别使用`__ca__`和`__cb__`地址空间。它们具有独立于Left/Right数据地址域的4KB逻辑容量,并非从普通L0A/L0B的64KB数据空间中划出;scale Tile的起始地址由配对数据Tile的起始地址推导: | ||
| 54 | + | ||
| 55 | +```text | ||
| 56 | +ScaleLeftAddr = LeftAddr >> 4 | ||
| 57 | +ScaleRightAddr = RightAddr >> 4 | ||
| 58 | +``` | ||
| 59 | + | ||
| 60 | +因此,64KB的L0A/L0B数据地址范围对应4KB的ScaleLeft/ScaleRight地址范围。例如,Left起始地址为`0x8000`时,配对的ScaleLeft起始地址为`0x0800`。该映射是MX矩阵指令的强制寻址约束。对于显式指定且编译期可知的Tile地址,框架会校验ScaleLeft/ScaleRight与Left/Right的地址映射;自动分配或动态地址无法在该阶段校验。映射不一致时,指令会从由Left/Right地址推导的位置读取scale,而不是从错误配置的scale Tile地址读取,导致计算结果错误。 | ||
| 61 | + | ||
| 62 | +> [!NOTE]说明 | ||
| 63 | +> 4KB的ScaleLeft/ScaleRight不是从64KB的L0A/L0B数据容量中划出的预留空间。使用ScaleLeft/ScaleRight时,Left/Right的数据地址域仍可使用完整64KB,不需要缩减为60KB。 | ||
| 64 | + | ||
| 65 | +这里的`/16`来自硬件地址右移4位,与“一个E8M0 scale对应K方向连续32个尾数元素”的数据分组规则不是同一概念。MX矩阵乘法的完整参数约束见[`matmul_mx`](../operation/matrix_computation/matmul_mx.md)。 | ||
| 46 | 66 | ||
| 47 | ## 调用示例 | 67 | ## 调用示例 |
| 48 | 68 | ||
| @@ -22,7 +22,7 @@ | |||
| 22 | 22 | ||
| 23 | | 取值 | 说明 | 硬件角色 | | 23 | | 取值 | 说明 | 硬件角色 | |
| 24 | |---|---|---| | 24 | |---|---|---| |
| 25 | -| `pypto_pro.language.PipeType.MTE1` | 搬运流水1 | L1 → L0A/L0B/Scaling(矩阵操作数与量化参数搬运) | | 25 | +| `pypto_pro.language.PipeType.MTE1` | 搬运流水1 | L1 → L0A/L0B/Scaling/ScaleLeft/ScaleRight(矩阵操作数与scale搬运) | |
| 26 | | `pypto_pro.language.PipeType.MTE2` | 搬运流水2 | GM → L1/UB(load搬入) | | 26 | | `pypto_pro.language.PipeType.MTE2` | 搬运流水2 | GM → L1/UB(load搬入) | |
| 27 | | `pypto_pro.language.PipeType.MTE3` | 搬运流水3 | UB → GM(store搬出)、UB → L1(move搬运) | | 27 | | `pypto_pro.language.PipeType.MTE3` | 搬运流水3 | UB → GM(store搬出)、UB → L1(move搬运) | |
| 28 | | `pypto_pro.language.PipeType.M` | 矩阵计算流水 | Cube/MAD(matmul计算) | | 28 | | `pypto_pro.language.PipeType.M` | 矩阵计算流水 | Cube/MAD(matmul计算) | |
| @@ -42,6 +42,7 @@ | |||
| 42 | | `store` | Acc(L0C) → GM | FIX | | 42 | | `store` | Acc(L0C) → GM | FIX | |
| 43 | | `move` | Mat(L1) → Left/Right(L0A/L0B) | MTE1 | | 43 | | `move` | Mat(L1) → Left/Right(L0A/L0B) | MTE1 | |
| 44 | | `move` | Mat(L1) → Scaling | MTE1 | | 44 | | `move` | Mat(L1) → Scaling | MTE1 | |
| 45 | +| `move` | Mat(L1) → ScaleLeft/ScaleRight | MTE1 | | ||
| 45 | | `move` | Mat(L1) → Vec(UB) | FIX | | 46 | | `move` | Mat(L1) → Vec(UB) | FIX | |
| 46 | | `move` | Mat(L1) → Acc(L0C) | FIX | | 47 | | `move` | Mat(L1) → Acc(L0C) | FIX | |
| 47 | | `move` | Acc(L0C) → Vec(UB) | FIX | | 48 | | `move` | Acc(L0C) → Vec(UB) | FIX | |
| @@ -45,7 +45,7 @@ | |||
| 45 | 45 | ||
| 46 | 以下低精度类型为存储和张量计算专用类型,**不支持**用于标量表达式: | 46 | 以下低精度类型为存储和张量计算专用类型,**不支持**用于标量表达式: |
| 47 | 47 | ||
| 48 | -`DT_FP4`、`DT_FP8E4M3FN`、`DT_FP8E5M2`、`DT_INT4`、`DT_UINT4`、`DT_HF4`、`DT_HF8` | 48 | +`DT_FP4`、`DT_FP8E4M3FN`、`DT_FP8E5M2`、`DT_FP8E8M0`、`DT_FP4E2M1`、`DT_FP4E1M2`、`DT_INT4`、`DT_UINT4`、`DT_HF4`、`DT_HF8` |
| 49 | 49 | ||
| 50 | ## 调用示例 | 50 | ## 调用示例 |
| 51 | 51 | ||
| @@ -68,6 +68,9 @@ x: pl.Tensor[[64, 128], pl.DT_FP16] | |||
| 68 | 68 | ||
| 69 | # 带布局的 tensor | 69 | # 带布局的 tensor |
| 70 | y: pl.Tensor[[64, 128], pl.DT_FP16, pl.NZ] | 70 | y: pl.Tensor[[64, 128], pl.DT_FP16, pl.NZ] |
| 71 | + | ||
| 72 | +# A矩阵的E8M0分组缩放因子:逻辑shape为[M,G]=[64,4],GM物理shape为[M,G/2,2]=[64,2,2] | ||
| 73 | +scale_a: pl.Tensor[[64, 2, 2], pl.DT_FP8E8M0] | ||
| 71 | 74 | ||
| 72 | # 动态维度声明(仅用于类型标注) | 75 | # 动态维度声明(仅用于类型标注) |
| 73 | dynamic_tensor: pl.Tensor[[pl.DYNAMIC, pl.DYNAMIC], pl.DT_FP32] | 76 | dynamic_tensor: pl.Tensor[[pl.DYNAMIC, pl.DYNAMIC], pl.DT_FP32] |
| @@ -27,8 +27,8 @@ | |||
| 27 | | `pl.DN` | 非分形列主序 | Tile | UB上`[ROWS, 1]`列向量(归约结果、histogram索引) | | 27 | | `pl.DN` | 非分形列主序 | Tile | UB上`[ROWS, 1]`列向量(归约结果、histogram索引) | |
| 28 | | `pl.NZ` | NZ分形排列 | Tensor / Tile | NZ GM Tensor(输出);L1 Mat(默认);A5的L0A(默认);L0C Acc(默认) | | 28 | | `pl.NZ` | NZ分形排列 | Tensor / Tile | NZ GM Tensor(输出);L1 Mat(默认);A5的L0A(默认);L0C Acc(默认) | |
| 29 | | `pl.ZN` | ZN分形排列 | Tile | L0B Right(默认);转置搬入时的L1 Mat | | 29 | | `pl.ZN` | ZN分形排列 | Tile | L0B Right(默认);转置搬入时的L1 Mat | |
| 30 | -| `pl.ZZ` | ZZ分形排列 | Tile | A3的L0A(默认) | | 30 | +| `pl.ZZ` | ZZ分形排列 | Tile | A3的L0A(默认);MX矩阵计算中,A矩阵的E8M0分组缩放因子在L1和ScaleLeft中的布局 | |
| 31 | -| `pl.NN` | NN分形排列 | — | 当前版本已定义但无公开API场景实际使用 | | 31 | +| `pl.NN` | NN分形排列 | Tile | MX矩阵计算中,B矩阵的E8M0分组缩放因子在L1和ScaleRight中的布局 | |
| 32 | 32 | ||
| 33 | 以上短名称分别等价于`pypto_pro.language.TensorLayout.ND`、`DN`、`NZ`、`ZN`、`NN`、`ZZ`。 | 33 | 以上短名称分别等价于`pypto_pro.language.TensorLayout.ND`、`DN`、`NZ`、`ZN`、`NN`、`ZZ`。 |
| 34 | 34 | ||
| @@ -45,6 +45,8 @@ x: pl.Tensor[[64, 128], pl.DT_FP16] # 默认 ND | |||
| 45 | x_nz: pl.Tensor[[64, 128], pl.DT_FP16, pl.NZ] # NZ 分形布局(用于输出) | 45 | x_nz: pl.Tensor[[64, 128], pl.DT_FP16, pl.NZ] # NZ 分形布局(用于输出) |
| 46 | ``` | 46 | ``` |
| 47 | 47 | ||
| 48 | +MX矩阵计算使用的E8M0分组缩放因子在GM中仍声明为普通`ND` Tensor;物理shape和搬运约束见[`matmul_mx`](../operation/matrix_computation/matmul_mx.md)和[`load`](../operation/memory_data_movement/load.md)。 | ||
| 49 | + | ||
| 48 | > [!IMPORTANT]重要 | 50 | > [!IMPORTANT]重要 |
| 49 | > 转置搬运由[`load`](../operation/memory_data_movement/load.md)/[`load_tile`](../operation/memory_data_movement/load_tile.md)的`order`参数决定(`order=[1,0]`即`is_transpose=True`),需与L1 Tile布局`ZN`配合。详见下文[转置搬入](#转置搬入)。 | 51 | > 转置搬运由[`load`](../operation/memory_data_movement/load.md)/[`load_tile`](../operation/memory_data_movement/load_tile.md)的`order`参数决定(`order=[1,0]`即`is_transpose=True`),需与L1 Tile布局`ZN`配合。详见下文[转置搬入](#转置搬入)。 |
| 50 | 52 | ||
| @@ -55,11 +57,13 @@ Tile通过[`pl.TileType`](TileType.md)的`layout`参数指定。不指定时, | |||
| 55 | | 内存空间 | A3默认 | A5默认 | 额外允许 | | 57 | | 内存空间 | A3默认 | A5默认 | 额外允许 | |
| 56 | |---|---|---|---| | 58 | |---|---|---|---| |
| 57 | | `Vec`(UB) | 无默认值 | 无默认值 | `ND`;`DN`(仅特定API要求的列主序场景) | | 59 | | `Vec`(UB) | 无默认值 | 无默认值 | `ND`;`DN`(仅特定API要求的列主序场景) | |
| 58 | -| `Mat`(L1) | `NZ` | `NZ` | `ZN`(转置搬入);`UINT64`/`INT64`还允许`ND` | | 60 | +| `Mat`(L1) | `NZ` | `NZ` | `ZN`(转置搬入);`DT_FP8E8M0`还允许`ZZ`、`NN`;`UINT64`/`INT64`还允许`ND` | |
| 59 | | `Left`(L0A) | `ZZ` | `NZ` | `ZZ`、`NZ` | | 61 | | `Left`(L0A) | `ZZ` | `NZ` | `ZZ`、`NZ` | |
| 60 | | `Right`(L0B) | `ZN` | `ZN` | — | | 62 | | `Right`(L0B) | `ZN` | `ZN` | — | |
| 61 | | `Acc`(L0C) | `NZ` | `NZ` | — | | 63 | | `Acc`(L0C) | `NZ` | `NZ` | — | |
| 62 | | `Scaling` | `ND` | `ND` | — | | 64 | | `Scaling` | `ND` | `ND` | — | |
| 65 | +| `ScaleLeft` | — | `ZZ` | — | | ||
| 66 | +| `ScaleRight` | — | `NN` | — | | ||
| 63 | 67 | ||
| 64 | --- | 68 | --- |
| 65 | 69 | ||
| @@ -167,7 +171,7 @@ acc_type = pl.TileType(shape=[64, 64], dtype=pl.DT_FP32, | |||
| 167 | ``` | 171 | ``` |
| 168 | 172 | ||
| 169 | ### A3架构L0A的ZZ布局 | 173 | ### A3架构L0A的ZZ布局 |
| 170 | - | 174 | + |
| 171 | A3架构下L0A(左矩阵)默认`ZZ`;A5架构下默认`NZ`。以下为显式指定`ZZ`的用法: | 175 | A3架构下L0A(左矩阵)默认`ZZ`;A5架构下默认`NZ`。以下为显式指定`ZZ`的用法: |
| 172 | 176 | ||
| 173 | ```python | 177 | ```python |
| @@ -192,6 +196,37 @@ def store_nz_cce_kernel( | |||
| 192 | pl.store(nz_out, acc, [0, 0]) # 按 NZ 分形写入 GM | 196 | pl.store(nz_out, acc, [0, 0]) # 按 NZ 分形写入 GM |
| 193 | ``` | 197 | ``` |
| 194 | 198 | ||
| 195 | -### NN布局 | 199 | +### MX scale的ZZ与NN布局 |
| 196 | - | 200 | + |
| 197 | -`NN`分形在当前版本中已定义(`TensorLayout.NN`),但尚无公开API场景实际使用。开发者无需显式指定该布局。 | 201 | +`ZZ`和`NN`分别用于存放MX矩阵计算中A矩阵和B矩阵的E8M0 scale。L1 Mat Tile默认使用`NZ`,因此A矩阵的scale需要显式指定`ZZ`,B矩阵的scale需要显式指定`NN`;ScaleLeft和ScaleRight Tile则分别默认使用`ZZ`和`NN`。 |
| 202 | + | ||
| 203 | +```python | ||
| 204 | +# A/B矩阵的E8M0 scale逻辑shape分别为[M,G]和[G,N],其中G=K/32。 | ||
| 205 | +M, G, N = 64, 4, 64 | ||
| 206 | + | ||
| 207 | +# L1 Mat的默认布局是NZ,因此需要显式指定ZZ或NN。 | ||
| 208 | +scale_a_l1_type = pl.TileType( | ||
| 209 | + shape=[M, G], | ||
| 210 | + dtype=pl.DT_FP8E8M0, | ||
| 211 | + target_memory=pl.MemorySpace.Mat, | ||
| 212 | + layout=pl.ZZ, | ||
| 213 | +) | ||
| 214 | +scale_b_l1_type = pl.TileType( | ||
| 215 | + shape=[G, N], | ||
| 216 | + dtype=pl.DT_FP8E8M0, | ||
| 217 | + target_memory=pl.MemorySpace.Mat, | ||
| 218 | + layout=pl.NN, | ||
| 219 | +) | ||
| 220 | + | ||
| 221 | +# ScaleLeft/ScaleRight分别默认使用ZZ/NN,无需再次指定layout。 | ||
| 222 | +scale_a_type = pl.TileType( | ||
| 223 | + shape=[M, G], | ||
| 224 | + dtype=pl.DT_FP8E8M0, | ||
| 225 | + target_memory=pl.MemorySpace.ScaleLeft, | ||
| 226 | +) | ||
| 227 | +scale_b_type = pl.TileType( | ||
| 228 | + shape=[G, N], | ||
| 229 | + dtype=pl.DT_FP8E8M0, | ||
| 230 | + target_memory=pl.MemorySpace.ScaleRight, | ||
| 231 | +) | ||
| 232 | +``` | ||
| @@ -44,9 +44,9 @@ pypto_pro.language.TileType(shape, dtype, target_memory=pypto_pro.language.Memor | |||
| 44 | |---|---|---| | 44 | |---|---|---| |
| 45 | | `shape` | 输入 | 长度为2的编译期常量整数列表,各维大小须为正整数;仅支持二维Tile<br>对齐及分形布局约束由使用该TileType的具体API检查 | | 45 | | `shape` | 输入 | 长度为2的编译期常量整数列表,各维大小须为正整数;仅支持二维Tile<br>对齐及分形布局约束由使用该TileType的具体API检查 | |
| 46 | | `dtype` | 输入 | [`pypto_pro.language.DataType`](DataType.md)枚举值<br>常用:`pypto_pro.language.DT_FP16`、`pypto_pro.language.DT_FP32`、`pypto_pro.language.DT_BF16`、`pypto_pro.language.DT_INT8`、`pypto_pro.language.DT_INT32` | | 46 | | `dtype` | 输入 | [`pypto_pro.language.DataType`](DataType.md)枚举值<br>常用:`pypto_pro.language.DT_FP16`、`pypto_pro.language.DT_FP32`、`pypto_pro.language.DT_BF16`、`pypto_pro.language.DT_INT8`、`pypto_pro.language.DT_INT32` | |
| 47 | -| `target_memory` | 输入 | [`pypto_pro.language.MemorySpace`](MemorySpace.md)枚举值<br>默认`pypto_pro.language.MemorySpace.Vec`(UB)<br>可选:`Vec`(UB)、`Mat`(L1)、`Left`(L0A)、`Right`(L0B)、`Acc`(L0C)、`Scaling` | | 47 | +| `target_memory` | 输入 | [`pypto_pro.language.MemorySpace`](MemorySpace.md)枚举值<br>默认`pypto_pro.language.MemorySpace.Vec`(UB)<br>可选:`Vec`(UB)、`Mat`(L1)、`Left`(L0A)、`Right`(L0B)、`Acc`(L0C)、`Scaling`、`ScaleLeft`、`ScaleRight` | |
| 48 | | `valid_shape` | 输入 | 编译期常量整数列表或`None`(默认)<br>具体整数(如`[32, 64]`):编译期确定有效形状<br>`None`:后端缺省行为等同于`[-1, -1]`(动态模式)<br>`[-1, -1]`:运行时动态设置有效形状,配合[`pypto_pro.language.set_validshape`](../operation/memory_vector_computation/transpose_and_element_access/set_validshape.md)使用 | | 48 | | `valid_shape` | 输入 | 编译期常量整数列表或`None`(默认)<br>具体整数(如`[32, 64]`):编译期确定有效形状<br>`None`:后端缺省行为等同于`[-1, -1]`(动态模式)<br>`[-1, -1]`:运行时动态设置有效形状,配合[`pypto_pro.language.set_validshape`](../operation/memory_vector_computation/transpose_and_element_access/set_validshape.md)使用 | |
| 49 | -| `layout` | 输入 | [`pypto_pro.language.TensorLayout`](TensorLayout.md)枚举值或`None`(默认)<br>不指定时按“内存空间 + 架构”自动取默认值(见下表)<br>`Mat`、`Left`、`Right`、`Acc`、`Scaling`的非法组合在构造时即报`ValueError`;`Vec`的可用布局由具体Tile API约束 | | 49 | +| `layout` | 输入 | [`pypto_pro.language.TensorLayout`](TensorLayout.md)枚举值或`None`(默认)<br>不指定时按“内存空间 + 架构”自动取默认值(见下表)<br>`Mat`、`Left`、`Right`、`Acc`、`Scaling`、`ScaleLeft`、`ScaleRight`的非法组合在构造时即报`ValueError`;`Vec`的可用布局由具体Tile API约束 | |
| 50 | | `fractal` | 输入 | 整数或`None`(默认)<br>`Acc`的FP32/INT32在未指定时自动设为1024<br>显式值会写入Tile硬件信息,取值要求和适用场景由具体Tile API决定 | | 50 | | `fractal` | 输入 | 整数或`None`(默认)<br>`Acc`的FP32/INT32在未指定时自动设为1024<br>显式值会写入Tile硬件信息,取值要求和适用场景由具体Tile API决定 | |
| 51 | | `pad` | 输入 | [`pypto_pro.language.TilePad`](TilePad.md)枚举值或整数0-3<br>`null`(0)不填充 / `zero`(1)补零 / `max`(2)补最大值 / `min`(3)补最小值<br>非法值报`ValueError`,非法类型报`TypeError` | | 51 | | `pad` | 输入 | [`pypto_pro.language.TilePad`](TilePad.md)枚举值或整数0-3<br>`null`(0)不填充 / `zero`(1)补零 / `max`(2)补最大值 / `min`(3)补最小值<br>非法值报`ValueError`,非法类型报`TypeError` | |
| 52 | | `compact` | 输入 | `None`(默认)或整数`0`、`1`、`2`<br>`None`/`0`:null;`1`:normal;`2`:row_plus_one<br>是否需要设置以及支持哪种模式,由使用该TileType的具体API和硬件路径决定。详见[`CompactMode`](CompactMode.md) | | 52 | | `compact` | 输入 | `None`(默认)或整数`0`、`1`、`2`<br>`None`/`0`:null;`1`:normal;`2`:row_plus_one<br>是否需要设置以及支持哪种模式,由使用该TileType的具体API和硬件路径决定。详见[`CompactMode`](CompactMode.md) | |
| @@ -63,11 +63,15 @@ pypto_pro.language.TileType(shape, dtype, target_memory=pypto_pro.language.Memor | |||
| 63 | | `Right` | `pl.ZN` | `pl.ZN` | | 63 | | `Right` | `pl.ZN` | `pl.ZN` | |
| 64 | | `Acc` | `pl.NZ` | `pl.NZ` | | 64 | | `Acc` | `pl.NZ` | `pl.NZ` | |
| 65 | | `Scaling` | `pl.ND` | `pl.ND` | | 65 | | `Scaling` | `pl.ND` | `pl.ND` | |
| 66 | +| `ScaleLeft` | — | `pl.ZZ` | | ||
| 67 | +| `ScaleRight` | — | `pl.NN` | | ||
| 66 | 68 | ||
| 67 | 补充规则: | 69 | 补充规则: |
| 68 | 70 | ||
| 69 | - `Mat`除默认`pl.NZ`外,还允许`pl.ZN`;当`dtype`为`UINT64`或`INT64`时,额外允许`pl.ND` | 71 | - `Mat`除默认`pl.NZ`外,还允许`pl.ZN`;当`dtype`为`UINT64`或`INT64`时,额外允许`pl.ND` |
| 70 | - `Left`跨架构兼容,同时允许`pl.ZZ`(A3默认)和`pl.NZ`(A5默认) | 72 | - `Left`跨架构兼容,同时允许`pl.ZZ`(A3默认)和`pl.NZ`(A5默认) |
| 73 | +- `Mat`中的E8M0 scale允许`pl.ZZ`和`pl.NN`,未指定`fractal`时自动取32 | ||
| 74 | +- `ScaleLeft`和`ScaleRight`仅A5支持,分别用于A矩阵和B矩阵的E8M0 scale;未指定`fractal`时自动取32,Tile地址须按32字节对齐 | ||
| 71 | 75 | ||
| 72 | ## 调用示例 | 76 | ## 调用示例 |
| 73 | 77 | ||
| @@ -17,7 +17,7 @@ | |||
| 17 | `section_vector`创建Vector区域,`section_cube`创建Cube区域。区域中的操作分别下沉到向量核或矩阵核执行。 | 17 | `section_vector`创建Vector区域,`section_cube`创建Cube区域。区域中的操作分别下沉到向量核或矩阵核执行。 |
| 18 | 18 | ||
| 19 | - **`section_vector`**:用于UB(`MemorySpace.Vec`)tile上的向量计算,包括GM↔UB搬运(`load`/`store`)、逐元素运算、归约、转置等。 | 19 | - **`section_vector`**:用于UB(`MemorySpace.Vec`)tile上的向量计算,包括GM↔UB搬运(`load`/`store`)、逐元素运算、归约、转置等。 |
| 20 | -- **`section_cube`**:用于L1/L0A/L0B/L0C tile上的矩阵计算,包括GM→L1搬运(`load`)、L1→L0A/L0B搬运(`move`)、矩阵乘(`matmul`)、L0C→GM回写(`store`)。 | 20 | +- **`section_cube`**:用于涉及L1/L0A/L0B/L0C以及E8M0分组缩放因子Tile的矩阵计算,包括GM→L1搬运(`load`)、L1→L0A/L0B/ScaleLeft/ScaleRight搬运(`move`)、矩阵乘(`matmul`/`matmul_mx`)、L0C→GM回写(`store`)。 |
| 21 | 21 | ||
| 22 | 同一kernel中可先后使用多个`section_vector` / `section_cube`,例如先在Cube区域完成matmul,再在Vector区域对结果做逐元素激活。 | 22 | 同一kernel中可先后使用多个`section_vector` / `section_cube`,例如先在Cube区域完成matmul,再在Vector区域对结果做逐元素激活。 |
| 23 | 23 | ||
| @@ -6,6 +6,8 @@ | |||
| 6 | 6 | ||
| 7 | matmul | 7 | matmul |
| 8 | matmul_acc | 8 | matmul_acc |
| 9 | +matmul_mx | ||
| 10 | +matmul_mx_acc | ||
| 9 | phase | 11 | phase |
| 10 | set_mm_layout_transform | 12 | set_mm_layout_transform |
| 11 | ``` | 13 | ``` |
| @@ -0,0 +1,250 @@ | |||
| 1 | +# pypto_pro.language.matmul_mx | ||
| 2 | + | ||
| 3 | +## 产品支持情况 | ||
| 4 | + | ||
| 5 | +<!-- npu="950" id1 --> | ||
| 6 | + | ||
| 7 | +- Ascend 950PR/Ascend 950DT:支持 | ||
| 8 | + | ||
| 9 | +<!-- end id1 --> | ||
| 10 | + | ||
| 11 | +<!-- npu="A3" id2 --> | ||
| 12 | + | ||
| 13 | +- Atlas A3 训练系列产品/Atlas A3 推理系列产品:不支持 | ||
| 14 | + | ||
| 15 | +<!-- end id2 --> | ||
| 16 | + | ||
| 17 | +<!-- npu="910b" id3 --> | ||
| 18 | + | ||
| 19 | +- Atlas A2 训练系列产品/Atlas A2 推理系列产品:不支持 | ||
| 20 | + | ||
| 21 | +<!-- end id3 --> | ||
| 22 | + | ||
| 23 | +## 功能说明 | ||
| 24 | + | ||
| 25 | +完成一次带E8M0分组缩放因子的MX矩阵乘法: | ||
| 26 | + | ||
| 27 | +```text | ||
| 28 | +dst = dequant(lhs, scale_a) @ dequant(rhs, scale_b) | ||
| 29 | +``` | ||
| 30 | + | ||
| 31 | +MX(Microscaling)矩阵计算采用分组缩放:矩阵数据沿K方向每连续32个元素为一组,每组共享一个E8M0缩放因子,该缩放因子称为MX scale,取值为`2^(e8m0-127)`。 | ||
| 32 | + | ||
| 33 | +MXFP8尾数支持E4M3与E5M2,MXFP4尾数支持E2M1与E1M2。同一侧的两种格式可以交叉组合;MXFP8与MXFP4不能混合使用。 | ||
| 34 | + | ||
| 35 | +数据通路由Left(L0A)及其配套的ScaleLeft缓冲区、Right(L0B)及其配套的ScaleRight缓冲区共同参与,计算结果写入Acc(L0C)。K维分块的首块使用本接口,后续块使用[`matmul_mx_acc`](matmul_mx_acc.md)。 | ||
| 36 | + | ||
| 37 | +## 函数原型 | ||
| 38 | + | ||
| 39 | +```python | ||
| 40 | +pypto_pro.language.matmul_mx( | ||
| 41 | + dst_tile, lhs_tile, rhs_tile, scale_a, scale_b, *, phase=None | ||
| 42 | +) | ||
| 43 | +``` | ||
| 44 | + | ||
| 45 | +## 参数类型 | ||
| 46 | + | ||
| 47 | + | ||
| 48 | +| 参数 | 输入/输出 | 说明 | | ||
| 49 | +| ---------- | --------- | ------------------------------------------------------------- | | ||
| 50 | +| `dst_tile` | 输出 | Acc/L0C Tile,保存FP32计算结果 | | ||
| 51 | +| `lhs_tile` | 输入 | Left/L0A Tile,MXFP8或MXFP4左矩阵尾数 | | ||
| 52 | +| `rhs_tile` | 输入 | Right/L0B Tile,MXFP8或MXFP4右矩阵尾数 | | ||
| 53 | +| `scale_a` | 输入 | ScaleLeft Tile,A矩阵的E8M0 scale | | ||
| 54 | +| `scale_b` | 输入 | ScaleRight Tile,B矩阵的E8M0 scale | | ||
| 55 | +| `phase` | 输入 | 可选,K维分块时使用`pl.AccPhase.Partial`或`pl.AccPhase.Final` | | ||
| 56 | + | ||
| 57 | +## 参数范围 | ||
| 58 | + | ||
| 59 | + | ||
| 60 | +| 参数 | 约束 | | ||
| 61 | +| ---------- | -------------------------------------------------------------------------------------------------------------------- | | ||
| 62 | +| `dst_tile` | dtype必须为`DT_FP32`;shape为`[M,N]`;内存空间必须为`MemorySpace.Acc` | | ||
| 63 | +| `lhs_tile` | dtype为`DT_FP8E4M3FN`、`DT_FP8E5M2`、`DT_FP4E2M1`或`DT_FP4E1M2`;shape为`[M,K]`;内存空间必须为`MemorySpace.Left` | | ||
| 64 | +| `rhs_tile` | 与`lhs_tile`同属MXFP8组或MXFP4组;shape为`[K,N]`;内存空间必须为`MemorySpace.Right` | | ||
| 65 | +| `scale_a` | dtype必须为`DT_FP8E8M0`;shape为`[M,K/32]`;内存空间必须为`MemorySpace.ScaleLeft`,默认`layout=pl.ZZ`、`fractal=32` | | ||
| 66 | +| `scale_b` | dtype必须为`DT_FP8E8M0`;shape为`[K/32,N]`;内存空间必须为`MemorySpace.ScaleRight`,默认`layout=pl.NN`、`fractal=32` | | ||
| 67 | + | ||
| 68 | +补充约束: | ||
| 69 | + | ||
| 70 | +- `lhs_tile`的第二维与`rhs_tile`的第一维必须相等,即两者的K维必须一致;K必须为64的倍数。 | ||
| 71 | +- scale Tile的逻辑shape必须与配对数据Tile的MX分组一致:`scale_a.shape == [M,K/32]`,`scale_b.shape == [K/32,N]`。该约束按逻辑shape校验,不要使用Tile分配字节数代替。 | ||
| 72 | +- scale Tile与数据Tile必须满足硬件地址绑定: | ||
| 73 | + | ||
| 74 | + ```text | ||
| 75 | + addr(scale_a) = addr(lhs_tile) >> 4 | ||
| 76 | + addr(scale_b) = addr(rhs_tile) >> 4 | ||
| 77 | + ``` | ||
| 78 | + | ||
| 79 | + 该关系是强制约束,而非地址规划建议。MX矩阵指令根据Left/Right地址隐式定位scale;scale搬入了其他地址时,该指令仍会读取上述映射地址,导致计算结果错误。地址空间的详细说明见[`MemorySpace`](../../basic_data_structures/MemorySpace.md)。 | ||
| 80 | + | ||
| 81 | +GM中的scale使用普通`DT_FP8E8M0` ND Tensor,并直接声明打包后的实际shape,例如`[M,G/2,2]`或`[G/2,N,2]`。框架不识别或校验group/phase轴,只在`load`目标为fractal-32 ZZ/NN Mat Tile时,根据目标和`order`选择PTO MX layout。MXFP4尾数在GM中以两个4 bit元素打包为一个字节,因此ND Tensor的最后一维是逻辑元素数的一半;搬入后的L1/L0 Tile shape仍使用逻辑shape。FP4主数据场景仍可通过`set_stride`设置按逻辑FP4元素计算的stride。 | ||
| 82 | + | ||
| 83 | +## 调用示例 | ||
| 84 | + | ||
| 85 | +### MXFP8示例 | ||
| 86 | + | ||
| 87 | +下面计算一个不分K块的MXFP8矩阵乘法。A scale的逻辑shape为`[128,4]`,B scale为`[4,128]`,因为每个scale覆盖32个K方向元素。 | ||
| 88 | + | ||
| 89 | +```python | ||
| 90 | +import pypto_pro.language as pl | ||
| 91 | + | ||
| 92 | +TILE = 128 | ||
| 93 | +SCALE_K = TILE // 32 | ||
| 94 | + | ||
| 95 | + | ||
| 96 | +@pl.jit(auto_mutex=True) | ||
| 97 | +def mxfp8_matmul_kernel( | ||
| 98 | + a: pl.Tensor[[TILE, TILE], pl.DT_FP8E4M3FN], | ||
| 99 | + b: pl.Tensor[[TILE, TILE], pl.DT_FP8E5M2], | ||
| 100 | + scale_a: pl.Tensor[[TILE, SCALE_K // 2, 2], pl.DT_FP8E8M0], | ||
| 101 | + scale_b: pl.Tensor[[SCALE_K // 2, TILE, 2], pl.DT_FP8E8M0], | ||
| 102 | + out: pl.Tensor[[TILE, TILE], pl.DT_FP32], | ||
| 103 | +): | ||
| 104 | + a_l1 = pl.make_tile_group( | ||
| 105 | + type=pl.TileType(shape=[TILE, TILE], dtype=pl.DT_FP8E4M3FN, | ||
| 106 | + target_memory=pl.MemorySpace.Mat, | ||
| 107 | + layout=pl.NZ), | ||
| 108 | + addrs=0x00000, mutex_ids=[0]) | ||
| 109 | + b_l1 = pl.make_tile_group( | ||
| 110 | + type=pl.TileType(shape=[TILE, TILE], dtype=pl.DT_FP8E5M2, | ||
| 111 | + target_memory=pl.MemorySpace.Mat, | ||
| 112 | + layout=pl.NZ), | ||
| 113 | + addrs=0x10000, mutex_ids=[1]) | ||
| 114 | + sa_l1 = pl.make_tile_group( | ||
| 115 | + type=pl.TileType(shape=[TILE, SCALE_K], dtype=pl.DT_FP8E8M0, | ||
| 116 | + target_memory=pl.MemorySpace.Mat, | ||
| 117 | + layout=pl.ZZ), | ||
| 118 | + addrs=0x20000, mutex_ids=[2]) | ||
| 119 | + sb_l1 = pl.make_tile_group( | ||
| 120 | + type=pl.TileType(shape=[SCALE_K, TILE], dtype=pl.DT_FP8E8M0, | ||
| 121 | + target_memory=pl.MemorySpace.Mat, | ||
| 122 | + layout=pl.NN), | ||
| 123 | + addrs=0x21000, mutex_ids=[3]) | ||
| 124 | + a_l0 = pl.make_tile_group( | ||
| 125 | + type=pl.TileType(shape=[TILE, TILE], dtype=pl.DT_FP8E4M3FN, | ||
| 126 | + target_memory=pl.MemorySpace.Left, | ||
| 127 | + layout=pl.NZ), | ||
| 128 | + addrs=0x0000, mutex_ids=[4]) | ||
| 129 | + b_l0 = pl.make_tile_group( | ||
| 130 | + type=pl.TileType(shape=[TILE, TILE], dtype=pl.DT_FP8E5M2, | ||
| 131 | + target_memory=pl.MemorySpace.Right, | ||
| 132 | + layout=pl.ZN), | ||
| 133 | + addrs=0x0000, mutex_ids=[5]) | ||
| 134 | + sa_l0 = pl.make_tile_group( | ||
| 135 | + type=pl.TileType(shape=[TILE, SCALE_K], dtype=pl.DT_FP8E8M0, | ||
| 136 | + target_memory=pl.MemorySpace.ScaleLeft, | ||
| 137 | + layout=pl.ZZ), | ||
| 138 | + addrs=0x0000, mutex_ids=[6]) | ||
| 139 | + sb_l0 = pl.make_tile_group( | ||
| 140 | + type=pl.TileType(shape=[SCALE_K, TILE], dtype=pl.DT_FP8E8M0, | ||
| 141 | + target_memory=pl.MemorySpace.ScaleRight, | ||
| 142 | + layout=pl.NN), | ||
| 143 | + addrs=0x0000, mutex_ids=[7]) | ||
| 144 | + acc = pl.make_tile_group( | ||
| 145 | + type=pl.TileType(shape=[TILE, TILE], dtype=pl.DT_FP32, | ||
| 146 | + target_memory=pl.MemorySpace.Acc, | ||
| 147 | + layout=pl.NZ, fractal=1024), | ||
| 148 | + addrs=0x0000, mutex_ids=[8]) | ||
| 149 | + | ||
| 150 | + with pl.section_cube(): | ||
| 151 | + al1, bl1 = a_l1.current(), b_l1.current() | ||
| 152 | + sal1, sbl1 = sa_l1.current(), sb_l1.current() | ||
| 153 | + al0, bl0 = a_l0.current(), b_l0.current() | ||
| 154 | + sal0, sbl0 = sa_l0.current(), sb_l0.current() | ||
| 155 | + ac = acc.current() | ||
| 156 | + pl.load(al1, a, [0, 0]) | ||
| 157 | + pl.load(bl1, b, [0, 0]) | ||
| 158 | + pl.load(sal1, scale_a, [0, 0, 0], order=[0, 1]) | ||
| 159 | + pl.load(sbl1, scale_b, [0, 0, 0], order=[0, 1]) | ||
| 160 | + pl.move(al0, al1) | ||
| 161 | + pl.move(bl0, bl1) | ||
| 162 | + pl.move(sal0, sal1) | ||
| 163 | + pl.move(sbl0, sbl1) | ||
| 164 | + pl.matmul_mx(ac, al0, bl0, sal0, sbl0) | ||
| 165 | + pl.store(out, ac, [0, 0]) | ||
| 166 | +``` | ||
| 167 | + | ||
| 168 | +### MXFP4示例 | ||
| 169 | + | ||
| 170 | +MXFP4在GM中使用紧凑的4 bit存储:最后一维相邻两个逻辑元素打包为一个字节,第一个元素放在低4 bit,第二个元素放在高4 bit。因此,逻辑shape为`[M,K]`和`[K,N]`的A、B,在Tensor标注中分别写成`[M,K/2]`和`[K,N/2]`。L1及L0 Tile仍使用未压缩的逻辑shape,并通过`set_stride`把Tensor stride设置为按逻辑FP4元素计数。 | ||
| 171 | + | ||
| 172 | +下面使用E2M1左矩阵和E1M2右矩阵,计算一个MXFP4交叉格式矩阵乘: | ||
| 173 | + | ||
| 174 | +```python | ||
| 175 | +import pypto_pro.language as pl | ||
| 176 | + | ||
| 177 | +TILE = 128 | ||
| 178 | +SCALE_K = TILE // 32 | ||
| 179 | + | ||
| 180 | + | ||
| 181 | +@pl.jit(auto_mutex=True) | ||
| 182 | +def mxfp4_matmul_kernel( | ||
| 183 | + a: pl.Tensor[[TILE, TILE // 2], pl.DT_FP4E2M1], | ||
| 184 | + b: pl.Tensor[[TILE, TILE // 2], pl.DT_FP4E1M2], | ||
| 185 | + scale_a: pl.Tensor[[TILE, SCALE_K // 2, 2], pl.DT_FP8E8M0], | ||
| 186 | + scale_b: pl.Tensor[[SCALE_K // 2, TILE, 2], pl.DT_FP8E8M0], | ||
| 187 | + out: pl.Tensor[[TILE, TILE], pl.DT_FP32], | ||
| 188 | +): | ||
| 189 | + a_l1 = pl.make_tile_group( | ||
| 190 | + type=pl.TileType(shape=[TILE, TILE], dtype=pl.DT_FP4E2M1, | ||
| 191 | + target_memory=pl.MemorySpace.Mat, layout=pl.NZ), | ||
| 192 | + addrs=0x00000, mutex_ids=[0]) | ||
| 193 | + b_l1 = pl.make_tile_group( | ||
| 194 | + type=pl.TileType(shape=[TILE, TILE], dtype=pl.DT_FP4E1M2, | ||
| 195 | + target_memory=pl.MemorySpace.Mat, layout=pl.NZ), | ||
| 196 | + addrs=0x10000, mutex_ids=[1]) | ||
| 197 | + sa_l1 = pl.make_tile_group( | ||
| 198 | + type=pl.TileType(shape=[TILE, SCALE_K], dtype=pl.DT_FP8E8M0, | ||
| 199 | + target_memory=pl.MemorySpace.Mat, layout=pl.ZZ), | ||
| 200 | + addrs=0x20000, mutex_ids=[2]) | ||
| 201 | + sb_l1 = pl.make_tile_group( | ||
| 202 | + type=pl.TileType(shape=[SCALE_K, TILE], dtype=pl.DT_FP8E8M0, | ||
| 203 | + target_memory=pl.MemorySpace.Mat, layout=pl.NN), | ||
| 204 | + addrs=0x21000, mutex_ids=[3]) | ||
| 205 | + a_l0 = pl.make_tile_group( | ||
| 206 | + type=pl.TileType(shape=[TILE, TILE], dtype=pl.DT_FP4E2M1, | ||
| 207 | + target_memory=pl.MemorySpace.Left, layout=pl.NZ), | ||
| 208 | + addrs=0x0000, mutex_ids=[4]) | ||
| 209 | + b_l0 = pl.make_tile_group( | ||
| 210 | + type=pl.TileType(shape=[TILE, TILE], dtype=pl.DT_FP4E1M2, | ||
| 211 | + target_memory=pl.MemorySpace.Right, layout=pl.ZN), | ||
| 212 | + addrs=0x0000, mutex_ids=[5]) | ||
| 213 | + sa_l0 = pl.make_tile_group( | ||
| 214 | + type=pl.TileType(shape=[TILE, SCALE_K], dtype=pl.DT_FP8E8M0, | ||
| 215 | + target_memory=pl.MemorySpace.ScaleLeft, layout=pl.ZZ), | ||
| 216 | + addrs=0x0000, mutex_ids=[6]) | ||
| 217 | + sb_l0 = pl.make_tile_group( | ||
| 218 | + type=pl.TileType(shape=[SCALE_K, TILE], dtype=pl.DT_FP8E8M0, | ||
| 219 | + target_memory=pl.MemorySpace.ScaleRight, layout=pl.NN), | ||
| 220 | + addrs=0x0000, mutex_ids=[7]) | ||
| 221 | + acc = pl.make_tile_group( | ||
| 222 | + type=pl.TileType(shape=[TILE, TILE], dtype=pl.DT_FP32, | ||
| 223 | + target_memory=pl.MemorySpace.Acc, layout=pl.NZ, fractal=1024), | ||
| 224 | + addrs=0x0000, mutex_ids=[8]) | ||
| 225 | + | ||
| 226 | + with pl.section_cube(): | ||
| 227 | + # Tensor shape按打包字节声明,stride按逻辑FP4元素设置。 | ||
| 228 | + pl.set_stride(a, [TILE, 1]) | ||
| 229 | + pl.set_stride(b, [TILE, 1]) | ||
| 230 | + | ||
| 231 | + al1, bl1 = a_l1.current(), b_l1.current() | ||
| 232 | + sal1, sbl1 = sa_l1.current(), sb_l1.current() | ||
| 233 | + al0, bl0 = a_l0.current(), b_l0.current() | ||
| 234 | + sal0, sbl0 = sa_l0.current(), sb_l0.current() | ||
| 235 | + ac = acc.current() | ||
| 236 | + pl.load(al1, a, [0, 0]) | ||
| 237 | + pl.load(bl1, b, [0, 0]) | ||
| 238 | + pl.load(sal1, scale_a, [0, 0, 0], order=[0, 1]) | ||
| 239 | + pl.load(sbl1, scale_b, [0, 0, 0], order=[0, 1]) | ||
| 240 | + pl.move(al0, al1) | ||
| 241 | + pl.move(bl0, bl1) | ||
| 242 | + pl.move(sal0, sal1) | ||
| 243 | + pl.move(sbl0, sbl1) | ||
| 244 | + pl.matmul_mx(ac, al0, bl0, sal0, sbl0) | ||
| 245 | + pl.store(out, ac, [0, 0]) | ||
| 246 | +``` | ||
| 247 | + | ||
| 248 | +E2M1 × E2M1、E1M2 × E1M2以及E1M2 × E2M1的写法相同,只需替换A、B Tensor和对应L1/L0 Tile的dtype。scale始终使用`DT_FP8E8M0`。 | ||
| 249 | + | ||
| 250 | +同时使用多组L0 buffer时,每组scale地址都必须与对应数据地址满足“右移4位”的绑定关系。可参考仓库中的`test_matmul_mx.py`完整用例。 | ||
| @@ -0,0 +1,88 @@ | |||
| 1 | +# pypto_pro.language.matmul_mx_acc | ||
| 2 | + | ||
| 3 | +## 产品支持情况 | ||
| 4 | + | ||
| 5 | +<!-- npu="950" id1 --> | ||
| 6 | +- Ascend 950PR/Ascend 950DT:支持 | ||
| 7 | +<!-- end id1 --> | ||
| 8 | +<!-- npu="A3" id2 --> | ||
| 9 | +- Atlas A3 训练系列产品/Atlas A3 推理系列产品:不支持 | ||
| 10 | +<!-- end id2 --> | ||
| 11 | +<!-- npu="910b" id3 --> | ||
| 12 | +- Atlas A2 训练系列产品/Atlas A2 推理系列产品:不支持 | ||
| 13 | +<!-- end id3 --> | ||
| 14 | + | ||
| 15 | +## 功能说明 | ||
| 16 | + | ||
| 17 | +在已有FP32累加器上继续累加一次MX矩阵乘积: | ||
| 18 | + | ||
| 19 | +```text | ||
| 20 | +dst = acc + dequant(lhs, scale_a) @ dequant(rhs, scale_b) | ||
| 21 | +``` | ||
| 22 | + | ||
| 23 | +主要用于K维分块累加。首个K块使用[`matmul_mx`](matmul_mx.md),其余K块使用本接口,且每个K块必须加载与该块对应的A/B E8M0 scale。 | ||
| 24 | + | ||
| 25 | +## 函数原型 | ||
| 26 | + | ||
| 27 | +```python | ||
| 28 | +pypto_pro.language.matmul_mx_acc( | ||
| 29 | + dst_tile, acc_tile, lhs_tile, rhs_tile, scale_a, scale_b, *, phase=None | ||
| 30 | +) | ||
| 31 | +``` | ||
| 32 | + | ||
| 33 | +## 参数类型 | ||
| 34 | + | ||
| 35 | +| 参数 | 输入/输出 | 说明 | | ||
| 36 | +|---|---|---| | ||
| 37 | +| `dst_tile` | 输出 | Acc/L0C Tile,保存累加结果 | | ||
| 38 | +| `acc_tile` | 输入 | Acc/L0C Tile,已有的FP32累加值,通常与`dst_tile`为同一Tile | | ||
| 39 | +| `lhs_tile` | 输入 | Left/L0A Tile,当前K块的MXFP8或MXFP4左矩阵尾数 | | ||
| 40 | +| `rhs_tile` | 输入 | Right/L0B Tile,当前K块的MXFP8或MXFP4右矩阵尾数 | | ||
| 41 | +| `scale_a` | 输入 | ScaleLeft Tile,当前K块的A矩阵E8M0 scale | | ||
| 42 | +| `scale_b` | 输入 | ScaleRight Tile,当前K块的B矩阵E8M0 scale | | ||
| 43 | +| `phase` | 输入 | 可选,K维分块时使用`pl.AccPhase.Partial`或`pl.AccPhase.Final` | | ||
| 44 | + | ||
| 45 | +## 参数范围 | ||
| 46 | + | ||
| 47 | +数据类型、shape、内存空间、scale布局及K对齐要求与[`matmul_mx`](matmul_mx.md)一致,此外: | ||
| 48 | + | ||
| 49 | +- `dst_tile`与`acc_tile`必须为Acc/L0C中的FP32 Tile,shape均为`[M,N]`。 | ||
| 50 | +- 首个K块不能使用未初始化的`acc_tile`,应调用`matmul_mx`建立初始累加值。 | ||
| 51 | +- 每个K块的scale Tile都必须与当前数据Tile满足`addr(scale_a) = addr(lhs_tile) >> 4`和`addr(scale_b) = addr(rhs_tile) >> 4`。多缓冲轮转时,每一组数据/scale Tile都须分别满足该关系。 | ||
| 52 | +- 使用`phase`时,非末块传`pl.AccPhase.Partial`,末块传`pl.AccPhase.Final`;写回GM时配合`phase=pl.STPhase.Final`。 | ||
| 53 | + | ||
| 54 | +## 调用示例 | ||
| 55 | + | ||
| 56 | +下面展示K维循环的核心部分。各Tile的创建方式见[`matmul_mx`](matmul_mx.md)示例;其中数据Tile shape为`[TILE,TILE]`,scale Tile shape分别为`[TILE,TILE/32]`和`[TILE/32,TILE]`。 | ||
| 57 | + | ||
| 58 | +```python | ||
| 59 | +with pl.section_cube(): | ||
| 60 | + ac = acc.current() | ||
| 61 | + for ki in pl.range(0, K_SIZE, TILE): | ||
| 62 | + al1, bl1 = a_l1.next(), b_l1.next() | ||
| 63 | + sal1, sbl1 = sa_l1.next(), sb_l1.next() | ||
| 64 | + al0, bl0 = a_l0.next(), b_l0.next() | ||
| 65 | + sal0, sbl0 = sa_l0.next(), sb_l0.next() | ||
| 66 | + | ||
| 67 | + pl.load(al1, a, [0, ki]) | ||
| 68 | + pl.load(bl1, b, [ki, 0]) | ||
| 69 | + pl.load(sal1, scale_a, [0, ki // 64, 0], order=[0, 1]) | ||
| 70 | + pl.load(sbl1, scale_b, [ki // 64, 0, 0], order=[0, 1]) | ||
| 71 | + pl.move(al0, al1) | ||
| 72 | + pl.move(bl0, bl1) | ||
| 73 | + pl.move(sal0, sal1) | ||
| 74 | + pl.move(sbl0, sbl1) | ||
| 75 | + | ||
| 76 | + if ki == 0: | ||
| 77 | + pl.matmul_mx(ac, al0, bl0, sal0, sbl0, phase=pl.AccPhase.Partial) | ||
| 78 | + elif ki + TILE < K_SIZE: | ||
| 79 | + pl.matmul_mx_acc( | ||
| 80 | + ac, ac, al0, bl0, sal0, sbl0, phase=pl.AccPhase.Partial) | ||
| 81 | + else: | ||
| 82 | + pl.matmul_mx_acc( | ||
| 83 | + ac, ac, al0, bl0, sal0, sbl0, phase=pl.AccPhase.Final) | ||
| 84 | + | ||
| 85 | + pl.store(out, ac, [0, 0], phase=pl.STPhase.Final) | ||
| 86 | +``` | ||
| 87 | + | ||
| 88 | +如果K只有一个块,应直接调用`matmul_mx(..., phase=pl.AccPhase.Final)`,不调用`matmul_mx_acc`。 | ||
| @@ -14,11 +14,11 @@ | |||
| 14 | 14 | ||
| 15 | ## 功能说明 | 15 | ## 功能说明 |
| 16 | 16 | ||
| 17 | -`matmul` / `matmul_acc`的`phase`参数(`pl.AccPhase`)与`store` / `store_tile`的`phase`参数(`pl.STPhase`)共同控制Cube(矩阵乘)与FixPipe(L0C→GM搬运)之间的**unit_flag硬件握手**。正确使用phase可以省去软件同步、提升流水并行度;使用不当则会导致精度问题或设备卡死。 | 17 | +`matmul` / `matmul_acc` / `matmul_mx` / `matmul_mx_acc`的`phase`参数(`pl.AccPhase`)与`store` / `store_tile`的`phase`参数(`pl.STPhase`)共同控制Cube(矩阵乘)与FixPipe(L0C→GM搬运)之间的**unit_flag硬件握手**。正确使用phase可以省去软件同步、提升流水并行度;使用不当则会导致精度问题或设备卡死。 |
| 18 | 18 | ||
| 19 | ## 硬件unit_flag机制 | 19 | ## 硬件unit_flag机制 |
| 20 | 20 | ||
| 21 | -### matmul / matmul_acc(AccPhase) | 21 | +### matmul系列接口(AccPhase) |
| 22 | 22 | ||
| 23 | `phase=pl.AccPhase.Partial`或`phase=pl.AccPhase.Final`均会使能硬件的unitFlag功能: | 23 | `phase=pl.AccPhase.Partial`或`phase=pl.AccPhase.Final`均会使能硬件的unitFlag功能: |
| 24 | 24 | ||
| @@ -57,8 +57,8 @@ | |||
| 57 | 57 | ||
| 58 | 如果phase使用不当,可能会导致精度问题或者卡死现象。使用时必须保证: | 58 | 如果phase使用不当,可能会导致精度问题或者卡死现象。使用时必须保证: |
| 59 | 59 | ||
| 60 | -1. **配对使用**:如果`matmul`或`matmul_acc`使用了phase,对应的`store`或`store_tile`也需要使用phase。 | 60 | +1. **配对使用**:如果任一`matmul`系列接口使用了phase,对应的`store`或`store_tile`也需要使用phase。 |
| 61 | -2. **Final收尾**:对于同一块L0C,`matmul`或`matmul_acc`的最后一轮写操作,以及`store`或`store_tile`的最后一轮读操作,必须使用`Final`模式。 | 61 | +2. **Final收尾**:对于同一块L0C,`matmul`系列接口的最后一轮写操作,以及`store`或`store_tile`的最后一轮读操作,必须使用`Final`模式。 |
| 62 | 62 | ||
| 63 | ## 错误案例 | 63 | ## 错误案例 |
| 64 | 64 | ||
| @@ -37,10 +37,10 @@ pypto_pro.language.load(dst_tile, src_tensor, offsets, *, order=None) | |||
| 37 | 37 | ||
| 38 | | 参数 | 输入/输出 | 说明 | | 38 | | 参数 | 输入/输出 | 说明 | |
| 39 | |---|---|---| | 39 | |---|---|---| |
| 40 | -| `dst_tile` | 输出 | 数据类型:b8、b16、b32、b64<br>尾块处理:<br>• 可通过set_validshape设置尾块大小,Tile shape需要32字节对齐,不对齐报错<br>• valid_shape可以不对齐<br>• Vec ND尾块不需要配置compact;涉及紧凑排列、分形转换或Cube计算时,按对应数据路径配置compact = 1,详见[`CompactMode`](../../basic_data_structures/CompactMode.md)和[尾块处理](../../../../tutorials/operator_development/tile_based_python_programming/tail_block_handling.md)<br>• 支持设定padding值<br>地址配置:<br>• 作为`load`目的Tile时,只支持`Mat`(L1)和`Vec`(UB);`Left`(L0A)、`Right`(L0B)、`Acc`(L0C)和`Scaling`等其他Tile内存空间由`move`、`matmul`或`store`等对应接口使用<br>• Cube侧目的Tile必须为`Mat`(L1),Vector侧目的Tile必须为`Vec`(UB)<br>• L1、UB缓冲区首地址必须32字节对齐,不对齐编译报错 | | 40 | +| `dst_tile` | 输出 | 数据类型:b8、b16、b32、b64<br>尾块处理:<br>• 可通过set_validshape设置尾块大小,Tile shape需要32字节对齐,不对齐报错<br>• valid_shape可以不对齐<br>• Vec ND尾块不需要配置compact;涉及紧凑排列、分形转换或Cube计算时,按对应数据路径配置compact = 1,详见[`CompactMode`](../../basic_data_structures/CompactMode.md)和[尾块处理](../../../../tutorials/operator_development/tile_based_python_programming/tail_block_handling.md)<br>• 支持设定padding值<br>地址配置:<br>• 作为`load`目的Tile时,只支持`Mat`(L1)和`Vec`(UB);`Left`(L0A)、`Right`(L0B)、`Acc`(L0C)、`Scaling`、`ScaleLeft`、`ScaleRight`等其他Tile内存空间由`move`、`matmul`或`store`等对应接口使用<br>• Cube侧目的Tile必须为`Mat`(L1),Vector侧目的Tile必须为`Vec`(UB);MX scale的E8M0 Tile先load到`Mat`(L1)的ZZ/NN layout Tile,再通过`move`搬入`ScaleLeft`/`ScaleRight`<br>• L1、UB缓冲区首地址必须32字节对齐,不对齐编译报错 | |
| 41 | | `src_tensor` | 输入 | 数据类型:b8、b16、b32、b64<br>layout:支持`ND`、`DN`、`NZ`<br>stride:支持配置stride,stride维度需要等于Tensor维度数,默认不配置时是尾轴stride = 1的连续场景 | | 41 | | `src_tensor` | 输入 | 数据类型:b8、b16、b32、b64<br>layout:支持`ND`、`DN`、`NZ`<br>stride:支持配置stride,stride维度需要等于Tensor维度数,默认不配置时是尾轴stride = 1的连续场景 | |
| 42 | | `offsets` | 输入 | 单位元素个数,大小不超过对应维度的shape,不支持负数索引 | | 42 | | `offsets` | 输入 | 单位元素个数,大小不超过对应维度的shape,不支持负数索引 | |
| 43 | -| `order` | 输入 | 只支持配置Tensor维度范围内的dim,只支持二维数组配置,其余配置报错<br>用于高维Tensor中指定Tile对应哪几个维度;order中轴索引的顺序决定是否转置:升序不转置(ND行主序),反序转置(DN列主序),需要配合Tensor的layout以及Tile的shape和stride填写<br>省略时默认取Tensor的最后两维`[ndim-2, ndim-1]`(不转置) | | 43 | +| `order` | 输入 | 只支持配置Tensor维度范围内的dim,只支持二维数组配置,其余配置报错<br>用于高维Tensor中指定Tile对应哪几个维度;order中轴索引的顺序决定是否转置:升序不转置(ND行主序),反序转置(DN列主序),需要配合Tensor的layout以及Tile的shape和stride填写<br>E8M0搬入fractal-32 ZZ/NN Tile时分别选择A/B scale layout,框架不从shape判断group/phase轴;最后一轴固定作为物理phase轴,不能在`order`中选择<br>省略时,普通Tensor默认取最后两维`[ndim-2, ndim-1]`;带物理尾轴的MX scale默认取尾轴前两维`[ndim-3, ndim-2]`,其他多维结构应显式指定两个矩阵轴 | |
| 44 | 44 | ||
| 45 | ## 流水类型 | 45 | ## 流水类型 |
| 46 | 46 | ||
| @@ -48,6 +48,8 @@ MTE2(GM → L1/UB的搬入流水)。 | |||
| 48 | 48 | ||
| 49 | ## 约束说明 | 49 | ## 约束说明 |
| 50 | 50 | ||
| 51 | +当前`DT_FP8E8M0` Tensor搬入`fractal=32`的`ZZ`/`NN` Mat(L1)Tile,仅支持作为`matmul_mx`/`matmul_mx_acc`的scale搬运。普通E8M0数据不支持使用该目标组合;满足该组合的`load`会按MX scale解释,并要求源Tensor的最后一轴是长度为2的物理phase轴。 | ||
| 52 | + | ||
| 51 | 开启`auto_mutex`时,若连续两次`pl.load`向同一个UB(或L1)Tile地址搬运数据,并且前一次搬入的数据没有被读取,则必须在两次`load`之间调用`pl.system.bar_mte2()`,再复用该地址。 | 53 | 开启`auto_mutex`时,若连续两次`pl.load`向同一个UB(或L1)Tile地址搬运数据,并且前一次搬入的数据没有被读取,则必须在两次`load`之间调用`pl.system.bar_mte2()`,再复用该地址。 |
| 52 | 54 | ||
| 53 | 关于复用Tile地址的完整同步规则,请参考下文“Tile地址复用与流水同步”。 | 55 | 关于复用Tile地址的完整同步规则,请参考下文“Tile地址复用与流水同步”。 |
| @@ -39,10 +39,10 @@ pypto_pro.language.load_tile(dst_tile, src_tensor, tile_offsets, *, order=None) | |||
| 39 | 39 | ||
| 40 | | 参数 | 输入/输出 | 说明 | | 40 | | 参数 | 输入/输出 | 说明 | |
| 41 | |---|---|---| | 41 | |---|---|---| |
| 42 | -| `dst_tile` | 输出 | 数据类型:b8、b16、b32、b64<br>尾块处理:<br>• 可通过set_validshape设置尾块大小,Tile shape需要32字节对齐,不对齐报错<br>• valid_shape可以不对齐<br>• Vec ND尾块不需要配置compact;涉及紧凑排列、分形转换或Cube计算时,按对应数据路径配置compact = 1,详见[`CompactMode`](../../basic_data_structures/CompactMode.md)和[尾块处理](../../../../tutorials/operator_development/tile_based_python_programming/tail_block_handling.md)<br>• 支持设定padding值<br>地址配置:<br>• 作为`load_tile`目的Tile时,只支持`Mat`(L1)和`Vec`(UB);`Left`(L0A)、`Right`(L0B)、`Acc`(L0C)和`Scaling`等其他Tile内存空间由`move`、`matmul`或`store`等对应接口使用<br>• Cube侧目的Tile必须为`Mat`(L1),Vector侧目的Tile必须为`Vec`(UB)<br>• L1、UB缓冲区首地址必须32字节对齐,不对齐编译报错 | | 42 | +| `dst_tile` | 输出 | 数据类型:b8、b16、b32、b64<br>尾块处理:<br>• 可通过set_validshape设置尾块大小,Tile shape需要32字节对齐,不对齐报错<br>• valid_shape可以不对齐<br>• Vec ND尾块不需要配置compact;涉及紧凑排列、分形转换或Cube计算时,按对应数据路径配置compact = 1,详见[`CompactMode`](../../basic_data_structures/CompactMode.md)和[尾块处理](../../../../tutorials/operator_development/tile_based_python_programming/tail_block_handling.md)<br>• 支持设定padding值<br>地址配置:<br>• 作为`load_tile`目的Tile时,只支持`Mat`(L1)和`Vec`(UB);`Left`(L0A)、`Right`(L0B)、`Acc`(L0C)、`Scaling`、`ScaleLeft`、`ScaleRight`等其他Tile内存空间由`move`、`matmul`或`store`等对应接口使用<br>• Cube侧目的Tile必须为`Mat`(L1),Vector侧目的Tile必须为`Vec`(UB);MX scale的E8M0 Tile先load到`Mat`(L1)的ZZ/NN layout Tile,再通过`move`搬入`ScaleLeft`/`ScaleRight`<br>• L1、UB缓冲区首地址必须32字节对齐,不对齐编译报错 | |
| 43 | | `src_tensor` | 输入 | 数据类型:b8、b16、b32、b64<br>layout:支持`ND`、`DN`、`NZ`<br>stride:支持配置stride,stride维度需要等于Tensor维度数,默认不配置时是尾轴stride = 1的连续场景 | | 43 | | `src_tensor` | 输入 | 数据类型:b8、b16、b32、b64<br>layout:支持`ND`、`DN`、`NZ`<br>stride:支持配置stride,stride维度需要等于Tensor维度数,默认不配置时是尾轴stride = 1的连续场景 | |
| 44 | | `tile_offsets` | 输入 | 单位为Tile块索引,换算后的绝对偏移不超过对应维度的shape,不支持负数索引<br>被切分的维度(由`order`指定)按`块索引 × tile该维大小`换算;其余维度的取值按绝对偏移直接使用 | | 44 | | `tile_offsets` | 输入 | 单位为Tile块索引,换算后的绝对偏移不超过对应维度的shape,不支持负数索引<br>被切分的维度(由`order`指定)按`块索引 × tile该维大小`换算;其余维度的取值按绝对偏移直接使用 | |
| 45 | -| `order` | 输入 | 只支持配置Tensor维度范围内的dim,只支持二维数组配置,其余配置报错<br>用于高维Tensor中指定Tile对应哪几个维度;order中轴索引的顺序决定是否转置:升序不转置(ND行主序),反序转置(DN列主序),需要配合Tensor的layout以及Tile的shape和stride填写<br>省略时默认取Tensor的最后两维`[ndim-2, ndim-1]`(不转置) | | 45 | +| `order` | 输入 | 只支持配置Tensor维度范围内两个互不重复的dim<br>每个元素按顺序表示对应Tile轴在Tensor中的绝对轴索引;升序为ND,反序为DN<br>E8M0搬入fractal-32 ZZ/NN Tile时,最后一轴固定作为物理phase轴,不能在`order`中选择;MX scale应显式指定两个矩阵轴<br>省略时默认取Tensor的最后两维`[ndim-2, ndim-1]`(不转置) | |
| 46 | 46 | ||
| 47 | ## 流水类型 | 47 | ## 流水类型 |
| 48 | 48 | ||
| @@ -50,6 +50,8 @@ MTE2(GM → L1/UB的搬入流水)。 | |||
| 50 | 50 | ||
| 51 | ## 约束说明 | 51 | ## 约束说明 |
| 52 | 52 | ||
| 53 | +当前`DT_FP8E8M0` Tensor搬入`fractal=32`的`ZZ`/`NN` Mat(L1)Tile,仅支持作为`matmul_mx`/`matmul_mx_acc`的scale搬运。普通E8M0数据不支持使用该目标组合;满足该组合的`load_tile`会按MX scale解释,并要求源Tensor的最后一轴是长度为2的物理phase轴。 | ||
| 54 | + | ||
| 53 | 开启`auto_mutex`时,若连续两次`pl.load_tile`向同一个UB(或L1)Tile地址搬运数据,并且前一次搬入的数据没有被读取,则必须在两次`load_tile`之间调用`pl.system.bar_mte2()`,再复用该地址。 | 55 | 开启`auto_mutex`时,若连续两次`pl.load_tile`向同一个UB(或L1)Tile地址搬运数据,并且前一次搬入的数据没有被读取,则必须在两次`load_tile`之间调用`pl.system.bar_mte2()`,再复用该地址。 |
| 54 | 56 | ||
| 55 | `load_tile`复用Tile地址的同步规则与`load`接口一致;详细说明请参考[`load`](load.md)文档中的“Tile地址复用与流水同步”。 | 57 | `load_tile`复用Tile地址的同步规则与`load`接口一致;详细说明请参考[`load`](load.md)文档中的“Tile地址复用与流水同步”。 |
| @@ -14,7 +14,7 @@ | |||
| 14 | 14 | ||
| 15 | ## 功能说明 | 15 | ## 功能说明 |
| 16 | 16 | ||
| 17 | -在L1、L0A/L0B、L0C、UB等各级内存之间搬运tile(如L1→L0A/L0B、L0C(Acc)→UB(Vec)、UB→L1等)。具体走哪条硬件搬运通路、用哪条流水,由**源与目的tile的内存空间**决定。 | 17 | +在L1、L0A/L0B、L0C、UB等各级内存之间搬运tile(如L1→L0A/L0B、L1→ScaleLeft/ScaleRight、L0C(Acc)→UB(Vec)、UB→L1等)。具体走哪条硬件搬运通路、用哪条流水,由**源与目的tile的内存空间**决定。 |
| 18 | 18 | ||
| 19 | 可在搬运的同时融合ReLU、预量化,或经fixpipe做量化(`scale`);也可通过`offset`从一块较宽的源tile中提取子块(对应后端`pto::TEXTRACT`)。 | 19 | 可在搬运的同时融合ReLU、预量化,或经fixpipe做量化(`scale`);也可通过`offset`从一块较宽的源tile中提取子块(对应后端`pto::TEXTRACT`)。 |
| 20 | 20 | ||
| @@ -40,7 +40,7 @@ pypto_pro.language.move(dst_tile, src_tile, offset=None, *, acc_to_vec_mode=None | |||
| 40 | | `offset` | 输入 | 可选,`[offset_m, offset_k]`;源tile不小于目的tile时为提取子块(TEXTRACT),源tile为目的tile的子块时自动转为嵌入(TINSERT,见功能说明) | | 40 | | `offset` | 输入 | 可选,`[offset_m, offset_k]`;源tile不小于目的tile时为提取子块(TEXTRACT),源tile为目的tile的子块时自动转为嵌入(TINSERT,见功能说明) | |
| 41 | | `acc_to_vec_mode` | 输入 | 可选,Acc→Vec搬运模式 | | 41 | | `acc_to_vec_mode` | 输入 | 可选,Acc→Vec搬运模式 | |
| 42 | | `relu_pre_mode` | 输入 | 可选,搬运时融合ReLU | | 42 | | `relu_pre_mode` | 输入 | 可选,搬运时融合ReLU | |
| 43 | -| `scale` | 输入 | 可选,随路量化比例(deqScalar / deqTensor路径) | | 43 | +| `scale` | 输入 | 可选,随路量化比例(deqScalar / deqTensor路径) | |
| 44 | 44 | ||
| 45 | ## 参数范围 | 45 | ## 参数范围 |
| 46 | 46 | ||
| @@ -51,7 +51,7 @@ pypto_pro.language.move(dst_tile, src_tile, offset=None, *, acc_to_vec_mode=None | |||
| 51 | | `offset` | 输入 | 二维`[offset_m, offset_k]`,单位为元素个数<br>**TEXTRACT(源≥目的)**:以源tile声明的物理`shape`为坐标系;`valid_shape`不改变offset的坐标原点和计量单位,每一维须满足`0 <= offset < src_tile.shape`<br>实际提取范围为`[offset, offset + dst_tile.valid_shape)`。使用尾块时,完整的`dst_tile.shape`可以超出offset后的剩余范围,但实际提取范围不得超出`src_tile.shape`;若源tile设置了更小的`valid_shape`,实际提取范围还须位于该有效区域内<br>**TINSERT(源<目的,自动转insert)**:改以目的tile为坐标系,须满足`offset[0] + src行数≤ dst行数`、`offset[1] + src列数≤ dst列数`,否则越界 | | 51 | | `offset` | 输入 | 二维`[offset_m, offset_k]`,单位为元素个数<br>**TEXTRACT(源≥目的)**:以源tile声明的物理`shape`为坐标系;`valid_shape`不改变offset的坐标原点和计量单位,每一维须满足`0 <= offset < src_tile.shape`<br>实际提取范围为`[offset, offset + dst_tile.valid_shape)`。使用尾块时,完整的`dst_tile.shape`可以超出offset后的剩余范围,但实际提取范围不得超出`src_tile.shape`;若源tile设置了更小的`valid_shape`,实际提取范围还须位于该有效区域内<br>**TINSERT(源<目的,自动转insert)**:改以目的tile为坐标系,须满足`offset[0] + src行数≤ dst行数`、`offset[1] + src列数≤ dst列数`,否则越界 | |
| 52 | | `acc_to_vec_mode` | 输入 | 取`pl.AccToVecMode.SingleModeVec0`/`pl.AccToVecMode.SingleModeVec1`/`pl.AccToVecMode.DualModeSplitM`/`pl.AccToVecMode.DualModeSplitN`;仅在源为`Acc`、目的为`Vec`时有意义。`scale`为`Tile`(per-channel)时只支持单vec模式(`DualModeSplitM`/`DualModeSplitN`报错) | | 52 | | `acc_to_vec_mode` | 输入 | 取`pl.AccToVecMode.SingleModeVec0`/`pl.AccToVecMode.SingleModeVec1`/`pl.AccToVecMode.DualModeSplitM`/`pl.AccToVecMode.DualModeSplitN`;仅在源为`Acc`、目的为`Vec`时有意义。`scale`为`Tile`(per-channel)时只支持单vec模式(`DualModeSplitM`/`DualModeSplitN`报错) | |
| 53 | | `relu_pre_mode` | 输入 | 默认`None`(不融合ReLU);可取`pl.ReluPreMode.NormalRelu` | | 53 | | `relu_pre_mode` | 输入 | 默认`None`(不融合ReLU);可取`pl.ReluPreMode.NormalRelu` | |
| 54 | -| `scale` | 输入 | 可选,随路量化比例:`float`(编译期标量)→ per-tensor量化;运行时`FP32`标量→自动重解释为IEEE-754位模式;运行时`INT`标量→须传预编码的float32位模式(`struct.pack("!f", v)`);`Tile`(INT64、`MemorySpace.Scaling`、shape `[1, N]`)→ per-channel量化(`move_fp`路径),用户预制deqTensor tile,框架直接复用(不自动分配/同步,用户负责load→move→sync(MTE1→FIX)),只支持单vec模式;`Tensor`不支持(per-channel须以`Tile`传入) | | 54 | +| `scale` | 输入 | 可选,随路量化比例:`float`(编译期标量)→ per-tensor量化;运行时`FP32`标量→自动重解释为IEEE-754位模式;运行时`INT`标量→须传预编码的float32位模式(`struct.pack("!f", v)`);`Tile`(INT64、`MemorySpace.Scaling`、shape `[1, N]`)→ per-channel量化(`move_fp`路径),用户预制deqTensor tile,框架直接复用(不自动分配/同步,用户负责load→move→sync(MTE1→FIX)),只支持单vec模式;`Tensor`不支持(per-channel须以`Tile`传入) | |
| 55 | 55 | ||
| 56 | ## 流水类型 | 56 | ## 流水类型 |
| 57 | 57 | ||
| @@ -61,11 +61,15 @@ pypto_pro.language.move(dst_tile, src_tile, offset=None, *, acc_to_vec_mode=None | |||
| 61 | |---|---| | 61 | |---|---| |
| 62 | | Acc(L0C) → Vec(UB) | FIX(fixpipe) | | 62 | | Acc(L0C) → Vec(UB) | FIX(fixpipe) | |
| 63 | | Mat(L1) → Left/Right(L0A/L0B) | MTE1 | | 63 | | Mat(L1) → Left/Right(L0A/L0B) | MTE1 | |
| 64 | +| Mat(L1) → ScaleLeft/ScaleRight | MTE1 | | ||
| 64 | | Mat(L1) → Vec(UB) | V | | 65 | | Mat(L1) → Vec(UB) | V | |
| 65 | | Mat(L1) → 其他 | FIX | | 66 | | Mat(L1) → 其他 | FIX | |
| 66 | | Vec(UB) → Mat(L1) | MTE3 | | 67 | | Vec(UB) → Mat(L1) | MTE3 | |
| 67 | | 其余 | V | | 68 | | 其余 | V | |
| 68 | 69 | ||
| 70 | +> [!NOTE]说明 | ||
| 71 | +> `Mat` → `ScaleLeft`/`ScaleRight`的`move`仅按目的Tile地址执行搬运,不会根据配对的Left/Right Tile自动修正地址。目的scale Tile必须预先满足`addr(ScaleLeft) = addr(Left) >> 4`或`addr(ScaleRight) = addr(Right) >> 4`;否则MX矩阵指令会读取错误的scale。 | ||
| 72 | + | ||
| 69 | ## 调用示例 | 73 | ## 调用示例 |
| 70 | 74 | ||
| 71 | 下面是一个完整matmul kernel:`pypto_pro.language.load`把左右矩阵从GM载入L1,`pypto_pro.language.move`再把L1数据搬到L0A/L0B供cube计算——`move`在此承担L1→L0A/L0B这一步。cube kernel开`auto_mutex`,同步由`make_tile_group`自动管理。 | 75 | 下面是一个完整matmul kernel:`pypto_pro.language.load`把左右矩阵从GM载入L1,`pypto_pro.language.move`再把L1数据搬到L0A/L0B供cube计算——`move`在此承担L1→L0A/L0B这一步。cube kernel开`auto_mutex`,同步由`make_tile_group`自动管理。 |
| @@ -41,7 +41,7 @@ pypto_pro.language.make_tile(tile_type, *, addr, size=None) -> tile | |||
| 41 | | 参数 | 输入/输出 | 说明 | | 41 | | 参数 | 输入/输出 | 说明 | |
| 42 | |---|---|---| | 42 | |---|---|---| |
| 43 | | `tile_type` | 输入 | 须为[`pypto_pro.language.TileType`](../../basic_data_structures/TileType.md),其内存空间决定该tile能用于哪些接口(如Left/Right用于matmul输入,Acc用于matmul输出) | | 43 | | `tile_type` | 输入 | 须为[`pypto_pro.language.TileType`](../../basic_data_structures/TileType.md),其内存空间决定该tile能用于哪些接口(如Left/Right用于matmul输入,Acc用于matmul输出) | |
| 44 | -| `addr` | 输入 | 内存空间内的字节偏移,必选,且须为编译期常量<br>须以关键字传入(`addr=`):与`size`同为两个裸整数时顺序无法自证,写反会把Tile放到错误地址<br>对齐要求:`Vec`(UB)和`Mat`(L1)为32字节,`Left`(L0A)和`Right`(L0B)为512字节,`Acc`(L0C)为64字节 | | 44 | +| `addr` | 输入 | 内存空间内的字节偏移,必选,且须为编译期常量<br>须以关键字传入(`addr=`):与`size`同为两个裸整数时顺序无法自证,写反会把Tile放到错误地址<br>对齐要求:`Vec`(UB)和`Mat`(L1)为32字节,`Left`(L0A)和`Right`(L0B)为512字节,`Acc`(L0C)为64字节,`ScaleLeft`/`ScaleRight`为32字节<br>创建MX scale Tile时不能独立规划地址:`ScaleLeft` Tile地址必须等于配对`Left` Tile地址右移4位,`ScaleRight`与`Right`同理 | |
| 45 | | `size` | 输入 | 与`addr`对应的地址范围大小,单位为字节,须为编译期正整数<br>缺省时按“元素数 × dtype字节数”从`TileType`的shape和dtype推导,例如`[64, 128]`的FP16 Tile为16384字节,与[`make_tile_group`](make_tile_group.md)的每槽大小一致<br>仅当实际占用大于该值时才需显式指定,例如NZ/ZN排布按分形向上对齐后需要预留更多空间 | | 45 | | `size` | 输入 | 与`addr`对应的地址范围大小,单位为字节,须为编译期正整数<br>缺省时按“元素数 × dtype字节数”从`TileType`的shape和dtype推导,例如`[64, 128]`的FP16 Tile为16384字节,与[`make_tile_group`](make_tile_group.md)的每槽大小一致<br>仅当实际占用大于该值时才需显式指定,例如NZ/ZN排布按分形向上对齐后需要预留更多空间 | |
| 46 | 46 | ||
| 47 | ## 调用示例 | 47 | ## 调用示例 |
| @@ -54,6 +54,15 @@ pypto_pro.language.make_tile_group(type=, addrs=, mutex_ids=None, depth=None) -> | |||
| 54 | | `depth` | 输入 | 正的编译期整数。非空`mutex_ids`未指定时由其长度推导;两者同时指定时必须相等 | | 54 | | `depth` | 输入 | 正的编译期整数。非空`mutex_ids`未指定时由其长度推导;两者同时指定时必须相等 | |
| 55 | 55 | ||
| 56 | ## 补充说明 | 56 | ## 补充说明 |
| 57 | + | ||
| 58 | +为MX多缓冲创建`ScaleLeft`/`ScaleRight` group时,scale地址列表必须与配对数据地址列表逐项绑定: | ||
| 59 | + | ||
| 60 | +```text | ||
| 61 | +scale_left_addrs[i] = left_addrs[i] >> 4 | ||
| 62 | +scale_right_addrs[i] = right_addrs[i] >> 4 | ||
| 63 | +``` | ||
| 64 | + | ||
| 65 | +例如,`Left` group的`addrs=[0x0000, 0x8000]`时,配对`ScaleLeft` group必须使用`addrs=[0x0000, 0x0800]`。不满足该关系时,scale会被搬到MX矩阵指令不会为该数据Tile读取的地址,导致计算结果错误。 | ||
| 57 | 66 | ||
| 58 | 返回一个group句柄,提供三个方法和下标形式取出裸Tile。配置非空`mutex_ids`时,Tile与mutex的映射会随返回值保留,供`auto_mutex`使用: | 67 | 返回一个group句柄,提供三个方法和下标形式取出裸Tile。配置非空`mutex_ids`时,Tile与mutex的映射会随返回值保留,供`auto_mutex`使用: |
| 59 | 68 | ||
| @@ -341,6 +341,10 @@ def kernel(..., | |||
| 341 | pl.matmul(acc_tile, a_left, b_right) # C = A × B | 341 | pl.matmul(acc_tile, a_left, b_right) # C = A × B |
| 342 | ``` | 342 | ``` |
| 343 | 343 | ||
| 344 | +### MXFP8/MXFP4矩阵乘 | ||
| 345 | + | ||
| 346 | +MX矩阵乘使用`pl.matmul_mx`/`pl.matmul_mx_acc`,除Left/Right尾数Tile外,还需要分别位于L0A配套ScaleLeft缓冲区和L0B配套ScaleRight缓冲区的E8M0 scale Tile。每个scale对应K方向连续32个尾数元素,K必须为64的倍数。MXFP8支持E4M3/E5M2,MXFP4支持E2M1/E1M2;完整参数约束、scale Tensor布局和调用示例参见[`matmul_mx`](../../../api/SIMD-API/operation/matrix_computation/matmul_mx.md)和[`matmul_mx_acc`](../../../api/SIMD-API/operation/matrix_computation/matmul_mx_acc.md)。 | ||
| 347 | + | ||
| 344 | ### K维分块累加 | 348 | ### K维分块累加 |
| 345 | 349 | ||
| 346 | 当K维度较大,无法一次装入L1/L0时,需要将K轴切分为多个分块,逐块累加。首块用`pl.matmul`写入累加器,其余块用[`pl.matmul_acc`](../../../api/SIMD-API/operation/matrix_computation/matmul_acc.md)累加到同一个L0C。 | 350 | 当K维度较大,无法一次装入L1/L0时,需要将K轴切分为多个分块,逐块累加。首块用`pl.matmul`写入累加器,其余块用[`pl.matmul_acc`](../../../api/SIMD-API/operation/matrix_computation/matmul_acc.md)累加到同一个L0C。 |
| @@ -9,7 +9,7 @@ PyPTO Pro中有三种核心数据抽象: | |||
| 9 | | 抽象 | 所在位置 | 创建方式 | 用途 | | 9 | | 抽象 | 所在位置 | 创建方式 | 用途 | |
| 10 | |:---|:---|:---|:---| | 10 | |:---|:---|:---|:---| |
| 11 | | **Tensor** | 全局内存(GM) | [`pl.Tensor[...]`](../../../api/SIMD-API/basic_data_structures/Tensor.md) / [`pl.make_tensor`](../../../api/SIMD-API/operation/resource_management/make_tensor.md) | 带shape和stride的GM Tensor视图 | | 11 | | **Tensor** | 全局内存(GM) | [`pl.Tensor[...]`](../../../api/SIMD-API/basic_data_structures/Tensor.md) / [`pl.make_tensor`](../../../api/SIMD-API/operation/resource_management/make_tensor.md) | 带shape和stride的GM Tensor视图 | |
| 12 | -| **Tile** | 片上缓冲区 | [`pl.make_tile`](../../../api/SIMD-API/operation/resource_management/make_tile.md) | 固定的片上缓冲区(Vec / Mat / Left / Right / Acc / Scaling) | | 12 | +| **Tile** | 片上缓冲区 | [`pl.make_tile`](../../../api/SIMD-API/operation/resource_management/make_tile.md) | 固定的片上缓冲区(Vec / Mat / Left / Right / Acc / Scaling / ScaleLeft / ScaleRight) | |
| 13 | | **TileGroup** | 片上缓冲区 | [`pl.make_tile_group`](../../../api/SIMD-API/operation/resource_management/make_tile_group.md) | 一组轮转的Tile,用于双缓冲 / N缓冲 | | 13 | | **TileGroup** | 片上缓冲区 | [`pl.make_tile_group`](../../../api/SIMD-API/operation/resource_management/make_tile_group.md) | 一组轮转的Tile,用于双缓冲 / N缓冲 | |
| 14 | 14 | ||
| 15 | ### Tensor | 15 | ### Tensor |
| @@ -82,6 +82,8 @@ class TileType: | |||
| 82 | | `Right` | L0B —— matmul右操作数 | | 82 | | `Right` | L0B —— matmul右操作数 | |
| 83 | | `Acc` | L0C —— matmul累加器(fp32/int32) | | 83 | | `Acc` | L0C —— matmul累加器(fp32/int32) | |
| 84 | | `Scaling` | 缩放/量化参数缓冲区 | | 84 | | `Scaling` | 缩放/量化参数缓冲区 | |
| 85 | +| `ScaleLeft` | L0A配套的MX左操作数E8M0 scale缓冲区 | | ||
| 86 | +| `ScaleRight` | L0B配套的MX右操作数E8M0 scale缓冲区 | | ||
| 85 | 87 | ||
| 86 | > [!NOTE]说明 | 88 | > [!NOTE]说明 |
| 87 | > 在同一款硬件上,**除了UB之外**,如果target_memory确定了,layout和fractal是确定的,可以不填。 | 89 | > 在同一款硬件上,**除了UB之外**,如果target_memory确定了,layout和fractal是确定的,可以不填。 |
| @@ -151,8 +153,8 @@ PyPTO Pro的流水类型(`pl.PipeType`)与硬件指令流水对应关系: | |||
| 151 | | PipeType | 含义 | 典型操作 | | 153 | | PipeType | 含义 | 典型操作 | |
| 152 | |:---|:---|:---| | 154 | |:---|:---|:---| |
| 153 | | `MTE2` | GM→L1/UB搬运 | `pl.load`/`pl.load_tile` | | 155 | | `MTE2` | GM→L1/UB搬运 | `pl.load`/`pl.load_tile` | |
| 154 | -| `MTE1` | L1→L0A/L0B搬运 | `pl.move` | | 156 | +| `MTE1` | L1→L0A/L0B/ScaleLeft/ScaleRight搬运 | `pl.move` | |
| 155 | -| `M` | 矩阵计算 | `pl.matmul` | | 157 | +| `M` | 矩阵计算 | `pl.matmul` / `pl.matmul_mx` | |
| 156 | | `V` | 向量计算 | `pl.add`/`pl.sub`/... | | 158 | | `V` | 向量计算 | `pl.add`/`pl.sub`/... | |
| 157 | | `MTE3` | UB→GM搬运 | `pl.store`/`pl.store_tile` | | 159 | | `MTE3` | UB→GM搬运 | `pl.store`/`pl.store_tile` | |
| 158 | | `FIX` | L0C→GM搬运 | `pl.store`(Acc→GM) | | 160 | | `FIX` | L0C→GM搬运 | `pl.store`(Acc→GM) | |
| @@ -33,7 +33,7 @@ AI Core中的计算单元主要包括Scalar、Vector和Cube三类。 | |||
| 33 | |:---|:---|:---| | 33 | |:---|:---|:---| |
| 34 | | Scalar | 执行地址计算、循环控制等标量工作,并把向量计算、矩阵计算、数据搬运和同步任务发射给对应单元。 | 核函数中的Python控制流、标量表达式和`pl.system.*`同步接口 | | 34 | | Scalar | 执行地址计算、循环控制等标量工作,并把向量计算、矩阵计算、数据搬运和同步任务发射给对应单元。 | 核函数中的Python控制流、标量表达式和`pl.system.*`同步接口 | |
| 35 | | Vector | 负责执行向量运算。 | `pl.section_vector()`中的Tile向量API,以及`@pl.vector_function`中的`vf.*` API | | 35 | | Vector | 负责执行向量运算。 | `pl.section_vector()`中的Tile向量API,以及`@pl.vector_function`中的`vf.*` API | |
| 36 | -| Cube | 负责执行矩阵运算。 | `pl.section_cube()`中的`pl.matmul`、`pl.matmul_acc`等矩阵API | | 36 | +| Cube | 负责执行矩阵运算。 | `pl.section_cube()`中的`pl.matmul`、`pl.matmul_acc`、`pl.matmul_mx`、`pl.matmul_mx_acc`等矩阵API | |
| 37 | 37 | ||
| 38 | ## 存储单元和搬运单元 | 38 | ## 存储单元和搬运单元 |
| 39 | 39 | ||
| @@ -56,6 +56,8 @@ PyPTO Pro使用[`TileType.target_memory`](../../api/SIMD-API/basic_data_structur | |||
| 56 | | `Right` | L0B Buffer | `matmul`右操作数 | | 56 | | `Right` | L0B Buffer | `matmul`右操作数 | |
| 57 | | `Acc` | L0C Buffer | `matmul`累加结果(通常为FP32/INT32) | | 57 | | `Acc` | L0C Buffer | `matmul`累加结果(通常为FP32/INT32) | |
| 58 | | `Scaling` | Scaling/FBuffer | 量化、反量化参数 | | 58 | | `Scaling` | Scaling/FBuffer | 量化、反量化参数 | |
| 59 | +| `ScaleLeft` | L0A Buffer(scale专用地址域) | A矩阵的E8M0 scale(分组缩放因子) | | ||
| 60 | +| `ScaleRight` | L0B Buffer(scale专用地址域) | B矩阵的E8M0 scale(分组缩放因子) | | ||
| 59 | 61 | ||
| 60 | 完整枚举说明参见[`pl.MemorySpace`](../../api/SIMD-API/basic_data_structures/MemorySpace.md)。 | 62 | 完整枚举说明参见[`pl.MemorySpace`](../../api/SIMD-API/basic_data_structures/MemorySpace.md)。 |
| 61 | 63 | ||
| @@ -65,7 +67,9 @@ DMA(Direct Memory Access)搬运单元负责Global Memory与Local Memory之 | |||
| 65 | |:---|:---|:---| | 67 | |:---|:---|:---| |
| 66 | | GM → L1/UB | MTE2 | `pl.load` / `pl.load_tile` | | 68 | | GM → L1/UB | MTE2 | `pl.load` / `pl.load_tile` | |
| 67 | | L1 → L0A/L0B | MTE1 | `pl.move` | | 69 | | L1 → L0A/L0B | MTE1 | `pl.move` | |
| 70 | +| L1 → ScaleLeft/ScaleRight | MTE1 | `pl.move` | | ||
| 68 | | L0A × L0B → L0C | M | `pl.matmul` / `pl.matmul_acc` | | 71 | | L0A × L0B → L0C | M | `pl.matmul` / `pl.matmul_acc` | |
| 72 | +| MX L0A × L0B → L0C | M | `pl.matmul_mx` / `pl.matmul_mx_acc` | | ||
| 69 | | UB → GM | MTE3 | `pl.store` / `pl.store_tile` | | 73 | | UB → GM | MTE3 | `pl.store` / `pl.store_tile` | |
| 70 | | L0C → GM | FIX | `pl.store` / `pl.store_tile` | | 74 | | L0C → GM | FIX | `pl.store` / `pl.store_tile` | |
| 71 | | UB ↔ VF Register File | VF load/store | `vf.load*` / `vf.store*` | | 75 | | UB ↔ VF Register File | VF load/store | `vf.load*` / `vf.store*` | |
| @@ -26,16 +26,20 @@ namespace ir { | |||
| 26 | * - Scaling: Scaling/FBuffer tile buffer | 26 | * - Scaling: Scaling/FBuffer tile buffer |
| 27 | * - Acc: Accumulator buffer | 27 | * - Acc: Accumulator buffer |
| 28 | * - Bias: Bias buffer | 28 | * - Bias: Bias buffer |
| 29 | + * - ScaleLeft: MX scale-specific address domain paired with L0A | ||
| 30 | + * - ScaleRight: MX scale-specific address domain paired with L0B | ||
| 29 | */ | 31 | */ |
| 30 | enum class MemorySpace { | 32 | enum class MemorySpace { |
| 31 | - DDR, ///< DDR memory (off-chip) | 33 | + DDR, ///< DDR memory (off-chip) |
| 32 | - Vec, ///< Vector/unified buffer (on-chip) | 34 | + Vec, ///< Vector/unified buffer (on-chip) |
| 33 | - Mat, ///< Matrix/L1 buffer | 35 | + Mat, ///< Matrix/L1 buffer |
| 34 | - Left, ///< Left matrix operand buffer | 36 | + Left, ///< Left matrix operand buffer |
| 35 | - Right, ///< Right matrix operand buffer | 37 | + Right, ///< Right matrix operand buffer |
| 36 | - Scaling, ///< Scaling/FBuffer buffer | 38 | + Scaling, ///< Scaling/FBuffer buffer |
| 37 | - Acc, ///< Accumulator buffer | 39 | + Acc, ///< Accumulator buffer |
| 38 | - Bias ///< Bias buffer | 40 | + Bias, ///< Bias buffer |
| 41 | + ScaleLeft, ///< MX scale-specific address domain paired with L0A | ||
| 42 | + ScaleRight ///< MX scale-specific address domain paired with L0B | ||
| 39 | }; | 43 | }; |
| 40 | 44 | ||
| 41 | /** | 45 | /** |
| @@ -45,6 +45,10 @@ std::string MemorySpaceToString(MemorySpace space) | |||
| 45 | return "Acc"; | 45 | return "Acc"; |
| 46 | case MemorySpace::Bias: | 46 | case MemorySpace::Bias: |
| 47 | return "Bias"; | 47 | return "Bias"; |
| 48 | + case MemorySpace::ScaleLeft: | ||
| 49 | + return "ScaleLeft"; | ||
| 50 | + case MemorySpace::ScaleRight: | ||
| 51 | + return "ScaleRight"; | ||
| 48 | default: | 52 | default: |
| 49 | return "Unknown"; | 53 | return "Unknown"; |
| 50 | } | 54 | } |
| @@ -68,6 +72,10 @@ MemorySpace StringToMemorySpace(const std::string& str) | |||
| 68 | return MemorySpace::Acc; | 72 | return MemorySpace::Acc; |
| 69 | if (str == "Bias") | 73 | if (str == "Bias") |
| 70 | return MemorySpace::Bias; | 74 | return MemorySpace::Bias; |
| 75 | + if (str == "ScaleLeft") | ||
| 76 | + return MemorySpace::ScaleLeft; | ||
| 77 | + if (str == "ScaleRight") | ||
| 78 | + return MemorySpace::ScaleRight; | ||
| 71 | throw ValueError("Unknown MemorySpace: " + str); | 79 | throw ValueError("Unknown MemorySpace: " + str); |
| 72 | } | 80 | } |
| 73 | 81 | ||
| @@ -16,6 +16,8 @@ | |||
| 16 | * block.matmul (out, lhs, rhs) | 16 | * block.matmul (out, lhs, rhs) |
| 17 | * block.matmul_acc (out, acc, lhs, rhs) | 17 | * block.matmul_acc (out, acc, lhs, rhs) |
| 18 | * block.matmul_bias (out, lhs, rhs, bias) | 18 | * block.matmul_bias (out, lhs, rhs, bias) |
| 19 | + * block.matmul_mx (out, lhs, rhs, scale_a, scale_b) | ||
| 20 | + * block.matmul_mx_acc (out, acc, lhs, rhs, scale_a, scale_b) | ||
| 19 | * block.gemv (out, lhs, rhs) | 21 | * block.gemv (out, lhs, rhs) |
| 20 | * block.gemv_acc (out, acc, lhs, rhs) | 22 | * block.gemv_acc (out, acc, lhs, rhs) |
| 21 | * block.gemv_bias (out, lhs, rhs, bias) | 23 | * block.gemv_bias (out, lhs, rhs, bias) |
| @@ -81,6 +83,37 @@ REGISTER_OP("block.matmul_bias") | |||
| 81 | return DeduceBlockOutTileType(args, kwargs, "block.matmul_bias", 4); | 83 | return DeduceBlockOutTileType(args, kwargs, "block.matmul_bias", 4); |
| 82 | }); | 84 | }); |
| 83 | 85 | ||
| 86 | +// block.matmul_mx: (out, lhs, rhs, scale_a, scale_b) -> out's type | ||
| 87 | +REGISTER_OP("block.matmul_mx") | ||
| 88 | + .set_op_category("BlockOp") | ||
| 89 | + .set_description("Block MX matmul: out = lhs @ rhs (with per-group E8M0 scale)") | ||
| 90 | + .add_argument("out", "Pre-allocated output tile [M,N] in Acc (TileType)") | ||
| 91 | + .add_argument("lhs", "Left matrix tile [M,K] (TileType, FP8/FP4)") | ||
| 92 | + .add_argument("rhs", "Right matrix tile [K,N] (TileType, FP8/FP4)") | ||
| 93 | + .add_argument("scale_a", "Left scale tile in ScaleLeft (TileType, E8M0)") | ||
| 94 | + .add_argument("scale_b", "Right scale tile in ScaleRight (TileType, E8M0)") | ||
| 95 | + .set_attr<int>("phase") | ||
| 96 | + .f_deduce_type([]([[maybe_unused]] const std::vector<ExprPtr>& args, | ||
| 97 | + [[maybe_unused]] const std::vector<std::pair<std::string, std::any>>& kwargs) { | ||
| 98 | + return DeduceBlockOutTileType(args, kwargs, "block.matmul_mx", 5); | ||
| 99 | + }); | ||
| 100 | + | ||
| 101 | +// block.matmul_mx_acc: (out, acc, lhs, rhs, scale_a, scale_b) -> out's type | ||
| 102 | +REGISTER_OP("block.matmul_mx_acc") | ||
| 103 | + .set_op_category("BlockOp") | ||
| 104 | + .set_description("Block MX matmul with accumulation: out = acc + lhs @ rhs") | ||
| 105 | + .add_argument("out", "Pre-allocated output tile [M,N] in Acc (TileType)") | ||
| 106 | + .add_argument("acc", "Accumulator tile [M,N] (TileType)") | ||
| 107 | + .add_argument("lhs", "Left matrix tile [M,K] (TileType, FP8/FP4)") | ||
| 108 | + .add_argument("rhs", "Right matrix tile [K,N] (TileType, FP8/FP4)") | ||
| 109 | + .add_argument("scale_a", "Left scale tile in ScaleLeft (TileType, E8M0)") | ||
| 110 | + .add_argument("scale_b", "Right scale tile in ScaleRight (TileType, E8M0)") | ||
| 111 | + .set_attr<int>("phase") | ||
| 112 | + .f_deduce_type([]([[maybe_unused]] const std::vector<ExprPtr>& args, | ||
| 113 | + [[maybe_unused]] const std::vector<std::pair<std::string, std::any>>& kwargs) { | ||
| 114 | + return DeduceBlockOutTileType(args, kwargs, "block.matmul_mx_acc", 6); | ||
| 115 | + }); | ||
| 116 | + | ||
| 84 | // block.gemv: (out, lhs, rhs) -> out's type | 117 | // block.gemv: (out, lhs, rhs) -> out's type |
| 85 | REGISTER_OP("block.gemv") | 118 | REGISTER_OP("block.gemv") |
| 86 | .set_op_category("BlockOp") | 119 | .set_op_category("BlockOp") |
| @@ -23,6 +23,7 @@ | |||
| 23 | #include <sstream> | 23 | #include <sstream> |
| 24 | #include <string> | 24 | #include <string> |
| 25 | #include <utility> | 25 | #include <utility> |
| 26 | +#include <vector> | ||
| 26 | 27 | ||
| 27 | #include "backend/backend_cce.h" | 28 | #include "backend/backend_cce.h" |
| 28 | #include "backend/common/backend.h" | 29 | #include "backend/common/backend.h" |
| @@ -124,6 +125,77 @@ static std::string GetReluPreModeCCE(int relu) | |||
| 124 | return ir::EnumToString(mode); | 125 | return ir::EnumToString(mode); |
| 125 | } | 126 | } |
| 126 | 127 | ||
| 128 | +static std::string BuildContiguousAxisStride(codegen::CCECodegen& codegen, const ir::TensorTypePtr& tensor_type, | ||
| 129 | + int axis) | ||
| 130 | +{ | ||
| 131 | + std::string stride = "1"; | ||
| 132 | + for (int i = static_cast<int>(tensor_type->shape_.size()) - 1; i > axis; --i) { | ||
| 133 | + const std::string dim = codegen.GetExprAsCode(tensor_type->shape_[static_cast<size_t>(i)]); | ||
| 134 | + stride = "(" + dim + " * " + stride + ")"; | ||
| 135 | + } | ||
| 136 | + return stride; | ||
| 137 | +} | ||
| 138 | + | ||
| 139 | +static bool IsMXLoad(const ir::TensorTypePtr& tensor_type, const ir::TileTypePtr& tile_type) | ||
| 140 | +{ | ||
| 141 | + if (tensor_type->dtype_ != ir::DataType::FP8E8M0 || tile_type->dtype_ != ir::DataType::FP8E8M0 || | ||
| 142 | + !tile_type->memref_.has_value() || tile_type->memref_.value()->memorySpace_ != ir::MemorySpace::Mat || | ||
| 143 | + !tile_type->hardwareInfo_.has_value()) { | ||
| 144 | + return false; | ||
| 145 | + } | ||
| 146 | + | ||
| 147 | + const auto& hw = tile_type->hardwareInfo_.value(); | ||
| 148 | + const bool is_zz = hw.blayout == ir::TileLayout::row_major && hw.slayout == ir::TileLayout::row_major; | ||
ZZ和NN只有scale left/right场景用么? ![]() ![]() | |||
| 149 | + const bool is_nn = hw.blayout == ir::TileLayout::col_major && hw.slayout == ir::TileLayout::col_major; | ||
| 150 | + return hw.fractal == 32 && (is_zz || is_nn); | ||
| 151 | +} | ||
| 152 | + | ||
| 153 | +static std::vector<int> ResolveMXLoadTileDims(const ir::CallPtr& op, const ir::TensorTypePtr& tensor_type) | ||
| 154 | +{ | ||
| 155 | + const int rank = static_cast<int>(tensor_type->shape_.size()); | ||
| 156 | + // MX scale tensors carry a trailing physical phase axis of size 2. | ||
| 157 | + IRCHECK(rank >= 3) << "MX scale load requires at least two matrix axes and one physical phase axis at " | ||
| 158 | + << op->span_.ToString(); | ||
| 159 | + const auto phase_dim = ir::As<ir::ConstInt>(tensor_type->shape_.back()); | ||
| 160 | + IRCHECK(phase_dim != nullptr && phase_dim->value_ == 2) | ||
| 161 | + << "MX scale load trailing physical phase axis must be statically equal to 2 at " << op->span_.ToString(); | ||
| 162 | + const std::vector<int> tile_dims = op->HasKwarg("tile_dims") ? op->GetKwarg<std::vector<int>>("tile_dims") : | ||
| 163 | + std::vector<int>{rank - 3, rank - 2}; | ||
| 164 | + IRCHECK(tile_dims[0] != rank - 1 && tile_dims[1] != rank - 1) | ||
| 165 | + << "MX scale load order cannot select the trailing physical phase axis at " << op->span_.ToString(); | ||
| 166 | + return tile_dims; | ||
| 167 | +} | ||
| 168 | + | ||
| 169 | +static void EmitMXLoad(codegen::CCECodegen& codegen, const ir::CallPtr& op, const ir::TensorTypePtr& tensor_type, | ||
| 170 | + const ir::TileTypePtr& tile_type, const std::vector<int>& tile_dims, const std::string& offset, | ||
| 171 | + const std::string& src_ptr, const std::string& out_name) | ||
| 172 | +{ | ||
| 173 | + const auto& hw = tile_type->hardwareInfo_.value(); | ||
| 174 | + const bool is_scale_a = hw.blayout == ir::TileLayout::row_major; | ||
| 175 | + | ||
| 176 | + const bool is_dn = op->HasKwarg("is_transpose") && op->GetKwarg<bool>("is_transpose"); | ||
| 177 | + const char* layout_name = is_scale_a ? (is_dn ? "Layout::MX_A_DN" : "Layout::MX_A_ND") : | ||
| 178 | + (is_dn ? "Layout::MX_B_DN" : "Layout::MX_B_ND"); | ||
| 179 | + | ||
| 180 | + const std::string major_stride = BuildContiguousAxisStride(codegen, tensor_type, tile_dims[0]); | ||
| 181 | + const std::string minor_stride = BuildContiguousAxisStride(codegen, tensor_type, tile_dims[1]); | ||
| 182 | + const std::string prefix = "mx_load_" + std::to_string(codegen.GetTileOffsetCounter()); | ||
| 183 | + const std::string shape_type = prefix + "Shape"; | ||
| 184 | + const std::string stride_type = prefix + "Stride"; | ||
| 185 | + const std::string global_type = prefix + "Type"; | ||
| 186 | + const std::string element_type = tensor_type->dtype_.ToCTypeString(); | ||
| 187 | + | ||
| 188 | + codegen.Emit("using " + shape_type + " = pto::TileShape2D<" + element_type + ", pto::DYNAMIC, pto::DYNAMIC, " + | ||
| 189 | + layout_name + ">;"); | ||
| 190 | + codegen.Emit("using " + stride_type + " = pto::Stride<pto::DYNAMIC, pto::DYNAMIC, pto::DYNAMIC, pto::DYNAMIC, 1>;"); | ||
| 191 | + codegen.Emit("using " + global_type + " = GlobalTensor<" + element_type + ", " + shape_type + ", " + stride_type + | ||
| 192 | + ", " + layout_name + ">;"); | ||
| 193 | + codegen.Emit(global_type + " " + prefix + "(" + src_ptr + " + " + offset + ", " + shape_type + | ||
| 194 | + "(static_cast<int64_t>(" + out_name + ".GetValidRow()), static_cast<int64_t>(" + out_name + | ||
| 195 | + ".GetValidCol())), " + stride_type + "(1, 1, " + major_stride + ", " + minor_stride + ", 1));"); | ||
| 196 | + codegen.Emit("TLOAD(" + out_name + ", " + prefix + ");"); | ||
| 197 | +} | ||
| 198 | + | ||
| 127 | static std::string GetSTPhaseCCE(const ir::CallPtr& op) | 199 | static std::string GetSTPhaseCCE(const ir::CallPtr& op) |
| 128 | { | 200 | { |
| 129 | if (!op->HasKwarg("phase")) { | 201 | if (!op->HasKwarg("phase")) { |
| @@ -342,10 +414,21 @@ static std::string MakeBlockOutLoadCodegenCCE(const ir::CallPtr& op, codegen::Co | |||
| 342 | auto src_tensor_type = std::dynamic_pointer_cast<const ir::TensorType>(src_tensor_var_ptr->GetType()); | 414 | auto src_tensor_type = std::dynamic_pointer_cast<const ir::TensorType>(src_tensor_var_ptr->GetType()); |
| 343 | CHECK(src_tensor_type != nullptr) << "block.load source must be TensorType"; | 415 | CHECK(src_tensor_type != nullptr) << "block.load source must be TensorType"; |
| 344 | 416 | ||
| 417 | + auto out_tile_type = ir::As<ir::TileType>(op->args_[0]->GetType()); | ||
| 418 | + const bool is_mx_load = IsMXLoad(src_tensor_type, out_tile_type); | ||
| 419 | + std::vector<int> mx_tile_dims; | ||
| 420 | + if (is_mx_load) { | ||
| 421 | + mx_tile_dims = ResolveMXLoadTileDims(op, src_tensor_type); | ||
| 422 | + } | ||
| 423 | + | ||
| 345 | std::string offset = cce::ComputeStrideBasedOffset(codegen, offsets_tuple, src_tensor_type); | 424 | std::string offset = cce::ComputeStrideBasedOffset(codegen, offsets_tuple, src_tensor_type); |
| 346 | std::string src_ptr = codegen.GetPointer(src_tensor_var); | 425 | std::string src_ptr = codegen.GetPointer(src_tensor_var); |
| 347 | std::string out_name = codegen.GetExprAsCode(op->args_[0]); | 426 | std::string out_name = codegen.GetExprAsCode(op->args_[0]); |
| 348 | 427 | ||
| 428 | + if (is_mx_load) { | ||
| 429 | + EmitMXLoad(codegen, op, src_tensor_type, out_tile_type, mx_tile_dims, offset, src_ptr, out_name); | ||
| 430 | + return ""; | ||
| 431 | + } | ||
| 349 | if (!cce::IsNZTensorType(src_tensor_type)) { | 432 | if (!cce::IsNZTensorType(src_tensor_type)) { |
| 350 | EmitSetShapeFromTile(codegen, src_tensor_var, out_name); | 433 | EmitSetShapeFromTile(codegen, src_tensor_var, out_name); |
| 351 | } | 434 | } |
| @@ -793,6 +876,54 @@ static std::string MakeBlockOutMatmulBiasCodegenCCE(const ir::CallPtr& op, codeg | |||
| 793 | return ""; | 876 | return ""; |
| 794 | } | 877 | } |
| 795 | 878 | ||
| 879 | +// ============================================================================ | ||
| 880 | +// block.matmul_mx - args = [dst, left, right, scale_a, scale_b] | ||
| 881 | +// Emits: TMATMUL_MX_IMPL[<Phase>](dst, left, scale_a, right, scale_b); | ||
| 882 | +// Scale tiles are passed for compile-time type validation; mad_mx reads | ||
| 883 | +// them implicitly via SFractal layout. | ||
| 884 | +// ============================================================================ | ||
| 885 | +static std::string MakeBlockOutMatmulMxCodegenCCE(const ir::CallPtr& op, codegen::CodegenBase& codegen_base) | ||
| 886 | +{ | ||
| 887 | + auto& codegen = dynamic_cast<codegen::CCECodegen&>(codegen_base); | ||
| 888 | + CHECK(op->args_.size() == 5) << "block.matmul_mx: expected 5 args (dst, left, right, scale_a, scale_b), got " | ||
| 889 | + << op->args_.size(); | ||
| 890 | + std::string dst = codegen.GetExprAsCode(op->args_[0]); | ||
| 891 | + std::string left = codegen.GetExprAsCode(op->args_[1]); | ||
| 892 | + std::string right = codegen.GetExprAsCode(op->args_[2]); | ||
| 893 | + std::string scale_a = codegen.GetExprAsCode(op->args_[3]); | ||
| 894 | + std::string scale_b = codegen.GetExprAsCode(op->args_[4]); | ||
| 895 | + | ||
| 896 | + std::string phase_template = GetAccPhaseCCE(op); | ||
| 897 | + std::string call = "TMATMUL_MX_IMPL"; | ||
| 898 | + if (!phase_template.empty()) { | ||
| 899 | + call += "<" + phase_template + ">"; | ||
| 900 | + } | ||
| 901 | + codegen.Emit(call + "(" + dst + ", " + left + ", " + scale_a + ", " + right + ", " + scale_b + ");"); | ||
| 902 | + return ""; | ||
| 903 | +} | ||
| 904 | + | ||
| 905 | +// block.matmul_mx_acc - args = [dst, acc, left, right, scale_a, scale_b] | ||
| 906 | +// Emits: TMATMUL_MX_IMPL[<Phase>](dst, acc, left, scale_a, right, scale_b); | ||
| 907 | +static std::string MakeBlockOutMatmulMxAccCodegenCCE(const ir::CallPtr& op, codegen::CodegenBase& codegen_base) | ||
| 908 | +{ | ||
| 909 | + auto& codegen = dynamic_cast<codegen::CCECodegen&>(codegen_base); | ||
| 910 | + CHECK(op->args_.size() == 6) << "block.matmul_mx_acc: expected 6 args, got " << op->args_.size(); | ||
| 911 | + std::string dst = codegen.GetExprAsCode(op->args_[0]); | ||
| 912 | + std::string acc = codegen.GetExprAsCode(op->args_[1]); | ||
| 913 | + std::string left = codegen.GetExprAsCode(op->args_[2]); | ||
| 914 | + std::string right = codegen.GetExprAsCode(op->args_[3]); | ||
| 915 | + std::string scale_a = codegen.GetExprAsCode(op->args_[4]); | ||
| 916 | + std::string scale_b = codegen.GetExprAsCode(op->args_[5]); | ||
| 917 | + | ||
| 918 | + std::string phase_template = GetAccPhaseCCE(op); | ||
| 919 | + std::string call = "TMATMUL_MX_IMPL"; | ||
| 920 | + if (!phase_template.empty()) { | ||
| 921 | + call += "<" + phase_template + ">"; | ||
| 922 | + } | ||
| 923 | + codegen.Emit(call + "(" + dst + ", " + acc + ", " + left + ", " + scale_a + ", " + right + ", " + scale_b + ");"); | ||
| 924 | + return ""; | ||
| 925 | +} | ||
| 926 | + | ||
| 796 | // block.cast - args = [dst, src] + mode kwarg | 927 | // block.cast - args = [dst, src] + mode kwarg |
| 797 | static std::string MakeBlockOutCastCodegenCCE(const ir::CallPtr& op, codegen::CodegenBase& codegen_base) | 928 | static std::string MakeBlockOutCastCodegenCCE(const ir::CallPtr& op, codegen::CodegenBase& codegen_base) |
| 798 | { | 929 | { |
| @@ -2001,6 +2132,18 @@ REGISTER_BACKEND_OP(BackendCCE, "block.matmul_bias") | |||
| 2001 | return MakeBlockOutMatmulBiasCodegenCCE(op, codegen); | 2132 | return MakeBlockOutMatmulBiasCodegenCCE(op, codegen); |
| 2002 | }); | 2133 | }); |
| 2003 | 2134 | ||
| 2135 | +REGISTER_BACKEND_OP(BackendCCE, "block.matmul_mx") | ||
| 2136 | + .set_pipe(ir::PipeType::M) | ||
| 2137 | + .f_codegen([](const ir::CallPtr& op, codegen::CodegenBase& codegen) { | ||
| 2138 | + return MakeBlockOutMatmulMxCodegenCCE(op, codegen); | ||
| 2139 | + }); | ||
| 2140 | + | ||
| 2141 | +REGISTER_BACKEND_OP(BackendCCE, "block.matmul_mx_acc") | ||
| 2142 | + .set_pipe(ir::PipeType::M) | ||
| 2143 | + .f_codegen([](const ir::CallPtr& op, codegen::CodegenBase& codegen) { | ||
| 2144 | + return MakeBlockOutMatmulMxAccCodegenCCE(op, codegen); | ||
| 2145 | + }); | ||
| 2146 | + | ||
| 2004 | REGISTER_BACKEND_OP(BackendCCE, "block.gemv") | 2147 | REGISTER_BACKEND_OP(BackendCCE, "block.gemv") |
| 2005 | .set_pipe(ir::PipeType::M) | 2148 | .set_pipe(ir::PipeType::M) |
| 2006 | .f_codegen([](const ir::CallPtr& op, codegen::CodegenBase& codegen) { | 2149 | .f_codegen([](const ir::CallPtr& op, codegen::CodegenBase& codegen) { |
| @@ -201,6 +201,10 @@ std::string TypeConverter::ConvertMemorySpaceToTileType(ir::MemorySpace space) c | |||
| 201 | return "TileType::Scaling"; | 201 | return "TileType::Scaling"; |
| 202 | case ir::MemorySpace::Bias: | 202 | case ir::MemorySpace::Bias: |
| 203 | return "TileType::Bias"; | 203 | return "TileType::Bias"; |
| 204 | + case ir::MemorySpace::ScaleLeft: | ||
| 205 | + return "TileType::ScaleLeft"; | ||
| 206 | + case ir::MemorySpace::ScaleRight: | ||
| 207 | + return "TileType::ScaleRight"; | ||
| 204 | case ir::MemorySpace::DDR: | 208 | case ir::MemorySpace::DDR: |
| 205 | // DDR is for GlobalTensor, not Tile - should not reach here | 209 | // DDR is for GlobalTensor, not Tile - should not reach here |
| 206 | throw pypto::ir::ValueError("DDR is for GlobalTensor, not Tile"); | 210 | throw pypto::ir::ValueError("DDR is for GlobalTensor, not Tile"); |
| @@ -941,6 +941,34 @@ TEST_F(BlockOpsOutMatmulTest, BlockMatmulAcc_ReturnsOutType) | |||
| 941 | EXPECT_NE(As<TileType>(call->GetType()), nullptr); | 941 | EXPECT_NE(As<TileType>(call->GetType()), nullptr); |
| 942 | } | 942 | } |
| 943 | 943 | ||
| 944 | +TEST_F(BlockOpsOutMatmulTest, BlockMatmulMx_ReturnsOutType) | ||
| 945 | +{ | ||
| 946 | + auto& reg = OpRegistry::GetInstance(); | ||
| 947 | + auto call = reg.Create( | ||
| 948 | + "block.matmul_mx", | ||
| 949 | + {MakeTileVar("o", {64, 64}, DataType::FP32), MakeTileVar("l", {64, 64}, DataType::FP8E4M3FN), | ||
| 950 | + MakeTileVar("r", {64, 64}, DataType::FP8E5M2), MakeTileVar("sa", {64, 2}, DataType::FP8E8M0), | ||
| 951 | + MakeTileVar("sb", {2, 64}, DataType::FP8E8M0)}, | ||
| 952 | + Sp()); | ||
| 953 | + auto rt = As<TileType>(call->GetType()); | ||
| 954 | + ASSERT_NE(rt, nullptr); | ||
| 955 | + EXPECT_EQ(rt->dtype_, DataType::FP32); | ||
| 956 | +} | ||
| 957 | + | ||
| 958 | +TEST_F(BlockOpsOutMatmulTest, BlockMatmulMxAcc_ReturnsOutType) | ||
| 959 | +{ | ||
| 960 | + auto& reg = OpRegistry::GetInstance(); | ||
| 961 | + auto call = reg.Create( | ||
| 962 | + "block.matmul_mx_acc", | ||
| 963 | + {MakeTileVar("o", {64, 64}, DataType::FP32), MakeTileVar("acc", {64, 64}, DataType::FP32), | ||
| 964 | + MakeTileVar("l", {64, 64}, DataType::FP4E2M1), MakeTileVar("r", {64, 64}, DataType::FP4E1M2), | ||
| 965 | + MakeTileVar("sa", {64, 2}, DataType::FP8E8M0), MakeTileVar("sb", {2, 64}, DataType::FP8E8M0)}, | ||
| 966 | + Sp()); | ||
| 967 | + auto rt = As<TileType>(call->GetType()); | ||
| 968 | + ASSERT_NE(rt, nullptr); | ||
| 969 | + EXPECT_EQ(rt->dtype_, DataType::FP32); | ||
| 970 | +} | ||
| 971 | + | ||
| 944 | TEST_F(BlockOpsOutMatmulTest, BlockGemv_ReturnsOutType) | 972 | TEST_F(BlockOpsOutMatmulTest, BlockGemv_ReturnsOutType) |
| 945 | { | 973 | { |
| 946 | auto& reg = OpRegistry::GetInstance(); | 974 | auto& reg = OpRegistry::GetInstance(); |
| @@ -85,6 +85,16 @@ ir::ExprPtr MakeOffsets(int64_t m, int64_t k) | |||
| 85 | ir::Span::Unknown()); | 85 | ir::Span::Unknown()); |
| 86 | } | 86 | } |
| 87 | 87 | ||
| 88 | +ir::ExprPtr MakeOffsets(const std::vector<int64_t>& values) | ||
| 89 | +{ | ||
| 90 | + std::vector<ir::ExprPtr> offsets; | ||
| 91 | + offsets.reserve(values.size()); | ||
| 92 | + for (int64_t value : values) { | ||
| 93 | + offsets.push_back(MakeConstInt(value)); | ||
| 94 | + } | ||
| 95 | + return std::make_shared<const ir::MakeTuple>(offsets, ir::Span::Unknown()); | ||
| 96 | +} | ||
| 97 | + | ||
| 88 | ir::CallPtr MakeCall(const std::string& name, std::vector<ir::ExprPtr> args) | 98 | ir::CallPtr MakeCall(const std::string& name, std::vector<ir::ExprPtr> args) |
| 89 | { | 99 | { |
| 90 | return std::make_shared<const ir::Call>(name, args, ir::Span::Unknown()); | 100 | return std::make_shared<const ir::Call>(name, args, ir::Span::Unknown()); |
| @@ -456,6 +466,32 @@ TEST(BackendCCEBlockOutOps, MatmulBias) | |||
| 456 | "TMATMUL_BIAS<AccPhase::Final>(dst, left, right, bias);"); | 466 | "TMATMUL_BIAS<AccPhase::Final>(dst, left, right, bias);"); |
| 457 | } | 467 | } |
| 458 | 468 | ||
| 469 | +TEST(BackendCCEBlockOutOps, MatmulMx) | ||
| 470 | +{ | ||
| 471 | + auto tile = MakeTileType(); | ||
| 472 | + auto args = std::vector<ir::ExprPtr>{MakeVar("dst", tile), MakeVar("left", tile), MakeVar("right", tile), | ||
| 473 | + MakeVar("scale_a", tile), MakeVar("scale_b", tile)}; | ||
| 474 | + EXPECT_CONTAINS(RunCodegen("block.matmul_mx", MakeCall("block.matmul_mx", args)), | ||
| 475 | + "TMATMUL_MX_IMPL(dst, left, scale_a, right, scale_b);"); | ||
| 476 | + | ||
| 477 | + auto call_phase = MakeCallWithKwargs("block.matmul_mx", args, {{"phase", 2}}); | ||
| 478 | + EXPECT_CONTAINS(RunCodegen("block.matmul_mx", call_phase), | ||
| 479 | + "TMATMUL_MX_IMPL<AccPhase::Final>(dst, left, scale_a, right, scale_b);"); | ||
| 480 | +} | ||
| 481 | + | ||
| 482 | +TEST(BackendCCEBlockOutOps, MatmulMxAcc) | ||
| 483 | +{ | ||
| 484 | + auto tile = MakeTileType(); | ||
| 485 | + auto args = std::vector<ir::ExprPtr>{MakeVar("dst", tile), MakeVar("acc", tile), MakeVar("left", tile), | ||
| 486 | + MakeVar("right", tile), MakeVar("scale_a", tile), MakeVar("scale_b", tile)}; | ||
| 487 | + EXPECT_CONTAINS(RunCodegen("block.matmul_mx_acc", MakeCall("block.matmul_mx_acc", args)), | ||
| 488 | + "TMATMUL_MX_IMPL(dst, acc, left, scale_a, right, scale_b);"); | ||
| 489 | + | ||
| 490 | + auto call_phase = MakeCallWithKwargs("block.matmul_mx_acc", args, {{"phase", 1}}); | ||
| 491 | + EXPECT_CONTAINS(RunCodegen("block.matmul_mx_acc", call_phase), | ||
| 492 | + "TMATMUL_MX_IMPL<AccPhase::Partial>(dst, acc, left, scale_a, right, scale_b);"); | ||
| 493 | +} | ||
| 494 | + | ||
| 459 | TEST(BackendCCEBlockOutOps, Cast) | 495 | TEST(BackendCCEBlockOutOps, Cast) |
| 460 | { | 496 | { |
| 461 | auto tile = MakeTileType(); | 497 | auto tile = MakeTileType(); |
| @@ -587,6 +623,183 @@ TEST(BackendCCEBlockOutOps, Load) | |||
| 587 | EXPECT_CONTAINS(code, "SetShape"); | 623 | EXPECT_CONTAINS(code, "SetShape"); |
| 588 | } | 624 | } |
| 589 | 625 | ||
| 626 | +TEST(BackendCCEBlockOutOps, InfersHighDimensionalMxScaleLoadFromDestinationAndOrder) | ||
| 627 | +{ | ||
| 628 | + auto tensor_type = MakeTensorType({2, 64, 3, 3, 2}, ir::DataType::FP8E8M0); | ||
| 629 | + auto zz_hw = ir::HardwareInfo(ir::TileLayout::row_major, ir::TileLayout::row_major, 32); | ||
| 630 | + auto nn_hw = ir::HardwareInfo(ir::TileLayout::col_major, ir::TileLayout::col_major, 32); | ||
| 631 | + auto zz_tile = MakeTileType({64, 6}, ir::DataType::FP8E8M0, MakeMemRef(ir::MemorySpace::Mat), zz_hw); | ||
| 632 | + auto nn_tile = MakeTileType({6, 64}, ir::DataType::FP8E8M0, MakeMemRef(ir::MemorySpace::Mat), nn_hw); | ||
| 633 | + auto* info = BackendCCE::Instance().GetOpInfo("block.load"); | ||
| 634 | + ASSERT_NE(info, nullptr); | ||
| 635 | + | ||
| 636 | + TestableCCECodegen a_codegen(ir::SectionKind::Cube); | ||
| 637 | + a_codegen.RegisterPointer("scale_a", "scale_a_ptr"); | ||
| 638 | + auto a_load = MakeCallWithKwargs( | ||
| 639 | + "block.load", {MakeVar("out_a", zz_tile), MakeVar("scale_a", tensor_type), MakeOffsets({1, 4, 2, 1, 0})}, | ||
| 640 | + {{"tile_dims", std::vector<int>{1, 3}}}); | ||
| 641 | + EXPECT_NO_THROW(info->codegen_func(a_load, a_codegen)); | ||
| 642 | + const auto a_code = a_codegen.GetEmittedCode(); | ||
| 643 | + EXPECT_CONTAINS(a_code, "pto::TileShape2D<float8_e8m0_t"); | ||
| 644 | + EXPECT_CONTAINS(a_code, "Layout::MX_A_ND"); | ||
| 645 | + EXPECT_CONTAINS(a_code, "pto::Stride<pto::DYNAMIC, pto::DYNAMIC, pto::DYNAMIC, pto::DYNAMIC, 1>"); | ||
| 646 | + EXPECT_CONTAINS(a_code, "scale_a_ptr +"); | ||
| 647 | + EXPECT_CONTAINS(a_code, "(1, 1, (3 * (3 * (2 * 1))), (2 * 1), 1)"); | ||
| 648 | + EXPECT_CONTAINS(a_code, "TLOAD(out_a, mx_load_0);"); | ||
| 649 | + EXPECT_NOT_CONTAINS(a_code, "TASSIGN(scale_a"); | ||
| 650 | + | ||
| 651 | + TestableCCECodegen b_codegen(ir::SectionKind::Cube); | ||
| 652 | + b_codegen.RegisterPointer("scale_b", "scale_b_ptr"); | ||
| 653 | + auto b_load = MakeCallWithKwargs( | ||
| 654 | + "block.load", {MakeVar("out_b", nn_tile), MakeVar("scale_b", tensor_type), MakeOffsets({1, 4, 2, 1, 0})}, | ||
| 655 | + {{"tile_dims", std::vector<int>{1, 3}}, {"is_transpose", true}}); | ||
| 656 | + EXPECT_NO_THROW(info->codegen_func(b_load, b_codegen)); | ||
| 657 | + const auto b_code = b_codegen.GetEmittedCode(); | ||
| 658 | + EXPECT_CONTAINS(b_code, "Layout::MX_B_DN"); | ||
| 659 | + EXPECT_CONTAINS(b_code, "TLOAD(out_b, mx_load_0);"); | ||
| 660 | +} | ||
| 661 | + | ||
| 662 | +TEST(BackendCCEBlockOutOps, RejectsMxScaleLoadSelectingPhysicalPhaseAxis) | ||
| 663 | +{ | ||
| 664 | + auto tensor_type = MakeTensorType({64, 1, 2}, ir::DataType::FP8E8M0); | ||
| 665 | + auto zz_hw = ir::HardwareInfo(ir::TileLayout::row_major, ir::TileLayout::row_major, 32); | ||
| 666 | + auto zz_tile = MakeTileType({64, 2}, ir::DataType::FP8E8M0, MakeMemRef(ir::MemorySpace::Mat), zz_hw); | ||
| 667 | + auto load = MakeCallWithKwargs("block.load", | ||
| 668 | + {MakeVar("out", zz_tile), MakeVar("scale", tensor_type), MakeOffsets({0, 0, 0})}, | ||
| 669 | + {{"tile_dims", std::vector<int>{1, 2}}}); | ||
| 670 | + auto* info = BackendCCE::Instance().GetOpInfo("block.load"); | ||
| 671 | + ASSERT_NE(info, nullptr); | ||
| 672 | + | ||
| 673 | + TestableCCECodegen codegen(ir::SectionKind::Cube); | ||
| 674 | + EXPECT_THROW(info->codegen_func(load, codegen), ir::ValueError); | ||
| 675 | +} | ||
| 676 | + | ||
| 677 | +TEST(BackendCCEBlockOutOps, RejectsMxScaleLoadWithInvalidPhysicalPhaseExtent) | ||
| 678 | +{ | ||
| 679 | + auto tensor_type = MakeTensorType({64, 1, 3}, ir::DataType::FP8E8M0); | ||
| 680 | + auto zz_hw = ir::HardwareInfo(ir::TileLayout::row_major, ir::TileLayout::row_major, 32); | ||
| 681 | + auto zz_tile = MakeTileType({64, 2}, ir::DataType::FP8E8M0, MakeMemRef(ir::MemorySpace::Mat), zz_hw); | ||
| 682 | + auto load = MakeCallWithKwargs( | ||
| 683 | + "block.load", {MakeVar("out", zz_tile), MakeVar("scale", tensor_type), MakeOffsets({0, 0, 0})}, {}); | ||
| 684 | + auto* info = BackendCCE::Instance().GetOpInfo("block.load"); | ||
| 685 | + ASSERT_NE(info, nullptr); | ||
| 686 | + | ||
| 687 | + TestableCCECodegen codegen(ir::SectionKind::Cube); | ||
| 688 | + EXPECT_THROW(info->codegen_func(load, codegen), ir::ValueError); | ||
| 689 | +} | ||
| 690 | + | ||
| 691 | +TEST(BackendCCEBlockOutOps, InfersAllMxScaleLayouts) | ||
| 692 | +{ | ||
| 693 | + auto zz_hw = ir::HardwareInfo(ir::TileLayout::row_major, ir::TileLayout::row_major, 32); | ||
| 694 | + auto nn_hw = ir::HardwareInfo(ir::TileLayout::col_major, ir::TileLayout::col_major, 32); | ||
| 695 | + auto zz_tile = MakeTileType({64, 6}, ir::DataType::FP8E8M0, MakeMemRef(ir::MemorySpace::Mat), zz_hw); | ||
| 696 | + auto nn_tile = MakeTileType({6, 64}, ir::DataType::FP8E8M0, MakeMemRef(ir::MemorySpace::Mat), nn_hw); | ||
| 697 | + auto* info = BackendCCE::Instance().GetOpInfo("block.load"); | ||
| 698 | + ASSERT_NE(info, nullptr); | ||
| 699 | + | ||
| 700 | + auto infer = [&](const std::vector<int64_t>& tensor_shape, const ir::TypePtr& tile, | ||
| 701 | + const std::vector<int64_t>& offsets, bool is_transpose) { | ||
| 702 | + auto tensor = MakeVar("scale", MakeTensorType(tensor_shape, ir::DataType::FP8E8M0)); | ||
| 703 | + std::vector<std::pair<std::string, std::any>> kwargs; | ||
| 704 | + if (is_transpose) { | ||
| 705 | + kwargs.emplace_back("is_transpose", true); | ||
| 706 | + } | ||
| 707 | + auto load = MakeCallWithKwargs("block.load", {MakeVar("out", tile), tensor, MakeOffsets(offsets)}, kwargs); | ||
| 708 | + TestableCCECodegen codegen(ir::SectionKind::Cube); | ||
| 709 | + codegen.RegisterPointer("scale", "scale_ptr"); | ||
| 710 | + EXPECT_NO_THROW(info->codegen_func(load, codegen)); | ||
| 711 | + return codegen.GetEmittedCode(); | ||
| 712 | + }; | ||
| 713 | + | ||
| 714 | + const auto a_nd = infer({64, 3, 2}, zz_tile, {4, 1, 0}, false); | ||
| 715 | + EXPECT_CONTAINS(a_nd, "Layout::MX_A_ND"); | ||
| 716 | + EXPECT_CONTAINS(a_nd, "(1, 1, (3 * (2 * 1)), (2 * 1), 1)"); | ||
| 717 | + EXPECT_CONTAINS(a_nd, "4 * (3 * 2) + 1 * (2) + 0"); | ||
| 718 | + | ||
| 719 | + const auto a_dn = infer({3, 64, 2}, zz_tile, {1, 4, 0}, true); | ||
| 720 | + EXPECT_CONTAINS(a_dn, "Layout::MX_A_DN"); | ||
| 721 | + EXPECT_CONTAINS(a_dn, "(1, 1, (64 * (2 * 1)), (2 * 1), 1)"); | ||
| 722 | + EXPECT_CONTAINS(a_dn, "1 * (64 * 2) + 4 * (2) + 0"); | ||
| 723 | + | ||
| 724 | + const auto b_nd = infer({3, 64, 2}, nn_tile, {1, 4, 0}, false); | ||
| 725 | + EXPECT_CONTAINS(b_nd, "Layout::MX_B_ND"); | ||
| 726 | + EXPECT_CONTAINS(b_nd, "(1, 1, (64 * (2 * 1)), (2 * 1), 1)"); | ||
| 727 | + EXPECT_CONTAINS(b_nd, "1 * (64 * 2) + 4 * (2) + 0"); | ||
| 728 | + | ||
| 729 | + const auto b_dn = infer({64, 3, 2}, nn_tile, {4, 1, 0}, true); | ||
| 730 | + EXPECT_CONTAINS(b_dn, "Layout::MX_B_DN"); | ||
| 731 | + EXPECT_CONTAINS(b_dn, "(1, 1, (3 * (2 * 1)), (2 * 1), 1)"); | ||
| 732 | + EXPECT_CONTAINS(b_dn, "4 * (3 * 2) + 1 * (2) + 0"); | ||
| 733 | +} | ||
| 734 | + | ||
| 735 | +TEST(BackendCCEBlockOutOps, InfersMxScaleLoadWithMiddleGroupAxis) | ||
| 736 | +{ | ||
| 737 | + auto tensor_type = MakeTensorType({2, 3, 3, 64, 2}, ir::DataType::FP8E8M0); | ||
| 738 | + auto nn_hw = ir::HardwareInfo(ir::TileLayout::col_major, ir::TileLayout::col_major, 32); | ||
| 739 | + auto nn_tile = MakeTileType({6, 64}, ir::DataType::FP8E8M0, MakeMemRef(ir::MemorySpace::Mat), nn_hw); | ||
| 740 | + auto* info = BackendCCE::Instance().GetOpInfo("block.load"); | ||
| 741 | + ASSERT_NE(info, nullptr); | ||
| 742 | + | ||
| 743 | + TestableCCECodegen codegen(ir::SectionKind::Cube); | ||
| 744 | + codegen.RegisterPointer("scale", "scale_ptr"); | ||
| 745 | + auto load = MakeCallWithKwargs( | ||
| 746 | + "block.load", {MakeVar("out", nn_tile), MakeVar("scale", tensor_type), MakeOffsets({1, 1, 1, 4, 0})}, | ||
| 747 | + {{"tile_dims", std::vector<int>{1, 3}}}); | ||
| 748 | + EXPECT_NO_THROW(info->codegen_func(load, codegen)); | ||
| 749 | + const auto generated = codegen.GetEmittedCode(); | ||
| 750 | + EXPECT_CONTAINS(generated, "Layout::MX_B_ND"); | ||
| 751 | + EXPECT_CONTAINS(generated, "(1, 1, (3 * (64 * (2 * 1))), (2 * 1), 1)"); | ||
| 752 | + EXPECT_CONTAINS(generated, "1 * (3 * 3 * 64 * 2) + 1 * (3 * 64 * 2) + 1 * (64 * 2) + 4 * (2) + 0"); | ||
| 753 | +} | ||
| 754 | + | ||
| 755 | +TEST(BackendCCEBlockOutOps, InfersMxLayoutPerLoadForSameTensor) | ||
| 756 | +{ | ||
| 757 | + auto tensor_type = MakeTensorType({64, 32, 2}, ir::DataType::FP8E8M0); | ||
| 758 | + auto tensor = MakeVar("scale", tensor_type); | ||
| 759 | + auto zz_hw = ir::HardwareInfo(ir::TileLayout::row_major, ir::TileLayout::row_major, 32); | ||
| 760 | + auto nn_hw = ir::HardwareInfo(ir::TileLayout::col_major, ir::TileLayout::col_major, 32); | ||
| 761 | + auto zz_tile = MakeTileType({64, 64}, ir::DataType::FP8E8M0, MakeMemRef(ir::MemorySpace::Mat), zz_hw); | ||
| 762 | + auto nn_tile = MakeTileType({64, 64}, ir::DataType::FP8E8M0, MakeMemRef(ir::MemorySpace::Mat), nn_hw); | ||
| 763 | + auto* info = BackendCCE::Instance().GetOpInfo("block.load"); | ||
| 764 | + ASSERT_NE(info, nullptr); | ||
| 765 | + | ||
| 766 | + TestableCCECodegen codegen(ir::SectionKind::Cube); | ||
| 767 | + codegen.RegisterPointer("scale", "scale_ptr"); | ||
| 768 | + auto a_load = MakeCallWithKwargs("block.load", {MakeVar("out_a", zz_tile), tensor, MakeOffsets({0, 0, 0})}, | ||
| 769 | + {{"tile_dims", std::vector<int>{0, 1}}}); | ||
| 770 | + auto b_load = MakeCallWithKwargs("block.load", {MakeVar("out_b", nn_tile), tensor, MakeOffsets({0, 0, 0})}, | ||
| 771 | + {{"tile_dims", std::vector<int>{0, 1}}, {"is_transpose", true}}); | ||
| 772 | + EXPECT_NO_THROW(info->codegen_func(a_load, codegen)); | ||
| 773 | + EXPECT_NO_THROW(info->codegen_func(b_load, codegen)); | ||
| 774 | + const auto generated = codegen.GetEmittedCode(); | ||
| 775 | + EXPECT_CONTAINS(generated, "Layout::MX_A_ND"); | ||
| 776 | + EXPECT_CONTAINS(generated, "Layout::MX_B_DN"); | ||
| 777 | + EXPECT_CONTAINS(generated, "TLOAD(out_a, mx_load_0);"); | ||
| 778 | + EXPECT_CONTAINS(generated, "TLOAD(out_b, mx_load_1);"); | ||
| 779 | +} | ||
| 780 | + | ||
| 781 | +TEST(BackendCCEBlockOutOps, EmitsInferredMxViewAtEachLoad) | ||
| 782 | +{ | ||
| 783 | + auto tensor = MakeTensorVar("scale", {64, 1, 2}, ir::DataType::FP8E8M0); | ||
| 784 | + auto zz_hw = ir::HardwareInfo(ir::TileLayout::row_major, ir::TileLayout::row_major, 32); | ||
| 785 | + auto tile_type = MakeTileType({64, 2}, ir::DataType::FP8E8M0, MakeMemRef(ir::MemorySpace::Mat), zz_hw); | ||
| 786 | + auto tile = MakeVar("tile", tile_type); | ||
| 787 | + auto make_tile = std::make_shared<const ir::Call>("block.make_tile", std::vector<ir::ExprPtr>{}, tile_type, | ||
| 788 | + ir::Span::Unknown()); | ||
| 789 | + auto tile_assign = std::make_shared<const ir::AssignStmt>(tile, make_tile, ir::Span::Unknown()); | ||
| 790 | + auto load = MakeCallWithKwargs("block.load", {tile, tensor, MakeOffsets({0, 0, 0})}, | ||
| 791 | + {{"tile_dims", std::vector<int>{0, 1}}}); | ||
| 792 | + auto body = std::make_shared<const ir::SeqStmts>( | ||
| 793 | + std::vector<ir::StmtPtr>{tile_assign, std::make_shared<const ir::EvalStmt>(load, ir::Span::Unknown())}, | ||
| 794 | + ir::Span::Unknown()); | ||
| 795 | + | ||
| 796 | + codegen::CCECodegen codegen(ir::SectionKind::Cube); | ||
| 797 | + const auto generated = codegen.GenerateSingle(MakeProgram(body, {tensor}), "a5"); | ||
| 798 | + EXPECT_CONTAINS(generated, "using mx_load_0Shape = pto::TileShape2D<float8_e8m0_t"); | ||
| 799 | + EXPECT_CONTAINS(generated, "TLOAD(tile"); | ||
| 800 | + EXPECT_CONTAINS(generated, ", mx_load_0);"); | ||
| 801 | +} | ||
| 802 | + | ||
| 590 | TEST(BackendCCEBlockOutOps, Store) | 803 | TEST(BackendCCEBlockOutOps, Store) |
| 591 | { | 804 | { |
| 592 | TestableCCECodegen codegen(ir::SectionKind::Vector); | 805 | TestableCCECodegen codegen(ir::SectionKind::Vector); |
| @@ -805,6 +805,12 @@ class MemorySpace(enum.IntEnum): | |||
| 805 | Bias = ... | 805 | Bias = ... |
| 806 | """Bias buffer.""" | 806 | """Bias buffer.""" |
| 807 | 807 | ||
| 808 | + ScaleLeft = ... | ||
| 809 | + """MX scale buffer in L0A.""" | ||
| 810 | + | ||
| 811 | + ScaleRight = ... | ||
| 812 | + """MX scale buffer in L0B.""" | ||
| 813 | + | ||
| 808 | 814 | ||
| 809 | class TensorLayout(enum.IntEnum): | 815 | class TensorLayout(enum.IntEnum): |
| 810 | """Tensor layout type enumeration.""" | 816 | """Tensor layout type enumeration.""" |
| @@ -33,6 +33,9 @@ __all__ = [ | |||
| 33 | "DT_FP4", | 33 | "DT_FP4", |
| 34 | "DT_FP8E4M3FN", | 34 | "DT_FP8E4M3FN", |
| 35 | "DT_FP8E5M2", | 35 | "DT_FP8E5M2", |
| 36 | + "DT_FP8E8M0", | ||
| 37 | + "DT_FP4E2M1", | ||
| 38 | + "DT_FP4E1M2", | ||
| 36 | "DT_FP16", | 39 | "DT_FP16", |
| 37 | "DT_FP32", | 40 | "DT_FP32", |
| 38 | "DT_BF16", | 41 | "DT_BF16", |
| @@ -49,6 +52,9 @@ DT_BOOL = DataType.BOOL | |||
| 49 | DT_FP4 = DataType.FP4 | 52 | DT_FP4 = DataType.FP4 |
| 50 | DT_FP8E4M3FN = DataType.FP8E4M3FN | 53 | DT_FP8E4M3FN = DataType.FP8E4M3FN |
| 51 | DT_FP8E5M2 = DataType.FP8E5M2 | 54 | DT_FP8E5M2 = DataType.FP8E5M2 |
| 55 | +DT_FP8E8M0 = DataType.FP8E8M0 | ||
| 56 | +DT_FP4E2M1 = DataType.FP4E2M1 | ||
| 57 | +DT_FP4E1M2 = DataType.FP4E1M2 | ||
| 52 | DT_FP16 = DataType.FP16 | 58 | DT_FP16 = DataType.FP16 |
| 53 | DT_FP32 = DataType.FP32 | 59 | DT_FP32 = DataType.FP32 |
| 54 | DT_HF4 = DataType.HF4 | 60 | DT_HF4 = DataType.HF4 |
| @@ -61,6 +61,9 @@ TileType = _types.TileType | |||
| 61 | FP4 = DataType.FP4 | 61 | FP4 = DataType.FP4 |
| 62 | FP8E4M3FN = DataType.FP8E4M3FN | 62 | FP8E4M3FN = DataType.FP8E4M3FN |
| 63 | FP8E5M2 = DataType.FP8E5M2 | 63 | FP8E5M2 = DataType.FP8E5M2 |
| 64 | +FP8E8M0 = DataType.FP8E8M0 | ||
| 65 | +FP4E2M1 = DataType.FP4E2M1 | ||
| 66 | +FP4E1M2 = DataType.FP4E1M2 | ||
| 64 | FP16 = DataType.FP16 | 67 | FP16 = DataType.FP16 |
| 65 | FP32 = DataType.FP32 | 68 | FP32 = DataType.FP32 |
| 66 | BF16 = DataType.BF16 | 69 | BF16 = DataType.BF16 |
| @@ -158,8 +158,9 @@ def _ir_load( | |||
| 158 | kwargs: dict[str, Any] = {} | 158 | kwargs: dict[str, Any] = {} |
| 159 | if is_transpose: | 159 | if is_transpose: |
| 160 | kwargs["is_transpose"] = is_transpose | 160 | kwargs["is_transpose"] = is_transpose |
| 161 | - default_tile_dims = list(range(tensor_ndim - tile_ndim, tensor_ndim)) | 161 | + # Specialized lowerings may use a different fallback, so preserve every |
| 162 | - if tile_dims != default_tile_dims: | 162 | + # explicitly supplied order, including the ordinary last-two-axes order. |
| 163 | + if order is not None: | ||
| 163 | kwargs["tile_dims"] = tile_dims | 164 | kwargs["tile_dims"] = tile_dims |
| 164 | if isinstance(offsets, _ir_core.MakeTuple): | 165 | if isinstance(offsets, _ir_core.MakeTuple): |
| 165 | _validate_offset_bounds("load", tensor.type.shape, offsets.elements) | 166 | _validate_offset_bounds("load", tensor.type.shape, offsets.elements) |
| @@ -199,8 +200,7 @@ def _ir_load_tile( | |||
| 199 | kwargs: dict[str, Any] = {} | 200 | kwargs: dict[str, Any] = {} |
| 200 | if is_transpose: | 201 | if is_transpose: |
| 201 | kwargs["is_transpose"] = is_transpose | 202 | kwargs["is_transpose"] = is_transpose |
| 202 | - default_tile_dims = list(range(tensor_ndim - tile_ndim, tensor_ndim)) | 203 | + if order is not None: |
| 203 | - if tile_dims != default_tile_dims: | ||
| 204 | kwargs["tile_dims"] = tile_dims | 204 | kwargs["tile_dims"] = tile_dims |
| 205 | return _ir_core.create_op_call(block_ir_op("load"), [out, tensor, abs_offsets], kwargs, actual_span) | 205 | return _ir_core.create_op_call(block_ir_op("load"), [out, tensor, abs_offsets], kwargs, actual_span) |
| 206 | 206 | ||
| @@ -585,11 +585,14 @@ def _ir_move( | |||
| 585 | (MemorySpace.Mat, MemorySpace.Scaling), | 585 | (MemorySpace.Mat, MemorySpace.Scaling), |
| 586 | (MemorySpace.Vec, MemorySpace.Mat), | 586 | (MemorySpace.Vec, MemorySpace.Mat), |
| 587 | (MemorySpace.Mat, MemorySpace.Bias), | 587 | (MemorySpace.Mat, MemorySpace.Bias), |
| 588 | + (MemorySpace.Mat, MemorySpace.ScaleLeft), | ||
| 589 | + (MemorySpace.Mat, MemorySpace.ScaleRight), | ||
| 588 | } | 590 | } |
| 589 | if _src_mem is not None and _dst_mem is not None and (_src_mem, _dst_mem) not in _supported_move_paths: | 591 | if _src_mem is not None and _dst_mem is not None and (_src_mem, _dst_mem) not in _supported_move_paths: |
| 590 | raise ValueError( | 592 | raise ValueError( |
| 591 | f"move: unsupported data path src({_src_mem.name})->dst({_dst_mem.name}), " | 593 | f"move: unsupported data path src({_src_mem.name})->dst({_dst_mem.name}), " |
| 592 | - f"supported paths: Mat->Left, Mat->Right, Mat->Scaling, Mat->Bias, Acc->Vec, Vec->Vec, Vec->Mat" | 594 | + f"supported paths: Mat->Left, Mat->Right, Mat->Scaling, Mat->Bias, Mat->ScaleLeft, " |
| 595 | + f"Mat->ScaleRight, Acc->Vec, Vec->Vec, Vec->Mat" | ||
| 593 | ) | 596 | ) |
| 594 | 597 | ||
| 595 | _check_move_shape_compat(out, src, offset, acc_to_vec_mode, actual_span) | 598 | _check_move_shape_compat(out, src, offset, acc_to_vec_mode, actual_span) |
| @@ -739,6 +742,9 @@ _SCALAR_UNSUPPORTED_DTYPES: tuple[DataType, ...] = ( | |||
| 739 | DataType.FP4, | 742 | DataType.FP4, |
| 740 | DataType.FP8E4M3FN, | 743 | DataType.FP8E4M3FN, |
| 741 | DataType.FP8E5M2, | 744 | DataType.FP8E5M2, |
| 745 | + DataType.FP8E8M0, | ||
| 746 | + DataType.FP4E2M1, | ||
| 747 | + DataType.FP4E1M2, | ||
| 742 | DataType.INT4, | 748 | DataType.INT4, |
| 743 | DataType.UINT4, | 749 | DataType.UINT4, |
| 744 | DataType.HF4, | 750 | DataType.HF4, |
| @@ -748,6 +754,9 @@ _SCALAR_UNSUPPORTED_DTYPES: tuple[DataType, ...] = ( | |||
| 748 | _SUPPORTED_DTYPES: tuple[DataType, ...] = ( | 754 | _SUPPORTED_DTYPES: tuple[DataType, ...] = ( |
| 749 | DataType.FP8E4M3FN, | 755 | DataType.FP8E4M3FN, |
| 750 | DataType.FP8E5M2, | 756 | DataType.FP8E5M2, |
| 757 | + DataType.FP8E8M0, | ||
| 758 | + DataType.FP4E2M1, | ||
| 759 | + DataType.FP4E1M2, | ||
| 751 | DataType.HF8, | 760 | DataType.HF8, |
| 752 | DataType.INT8, | 761 | DataType.INT8, |
| 753 | DataType.FP16, | 762 | DataType.FP16, |
| @@ -896,6 +905,13 @@ def _validate_tile_dims( | |||
| 896 | ) -> list[int]: | 905 | ) -> list[int]: |
| 897 | if tile_dims is None: | 906 | if tile_dims is None: |
| 898 | tile_dims = list(range(tensor_ndim - tile_ndim, tensor_ndim)) | 907 | tile_dims = list(range(tensor_ndim - tile_ndim, tensor_ndim)) |
| 908 | + if len(tile_dims) != tile_ndim: | ||
| 909 | + raise ValueError(f"{op_name}: order must contain exactly {tile_ndim} axes, got {tile_dims}") | ||
| 910 | + if len(set(tile_dims)) != len(tile_dims): | ||
| 911 | + raise ValueError(f"{op_name}: order axes must be unique, got {tile_dims}") | ||
| 912 | + for dim in tile_dims: | ||
| 913 | + if dim < 0 or dim >= tensor_ndim: | ||
| 914 | + raise ValueError(f"{op_name}: order axis {dim} is out of range for Tensor rank {tensor_ndim}") | ||
| 899 | return tile_dims | 915 | return tile_dims |
| 900 | 916 | ||
| 901 | 917 | ||
| @@ -1171,6 +1187,8 @@ _DEFAULT_LAYOUTS_A5: dict[MemorySpace, TensorLayout] = { | |||
| 1171 | MemorySpace.Right: TensorLayout.ZN, | 1187 | MemorySpace.Right: TensorLayout.ZN, |
| 1172 | MemorySpace.Scaling: TensorLayout.ND, | 1188 | MemorySpace.Scaling: TensorLayout.ND, |
| 1173 | MemorySpace.Acc: TensorLayout.NZ, | 1189 | MemorySpace.Acc: TensorLayout.NZ, |
| 1190 | + MemorySpace.ScaleLeft: TensorLayout.ZZ, | ||
| 1191 | + MemorySpace.ScaleRight: TensorLayout.NN, | ||
| 1174 | } | 1192 | } |
| 1175 | 1193 | ||
| 1176 | mem_id: int = 0 | 1194 | mem_id: int = 0 |
| @@ -1199,6 +1217,13 @@ def _apply_default_layout(tt: "TileType") -> None: | |||
| 1199 | arch = _get_current_arch() | 1217 | arch = _get_current_arch() |
| 1200 | layout_dict = _DEFAULT_LAYOUTS_A5 if arch == "a5" else _DEFAULT_LAYOUTS_A3 | 1218 | layout_dict = _DEFAULT_LAYOUTS_A5 if arch == "a5" else _DEFAULT_LAYOUTS_A3 |
| 1201 | default_layout = layout_dict.get(tt.target_memory) | 1219 | default_layout = layout_dict.get(tt.target_memory) |
| 1220 | + | ||
| 1221 | + if tt.target_memory in (MemorySpace.ScaleLeft, MemorySpace.ScaleRight): | ||
| 1222 | + if default_layout is None: | ||
| 1223 | + raise ValueError(f"{tt.target_memory.name} is only supported on A5, got architecture '{arch}'") | ||
| 1224 | + if tt.fractal is None: | ||
| 1225 | + tt.fractal = 32 | ||
| 1226 | + | ||
| 1202 | if default_layout is None: | 1227 | if default_layout is None: |
| 1203 | return | 1228 | return |
| 1204 | 1229 | ||
| @@ -1212,6 +1237,8 @@ def _apply_default_layout(tt: "TileType") -> None: | |||
| 1212 | allowed_layouts.add(TensorLayout.ZN) | 1237 | allowed_layouts.add(TensorLayout.ZN) |
| 1213 | if tt.dtype in (DataType.UINT64, DataType.INT64): | 1238 | if tt.dtype in (DataType.UINT64, DataType.INT64): |
| 1214 | allowed_layouts.add(TensorLayout.ND) | 1239 | allowed_layouts.add(TensorLayout.ND) |
| 1240 | + if tt.dtype == DataType.FP8E8M0: | ||
| 1241 | + allowed_layouts.update({TensorLayout.ZZ, TensorLayout.NN}) | ||
| 1215 | 1242 | ||
| 1216 | if tt.layout not in allowed_layouts: | 1243 | if tt.layout not in allowed_layouts: |
| 1217 | space_name = tt.target_memory.name | 1244 | space_name = tt.target_memory.name |
| @@ -1226,6 +1253,13 @@ def _apply_default_layout(tt: "TileType") -> None: | |||
| 1226 | if tt.dtype in (DataType.FP32, DataType.INT32): | 1253 | if tt.dtype in (DataType.FP32, DataType.INT32): |
| 1227 | tt.fractal = 1024 | 1254 | tt.fractal = 1024 |
| 1228 | 1255 | ||
| 1256 | + if ( | ||
| 1257 | + tt.target_memory == MemorySpace.Mat | ||
| 1258 | + and tt.dtype == DataType.FP8E8M0 | ||
| 1259 | + and tt.layout in (TensorLayout.ZZ, TensorLayout.NN) | ||
| 1260 | + and tt.fractal is None | ||
| 1261 | + ): | ||
| 1262 | + tt.fractal = 32 | ||
| 1229 | 1263 | ||
| 1230 | @dataclass | 1264 | @dataclass |
| 1231 | class TileType: | 1265 | class TileType: |
| @@ -1259,6 +1293,8 @@ _MEMORY_ALIGNMENT: dict[MemorySpace, int] = { | |||
| 1259 | MemorySpace.Left: 512, | 1293 | MemorySpace.Left: 512, |
| 1260 | MemorySpace.Right: 512, | 1294 | MemorySpace.Right: 512, |
| 1261 | MemorySpace.Acc: 64, | 1295 | MemorySpace.Acc: 64, |
| 1296 | + MemorySpace.ScaleLeft: 32, | ||
| 1297 | + MemorySpace.ScaleRight: 32, | ||
| 1262 | } | 1298 | } |
| 1263 | 1299 | ||
| 1264 | 1300 | ||
| @@ -1882,3 +1918,170 @@ def _parse_matmul_acc(self, call: ast.Call) -> Expr: | |||
| 1882 | args = [self.parse_expression(arg) for arg in call.args] | 1918 | args = [self.parse_expression(arg) for arg in call.args] |
| 1883 | kwargs = self.parse_op_kwargs(call) | 1919 | kwargs = self.parse_op_kwargs(call) |
| 1884 | return _ir_matmul_acc(*args, **kwargs, span=span) | 1920 | return _ir_matmul_acc(*args, **kwargs, span=span) |
| 1921 | + | ||
| 1922 | + | ||
| 1923 | +_MX_FP8_DTYPES = (DataType.FP8E4M3FN, DataType.FP8E5M2) | ||
| 1924 | +_MX_FP4_DTYPES = (DataType.FP4E2M1, DataType.FP4E1M2) | ||
| 1925 | + | ||
| 1926 | + | ||
| 1927 | +def _check_mx_scale_tile( | ||
| 1928 | + op_name: str, | ||
| 1929 | + scale: Expr | None, | ||
| 1930 | + data: Expr, | ||
| 1931 | + *, | ||
| 1932 | + is_left: bool, | ||
| 1933 | +) -> None: | ||
| 1934 | + """Validate an MX scale tile and its shape/address relationship to the paired data tile.""" | ||
| 1935 | + if is_left: | ||
| 1936 | + scale_name, data_name, group_axis = "scale_a", "lhs_tile", 1 | ||
| 1937 | + expected_space, expected_desc = MemorySpace.ScaleLeft, "L0A (ScaleLeft)" | ||
| 1938 | + else: | ||
| 1939 | + scale_name, data_name, group_axis = "scale_b", "rhs_tile", 0 | ||
| 1940 | + expected_space, expected_desc = MemorySpace.ScaleRight, "L0B (ScaleRight)" | ||
| 1941 | + | ||
| 1942 | + if scale is None: | ||
| 1943 | + raise ValueError(f"{op_name}: {scale_name} is required") | ||
| 1944 | + scale_type = getattr(scale, "type", None) | ||
| 1945 | + if not isinstance(scale_type, _IRTileType): | ||
| 1946 | + raise ValueError(f"{op_name}: {scale_name} must be a Tile") | ||
| 1947 | + if scale_type.dtype != DataType.FP8E8M0: | ||
| 1948 | + raise ValueError(f"{op_name}: {scale_name} must use FP8E8M0 dtype, got {scale_type.dtype}") | ||
| 1949 | + _check_tile_memory_space(op_name, scale_name, scale, expected_space, expected_desc) | ||
| 1950 | + | ||
| 1951 | + data_type = data.type | ||
| 1952 | + data_shape = _tile_shape_ints(data_type) | ||
| 1953 | + scale_shape = _tile_shape_ints(scale_type) | ||
| 1954 | + if data_shape is not None and scale_shape is not None: | ||
| 1955 | + expected_shape = data_shape.copy() | ||
| 1956 | + expected_shape[group_axis] //= 32 | ||
| 1957 | + if scale_shape != expected_shape: | ||
| 1958 | + raise ValueError( | ||
| 1959 | + f"{op_name}: {scale_name} shape must match {data_name} MX groups, " | ||
| 1960 | + f"expected {expected_shape} for {data_name} shape {data_shape}, got {scale_shape}." | ||
| 1961 | + ) | ||
| 1962 | + | ||
| 1963 | + # A5 mad_mx receives only the L0A/L0B data pointers and derives the | ||
| 1964 | + # corresponding L0AMX/L0BMX address by shifting right four bits. Skip | ||
| 1965 | + # auto-allocated tiles or non-constant addresses, which cannot be proven here. | ||
| 1966 | + data_memref = data_type.memref | ||
| 1967 | + scale_memref = scale_type.memref | ||
| 1968 | + if data_memref is None or scale_memref is None: | ||
| 1969 | + return | ||
| 1970 | + | ||
| 1971 | + data_addr = data_memref.addr | ||
| 1972 | + scale_addr = scale_memref.addr | ||
| 1973 | + if not isinstance(data_addr, ConstInt) or not isinstance(scale_addr, ConstInt): | ||
| 1974 | + return | ||
| 1975 | + | ||
| 1976 | + expected_scale_addr = data_addr.value >> 4 | ||
| 1977 | + if scale_addr.value != expected_scale_addr: | ||
| 1978 | + raise ValueError( | ||
| 1979 | + f"{op_name}: {scale_name} address must equal {data_name} address >> 4, " | ||
| 1980 | + f"got {data_name}=0x{data_addr.value:X}, expected {scale_name}=0x{expected_scale_addr:X}, " | ||
| 1981 | + f"actual {scale_name}=0x{scale_addr.value:X}." | ||
| 1982 | + ) | ||
| 1983 | + | ||
| 1984 | + | ||
| 1985 | +def _check_mx_operands( | ||
| 1986 | + op_name: str, | ||
| 1987 | + dst: Expr, | ||
| 1988 | + lhs: Expr, | ||
| 1989 | + rhs: Expr, | ||
| 1990 | + scale_a: Expr, | ||
| 1991 | + scale_b: Expr, | ||
| 1992 | + acc: Expr | None = None, | ||
| 1993 | +) -> None: | ||
| 1994 | + """Run the common declared-type and shape checks for MX matmul variants.""" | ||
| 1995 | + _check_tile_memory_space(op_name, "dst_tile", dst, MemorySpace.Acc, "L0C (Acc)") | ||
| 1996 | + _check_tile_memory_space(op_name, "lhs_tile", lhs, MemorySpace.Left, "L0A (Left)") | ||
| 1997 | + _check_tile_memory_space(op_name, "rhs_tile", rhs, MemorySpace.Right, "L0B (Right)") | ||
| 1998 | + if acc is not None: | ||
| 1999 | + _check_tile_memory_space(op_name, "acc_tile", acc, MemorySpace.Acc, "L0C (Acc)") | ||
| 2000 | + | ||
| 2001 | + dst_shape = _tile_shape_ints(dst.type) | ||
| 2002 | + lhs_shape = _tile_shape_ints(lhs.type) | ||
| 2003 | + rhs_shape = _tile_shape_ints(rhs.type) | ||
| 2004 | + lhs_k = lhs_shape[1] if lhs_shape is not None else None | ||
| 2005 | + rhs_k = rhs_shape[0] if rhs_shape is not None else None | ||
| 2006 | + | ||
| 2007 | + if lhs_k is not None and rhs_k is not None and lhs_k != rhs_k: | ||
| 2008 | + raise ValueError(f"{op_name}: lhs and rhs K dimensions must match, got lhs K={lhs_k}, rhs K={rhs_k}.") | ||
| 2009 | + for name, k_value in (("lhs", lhs_k), ("rhs", rhs_k)): | ||
| 2010 | + if k_value is not None and k_value % 64 != 0: | ||
| 2011 | + raise ValueError( | ||
| 2012 | + f"{op_name}: K dimension must be a multiple of 64 for MX matmul, got {name} K={k_value}." | ||
| 2013 | + ) | ||
| 2014 | + | ||
| 2015 | + if dst_shape is not None and lhs_shape is not None and rhs_shape is not None: | ||
| 2016 | + expected_shape = [lhs_shape[0], rhs_shape[1]] | ||
| 2017 | + if dst_shape != expected_shape: | ||
| 2018 | + raise ValueError( | ||
| 2019 | + f"{op_name}: dst_tile shape must be [lhs M, rhs N], " | ||
| 2020 | + f"expected {expected_shape}, got {dst_shape}." | ||
| 2021 | + ) | ||
| 2022 | + if acc is not None: | ||
| 2023 | + acc_shape = _tile_shape_ints(acc.type) | ||
| 2024 | + if dst_shape is not None and acc_shape is not None and acc_shape != dst_shape: | ||
| 2025 | + raise ValueError( | ||
| 2026 | + f"{op_name}: acc_tile shape must match dst_tile shape, " | ||
| 2027 | + f"got acc_tile={acc_shape}, dst_tile={dst_shape}." | ||
| 2028 | + ) | ||
| 2029 | + if acc.type.dtype != DataType.FP32: | ||
| 2030 | + raise ValueError(f"{op_name}: acc_tile must use FP32 dtype, got {acc.type.dtype}.") | ||
| 2031 | + | ||
| 2032 | + _check_mx_scale_tile(op_name, scale_a, lhs, is_left=True) | ||
| 2033 | + _check_mx_scale_tile(op_name, scale_b, rhs, is_left=False) | ||
| 2034 | + | ||
| 2035 | + a_dtype, b_dtype, dst_dtype = lhs.type.dtype, rhs.type.dtype, dst.type.dtype | ||
| 2036 | + valid_input_dtypes = (a_dtype in _MX_FP8_DTYPES and b_dtype in _MX_FP8_DTYPES) or ( | ||
| 2037 | + a_dtype in _MX_FP4_DTYPES and b_dtype in _MX_FP4_DTYPES | ||
| 2038 | + ) | ||
| 2039 | + if not valid_input_dtypes or dst_dtype != DataType.FP32: | ||
| 2040 | + raise ValueError( | ||
| 2041 | + f"{op_name}: (lhs,rhs) must be FP8/FP4 combo and dst FP32, " | ||
| 2042 | + f"got ({a_dtype},{b_dtype},{dst_dtype})." | ||
| 2043 | + ) | ||
| 2044 | + | ||
| 2045 | + | ||
| 2046 | +def _ir_matmul_mx( | ||
| 2047 | + dst: Expr, lhs: Expr, rhs: Expr, scale_a: Expr, scale_b: Expr, | ||
| 2048 | + *, span: Span | None = None, phase: AccPhase | None = None | ||
| 2049 | +) -> Expr: | ||
| 2050 | + actual_span = span or _span() | ||
| 2051 | + _check_mx_operands("matmul_mx", dst, lhs, rhs, scale_a, scale_b) | ||
| 2052 | + kwargs: dict[str, Any] = {} | ||
| 2053 | + if phase is not None: | ||
| 2054 | + kwargs["phase"] = phase | ||
| 2055 | + return _ir_core.create_op_call( | ||
| 2056 | + block_ir_op("matmul_mx"), [dst, lhs, rhs, scale_a, scale_b], kwargs, actual_span | ||
| 2057 | + ) | ||
| 2058 | + | ||
| 2059 | + | ||
| 2060 | +def _ir_matmul_mx_acc( | ||
| 2061 | + dst: Expr, acc: Expr, lhs: Expr, rhs: Expr, scale_a: Expr, scale_b: Expr, | ||
| 2062 | + *, span: Span | None = None, phase: AccPhase | None = None | ||
| 2063 | +) -> Expr: | ||
| 2064 | + actual_span = span or _span() | ||
| 2065 | + _check_mx_operands("matmul_mx_acc", dst, lhs, rhs, scale_a, scale_b, acc) | ||
| 2066 | + kwargs: dict[str, Any] = {} | ||
| 2067 | + if phase is not None: | ||
| 2068 | + kwargs["phase"] = phase | ||
| 2069 | + return _ir_core.create_op_call( | ||
| 2070 | + block_ir_op("matmul_mx_acc"), [dst, acc, lhs, rhs, scale_a, scale_b], kwargs, actual_span | ||
| 2071 | + ) | ||
| 2072 | + | ||
| 2073 | + | ||
| 2074 | +@op_impl("matmul_mx") | ||
| 2075 | +def _parse_matmul_mx(self, call: ast.Call) -> Expr: | ||
| 2076 | + span = self.span_tracker.get_span(call) | ||
| 2077 | + args = [self.parse_expression(arg) for arg in call.args] | ||
| 2078 | + kwargs = self.parse_op_kwargs(call) | ||
| 2079 | + return _ir_matmul_mx(*args, **kwargs, span=span) | ||
| 2080 | + | ||
| 2081 | + | ||
| 2082 | +@op_impl("matmul_mx_acc") | ||
| 2083 | +def _parse_matmul_mx_acc(self, call: ast.Call) -> Expr: | ||
| 2084 | + span = self.span_tracker.get_span(call) | ||
| 2085 | + args = [self.parse_expression(arg) for arg in call.args] | ||
| 2086 | + kwargs = self.parse_op_kwargs(call) | ||
| 2087 | + return _ir_matmul_mx_acc(*args, **kwargs, span=span) | ||
| @@ -138,6 +138,8 @@ __all__ = [ | |||
| 138 | # Matrix | 138 | # Matrix |
| 139 | "matmul", | 139 | "matmul", |
| 140 | "matmul_acc", | 140 | "matmul_acc", |
| 141 | + "matmul_mx", | ||
| 142 | + "matmul_mx_acc", | ||
| 141 | "transpose", | 143 | "transpose", |
| 142 | # Reductions | 144 | # Reductions |
| 143 | "sum", | 145 | "sum", |
| @@ -315,6 +317,8 @@ from ._api import ( | |||
| 315 | make_tile_group, | 317 | make_tile_group, |
| 316 | matmul, | 318 | matmul, |
| 317 | matmul_acc, | 319 | matmul_acc, |
| 320 | + matmul_mx, | ||
| 321 | + matmul_mx_acc, | ||
| 318 | max, | 322 | max, |
| 319 | maximum, | 323 | maximum, |
| 320 | min, | 324 | min, |
| @@ -631,6 +631,44 @@ def matmul_acc( | |||
| 631 | """ | 631 | """ |
| 632 | 632 | ||
| 633 | 633 | ||
| 634 | +@_api_decl | ||
| 635 | +def matmul_mx( | ||
| 636 | + dst_tile: Tile, lhs_tile: Tile, rhs_tile: Tile, scale_a: Tile, scale_b: Tile, | ||
| 637 | + *, phase: Optional[AccPhase] = None | ||
| 638 | +) -> None: | ||
| 639 | + """MX matmul with per-group E8M0 scale: ``dst = lhs @ rhs`` | ||
| 640 | + | ||
| 641 | + Left/Right tiles use FP8/FP4 dtype; scale tiles use E8M0 in ScaleLeft/ScaleRight. | ||
| 642 | + Hardware mad_mx reads scale implicitly via SFractal layout. | ||
| 643 | + | ||
| 644 | + Args: | ||
| 645 | + dst_tile: Accumulator Tile (L0C, output, FP32) | ||
| 646 | + lhs_tile: Left matrix Tile (L0A, FP8/FP4) | ||
| 647 | + rhs_tile: Right matrix Tile (L0B, FP8/FP4) | ||
| 648 | + scale_a: Left scale Tile (ScaleLeft, E8M0) | ||
| 649 | + scale_b: Right scale Tile (ScaleRight, E8M0) | ||
| 650 | + phase: Optional — ``pl.AccPhase.Partial`` or ``pl.AccPhase.Final`` | ||
| 651 | + """ | ||
| 652 | + | ||
| 653 | + | ||
| 654 | +@_api_decl | ||
| 655 | +def matmul_mx_acc( | ||
| 656 | + dst_tile: Tile, acc_tile: Tile, lhs_tile: Tile, rhs_tile: Tile, scale_a: Tile, scale_b: Tile, | ||
| 657 | + *, phase: Optional[AccPhase] = None | ||
| 658 | +) -> None: | ||
| 659 | + """MX matmul with accumulation: ``dst = acc + lhs @ rhs`` | ||
| 660 | + | ||
| 661 | + Args: | ||
| 662 | + dst_tile: Destination Tile (L0C, output, FP32) | ||
| 663 | + acc_tile: Accumulator Tile (existing value to add to) | ||
| 664 | + lhs_tile: Left matrix Tile (L0A, FP8/FP4) | ||
| 665 | + rhs_tile: Right matrix Tile (L0B, FP8/FP4) | ||
| 666 | + scale_a: Left scale Tile (ScaleLeft, E8M0) | ||
| 667 | + scale_b: Right scale Tile (ScaleRight, E8M0) | ||
| 668 | + phase: Optional — ``pl.AccPhase.Partial`` or ``pl.AccPhase.Final`` | ||
| 669 | + """ | ||
| 670 | + | ||
| 671 | + | ||
| 634 | @_api_decl | 672 | @_api_decl |
| 635 | def transpose(out: Tile, src: Tile) -> None: | 673 | def transpose(out: Tile, src: Tile) -> None: |
| 636 | """Transpose Tile by swapping the last two dimensions. | 674 | """Transpose Tile by swapping the last two dimensions. |
| @@ -1225,7 +1225,7 @@ class CallParserMixin: | |||
| 1225 | seen.add(tref.slot_id) | 1225 | seen.add(tref.slot_id) |
| 1226 | unique_refs.append(tref) | 1226 | unique_refs.append(tref) |
| 1227 | 1227 | ||
| 1228 | - if op_name in ("matmul", "matmul_acc", "store", "store_tile"): | 1228 | + if op_name in ("matmul", "matmul_acc", "matmul_mx", "matmul_mx_acc", "store", "store_tile"): |
| 1229 | phase = None | 1229 | phase = None |
| 1230 | for kw in call.keywords: | 1230 | for kw in call.keywords: |
| 1231 | if kw.arg == "phase": | 1231 | if kw.arg == "phase": |
| @@ -77,7 +77,8 @@ def get_move_pipe( | |||
| 77 | if src_memory == MemorySpace.Acc and target_memory == MemorySpace.Vec: | 77 | if src_memory == MemorySpace.Acc and target_memory == MemorySpace.Vec: |
| 78 | return PipeType.FIX | 78 | return PipeType.FIX |
| 79 | if src_memory == MemorySpace.Mat: | 79 | if src_memory == MemorySpace.Mat: |
| 80 | - if target_memory in (MemorySpace.Left, MemorySpace.Right, MemorySpace.Bias): | 80 | + if target_memory in (MemorySpace.Left, MemorySpace.Right, MemorySpace.Bias, MemorySpace.ScaleLeft, |
| 81 | + MemorySpace.ScaleRight): | ||
| 81 | return PipeType.MTE1 | 82 | return PipeType.MTE1 |
| 82 | if target_memory == MemorySpace.Vec: | 83 | if target_memory == MemorySpace.Vec: |
| 83 | return PipeType.V | 84 | return PipeType.V |
| @@ -124,6 +125,8 @@ _BLOCK_OP_TILE_ROLES: dict[str, list] = { | |||
| 124 | "matmul": ["W", "R", "R"], # matmul(out, lhs, rhs) | 125 | "matmul": ["W", "R", "R"], # matmul(out, lhs, rhs) |
| 125 | "matmul_acc": ["W", "RW", "R", "R"], # matmul_acc(out, acc, lhs, rhs) | 126 | "matmul_acc": ["W", "RW", "R", "R"], # matmul_acc(out, acc, lhs, rhs) |
| 126 | "matmul_bias": ["W", "R", "R", "R"], # matmul_bias(out, lhs, rhs, bias) | 127 | "matmul_bias": ["W", "R", "R", "R"], # matmul_bias(out, lhs, rhs, bias) |
| 128 | + "matmul_mx": ["W", "R", "R", "R", "R"], # matmul_mx(out, lhs, rhs, scale_a, scale_b) | ||
| 129 | + "matmul_mx_acc": ["W", "RW", "R", "R", "R", "R"], # matmul_mx_acc(out, acc, lhs, rhs, scale_a, scale_b) | ||
| 127 | "gemv": ["W", "R", "R"], | 130 | "gemv": ["W", "R", "R"], |
| 128 | "gemv_acc": ["W", "RW", "R", "R"], | 131 | "gemv_acc": ["W", "RW", "R", "R"], |
| 129 | "gemv_bias": ["W", "R", "R", "R"], | 132 | "gemv_bias": ["W", "R", "R", "R"], |
| @@ -93,6 +93,8 @@ class TypeResolver: | |||
| 93 | "Scaling": ir.MemorySpace.Scaling, | 93 | "Scaling": ir.MemorySpace.Scaling, |
| 94 | "Acc": ir.MemorySpace.Acc, | 94 | "Acc": ir.MemorySpace.Acc, |
| 95 | "Bias": ir.MemorySpace.Bias, | 95 | "Bias": ir.MemorySpace.Bias, |
| 96 | + "ScaleLeft": ir.MemorySpace.ScaleLeft, | ||
| 97 | + "ScaleRight": ir.MemorySpace.ScaleRight, | ||
| 96 | } | 98 | } |
| 97 | 99 | ||
| 98 | def __init__( | 100 | def __init__( |
| @@ -110,6 +110,9 @@ _ORIG_DTYPE_TO_PYPTO = { | |||
| 110 | "dt_bf16": DataType.BF16, | 110 | "dt_bf16": DataType.BF16, |
| 111 | "dt_float8_e4m3fn": DataType.FP8E4M3FN, | 111 | "dt_float8_e4m3fn": DataType.FP8E4M3FN, |
| 112 | "dt_float8_e5m2": DataType.FP8E5M2, | 112 | "dt_float8_e5m2": DataType.FP8E5M2, |
| 113 | + "dt_float8_e8m0": DataType.FP8E8M0, | ||
| 114 | + "dt_fp4_e2m1": DataType.FP4E2M1, | ||
| 115 | + "dt_fp4_e1m2": DataType.FP4E1M2, | ||
| 113 | "dt_hifloat8": DataType.HF8, | 116 | "dt_hifloat8": DataType.HF8, |
| 114 | } | 117 | } |
| 115 | 118 | ||
| @@ -38,6 +38,8 @@ _MEMORY_NAMES = { | |||
| 38 | "Left": MemorySpace.Left, | 38 | "Left": MemorySpace.Left, |
| 39 | "Right": MemorySpace.Right, | 39 | "Right": MemorySpace.Right, |
| 40 | "Acc": MemorySpace.Acc, | 40 | "Acc": MemorySpace.Acc, |
| 41 | + "ScaleLeft": MemorySpace.ScaleLeft, | ||
| 42 | + "ScaleRight": MemorySpace.ScaleRight, | ||
| 41 | } | 43 | } |
| 42 | 44 | ||
| 43 | 45 | ||
| @@ -485,6 +485,8 @@ void BindTypeClass(py::module_& ir) | |||
| 485 | .value("Scaling", MemorySpace::Scaling, "Scaling/FBuffer buffer") | 485 | .value("Scaling", MemorySpace::Scaling, "Scaling/FBuffer buffer") |
| 486 | .value("Acc", MemorySpace::Acc, "Accumulator buffer") | 486 | .value("Acc", MemorySpace::Acc, "Accumulator buffer") |
| 487 | .value("Bias", MemorySpace::Bias, "Bias buffer") | 487 | .value("Bias", MemorySpace::Bias, "Bias buffer") |
| 488 | + .value("ScaleLeft", MemorySpace::ScaleLeft, "MX scale buffer in L0A") | ||
| 489 | + .value("ScaleRight", MemorySpace::ScaleRight, "MX scale buffer in L0B") | ||
| 488 | .export_values(); | 490 | .export_values(); |
| 489 | 491 | ||
| 490 | ir.attr("Mem") = ir.attr("MemorySpace"); | 492 | ir.attr("Mem") = ir.attr("MemorySpace"); |
| @@ -0,0 +1,244 @@ | |||
| 1 | +#!/usr/bin/env python3 | ||
| 2 | +# coding: utf-8 | ||
| 3 | +# Copyright (c) 2026 Huawei Technologies Co., Ltd. | ||
| 4 | +# This program is free software, you can redistribute it and/or modify it under the terms and conditions of | ||
| 5 | +# CANN Open Software License Agreement Version 2.0 (the "License"). | ||
| 6 | +# Please refer to the License for details. You may not use this file except in compliance with the License. | ||
| 7 | +# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | ||
| 8 | +# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | ||
| 9 | +# See LICENSE in the root of the software repository for the full text of the License. | ||
| 10 | +# ----------------------------------------------------------------------------------------------------------- | ||
| 11 | +"""Host-side validation tests for MX block matmul construction.""" | ||
| 12 | + | ||
| 13 | +from itertools import count | ||
| 14 | + | ||
| 15 | +from pypto_pro import DataType, ir | ||
| 16 | +from pypto_pro.ir.op.block_ops import ( | ||
| 17 | + TileType, | ||
| 18 | + _ir_load, | ||
| 19 | + _ir_matmul_mx, | ||
| 20 | + _ir_matmul_mx_acc, | ||
| 21 | + _validate_tile_addr_alignment, | ||
| 22 | +) | ||
| 23 | +import pytest | ||
| 24 | + | ||
| 25 | +_MEMREF_IDS = count() | ||
| 26 | + | ||
| 27 | + | ||
| 28 | +def _tile(name, shape, dtype, memory_space, addr=0): | ||
| 29 | + span = ir.Span.unknown() | ||
| 30 | + dims = [ir.ConstInt(dim, DataType.INDEX, span) for dim in shape] | ||
| 31 | + memref = ir.MemRef( | ||
| 32 | + memory_space, | ||
| 33 | + ir.ConstInt(addr, DataType.INT64, span), | ||
| 34 | + 65536, | ||
| 35 | + next(_MEMREF_IDS), | ||
| 36 | + ) | ||
| 37 | + return ir.Var(name, ir.TileType(dims, dtype, memref), span) | ||
| 38 | + | ||
| 39 | + | ||
| 40 | +def _tensor(name, shape, dtype): | ||
| 41 | + span = ir.Span.unknown() | ||
| 42 | + dims = [ir.ConstInt(dim, DataType.INDEX, span) for dim in shape] | ||
| 43 | + return ir.Var(name, ir.TensorType(dims, dtype), span) | ||
| 44 | + | ||
| 45 | + | ||
| 46 | +def _mx_tiles(*, k=64, lhs_dtype=DataType.FP8E4M3FN, | ||
| 47 | + rhs_dtype=DataType.FP8E5M2, dst_dtype=DataType.FP32, | ||
| 48 | + scale_a_dtype=DataType.FP8E8M0, | ||
| 49 | + scale_a_space=ir.MemorySpace.ScaleLeft): | ||
| 50 | + return { | ||
| 51 | + "dst": _tile("dst", [64, 64], dst_dtype, ir.MemorySpace.Acc), | ||
| 52 | + "acc": _tile("acc", [64, 64], DataType.FP32, ir.MemorySpace.Acc), | ||
| 53 | + "lhs": _tile("lhs", [64, k], lhs_dtype, ir.MemorySpace.Left), | ||
| 54 | + "rhs": _tile("rhs", [k, 64], rhs_dtype, ir.MemorySpace.Right), | ||
| 55 | + "scale_a": _tile("scale_a", [64, k // 32], scale_a_dtype, scale_a_space), | ||
| 56 | + "scale_b": _tile("scale_b", [k // 32, 64], DataType.FP8E8M0, ir.MemorySpace.ScaleRight), | ||
| 57 | + } | ||
| 58 | + | ||
| 59 | + | ||
| 60 | +def test_load_preserves_explicit_default_order_in_ir(): | ||
| 61 | + src = _tensor("scale", [64, 1, 2], DataType.FP8E8M0) | ||
| 62 | + dst = _tile("scale_l1", [64, 2], DataType.FP8E8M0, ir.MemorySpace.Mat) | ||
| 63 | + | ||
| 64 | + call = _ir_load(dst, src, [0, 0, 0], order=[1, 2]) | ||
| 65 | + | ||
| 66 | + assert '"tile_dims": [1, 2]' in str(call) | ||
| 67 | + | ||
| 68 | + | ||
| 69 | +def test_matmul_mx_builds_registered_call(): | ||
| 70 | + t = _mx_tiles() | ||
| 71 | + call = _ir_matmul_mx(t["dst"], t["lhs"], t["rhs"], t["scale_a"], t["scale_b"]) | ||
| 72 | + | ||
| 73 | + assert call.name == "block.matmul_mx" | ||
| 74 | + assert call.type.dtype == DataType.FP32 | ||
| 75 | + assert [arg.name for arg in call.args] == ["dst", "lhs", "rhs", "scale_a", "scale_b"] | ||
| 76 | + | ||
| 77 | + | ||
| 78 | +def test_matmul_mx_acc_builds_registered_call(): | ||
| 79 | + t = _mx_tiles(lhs_dtype=DataType.FP4E2M1, rhs_dtype=DataType.FP4E1M2) | ||
| 80 | + call = _ir_matmul_mx_acc( | ||
| 81 | + t["dst"], t["acc"], t["lhs"], t["rhs"], t["scale_a"], t["scale_b"] | ||
| 82 | + ) | ||
| 83 | + | ||
| 84 | + assert call.name == "block.matmul_mx_acc" | ||
| 85 | + assert call.type.dtype == DataType.FP32 | ||
| 86 | + assert [arg.name for arg in call.args] == ["dst", "acc", "lhs", "rhs", "scale_a", "scale_b"] | ||
| 87 | + | ||
| 88 | + | ||
| 89 | +def test_matmul_mx_rejects_unaligned_k(): | ||
| 90 | + t = _mx_tiles(k=32) | ||
| 91 | + with pytest.raises(ValueError, match="K dimension must be a multiple of 64"): | ||
| 92 | + _ir_matmul_mx(t["dst"], t["lhs"], t["rhs"], t["scale_a"], t["scale_b"]) | ||
| 93 | + | ||
| 94 | + | ||
| 95 | +def test_matmul_mx_rejects_mismatched_k(): | ||
| 96 | + t = _mx_tiles(k=64) | ||
| 97 | + t["rhs"] = _tile("rhs", [128, 64], DataType.FP8E5M2, ir.MemorySpace.Right) | ||
| 98 | + with pytest.raises(ValueError, match=r"K dimensions must match, got lhs K=64, rhs K=128"): | ||
| 99 | + _ir_matmul_mx(t["dst"], t["lhs"], t["rhs"], t["scale_a"], t["scale_b"]) | ||
| 100 | + | ||
| 101 | + | ||
| 102 | +def test_matmul_mx_rejects_mismatched_output_shape(): | ||
| 103 | + t = _mx_tiles() | ||
| 104 | + t["dst"] = _tile("dst", [32, 64], DataType.FP32, ir.MemorySpace.Acc) | ||
| 105 | + | ||
| 106 | + with pytest.raises(ValueError, match=r"dst_tile shape must be \[lhs M, rhs N\]"): | ||
| 107 | + _ir_matmul_mx(t["dst"], t["lhs"], t["rhs"], t["scale_a"], t["scale_b"]) | ||
| 108 | + | ||
| 109 | + | ||
| 110 | +def test_matmul_mx_acc_rejects_mismatched_acc_shape(): | ||
| 111 | + t = _mx_tiles() | ||
| 112 | + t["acc"] = _tile("acc", [64, 32], DataType.FP32, ir.MemorySpace.Acc) | ||
| 113 | + | ||
| 114 | + with pytest.raises(ValueError, match=r"acc_tile shape must match dst_tile shape"): | ||
| 115 | + _ir_matmul_mx_acc(t["dst"], t["acc"], t["lhs"], t["rhs"], t["scale_a"], t["scale_b"]) | ||
| 116 | + | ||
| 117 | + | ||
| 118 | +def test_matmul_mx_acc_rejects_non_fp32_acc(): | ||
| 119 | + t = _mx_tiles() | ||
| 120 | + t["acc"] = _tile("acc", [64, 64], DataType.FP16, ir.MemorySpace.Acc) | ||
| 121 | + | ||
| 122 | + with pytest.raises(ValueError, match=r"acc_tile must use FP32 dtype"): | ||
| 123 | + _ir_matmul_mx_acc(t["dst"], t["acc"], t["lhs"], t["rhs"], t["scale_a"], t["scale_b"]) | ||
| 124 | + | ||
| 125 | + | ||
| 126 | +@pytest.mark.parametrize( | ||
| 127 | + "lhs_dtype,rhs_dtype,dst_dtype", | ||
| 128 | + [ | ||
| 129 | + (DataType.FP8E4M3FN, DataType.FP4E2M1, DataType.FP32), | ||
| 130 | + (DataType.FP8E4M3FN, DataType.FP8E5M2, DataType.FP16), | ||
| 131 | + ], | ||
| 132 | +) | ||
| 133 | +def test_matmul_mx_rejects_invalid_dtype_combinations(lhs_dtype, rhs_dtype, dst_dtype): | ||
| 134 | + t = _mx_tiles(lhs_dtype=lhs_dtype, rhs_dtype=rhs_dtype, dst_dtype=dst_dtype) | ||
| 135 | + with pytest.raises(ValueError, match="must be FP8/FP4 combo and dst FP32"): | ||
| 136 | + _ir_matmul_mx(t["dst"], t["lhs"], t["rhs"], t["scale_a"], t["scale_b"]) | ||
| 137 | + | ||
| 138 | + | ||
| 139 | +def test_matmul_mx_rejects_scale_in_wrong_memory_space(): | ||
| 140 | + t = _mx_tiles(scale_a_space=ir.MemorySpace.Mat) | ||
| 141 | + with pytest.raises(ValueError, match="scale_a must be in L0A.*ScaleLeft"): | ||
| 142 | + _ir_matmul_mx(t["dst"], t["lhs"], t["rhs"], t["scale_a"], t["scale_b"]) | ||
| 143 | + | ||
| 144 | + | ||
| 145 | +def test_matmul_mx_rejects_scale_with_wrong_dtype(): | ||
| 146 | + t = _mx_tiles(scale_a_dtype=DataType.FP16) | ||
| 147 | + with pytest.raises(ValueError, match="scale_a must use FP8E8M0 dtype"): | ||
| 148 | + _ir_matmul_mx(t["dst"], t["lhs"], t["rhs"], t["scale_a"], t["scale_b"]) | ||
| 149 | + | ||
| 150 | + | ||
| 151 | +@pytest.mark.parametrize( | ||
| 152 | + "scale_key,shape,error_pattern", | ||
| 153 | + [ | ||
| 154 | + ("scale_a", [32, 2], r"scale_a shape must match lhs_tile MX groups"), | ||
| 155 | + ("scale_a", [64, 4], r"scale_a shape must match lhs_tile MX groups"), | ||
| 156 | + ("scale_b", [4, 64], r"scale_b shape must match rhs_tile MX groups"), | ||
| 157 | + ("scale_b", [2, 32], r"scale_b shape must match rhs_tile MX groups"), | ||
| 158 | + ], | ||
| 159 | +) | ||
| 160 | +def test_matmul_mx_rejects_mismatched_scale_shape(scale_key, shape, error_pattern): | ||
| 161 | + t = _mx_tiles() | ||
| 162 | + space = ir.MemorySpace.ScaleLeft if scale_key == "scale_a" else ir.MemorySpace.ScaleRight | ||
| 163 | + t[scale_key] = _tile(scale_key, shape, DataType.FP8E8M0, space) | ||
| 164 | + | ||
| 165 | + with pytest.raises(ValueError, match=error_pattern): | ||
| 166 | + _ir_matmul_mx(t["dst"], t["lhs"], t["rhs"], t["scale_a"], t["scale_b"]) | ||
| 167 | + | ||
| 168 | + | ||
| 169 | +def test_matmul_mx_acc_rejects_missing_scale(): | ||
| 170 | + t = _mx_tiles() | ||
| 171 | + with pytest.raises(ValueError, match="scale_b is required"): | ||
| 172 | + _ir_matmul_mx_acc(t["dst"], t["acc"], t["lhs"], t["rhs"], t["scale_a"], None) | ||
| 173 | + | ||
| 174 | + | ||
| 175 | +def test_matmul_mx_accepts_paired_scale_addresses(): | ||
| 176 | + t = _mx_tiles() | ||
| 177 | + t["lhs"] = _tile("lhs", [64, 64], DataType.FP8E4M3FN, ir.MemorySpace.Left, addr=0x8000) | ||
| 178 | + t["rhs"] = _tile("rhs", [64, 64], DataType.FP8E5M2, ir.MemorySpace.Right, addr=0x4000) | ||
| 179 | + t["scale_a"] = _tile( | ||
| 180 | + "scale_a", [64, 2], DataType.FP8E8M0, ir.MemorySpace.ScaleLeft, addr=0x0800 | ||
| 181 | + ) | ||
| 182 | + t["scale_b"] = _tile( | ||
| 183 | + "scale_b", [2, 64], DataType.FP8E8M0, ir.MemorySpace.ScaleRight, addr=0x0400 | ||
| 184 | + ) | ||
| 185 | + | ||
| 186 | + _ir_matmul_mx(t["dst"], t["lhs"], t["rhs"], t["scale_a"], t["scale_b"]) | ||
| 187 | + | ||
| 188 | + | ||
| 189 | +@pytest.mark.parametrize( | ||
| 190 | + "data_key,scale_key,data_addr,scale_addr,error_pattern", | ||
| 191 | + [ | ||
| 192 | + ("lhs", "scale_a", 0x8000, 0x0400, r"scale_a address must equal lhs_tile address >> 4"), | ||
| 193 | + ("rhs", "scale_b", 0x4000, 0x0200, r"scale_b address must equal rhs_tile address >> 4"), | ||
| 194 | + ], | ||
| 195 | +) | ||
| 196 | +def test_matmul_mx_rejects_unpaired_scale_address( | ||
| 197 | + data_key, scale_key, data_addr, scale_addr, error_pattern | ||
| 198 | +): | ||
| 199 | + t = _mx_tiles() | ||
| 200 | + if data_key == "lhs": | ||
| 201 | + t[data_key] = _tile(data_key, [64, 64], DataType.FP8E4M3FN, ir.MemorySpace.Left, addr=data_addr) | ||
| 202 | + t[scale_key] = _tile(scale_key, [64, 2], DataType.FP8E8M0, ir.MemorySpace.ScaleLeft, addr=scale_addr) | ||
| 203 | + else: | ||
| 204 | + t[data_key] = _tile(data_key, [64, 64], DataType.FP8E5M2, ir.MemorySpace.Right, addr=data_addr) | ||
| 205 | + t[scale_key] = _tile(scale_key, [2, 64], DataType.FP8E8M0, ir.MemorySpace.ScaleRight, addr=scale_addr) | ||
| 206 | + | ||
| 207 | + with pytest.raises(ValueError, match=error_pattern): | ||
| 208 | + _ir_matmul_mx(t["dst"], t["lhs"], t["rhs"], t["scale_a"], t["scale_b"]) | ||
| 209 | + | ||
| 210 | + | ||
| 211 | +def test_matmul_mx_skips_address_check_without_explicit_memref(): | ||
| 212 | + t = _mx_tiles() | ||
| 213 | + span = ir.Span.unknown() | ||
| 214 | + shape = [ir.ConstInt(dim, DataType.INDEX, span) for dim in [64, 64]] | ||
| 215 | + scale_shape = [ir.ConstInt(dim, DataType.INDEX, span) for dim in [64, 2]] | ||
| 216 | + t["lhs"] = ir.Var("lhs", ir.TileType(shape, DataType.FP8E4M3FN), span) | ||
| 217 | + t["scale_a"] = ir.Var("scale_a", ir.TileType(scale_shape, DataType.FP8E8M0), span) | ||
| 218 | + | ||
| 219 | + _ir_matmul_mx(t["dst"], t["lhs"], t["rhs"], t["scale_a"], t["scale_b"]) | ||
| 220 | + | ||
| 221 | + | ||
| 222 | +@pytest.mark.parametrize( | ||
| 223 | + "target_memory,layout", | ||
| 224 | + [ | ||
| 225 | + (ir.MemorySpace.Mat, ir.TensorLayout.ZZ), | ||
| 226 | + (ir.MemorySpace.Mat, ir.TensorLayout.NN), | ||
| 227 | + (ir.MemorySpace.ScaleLeft, ir.TensorLayout.ZZ), | ||
| 228 | + (ir.MemorySpace.ScaleRight, ir.TensorLayout.NN), | ||
| 229 | + ], | ||
| 230 | +) | ||
| 231 | +def test_mx_scale_tile_defaults_to_fractal_32(target_memory, layout, monkeypatch): | ||
| 232 | + if target_memory in (ir.MemorySpace.ScaleLeft, ir.MemorySpace.ScaleRight): | ||
| 233 | + monkeypatch.setenv("PYPTOPRO_JIT_ARCH", "a5") | ||
| 234 | + tile_type = TileType( | ||
| 235 | + shape=[64, 2], dtype=DataType.FP8E8M0, target_memory=target_memory, layout=layout | ||
| 236 | + ) | ||
| 237 | + assert tile_type.fractal == 32 | ||
| 238 | + | ||
| 239 | + | ||
| 240 | +@pytest.mark.parametrize("memory_space", [ir.MemorySpace.ScaleLeft, ir.MemorySpace.ScaleRight]) | ||
| 241 | +def test_mx_scale_memory_requires_32_byte_alignment(memory_space): | ||
| 242 | + _validate_tile_addr_alignment(0x20, memory_space) | ||
| 243 | + with pytest.raises(ValueError, match="32-byte aligned"): | ||
| 244 | + _validate_tile_addr_alignment(0x01, memory_space) | ||


Scaling/ScaleLeft/ScaleRight是什么,用户理解么