Merged
feat(pypto_pro): unified scale parameter for fixpipe quantization (per-tensor/per-channel/dynamic) #5399
gravel1997Add on Aug 11
feat(pypto_pro): unified scale parameter for fixpipe quantization (per-tensor/per-channel/dynamic) #5399
Merged
Merged fromgravel1997/pyptofix_pipe_quant_tileintocann/pyptomaster
Total: 26 files changed+7497-1225
| @@ -14,42 +14,40 @@ | |||
| 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、L0C(Acc)→UB(Vec)、UB→L1 等)。具体走哪条硬件搬运通路、用哪条流水,由**源与目的 tile 的内存空间**决定。 |
| 18 | 18 | ||
| 19 | -可在搬运的同时融合ReLU、预量化,或经fixpipe做量化(`fp_tile`);也可通过`offset`从一块较宽的源tile中提取子块(对应后端`pto::TEXTRACT`)。 | 19 | +可在搬运的同时融合 ReLU、预量化,或经 fixpipe 做量化(`scale`);也可通过 `offset` 从一块较宽的源 tile 中提取子块(对应后端 `pto::TEXTRACT`)。 |
| 20 | 20 | ||
| 21 | -与[`pypto_pro.language.load`](load.md)/[`pypto_pro.language.store`](store.md)(tensor↔tile,跨GM)不同,`move`是tile↔tile,不涉及GM。 | 21 | +与 [`pypto_pro.language.load`](load.md)/[`pypto_pro.language.store`](store.md)(tensor↔tile,跨 GM)不同,`move` 是 tile↔tile,不涉及 GM。 |
| 22 | 22 | ||
| 23 | ## 函数原型 | 23 | ## 函数原型 |
| 24 | 24 | ||
| 25 | ```python | 25 | ```python |
| 26 | pypto_pro.language.move(dst_tile, src_tile, offset=None, *, acc_to_vec_mode=None, | 26 | pypto_pro.language.move(dst_tile, src_tile, offset=None, *, acc_to_vec_mode=None, |
| 27 | - relu_pre_mode=None, pre_quant_scalar=None, fp_tile=None) | 27 | + relu_pre_mode=None, scale=None) |
| 28 | ``` | 28 | ``` |
| 29 | 29 | ||
| 30 | ## 参数类型 | 30 | ## 参数类型 |
| 31 | 31 | ||
| 32 | | 参数 | 输入/输出 | 说明 | | 32 | | 参数 | 输入/输出 | 说明 | |
| 33 | |---|---|---| | 33 | |---|---|---| |
| 34 | -| `dst_tile` | 输出 | 目标tile,搬入目的地;其内存空间决定TMOV变体 | | 34 | +| `dst_tile` | 输出 | 目标 tile,搬入目的地;其内存空间决定 TMOV 变体 | |
| 35 | -| `src_tile` | 输入 | 源tile | | 35 | +| `src_tile` | 输入 | 源 tile | |
| 36 | -| `offset` | 输入 | 可选,`[offset_m, offset_k]`,从较宽的源tile中提取子块 | | 36 | +| `offset` | 输入 | 可选,`[offset_m, offset_k]`,从较宽的源 tile 中提取子块 | |
| 37 | -| `acc_to_vec_mode` | 输入 | 可选,Acc→Vec搬运模式 | | 37 | +| `acc_to_vec_mode` | 输入 | 可选,Acc→Vec 搬运模式 | |
| 38 | -| `relu_pre_mode` | 输入 | 可选,搬运时融合ReLU | | 38 | +| `relu_pre_mode` | 输入 | 可选,搬运时融合 ReLU | |
| 39 | -| `pre_quant_scalar` | 输入 | 可选,预量化标量 | | 39 | +| `scale` | 输入 | 可选,随路量化比例(deqScalar / deqTensor 路径) | |
| 40 | -| `fp_tile` | 输入 | 可选,fixpipe量化参数tile | | ||
| 41 | 40 | ||
| 42 | ## 参数范围 | 41 | ## 参数范围 |
| 43 | 42 | ||
| 44 | | 参数 | 输入/输出 | 说明 | | 43 | | 参数 | 输入/输出 | 说明 | |
| 45 | |---|---|---| | 44 | |---|---|---| |
| 46 | -| `dst_tile` | 输出 | 数据类型:b8、b16、b32、b64<br>内存空间与源共同决定流水(见“流水类型”);首地址必须32字节对齐 | | 45 | +| `dst_tile` | 输出 | 数据类型:b8、b16、b32、b64<br>内存空间与源共同决定流水(见“流水类型”);首地址必须 32 字节对齐 | |
| 47 | -| `src_tile` | 输入 | 数据类型:b8、b16、b32、b64<br>使用`offset`提取子块时,源tile须不小于目的tile | | 46 | +| `src_tile` | 输入 | 数据类型:b8、b16、b32、b64<br>使用 `offset` 提取子块时,源 tile 须不小于目的 tile | |
| 48 | -| `offset` | 输入 | 二维`[offset_m, offset_k]`,单位为元素个数<br>以源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`,实际提取范围还须位于该有效区域内 | | 47 | +| `offset` | 输入 | 二维 `[offset_m, offset_k]`,单位为元素个数<br>以源 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`,实际提取范围还须位于该有效区域内 | |
| 49 | -| `acc_to_vec_mode` | 输入 | 取`pl.AccToVecMode.SingleModeVec0`/`pl.AccToVecMode.SingleModeVec1`/`pl.AccToVecMode.DualModeSplitM`/`pl.AccToVecMode.DualModeSplitN`;仅在源为`Acc`、目的为`Vec`时有意义。`fp_tile`存在时只支持单vec模式(`DualModeSplitM`/`DualModeSplitN`报错) | | 48 | +| `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` 报错) | |
| 50 | -| `relu_pre_mode` | 输入 | 默认`None`(不融合ReLU);可取`pl.ReluPreMode.NormalRelu` | | 49 | +| `relu_pre_mode` | 输入 | 默认 `None`(不融合 ReLU);可取 `pl.ReluPreMode.NormalRelu` | |
| 51 | -| `pre_quant_scalar` | 输入 | 整数预量化标量;与`fp_tile`互斥 | | 50 | +| `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` 传入) | |
| 52 | -| `fp_tile` | 输入 | 提供时改走`move_fp`路径(fixpipe量化);与`pre_quant_scalar`互斥,且只支持单vec模式 | | ||
| 53 | 51 | ||
| 54 | ## 流水类型 | 52 | ## 流水类型 |
| 55 | 53 | ||
| @@ -66,7 +64,7 @@ pypto_pro.language.move(dst_tile, src_tile, offset=None, *, acc_to_vec_mode=None | |||
| 66 | 64 | ||
| 67 | ## 调用示例 | 65 | ## 调用示例 |
| 68 | 66 | ||
| 69 | -下面是一个完整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`自动管理。 | 67 | +下面是一个完整 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` 自动管理。 |
| 70 | 68 | ||
| 71 | ```python | 69 | ```python |
| 72 | import pypto_pro.language as pl | 70 | import pypto_pro.language as pl |
| @@ -106,28 +104,28 @@ def matmul_move_kernel( | |||
| 106 | 其他典型用法(节选): | 104 | 其他典型用法(节选): |
| 107 | 105 | ||
| 108 | ```python | 106 | ```python |
| 109 | -# L0C(Acc) → UB(Vec),搬运时预量化 | 107 | +# L0C(Acc) → UB(Vec),搬运时随路量化(缩放 2.0) |
| 110 | -pl.move(vec_tile, acc, pre_quant_scalar=DEQ_SCALAR_BITS, acc_to_vec_mode=pl.AccToVecMode.SingleModeVec0) | 108 | +pl.move(vec_tile, acc, scale=2.0, acc_to_vec_mode=pl.AccToVecMode.SingleModeVec0) |
| 111 | 109 | ||
| 112 | # 从宽源 tile 提取子块(TEXTRACT) | 110 | # 从宽源 tile 提取子块(TEXTRACT) |
| 113 | pl.move(cur_a_left, a_wide_slot, offset=[0, KL0]) | 111 | pl.move(cur_a_left, a_wide_slot, offset=[0, KL0]) |
| 114 | ``` | 112 | ``` |
| 115 | 113 | ||
| 116 | -## pl.AccToVecMode.DualModeSplitM / pl.AccToVecMode.DualModeSplitN尾块处理 | 114 | +## pl.AccToVecMode.DualModeSplitM / pl.AccToVecMode.DualModeSplitN 尾块处理 |
| 117 | 115 | ||
| 118 | ### 硬件约束 | 116 | ### 硬件约束 |
| 119 | 117 | ||
| 120 | -- **pl.AccToVecMode.DualModeSplitM**:对M轴进行切分,硬件会往每一块Vec写`M/2 * N`数据,其中M必须是2的倍数。 | 118 | +- **pl.AccToVecMode.DualModeSplitM**:对 M 轴进行切分,硬件会往每一块 Vec 写 `M/2 * N` 数据,其中 M 必须是 2 的倍数。 |
| 121 | -- **pl.AccToVecMode.DualModeSplitN**:对N轴进行切分,硬件会往每一块Vec写`M * N/2`数据,其中N必须是32的倍数。 | 119 | +- **pl.AccToVecMode.DualModeSplitN**:对 N 轴进行切分,硬件会往每一块 Vec 写 `M * N/2` 数据,其中 N 必须是 32 的倍数。 |
| 122 | 120 | ||
| 123 | 这里的M和N指的是元素个数,与数据类型无关。 | 121 | 这里的M和N指的是元素个数,与数据类型无关。 |
| 124 | 122 | ||
| 125 | -从GM→L1→L0A/L0B→L0C的过程中,所有tile的`valid_shape`始终使用**实际尾块大小**。在L0C→Vec的`move`搬运阶段,如果使用`pl.AccToVecMode.DualModeSplitM`或`pl.AccToVecMode.DualModeSplitN`,框架会**自动**在move之前对L0C的`valid_shape`做向上对齐,用户无需手动设置对齐后的值,但需要了解在Vec侧的切分策略: | 123 | +从 GM→L1→L0A/L0B→L0C 的过程中,所有 tile 的 `valid_shape` 始终使用**实际尾块大小**。在 L0C→Vec 的 `move` 搬运阶段,如果使用 `pl.AccToVecMode.DualModeSplitM` 或 `pl.AccToVecMode.DualModeSplitN`,框架会**自动**在 move 之前对 L0C 的 `valid_shape` 做向上对齐,用户无需手动设置对齐后的值,但需要了解在Vec侧的切分策略: |
| 126 | 124 | ||
| 127 | -- **M轴切分策略**:M轴向上对齐到2的倍数,Vec0(sub_id = 0)得到前`aligned_M / 2`行,Vec1(sub_id = 1)得到剩余`原始M - aligned_M / 2`行。例如M = 33,框架对齐到34,Vec0得到17行,Vec1得到33-17 = 16行。 | 125 | +- **M轴 切分策略**:M 轴向上对齐到2的倍数,Vec0(sub_id=0)得到前 `aligned_M / 2` 行,Vec1(sub_id=1)得到剩余 `原始M - aligned_M / 2` 行。例如 M=33,框架对齐到 34,Vec0 得到 17 行,Vec1 得到 33-17=16 行。 |
| 128 | - - 当尾块M = 1时,Vec0直接取实际尾块大小,Vec1为0。 | 126 | + - 当尾块 M = 1 时,Vec0 直接取实际尾块大小,Vec1 为 0。 |
| 129 | -- **N轴切分策略**:N轴向上对齐到32的倍数,Vec0(sub_id = 0)得到前`aligned_N / 2`列,Vec1(sub_id = 1)得到剩余`原始N - aligned_N / 2`列。例如N = 33,框架对齐到64,Vec0得到32列,Vec1得到33-32 = 1列。再例如N = 65时,框架对齐到96,Vec0得到48列,Vec1得到65-48 = 17列。 | 127 | +- **N轴 切分策略**:N 轴向上对齐到32的倍数,Vec0(sub_id=0)得到前 `aligned_N / 2` 列,Vec1(sub_id=1)得到剩余 `原始N - aligned_N / 2` 列。例如 N=33,框架对齐到 64,Vec0 得到 32 列,Vec1 得到 33-32=1 列。再例如 N=65 时,框架对齐到 96,Vec0 得到 48 列,Vec1 得到 65-48=17 列。 |
| 130 | - - 当尾块N ≤ 16时,Vec0直接取实际尾块大小,Vec1为0。 | 128 | + - 当尾块 N ≤ 16 时,Vec0 直接取实际尾块大小,Vec1 为 0。 |
| 131 | 129 | ||
| 132 | ### 总体流程 | 130 | ### 总体流程 |
| 133 | 131 | ||
| @@ -140,12 +138,12 @@ L0C → Vec (move) : 框架自动对齐 Acc valid_shape(用户无需感知 | |||
| 140 | Vec侧 : Vec0/Vec1 valid_shape = 切分后的实际份额(用户需自行计算) | 138 | Vec侧 : Vec0/Vec1 valid_shape = 切分后的实际份额(用户需自行计算) |
| 141 | ``` | 139 | ``` |
| 142 | 140 | ||
| 143 | -### pl.AccToVecMode.DualModeSplitM尾块(M轴按2对齐对半切分) | 141 | +### pl.AccToVecMode.DualModeSplitM 尾块(M 轴按2对齐对半切分) |
| 144 | 142 | ||
| 145 | -`pl.AccToVecMode.DualModeSplitM`要求M为偶数。尾块M为奇数时,框架在`move`之前自动将Acc的`validRow`向上对齐到2的倍数。**用户无需手动对齐。** | 143 | +`pl.AccToVecMode.DualModeSplitM` 要求 M 为偶数。尾块 M 为奇数时,框架在 `move` 之前自动将 Acc 的 `validRow` 向上对齐到 2 的倍数。**用户无需手动对齐。** |
| 146 | 144 | ||
| 147 | -- **框架自动对齐**:`validRow`从`valid_m`变为`(valid_m + 1) / 2 * 2`(如33 → 34) | 145 | +- **框架自动对齐**:`validRow` 从 `valid_m` 变为 `(valid_m + 1) / 2 * 2`(如 33 → 34) |
| 148 | -- **V侧切分计算**:`v0 = (valid_m + 1) // 2 * 2 // 2`(如34 → v0 = 17),`v1 = valid_m - v0`(如33-17 = 16) | 146 | +- **V 侧切分计算**:`v0 = (valid_m + 1) // 2 * 2 // 2`(如 34 → v0=17),`v1 = valid_m - v0`(如 33-17=16) |
| 149 | 147 | ||
| 150 | ```python | 148 | ```python |
| 151 | # cube section: 用户只需设置实际 valid_m,无需手动对齐 | 149 | # cube section: 用户只需设置实际 valid_m,无需手动对齐 |
| @@ -162,13 +160,13 @@ else: | |||
| 162 | pl.set_validshape(vec, [v1, N]) | 160 | pl.set_validshape(vec, [v1, N]) |
| 163 | ``` | 161 | ``` |
| 164 | 162 | ||
| 165 | -### pl.AccToVecMode.DualModeSplitN尾块(N轴按32对齐切分) | 163 | +### pl.AccToVecMode.DualModeSplitN 尾块(N 轴按 32 对齐切分) |
| 166 | 164 | ||
| 167 | -`pl.AccToVecMode.DualModeSplitN`要求N为32的倍数。尾块N不满足时,框架在`move`之前自动将Acc的`validCol`向上对齐到32的倍数。**用户只需在matmul前设置实际valid_n,无需手动对齐。** | 165 | +`pl.AccToVecMode.DualModeSplitN` 要求 N 为 32 的倍数。尾块 N 不满足时,框架在 `move` 之前自动将 Acc 的 `validCol` 向上对齐到 32 的倍数。**用户只需在 matmul 前设置实际 valid_n,无需手动对齐。** |
| 168 | 166 | ||
| 169 | -- **框架自动对齐**:`validCol`从`valid_n`变为`(valid_n + 31) / 32 * 32`(如33 → 64) | 167 | +- **框架自动对齐**:`validCol` 从 `valid_n` 变为 `(valid_n + 31) / 32 * 32`(如 33 → 64) |
| 170 | -- **V侧切分计算**:`v0 = (valid_n + 31) // 32 * 32 // 2`(如64 → v0 = 32),`v1 = valid_n - v0`(如33-32 = 1) | 168 | +- **V 侧切分计算**:`v0 = (valid_n + 31) // 32 * 32 // 2`(如 64 → v0=32),`v1 = valid_n - v0`(如 33-32=1) |
| 171 | -- **尾块 ≤ 16的特殊情况**:当尾块N ≤ 16时,`v0`直接取实际尾块大小(`v0 = valid_n`),`v1 = 0`。 | 169 | +- **尾块 ≤ 16 的特殊情况**:当尾块 N ≤ 16 时,`v0` 直接取实际尾块大小(`v0 = valid_n`),`v1 = 0`。 |
| 172 | 170 | ||
| 173 | ```python | 171 | ```python |
| 174 | # cube section: 用户只需设置实际 valid_n,无需手动对齐 | 172 | # cube section: 用户只需设置实际 valid_n,无需手动对齐 |
| @@ -187,15 +185,15 @@ else: | |||
| 187 | 185 | ||
| 188 | ### 尾块切分规则总结 | 186 | ### 尾块切分规则总结 |
| 189 | 187 | ||
| 190 | -| 模式 | 框架自动对齐 | Vec0份额 | Vec1份额 | 非对齐尾块示例(M/N = 33) | 对应用例 | | 188 | +| 模式 | 框架自动对齐 | Vec0 份额 | Vec1 份额 | 非对齐尾块示例(M/N=33) | 对应用例 | |
| 191 | |------|------------|----------|----------|---------------------|---------| | 189 | |------|------------|----------|----------|---------------------|---------| |
| 192 | -| `pl.AccToVecMode.DualModeSplitM` | M向上对齐到2的倍数 | `aligned_M // 2` | `原始M - v0` | M = 33→对齐34→v0 = 17, v1 = 16 | `test_split_m_odd_tail` | | 190 | +| `pl.AccToVecMode.DualModeSplitM` | M 向上对齐到 2 的倍数 | `aligned_M // 2` | `原始M - v0` | M=33→对齐34→v0=17, v1=16 | `test_split_m_odd_tail` | |
| 193 | -| `pl.AccToVecMode.DualModeSplitN` | N向上对齐到32的倍数 | `aligned_N // 2` | `原始N - v0` | N = 33→对齐64→v0 = 32, v1 = 1 | `test_split_n_odd_tail` | | 191 | +| `pl.AccToVecMode.DualModeSplitN` | N 向上对齐到 32 的倍数 | `aligned_N // 2` | `原始N - v0` | N=33→对齐64→v0=32, v1=1 | `test_split_n_odd_tail` | |
| 194 | 192 | ||
| 195 | -> [!CAUTION]注意 | 193 | +> **注意**: |
| 196 | > | 194 | > |
| 197 | -> - GM→L1→L0A/L0B→L0C全程使用**实际尾块大小**的`valid_shape`,确保matmul只计算有效数据。 | 195 | +> - GM→L1→L0A/L0B→L0C 全程使用**实际尾块大小**的 `valid_shape`,确保 matmul 只计算有效数据。 |
| 198 | -> - L0C→Vec的`move`时,框架自动对Acc的`valid_shape`做对齐,用户无需手动设置对齐值。 | 196 | +> - L0C→Vec 的 `move` 时,框架自动对 Acc 的 `valid_shape` 做对齐,用户无需手动设置对齐值。 |
| 199 | -> - V侧(vector section)用户需自行计算Vec0/Vec1并设置Vec的`valid_shape`,框架不自动处理。 | 197 | +> - V 侧(vector section)用户需自行计算 Vec0/Vec1 并设置 Vec 的 `valid_shape`,框架不自动处理。 |
| 200 | -> - 切M轴时,若M = 1,则Vec0 = 1,Vec1 = 0。 | 198 | +> - 切 M 轴时,若 M=1,则 Vec0 = 1,Vec1 = 0。 |
| 201 | -> - 切N轴时,若N <= 16,则Vec0 = N,Vec1 = 0。 | 199 | +> - 切 N 轴时,若 N<=16,则 Vec0 = N,Vec1 = 0。 |
| @@ -14,54 +14,52 @@ | |||
| 14 | 14 | ||
| 15 | ## 功能说明 | 15 | ## 功能说明 |
| 16 | 16 | ||
| 17 | -把L1/UB Tile的结果按**绝对元素坐标**写回GM,是[`pypto_pro.language.load`](load.md)的反向操作。写出过程中可顺带融合ReLU、预量化,或对目的地址做原子累加。 | 17 | +把 L1/UB Tile 的结果按**绝对元素坐标**写回 GM,是 [`pypto_pro.language.load`](load.md) 的反向操作。写出过程中可顺带融合 ReLU、预量化,或对目的地址做原子累加。 |
| 18 | 18 | ||
| 19 | -源tile可以来自不同内存空间(如`Vec`(UB)、`Acc`(L0C)):源在`Acc`时由FIX(fixpipe)流水写回GM,其余情况走MTE3流水。 | 19 | +源 tile 可以来自不同内存空间(如 `Vec`(UB)、`Acc`(L0C)):源在 `Acc` 时由 FIX(fixpipe)流水写回 GM,其余情况走 MTE3 流水。 |
| 20 | 20 | ||
| 21 | -如果希望按“第几块tile”定位写出位置,需要使用[`pypto_pro.language.store_tile`](store_tile.md)。 | 21 | +如果希望按"第几块 tile"定位写出位置,需要使用 [`pypto_pro.language.store_tile`](store_tile.md)。 |
| 22 | 22 | ||
| 23 | ## 函数原型 | 23 | ## 函数原型 |
| 24 | 24 | ||
| 25 | ```python | 25 | ```python |
| 26 | -pypto_pro.language.store(dst_tensor, src_tile, offsets, *, relu_pre_mode=None, pre_quant_scalar=None, | 26 | +pypto_pro.language.store(dst_tensor, src_tile, offsets, *, relu_pre_mode=None, scale=None, |
| 27 | - fp_tile=None, order=None, atomic=pl.AtomicType.AtomicNone, phase=None) | 27 | + order=None, atomic=pl.AtomicType.AtomicNone, phase=None) |
| 28 | ``` | 28 | ``` |
| 29 | 29 | ||
| 30 | ## 参数类型 | 30 | ## 参数类型 |
| 31 | 31 | ||
| 32 | | 参数 | 输入/输出 | 说明 | | 32 | | 参数 | 输入/输出 | 说明 | |
| 33 | |---|---|---| | 33 | |---|---|---| |
| 34 | -| `dst_tensor` | 输出 | 目标GM tensor,写出目的地 | | 34 | +| `dst_tensor` | 输出 | 目标 GM tensor,写出目的地 | |
| 35 | -| `src_tile` | 输入 | 源tile,待写回GM的数据 | | 35 | +| `src_tile` | 输入 | 源 tile,待写回 GM 的数据 | |
| 36 | -| `offsets` | 输入 | GM写入的各维**绝对元素偏移**,长度等于`dst_tensor`维数 | | 36 | +| `offsets` | 输入 | GM 写入的各维**绝对元素偏移**,长度等于 `dst_tensor` 维数 | |
| 37 | -| `relu_pre_mode` | 输入 | 可选,写出前融合ReLU | | 37 | +| `relu_pre_mode` | 输入 | 可选,写出前融合 ReLU | |
| 38 | -| `pre_quant_scalar` | 输入 | 可选,写出前预量化标量 | | 38 | +| `scale` | 输入 | 可选,随路量化比例(deqScalar / deqTensor 路径) | |
| 39 | -| `fp_tile` | 输入 | 可选,fixpipe量化参数tile | | 39 | +| `order` | 输入 | 可选,Tile 维度在目标 tensor 维度中对应哪几根轴 | |
| 40 | -| `order` | 输入 | 可选,Tile维度在目标tensor维度中对应哪几根轴 | | ||
| 41 | | `atomic` | 输入 | 原子写模式 | | 40 | | `atomic` | 输入 | 原子写模式 | |
| 42 | -| `phase` | 输入 | 可选,matmul累加链路的fixpipe写回GM阶段 | | 41 | +| `phase` | 输入 | 可选,matmul 累加链路的 fixpipe 写回 GM 阶段 | |
| 43 | 42 | ||
| 44 | ## 参数范围 | 43 | ## 参数范围 |
| 45 | 44 | ||
| 46 | | 参数 | 输入/输出 | 说明 | | 45 | | 参数 | 输入/输出 | 说明 | |
| 47 | |---|---|---| | 46 | |---|---|---| |
| 48 | -| `dst_tensor` | 输出 | 数据类型:b8、b16、b32、b64<br>layout:支持`ND`、`DN`、`NZ`<br>offsets换算后的写入范围不得越过对应维度shape<br>原子累加时须预先初始化为零(或已知初值),累加在其上叠加 | | 47 | +| `dst_tensor` | 输出 | 数据类型:b8、b16、b32、b64<br>layout:支持 `ND`、`DN`、`NZ`<br>offsets 换算后的写入范围不得越过对应维度 shape<br>原子累加时须预先初始化为零(或已知初值),累加在其上叠加 | |
| 49 | -| `src_tile` | 输入 | 数据类型:b8、b16、b32、b64<br>内存空间:源在`Acc`(L0C)时由FIX流水写回GM,其余(如`Vec`/UB)走MTE3流水<br>首地址必须32字节对齐 | | 48 | +| `src_tile` | 输入 | 数据类型:b8、b16、b32、b64<br>内存空间:源在 `Acc`(L0C) 时由 FIX 流水写回 GM,其余(如 `Vec`/UB)走 MTE3 流水<br>首地址必须 32 字节对齐 | |
| 50 | -| `offsets` | 输入 | 单位元素个数,大小不超过对应维度的shape,不支持负数索引 | | 49 | +| `offsets` | 输入 | 单位元素个数,大小不超过对应维度的 shape,不支持负数索引 | |
| 51 | -| `relu_pre_mode` | 输入 | 默认`None`(不融合ReLU);可取`pl.ReluPreMode.NormalRelu`;与`fp_tile`互斥 | | 50 | +| `relu_pre_mode` | 输入 | 默认 `None`(不融合 ReLU);可取 `pl.ReluPreMode.NormalRelu`;与 `scale` 为 `Tile`(per-channel)时互斥 | |
| 52 | -| `pre_quant_scalar` | 输入 | 整数,以i64位模式编码;与`fp_tile`互斥 | | 51 | +| `scale` | 输入 | 可选,随路量化比例:`float`(编译期标量)→ per-tensor 量化;运行时 `FP32` 标量 → 自动重解释为 IEEE-754 位模式;运行时 `INT` 标量 → 须传预编码的 float32 位模式(`struct.pack("!f", v)`);`Tile`(INT64、`MemorySpace.Scaling`、shape `[1, N]`)→ per-channel 量化(`store_fp` 路径),用户预制 deqTensor tile,框架直接复用(不自动分配/同步,用户负责 load→move→sync(MTE1→FIX)),与 `relu_pre_mode`、`phase` 互斥;`Tensor` 不支持(per-channel 须以 `Tile` 传入);`[N, 1]` 逐行量化不支持 | |
| 53 | -| `fp_tile` | 输入 | 提供时改走`store_fp`路径,与`relu_pre_mode`、`pre_quant_scalar`、`phase`均互斥 | | 52 | +| `order` | 输入 | 只支持配置 tensor 维度范围内的 dim,只支持二维数组配置,其余配置报错 | |
| 54 | -| `order` | 输入 | 只支持配置tensor维度范围内的dim,只支持二维数组配置,其余配置报错 | | 53 | +| `atomic` | 输入 | `pl.AtomicType.AtomicNone`(默认,覆盖写)或 `pl.AtomicType.AtomicAdd`(原子累加,硬件对每个目的地址做元素级加法) | |
| 55 | -| `atomic` | 输入 | `pl.AtomicType.AtomicNone`(默认,覆盖写)或`pl.AtomicType.AtomicAdd`(原子累加,硬件对每个目的地址做元素级加法) | | 54 | +| `phase` | 输入 | `pl.STPhase.Unspecified`/`pl.STPhase.Partial`(中间累加步)/`pl.STPhase.Final`(最终步);用硬件 unit_flag 接管 cube/fixp 间的握手,仅在 matmul 多步累加写回 GM 时使用;与 `scale` 为 `Tile`(per-channel)时互斥 | |
| 56 | -| `phase` | 输入 | `pl.STPhase.Unspecified`/`pl.STPhase.Partial`(中间累加步)/`pl.STPhase.Final`(最终步);用硬件unit_flag接管cube/fixp间的握手,仅在matmul多步累加写回GM时使用;与`fp_tile`互斥 | | ||
| 57 | 55 | ||
| 58 | ## 流水类型 | 56 | ## 流水类型 |
| 59 | 57 | ||
| 60 | -MTE3(L1/UB → GM的搬出流水);当`src_tile`位于`Acc`(L0C)时为FIX(fixpipe)。 | 58 | +MTE3(L1/UB → GM 的搬出流水);当 `src_tile` 位于 `Acc`(L0C) 时为 FIX(fixpipe)。 |
| 61 | 59 | ||
| 62 | ## 调用示例 | 60 | ## 调用示例 |
| 63 | 61 | ||
| 64 | -下面是一个完整kernel:从GM载入两个输入,相加后用`pypto_pro.language.store`把UB上的结果写回GM。vector kernel开`auto_mutex`,同步由`make_tile_group`自动管理。 | 62 | +下面是一个完整 kernel:从 GM 载入两个输入,相加后用 `pypto_pro.language.store` 把 UB 上的结果写回 GM。vector kernel 开 `auto_mutex`,同步由 `make_tile_group` 自动管理。 |
| 65 | 63 | ||
| 66 | ```python | 64 | ```python |
| 67 | import pypto_pro.language as pl | 65 | import pypto_pro.language as pl |
| @@ -14,55 +14,53 @@ | |||
| 14 | 14 | ||
| 15 | ## 功能说明 | 15 | ## 功能说明 |
| 16 | 16 | ||
| 17 | -把UB(`Vec`)或L0C(`Acc`)Tile的结果写回GM,与[`pypto_pro.language.store`](store.md)的区别在于:偏移以**Tile块索引**为单位,内部自动按`块索引 × tile_shape`换算成绝对元素坐标。是[`pypto_pro.language.load_tile`](load_tile.md)的反向操作。 | 17 | +把 UB(`Vec`)或 L0C(`Acc`)Tile 的结果写回 GM,与 [`pypto_pro.language.store`](store.md) 的区别在于:偏移以 **tile 块索引**为单位,内部自动按 `块索引 × tile_shape` 换算成绝对元素坐标。是 [`pypto_pro.language.load_tile`](load_tile.md) 的反向操作。 |
| 18 | 18 | ||
| 19 | -例如Tile shape为`[64, 128]`时,`tile_offsets=[2, 2]`等价于[`pypto_pro.language.store`](store.md)的绝对偏移`[128, 256]`。 | 19 | +例如 tile shape 为 `[64, 128]` 时,`tile_offsets=[2, 2]` 等价于 [`pypto_pro.language.store`](store.md) 的绝对偏移 `[128, 256]`。 |
| 20 | 20 | ||
| 21 | -下图以UB源Tile为例展示按块索引写回GM Tensor的过程。块索引先换算为元素偏移,再确定目标块的落点;L0C源Tile使用FIX流水。 | 21 | +下图以 UB 源 Tile 为例展示按块索引写回 GM Tensor 的过程。块索引先换算为元素偏移,再确定目标块的落点;L0C 源 Tile 使用 FIX 流水。 |
| 22 | 22 | ||
| 23 | - | 23 | + |
| 24 | 24 | ||
| 25 | ## 函数原型 | 25 | ## 函数原型 |
| 26 | 26 | ||
| 27 | ```python | 27 | ```python |
| 28 | -pypto_pro.language.store_tile(dst_tensor, src_tile, tile_offsets, *, relu_pre_mode=None, pre_quant_scalar=None, fp_tile=None, order=None, atomic=pl.AtomicType.AtomicNone, phase=None) | 28 | +pypto_pro.language.store_tile(dst_tensor, src_tile, tile_offsets, *, relu_pre_mode=None, scale=None, order=None, atomic=pl.AtomicType.AtomicNone, phase=None) |
| 29 | ``` | 29 | ``` |
| 30 | 30 | ||
| 31 | ## 参数类型 | 31 | ## 参数类型 |
| 32 | 32 | ||
| 33 | | 参数 | 输入/输出 | 说明 | | 33 | | 参数 | 输入/输出 | 说明 | |
| 34 | |---|---|---| | 34 | |---|---|---| |
| 35 | -| `dst_tensor` | 输出 | 目标GM Tensor,写出目的地 | | 35 | +| `dst_tensor` | 输出 | 目标 GM tensor,写出目的地 | |
| 36 | -| `src_tile` | 输入 | 源Tile,内存空间只能是`Vec`(UB)或`Acc`(L0C) | | 36 | +| `src_tile` | 输入 | 源 Tile,内存空间只能是 `Vec`(UB) 或 `Acc`(L0C) | |
| 37 | -| `tile_offsets` | 输入 | 以Tile为单位的块索引,内部换算为`块索引 × tile_shape`的绝对元素偏移 | | 37 | +| `tile_offsets` | 输入 | 以 tile 为单位的块索引,内部换算为 `块索引 × tile_shape` 的绝对元素偏移 | |
| 38 | -| `relu_pre_mode` | 输入 | 可选,写回前融合ReLU | | 38 | +| `relu_pre_mode` | 输入 | 可选,写回前融合 ReLU | |
| 39 | -| `pre_quant_scalar` | 输入 | 可选,写回前量化标量 | | 39 | +| `scale` | 输入 | 可选,随路量化比例(deqScalar / deqTensor 路径) | |
| 40 | -| `fp_tile` | 输入 | 可选,fixpipe量化Tile | | 40 | +| `order` | 输入 | 可选,Tile 维度在目标 tensor 维度中对应哪几根轴 | |
| 41 | -| `order` | 输入 | 可选,Tile维度在目标Tensor维度中对应哪几根轴 | | 41 | +| `atomic` | 输入 | 可选,原子写模式,默认 `pl.AtomicType.AtomicNone` | |
| 42 | -| `atomic` | 输入 | 可选,原子写模式,默认`pl.AtomicType.AtomicNone` | | 42 | +| `phase` | 输入 | 可选,fixpipe 分阶段写回模式 | |
| 43 | -| `phase` | 输入 | 可选,fixpipe分阶段写回模式 | | ||
| 44 | 43 | ||
| 45 | ## 参数范围 | 44 | ## 参数范围 |
| 46 | 45 | ||
| 47 | | 参数 | 输入/输出 | 说明 | | 46 | | 参数 | 输入/输出 | 说明 | |
| 48 | |---|---|---| | 47 | |---|---|---| |
| 49 | -| `dst_tensor` | 输出 | 数据类型:b8、b16、b32、b64<br>layout:支持`ND`、`DN`、`NZ`<br>换算后的写入范围不得越过对应维度shape | | 48 | +| `dst_tensor` | 输出 | 数据类型:b8、b16、b32、b64<br>layout:支持 `ND`、`DN`、`NZ`<br>换算后的写入范围不得越过对应维度 shape | |
| 50 | -| `src_tile` | 输入 | 数据类型:b8、b16、b32、b64<br>内存空间:只支持`Vec`(UB)和`Acc`(L0C);UB源通过MTE3写回,L0C源通过FIX写回<br>地址对齐:UB为32字节,L0C为64字节 | | 49 | +| `src_tile` | 输入 | 数据类型:b8、b16、b32、b64<br>内存空间:只支持 `Vec`(UB) 和 `Acc`(L0C);UB 源通过 MTE3 写回,L0C 源通过 FIX 写回<br>地址对齐:UB 为 32 字节,L0C 为 64 字节 | |
| 51 | -| `tile_offsets` | 输入 | 单位为Tile块索引,元素支持整型常量或运行时整型标量表达式,换算后的绝对偏移不超过对应维度的shape,不支持负数索引<br>被切分的维度(由`order`指定)按`块索引 × tile该维大小`换算;其余维度的取值按绝对偏移直接使用 | | 50 | +| `tile_offsets` | 输入 | 单位为 tile 块索引,支持运行时 `Expr`,换算后的绝对偏移不超过对应维度的 shape,不支持负数索引<br>被切分的维度(由 `order` 指定)按 `块索引 × tile 该维大小` 换算;其余维度的取值按绝对偏移直接使用 | |
| 52 | -| `relu_pre_mode` | 输入 | 可选,支持`pl.ReluPreMode.NormalRelu`;与`fp_tile`互斥 | | 51 | +| `relu_pre_mode` | 输入 | 可选,支持 `pl.ReluPreMode.NormalRelu`;与 `scale` 为 `Tile`(per-channel)时互斥 | |
| 53 | -| `pre_quant_scalar` | 输入 | 可选,预量化标量(i64 bit pattern);与`fp_tile`互斥 | | 52 | +| `scale` | 输入 | 可选,随路量化比例:`float`(编译期标量)→ per-tensor 量化;运行时 `FP32` 标量 → 自动重解释为 IEEE-754 位模式;运行时 `INT` 标量 → 须传预编码的 float32 位模式(`struct.pack("!f", v)`);`Tile`(INT64、`MemorySpace.Scaling`、shape `[1, N]`)→ per-channel 量化(`store_fp` 路径),用户预制 deqTensor tile,框架直接复用(不自动分配/同步,用户负责 load→move→sync(MTE1→FIX)),与 `relu_pre_mode`、`phase` 互斥;`Tensor` 不支持(per-channel 须以 `Tile` 传入);`[N, 1]` 逐行量化不支持 | |
| 54 | -| `fp_tile` | 输入 | 可选,启用`store_fp`路径的量化Tile;与`relu_pre_mode`、`pre_quant_scalar`、`phase`互斥 | | 53 | +| `order` | 输入 | 只支持配置 tensor 维度范围内的 dim,只支持二维数组配置,其余配置报错<br>用于高维 tensor 中指定 tile 对应哪几个维度;不配置时默认取 tensor 的最后两维 | |
| 55 | -| `order` | 输入 | 只支持配置Tensor维度范围内的dim,只支持二维数组配置,其余配置报错<br>用于高维Tensor中指定Tile对应哪几个维度;不配置时默认取Tensor的最后两维 | | 54 | +| `atomic` | 输入 | 支持 `pl.AtomicType.AtomicNone`(覆盖写)或 `pl.AtomicType.AtomicAdd`(原子累加) | |
| 56 | -| `atomic` | 输入 | 支持`pl.AtomicType.AtomicNone`(覆盖写)或`pl.AtomicType.AtomicAdd`(原子累加) | | 55 | +| `phase` | 输入 | 可选,支持 `pl.STPhase.Partial` 或 `pl.STPhase.Final`;与 `scale` 为 `Tile`(per-channel)时互斥 | |
| 57 | -| `phase` | 输入 | 可选,支持`pl.STPhase.Partial`或`pl.STPhase.Final`;与`fp_tile`互斥 | | ||
| 58 | 56 | ||
| 59 | ## 流水类型 | 57 | ## 流水类型 |
| 60 | 58 | ||
| 61 | -源Tile位于`Vec`(UB)时为MTE3(UB → GM);源Tile位于`Acc`(L0C)时为FIX(L0C → GM)。不支持从L1直接调用`store_tile`写回GM。 | 59 | +源 Tile 位于 `Vec`(UB) 时为 MTE3(UB → GM);源 Tile 位于 `Acc`(L0C) 时为 FIX(L0C → GM)。不支持从 L1 直接调用 `store_tile` 写回 GM。 |
| 62 | 60 | ||
| 63 | ## 调用示例 | 61 | ## 调用示例 |
| 64 | 62 | ||
| 65 | -下面是一个完整Kernel:把同一块UB结果按块索引逐块写到GM输出的不同位置。`pypto_pro.language.store_tile`用块号`[ti, 0]`定位,内部自动换算为绝对偏移`[ti*64, 0]`。Vector Kernel开启`auto_mutex`,同步由`make_tile_group`自动管理。 | 63 | +下面是一个完整 kernel:把同一块 UB 结果按块索引逐块写到 GM 输出的不同位置。`pypto_pro.language.store_tile` 用块号 `[ti, 0]` 定位,内部自动换算为绝对偏移 `[ti*64, 0]`。vector kernel 开 `auto_mutex`,同步由 `make_tile_group` 自动管理。 |
| 66 | 64 | ||
| 67 | ```python | 65 | ```python |
| 68 | import pypto_pro.language as pl | 66 | import pypto_pro.language as pl |
| @@ -86,6 +84,6 @@ def store_tile_kernel( | |||
| 86 | 其他典型用法(节选): | 84 | 其他典型用法(节选): |
| 87 | 85 | ||
| 88 | ```python | 86 | ```python |
| 89 | -# 4D BSND Tensor:Tile 对应第 1、3 维,其余维按绝对偏移 | 87 | +# 4D BSND tensor:tile 对应第 1、3 维,其余维按绝对偏移 |
| 90 | pl.store_tile(p_buf, p_f16, [b_idx, qi * 2 + sub_id, n_idx, ki], order=[1, 3]) | 88 | pl.store_tile(p_buf, p_f16, [b_idx, qi * 2 + sub_id, n_idx, ki], order=[1, 3]) |
| 91 | ``` | 89 | ``` |
| @@ -225,10 +225,10 @@ add_kernel[None, num_cores](x, y, z) | |||
| 225 | def scaled_kernel( | 225 | def scaled_kernel( |
| 226 | a: pl.Tensor[[64, 64], pl.DT_FP32], | 226 | a: pl.Tensor[[64, 64], pl.DT_FP32], |
| 227 | out: pl.Tensor[[64, 64], pl.DT_INT8], | 227 | out: pl.Tensor[[64, 64], pl.DT_INT8], |
| 228 | - scale_bits: pl.DT_INT32, # <-- 运行时标量 | 228 | + scale_bits: pl.DT_INT32, # <-- 运行时标量(预编码的 float32 位模式) |
| 229 | ): | 229 | ): |
| 230 | ... | 230 | ... |
| 231 | - pl.store(out, acc, [0, 0], pre_quant_scalar=scale_bits) | 231 | + pl.store(out, acc, [0, 0], scale=scale_bits) |
| 232 | 232 | ||
| 233 | # Host侧启动 | 233 | # Host侧启动 |
| 234 | scaled_kernel(a, out, scale_bits) # 直接传 int | 234 | scaled_kernel(a, out, scale_bits) # 直接传 int |
| @@ -83,6 +83,41 @@ static std::string GetAtomicTypeCCE(int atomic) | |||
| 83 | return ir::EnumToString(mode); | 83 | return ir::EnumToString(mode); |
| 84 | } | 84 | } |
| 85 | 85 | ||
| 86 | +// ============================================================================ | ||
| 87 | +// Helper: build the deqScalar (uint64) expression for a fixpipe preQuant operand. | ||
| 88 | +// | ||
| 89 | +// The deqScalar register's low 32 bits are the IEEE-754 float32 bit pattern of | ||
| 90 | +// the scale; bit 46 selects signed-int8 requantization. A runtime FP32 scalar | ||
| 91 | +// must therefore be *reinterpreted* (bitcast), not numerically converted: | ||
| 92 | +// - static_cast<uint64_t>(float) does fp_to_uint, which both mis-encodes the | ||
| 93 | +// bits (2.0 -> 2 instead of 0x40000000) and crashes the bisheng backend | ||
| 94 | +// ("Cannot select: i64 = fp_to_uint ... undef") for GM-loaded scalars. | ||
| 95 | +// - __builtin_bit_cast(uint32_t, float) reinterprets the bits (used by the | ||
| 96 | +// pto-isa headers), so it is supported in generated device code. | ||
| 97 | +// ============================================================================ | ||
| 98 | +static std::string MakePreQuantExprCCE(codegen::CCECodegen& codegen, const ir::ExprPtr& pre_quant, | ||
| 99 | + ir::DataType dst_dtype) | ||
| 100 | +{ | ||
| 101 | + std::string code = codegen.GetExprAsCode(pre_quant); | ||
| 102 | + auto scalar_type = ir::As<ir::ScalarType>(pre_quant->GetType()); | ||
| 103 | + if (scalar_type != nullptr && scalar_type->dtype_ == DataType::FP32) { | ||
| 104 | + // Runtime float scale value: reinterpret its bits as the deqScalar low word. | ||
| 105 | + code = "static_cast<uint64_t>(__builtin_bit_cast(uint32_t, " + code + "))"; | ||
| 106 | + } else { | ||
| 107 | + // Compile-time encoded bits or runtime integer bits: widen as-is. | ||
| 108 | + code = "static_cast<uint64_t>(" + code + ")"; | ||
| 109 | + } | ||
| 110 | + if (dst_dtype == DataType::INT8) { | ||
| 111 | + // For a signed-int8 output, bit46 of the deqScalar register selects signed | ||
| 112 | + // (vs unsigned) requantization on the fixpipe; the hardware reads negative | ||
| 113 | + // L0C values as signed only when this flag is set, otherwise they saturate | ||
| 114 | + // to 0 as if unsigned. Emit the bit set as a runtime expression so it works | ||
| 115 | + // for both constant and dynamic scales. | ||
| 116 | + code = "(" + code + " & ~(1ULL << 46)) | (1ULL << 46)"; | ||
| 117 | + } | ||
| 118 | + return code; | ||
| 119 | +} | ||
| 120 | + | ||
| 86 | static std::string GetReluPreModeCCE(int relu) | 121 | static std::string GetReluPreModeCCE(int relu) |
| 87 | { | 122 | { |
| 88 | auto mode = static_cast<ir::ReluPreMode>(relu); | 123 | auto mode = static_cast<ir::ReluPreMode>(relu); |
| @@ -413,38 +448,30 @@ static std::string MakeBlockOutStoreCodegenCCE(const ir::CallPtr& op, codegen::C | |||
| 413 | // pto-isa: low 32 bits = float32 bit-pattern of the scale, bit46 = signed-int8 flag. | 448 | // pto-isa: low 32 bits = float32 bit-pattern of the scale, bit46 = signed-int8 flag. |
| 414 | // It may be a compile-time constant or a runtime scalar. | 449 | // It may be a compile-time constant or a runtime scalar. |
| 415 | if (op->args_.size() > 3) { | 450 | if (op->args_.size() > 3) { |
| 416 | - std::string pre_quant = codegen.GetExprAsCode(op->args_[3]); | 451 | + args += ", " + MakePreQuantExprCCE(codegen, op->args_[3], dst_tensor_type->dtype_); |
| 417 | - if (dst_tensor_type->dtype_ == DataType::INT8) { | ||
| 418 | - // For a signed-int8 output, bit46 of the deqScalar register selects signed (vs unsigned) | ||
| 419 | - // requantization on the fixpipe; the hardware reads negative L0C values as signed only when | ||
| 420 | - // this flag is set, otherwise they saturate to 0 as if unsigned. Emit the bit set as a | ||
| 421 | - // runtime expression so it works for both constant and dynamic scales. The value is already | ||
| 422 | - // uint64, so cast straight to uint64_t (no uint32 narrowing that would drop high bits). | ||
| 423 | - args += ", ((static_cast<uint64_t>(" + pre_quant + ") & ~(1ULL << 46)) | (1ULL << 46))"; | ||
| 424 | - } else { | ||
| 425 | - args += ", static_cast<uint64_t>(" + pre_quant + ")"; | ||
| 426 | - } | ||
| 427 | } | 452 | } |
| 428 | 453 | ||
| 429 | // Emit atomic mode before TSTORE if atomic mode is add (pto-isa API) | 454 | // Emit atomic mode before TSTORE if atomic mode is add (pto-isa API) |
| 430 | if (atomic_enum == "AtomicType::AtomicAdd") { | 455 | if (atomic_enum == "AtomicType::AtomicAdd") { |
| 431 | - // Get dtype from tile type for set_atomic_dtype | 456 | + // Get dtype from the DESTINATION tensor for set_atomic_dtype: the atomic add |
| 432 | - auto src_tile_type = std::dynamic_pointer_cast<const ir::TileType>(op->args_[1]->GetType()); | 457 | + // accumulates into GM memory, so the atomic engine must operate on the GM |
| 433 | - if (src_tile_type) { | 458 | + // (dst) dtype. pto-isa TSTORE_IMPL does the same — SetAtomicAdd<DstT>() with |
| 434 | - auto dtype = src_tile_type->dtype_; | 459 | + // DstT = GlobalData::RawDType. Using the Acc (src) dtype here is wrong when |
| 435 | - if (dtype == DataType::FP32) { | 460 | + // the store quantizes (e.g. FP32 Acc -> INT8 GM), causing a dtype mismatch |
| 436 | - codegen.Emit("set_atomic_f32();"); | 461 | + // in the atomic engine (NPU device error 507015). |
| 437 | - } else if (dtype == DataType::FP16) { | 462 | + auto dtype = dst_tensor_type->dtype_; |
| 438 | - codegen.Emit("set_atomic_f16();"); | 463 | + if (dtype == DataType::FP32) { |
| 439 | - } else if (dtype == DataType::BF16) { | 464 | + codegen.Emit("set_atomic_f32();"); |
| 440 | - codegen.Emit("set_atomic_bf16();"); | 465 | + } else if (dtype == DataType::FP16) { |
| 441 | - } else if (dtype == DataType::INT32) { | 466 | + codegen.Emit("set_atomic_f16();"); |
| 442 | - codegen.Emit("set_atomic_s32();"); | 467 | + } else if (dtype == DataType::BF16) { |
| 443 | - } else if (dtype == DataType::INT16) { | 468 | + codegen.Emit("set_atomic_bf16();"); |
| 444 | - codegen.Emit("set_atomic_s16();"); | 469 | + } else if (dtype == DataType::INT32) { |
| 445 | - } else if (dtype == DataType::INT8) { | 470 | + codegen.Emit("set_atomic_s32();"); |
| 446 | - codegen.Emit("set_atomic_s8();"); | 471 | + } else if (dtype == DataType::INT16) { |
| 447 | - } | 472 | + codegen.Emit("set_atomic_s16();"); |
| 473 | + } else if (dtype == DataType::INT8) { | ||
| 474 | + codegen.Emit("set_atomic_s8();"); | ||
| 448 | } | 475 | } |
| 449 | codegen.Emit("set_atomic_add();"); | 476 | codegen.Emit("set_atomic_add();"); |
| 450 | } | 477 | } |
| @@ -618,18 +645,12 @@ static std::string MakeBlockOutMoveCodegenCCE(const ir::CallPtr& op, codegen::Co | |||
| 618 | std::string args = dst + ", " + src; | 645 | std::string args = dst + ", " + src; |
| 619 | 646 | ||
| 620 | if (pre_quant_operand != nullptr) { | 647 | if (pre_quant_operand != nullptr) { |
| 621 | - std::string pre_quant = codegen.GetExprAsCode(pre_quant_operand); | ||
| 622 | auto dst_tile_type = ir::As<ir::TileType>(op->args_[0]->GetType()); | 648 | auto dst_tile_type = ir::As<ir::TileType>(op->args_[0]->GetType()); |
| 623 | - if (dst_tile_type != nullptr && dst_tile_type->dtype_ == DataType::INT8) { | 649 | + ir::DataType dst_dtype = DataType::INT8; |
| 624 | - // For a signed-int8 output, bit46 of the deqScalar register selects signed (vs unsigned) | 650 | + if (dst_tile_type != nullptr) { |
| 625 | - // requantization on the fixpipe; negative L0C values are read as signed only when this flag | 651 | + dst_dtype = dst_tile_type->dtype_; |
| 626 | - // is set, otherwise they saturate to 0 as if unsigned. Emit as a runtime expression so it | ||
| 627 | - // works for both constant and dynamic scales. The value is already uint64, so cast straight | ||
| 628 | - // to uint64_t (no uint32 narrowing that would drop high bits). | ||
| 629 | - args += ", ((static_cast<uint64_t>(" + pre_quant + ") & ~(1ULL << 46)) | (1ULL << 46))"; | ||
| 630 | - } else { | ||
| 631 | - args += ", static_cast<uint64_t>(" + pre_quant + ")"; | ||
| 632 | } | 652 | } |
| 653 | + args += ", " + MakePreQuantExprCCE(codegen, pre_quant_operand, dst_dtype); | ||
| 633 | } | 654 | } |
| 634 | 655 | ||
| 635 | codegen.Emit("TMOV<std::remove_reference_t<decltype(" + dst + ")>, std::remove_reference_t<decltype(" + src + ")>" + | 656 | codegen.Emit("TMOV<std::remove_reference_t<decltype(" + dst + ")>, std::remove_reference_t<decltype(" + src + ")>" + |
| @@ -21,6 +21,7 @@ from collections.abc import Sequence | |||
| 21 | from dataclasses import dataclass | 21 | from dataclasses import dataclass |
| 22 | import enum | 22 | import enum |
| 23 | import os | 23 | import os |
| 24 | +import struct | ||
| 24 | from typing import Any, Optional | 25 | from typing import Any, Optional |
| 25 | 26 | ||
| 26 | from pypto.pypto_impl import ir as _ir_core | 27 | from pypto.pypto_impl import ir as _ir_core |
| @@ -204,6 +205,50 @@ def _ir_load_tile( | |||
| 204 | 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) |
| 205 | 206 | ||
| 206 | 207 | ||
| 208 | +def _encode_deq_scalar(scale: float) -> int: | ||
| 209 | + scale_bits = struct.unpack("!I", struct.pack("!f", scale))[0] | ||
| 210 | + return scale_bits | ||
| 211 | + | ||
| 212 | + | ||
| 213 | +def _resolve_scale_param( | ||
| 214 | + scale: Any, | ||
| 215 | + span: Span, | ||
| 216 | +) -> tuple[Optional["int | Expr"], Optional[Expr]]: | ||
| 217 | + if scale is None: | ||
| 218 | + return None, None | ||
| 219 | + if isinstance(scale, (int, float)): | ||
| 220 | + encoded = _encode_deq_scalar(float(scale)) | ||
| 221 | + return encoded, None | ||
| 222 | + if isinstance(scale, Expr): | ||
| 223 | + scale_type = getattr(scale, "type", None) | ||
| 224 | + if isinstance(scale_type, _ir_core.TileType): | ||
| 225 | + # User-prepared Scaling tile (per-channel): already validated by | ||
| 226 | + # _auto_alloc_scaling_tile_hook before the builder runs; resolve it | ||
| 227 | + # here to the store_fp/move_fp operand. | ||
| 228 | + return None, scale | ||
| 229 | + if not isinstance(scale_type, _ir_core.ScalarType): | ||
| 230 | + raise TypeError( | ||
| 231 | + f"scale Expr must be a runtime scalar, got {type(scale_type).__name__}; " | ||
| 232 | + f"per-channel quantization requires a user-prepared Scaling Tile" | ||
| 233 | + ) | ||
| 234 | + # Only FP32 (auto bitcast in codegen) and INT32/INT64 (user passes the | ||
| 235 | + # pre-encoded float32 bit pattern) are supported as runtime scalars: | ||
| 236 | + # FP16/BF16 would be numerically converted to uint64 (wrong bits, and | ||
| 237 | + # fp_to_uint crashes the bisheng backend), and narrower/unsigned ints | ||
| 238 | + # risk sign-extension or truncation of the bit pattern. | ||
| 239 | + if scale_type.dtype not in (DataType.FP32, DataType.INT32, DataType.INT64): | ||
| 240 | + raise TypeError( | ||
| 241 | + f"scale runtime scalar dtype {scale_type.dtype} is not supported — pass " | ||
| 242 | + f"an FP32 scalar (auto-reinterpreted as its IEEE-754 bit pattern) or an " | ||
| 243 | + f"INT32/INT64 scalar carrying the pre-encoded float32 bit pattern " | ||
| 244 | + f"(struct.pack(\"!f\", scale))" | ||
| 245 | + ) | ||
| 246 | + return scale, None | ||
| 247 | + raise TypeError( | ||
| 248 | + f"scale must be float, int, Expr, or Tile, got {type(scale).__name__}" | ||
| 249 | + ) | ||
| 250 | + | ||
| 251 | + | ||
| 207 | def _ir_store( | 252 | def _ir_store( |
| 208 | out: Expr, | 253 | out: Expr, |
| 209 | tile: Expr, | 254 | tile: Expr, |
| @@ -211,8 +256,7 @@ def _ir_store( | |||
| 211 | *, | 256 | *, |
| 212 | span: Span | None = None, | 257 | span: Span | None = None, |
| 213 | relu_pre_mode: ReluPreMode | None = None, | 258 | relu_pre_mode: ReluPreMode | None = None, |
| 214 | - pre_quant_scalar: int | Expr | None = None, | 259 | + scale: Any = None, |
| 215 | - fp_tile: Expr | None = None, | ||
| 216 | order: list[int] | None = None, | 260 | order: list[int] | None = None, |
| 217 | atomic: AtomicType = AtomicType.AtomicNone, | 261 | atomic: AtomicType = AtomicType.AtomicNone, |
| 218 | phase: STPhase | None = None, | 262 | phase: STPhase | None = None, |
| @@ -245,14 +289,20 @@ def _ir_store( | |||
| 245 | raise ValueError(f"{op_name}: order must be ascending, got {order}") | 289 | raise ValueError(f"{op_name}: order must be ascending, got {order}") |
| 246 | _validate_offsets(offsets_tuple, tile_dims, tile_shape, out.type.shape, op_name) | 290 | _validate_offsets(offsets_tuple, tile_dims, tile_shape, out.type.shape, op_name) |
| 247 | 291 | ||
| 248 | - # Validate offset bounds at Python frontend level | ||
| 249 | _validate_offset_bounds("store", out.type.shape, offsets_tuple.elements) | 292 | _validate_offset_bounds("store", out.type.shape, offsets_tuple.elements) |
| 293 | + | ||
| 294 | + pre_quant_scalar, fp_tile = _resolve_scale_param(scale, actual_span) | ||
| 295 | + | ||
| 296 | + _check_scale_dst_supported( | ||
| 297 | + getattr(tile.type, "dtype", None), | ||
| 298 | + getattr(out.type, "dtype", None), | ||
| 299 | + pre_quant_scalar is not None or fp_tile is not None, | ||
| 300 | + op_name, | ||
| 301 | + ) | ||
| 250 | if fp_tile is not None and relu_pre_mode is not None: | 302 | if fp_tile is not None and relu_pre_mode is not None: |
| 251 | - raise ValueError("fp_tile cannot be used together with relu_pre_mode") | 303 | + raise ValueError("scale (per-channel) cannot be used together with relu_pre_mode") |
| 252 | - if fp_tile is not None and pre_quant_scalar is not None: | ||
| 253 | - raise ValueError("fp_tile cannot be used together with pre_quant_scalar") | ||
| 254 | if fp_tile is not None and phase is not None: | 304 | if fp_tile is not None and phase is not None: |
| 255 | - raise ValueError("fp_tile cannot be combined with phase") | 305 | + raise ValueError("scale (per-channel) cannot be combined with phase") |
| 256 | if fp_tile is not None: | 306 | if fp_tile is not None: |
| 257 | return _ir_core.create_op_call(block_ir_op("store_fp"), [out, tile, fp_tile, offsets_tuple], {}, actual_span) | 307 | return _ir_core.create_op_call(block_ir_op("store_fp"), [out, tile, fp_tile, offsets_tuple], {}, actual_span) |
| 258 | 308 | ||
| @@ -302,8 +352,7 @@ def _ir_store_tile( | |||
| 302 | *, | 352 | *, |
| 303 | span: Span | None = None, | 353 | span: Span | None = None, |
| 304 | relu_pre_mode: ReluPreMode | None = None, | 354 | relu_pre_mode: ReluPreMode | None = None, |
| 305 | - pre_quant_scalar: int | Expr | None = None, | 355 | + scale: Any = None, |
| 306 | - fp_tile: Expr | None = None, | ||
| 307 | order: list[int] | None = None, | 356 | order: list[int] | None = None, |
| 308 | atomic: AtomicType = AtomicType.AtomicNone, | 357 | atomic: AtomicType = AtomicType.AtomicNone, |
| 309 | phase: STPhase | None = None, | 358 | phase: STPhase | None = None, |
| @@ -332,14 +381,20 @@ def _ir_store_tile( | |||
| 332 | _validate_offsets(offsets_tuple, tile_dims, tile_shape, out.type.shape, op_name, use_tile_absolute=True) | 381 | _validate_offsets(offsets_tuple, tile_dims, tile_shape, out.type.shape, op_name, use_tile_absolute=True) |
| 333 | 382 | ||
| 334 | abs_offsets = _compute_absolute_offsets(offsets_tuple, tile_shape, tile_dims, actual_span) | 383 | abs_offsets = _compute_absolute_offsets(offsets_tuple, tile_shape, tile_dims, actual_span) |
| 335 | - # Validate offset bounds at Python frontend level | ||
| 336 | _validate_offset_bounds("store_tile", out.type.shape, abs_offsets.elements) | 384 | _validate_offset_bounds("store_tile", out.type.shape, abs_offsets.elements) |
| 385 | + | ||
| 386 | + pre_quant_scalar, fp_tile = _resolve_scale_param(scale, actual_span) | ||
| 387 | + | ||
| 388 | + _check_scale_dst_supported( | ||
| 389 | + getattr(tile.type, "dtype", None), | ||
| 390 | + getattr(out.type, "dtype", None), | ||
| 391 | + pre_quant_scalar is not None or fp_tile is not None, | ||
| 392 | + op_name, | ||
| 393 | + ) | ||
| 337 | if fp_tile is not None and relu_pre_mode is not None: | 394 | if fp_tile is not None and relu_pre_mode is not None: |
| 338 | - raise ValueError("fp_tile cannot be used together with relu_pre_mode") | 395 | + raise ValueError("scale (per-channel) cannot be used together with relu_pre_mode") |
| 339 | - if fp_tile is not None and pre_quant_scalar is not None: | ||
| 340 | - raise ValueError("fp_tile cannot be used together with pre_quant_scalar") | ||
| 341 | if fp_tile is not None and phase is not None: | 396 | if fp_tile is not None and phase is not None: |
| 342 | - raise ValueError("fp_tile cannot be combined with phase") | 397 | + raise ValueError("scale (per-channel) cannot be combined with phase") |
| 343 | if fp_tile is not None: | 398 | if fp_tile is not None: |
| 344 | return _ir_core.create_op_call(block_ir_op("store_fp"), [out, tile, fp_tile, abs_offsets], {}, actual_span) | 399 | return _ir_core.create_op_call(block_ir_op("store_fp"), [out, tile, fp_tile, abs_offsets], {}, actual_span) |
| 345 | kwargs = _build_store_kwargs( | 400 | kwargs = _build_store_kwargs( |
| @@ -451,8 +506,7 @@ def _ir_move( | |||
| 451 | span: Span | None = None, | 506 | span: Span | None = None, |
| 452 | acc_to_vec_mode: AccToVecMode | None = None, | 507 | acc_to_vec_mode: AccToVecMode | None = None, |
| 453 | relu_pre_mode: ReluPreMode | None = None, | 508 | relu_pre_mode: ReluPreMode | None = None, |
| 454 | - pre_quant_scalar: int | Expr | None = None, | 509 | + scale: Any = None, |
| 455 | - fp_tile: Expr | None = None, | ||
| 456 | ) -> Expr: | 510 | ) -> Expr: |
| 457 | actual_span = span or _span() | 511 | actual_span = span or _span() |
| 458 | if not isinstance(out.type, _ir_core.TileType): | 512 | if not isinstance(out.type, _ir_core.TileType): |
| @@ -473,18 +527,24 @@ def _ir_move( | |||
| 473 | f"move: unsupported data path src({_src_mem.name})->dst({_dst_mem.name}), " | 527 | f"move: unsupported data path src({_src_mem.name})->dst({_dst_mem.name}), " |
| 474 | f"supported paths: Mat->Left, Mat->Right, Acc->Vec, Vec->Vec" | 528 | f"supported paths: Mat->Left, Mat->Right, Acc->Vec, Vec->Vec" |
| 475 | ) | 529 | ) |
| 476 | - if fp_tile is not None and pre_quant_scalar is not None: | 530 | + |
| 477 | - raise ValueError("fp_tile cannot be used together with pre_quant_scalar") | ||
| 478 | - if fp_tile is not None and acc_to_vec_mode in {AccToVecMode.DualModeSplitM, AccToVecMode.DualModeSplitN}: | ||
| 479 | - raise ValueError("fp_tile only supports single-mode acc_to_vec_mode") | ||
| 480 | - # Validate src/dst tile shape compatibility (issue #99: transpose-style mismatch) | ||
| 481 | _check_move_shape_compat(out, src, offset, acc_to_vec_mode, actual_span) | 531 | _check_move_shape_compat(out, src, offset, acc_to_vec_mode, actual_span) |
| 482 | - # Validate offset bounds at Python frontend level | ||
| 483 | if offset is not None: | 532 | if offset is not None: |
| 484 | if isinstance(offset, _ir_core.MakeTuple): | 533 | if isinstance(offset, _ir_core.MakeTuple): |
| 485 | _validate_offset_bounds("move", src.type.shape, offset.elements) | 534 | _validate_offset_bounds("move", src.type.shape, offset.elements) |
| 486 | elif isinstance(offset, (list, tuple)): | 535 | elif isinstance(offset, (list, tuple)): |
| 487 | _validate_offset_bounds("move", src.type.shape, offset) | 536 | _validate_offset_bounds("move", src.type.shape, offset) |
| 537 | + | ||
| 538 | + pre_quant_scalar, fp_tile = _resolve_scale_param(scale, actual_span) | ||
| 539 | + | ||
| 540 | + _check_scale_dst_supported( | ||
| 541 | + getattr(src.type, "dtype", None), | ||
| 542 | + getattr(out.type, "dtype", None), | ||
| 543 | + pre_quant_scalar is not None or fp_tile is not None, | ||
| 544 | + "move", | ||
| 545 | + ) | ||
| 546 | + if fp_tile is not None and acc_to_vec_mode in {AccToVecMode.DualModeSplitM, AccToVecMode.DualModeSplitN}: | ||
| 547 | + raise ValueError("scale (per-channel) only supports single-mode acc_to_vec_mode") | ||
| 488 | kwargs: dict[str, Any] = {} | 548 | kwargs: dict[str, Any] = {} |
| 489 | if acc_to_vec_mode is not None: | 549 | if acc_to_vec_mode is not None: |
| 490 | kwargs["acc_to_vec_mode"] = acc_to_vec_mode | 550 | kwargs["acc_to_vec_mode"] = acc_to_vec_mode |
| @@ -492,9 +552,6 @@ def _ir_move( | |||
| 492 | kwargs["relu_pre_mode"] = relu_pre_mode | 552 | kwargs["relu_pre_mode"] = relu_pre_mode |
| 493 | if fp_tile is not None: | 553 | if fp_tile is not None: |
| 494 | return _ir_core.create_op_call(block_ir_op("move_fp"), [out, src, fp_tile], kwargs, actual_span) | 554 | return _ir_core.create_op_call(block_ir_op("move_fp"), [out, src, fp_tile], kwargs, actual_span) |
| 495 | - # Positional operands: [out, src, (offset tuple)?, (pre_quant_scalar)?]. | ||
| 496 | - # offset is a TupleType, pre_quant_scalar is a ScalarType — the backend disambiguates by type, | ||
| 497 | - # so pre_quant_scalar can be a runtime scalar value, not just a compile-time constant. | ||
| 498 | args = [out, src] | 555 | args = [out, src] |
| 499 | if offset is not None: | 556 | if offset is not None: |
| 500 | args.append(_to_make_tuple(offset, actual_span)) | 557 | args.append(_to_make_tuple(offset, actual_span)) |
| @@ -722,6 +779,31 @@ def _validate_dtype(dtype: DataType | None, role: str, op_name: str) -> None: | |||
| 722 | raise ValueError(f"{op_name}: unsupported {role} dtype {dtype}, supported: b8/b16/b32/b64") | 779 | raise ValueError(f"{op_name}: unsupported {role} dtype {dtype}, supported: b8/b16/b32/b64") |
| 723 | 780 | ||
| 724 | 781 | ||
| 782 | +def _check_scale_dst_supported(src_dtype: DataType | None, dst_dtype: DataType | None, is_quant_active: bool, | ||
| 783 | + op_name: str) -> None: | ||
| 784 | + """Reject scale quantization to dtype combinations the hardware fixpipe cannot produce. | ||
| 785 | + | ||
| 786 | + The fixpipe has no unsigned requantization (UINT8 output) and only dequantizes | ||
| 787 | + INT32→FP16 (not INT32→BF16); FP32→BF16 only supports a no-scale truncation. | ||
| 788 | + These combos compile but fault on device (NPU device error 507015), so surface | ||
| 789 | + them as parse-time errors instead of a device crash. | ||
| 790 | + """ | ||
| 791 | + if not is_quant_active: | ||
| 792 | + return | ||
| 793 | + if dst_dtype == DataType.UINT8: | ||
| 794 | + raise ValueError( | ||
| 795 | + f"{op_name}: scale quantization to UINT8 is not supported — the hardware " | ||
| 796 | + "fixpipe has no unsigned requantization path. Use an INT8 output, or quantize " | ||
| 797 | + "in the Vector (UB) domain." | ||
| 798 | + ) | ||
| 799 | + if dst_dtype == DataType.BF16 and src_dtype in (DataType.FP32, DataType.INT32): | ||
| 800 | + raise ValueError( | ||
| 801 | + f"{op_name}: scale quantization from {src_dtype} to BF16 is not supported — " | ||
| 802 | + "the fixpipe only dequantizes INT32→FP16 and only truncates FP32→BF16 without " | ||
| 803 | + "a scale. Write FP16 output, or drop the scale and truncate in the Vector (UB) domain." | ||
| 804 | + ) | ||
| 805 | + | ||
| 806 | + | ||
| 725 | def _resolve_order( | 807 | def _resolve_order( |
| 726 | order: list[int] | None, | 808 | order: list[int] | None, |
| 727 | tensor_ndim: int, | 809 | tensor_ndim: int, |
| @@ -1207,7 +1289,8 @@ def _parse_make_tile(self, call: ast.Call) -> Expr: | |||
| 1207 | kwargs.setdefault("compact", tile_type.compact) | 1289 | kwargs.setdefault("compact", tile_type.compact) |
| 1208 | args = args[1:] | 1290 | args = args[1:] |
| 1209 | 1291 | ||
| 1210 | - return make_tile(*args, **kwargs, span=span) | 1292 | + result = make_tile(*args, **kwargs, span=span) |
| 1293 | + return result | ||
| 1211 | 1294 | ||
| 1212 | 1295 | ||
| 1213 | 1296 | ||
| @@ -1217,6 +1300,113 @@ def _resolve_order_kwarg(self, call: ast.Call, kwargs: dict) -> None: | |||
| 1217 | kwargs["order"] = order | 1300 | kwargs["order"] = order |
| 1218 | 1301 | ||
| 1219 | 1302 | ||
| 1303 | +def _static_shape_ints(shape, what: str) -> list[int]: | ||
| 1304 | + """Resolve a scale Tile shape to plain ints (hardware deqTensor constraints).""" | ||
| 1305 | + ints = [] | ||
| 1306 | + for dim in shape: | ||
| 1307 | + if isinstance(dim, ConstInt): | ||
| 1308 | + ints.append(int(dim.value)) | ||
| 1309 | + elif isinstance(dim, int): | ||
| 1310 | + ints.append(dim) | ||
| 1311 | + else: | ||
| 1312 | + raise ValueError(f"{what} shape must contain static integer dimensions, got {type(dim)}") | ||
| 1313 | + return ints | ||
| 1314 | + | ||
| 1315 | + | ||
| 1316 | +def _validate_fp_shape_dtype(fp_shape_ints: list[int], scale_dtype: DataType, what: str) -> None: | ||
| 1317 | + """Validate a per-channel scale Tile against the FixPipe deqTensor constraints. | ||
| 1318 | + | ||
| 1319 | + Hardware FixPipe deqTensor (pto-isa TMov.hpp): row must be 1; | ||
| 1320 | + col * sizeof(int64) 128B-aligned (col % 16 == 0); col * sizeof(int64) <= 4KB FB (col <= 512). | ||
| 1321 | + ``[N, 1]`` per-row scaling is NOT supported — it fails at compile time with | ||
| 1322 | + "TMov: When TileType is Scaling, row must be 1." | ||
| 1323 | + """ | ||
| 1324 | + if len(fp_shape_ints) != 2: | ||
| 1325 | + raise ValueError(f"{what} must be 2D, got shape {fp_shape_ints}") | ||
| 1326 | + if fp_shape_ints[0] != 1: | ||
| 1327 | + raise ValueError( | ||
| 1328 | + f"{what} must have shape [1, N] (row == 1), got [{fp_shape_ints[0]}, {fp_shape_ints[1]}]. " | ||
| 1329 | + f"Hardware FixPipe deqTensor only supports per-column scaling ([1, N]); " | ||
| 1330 | + f"[N, 1] per-row scaling is not supported. " | ||
| 1331 | + f"Per-token (row-wise) quantization must be done in the Vector (UB) domain." | ||
| 1332 | + ) | ||
| 1333 | + if fp_shape_ints[1] % 16 != 0: | ||
| 1334 | + raise ValueError( | ||
| 1335 | + f"{what} [1, N]: N must be a multiple of 16 (128B alignment for INT64), " | ||
| 1336 | + f"got [{fp_shape_ints[0]}, {fp_shape_ints[1]}]" | ||
| 1337 | + ) | ||
| 1338 | + if fp_shape_ints[1] > 512: | ||
| 1339 | + raise ValueError( | ||
| 1340 | + f"{what} [1, N]: N must be <= 512 (4KB fixpipe buffer limit for INT64), " | ||
| 1341 | + f"got [{fp_shape_ints[0]}, {fp_shape_ints[1]}]" | ||
| 1342 | + ) | ||
| 1343 | + if scale_dtype == DataType.FP32: | ||
| 1344 | + raise ValueError( | ||
| 1345 | + f"{what} dtype FP32 is not supported. " | ||
| 1346 | + f"Please convert FP32 scale to INT64 using torch_npu.npu_trans_quant_param() before passing to kernel. " | ||
| 1347 | + f"Example: scale_int64 = torch_npu.npu_trans_quant_param(scale_fp32.npu())" | ||
| 1348 | + ) | ||
| 1349 | + if scale_dtype != DataType.INT64: | ||
| 1350 | + raise ValueError( | ||
| 1351 | + f"{what} dtype must be INT64, got {scale_dtype}. " | ||
| 1352 | + f"For FP32 scale, use torch_npu.npu_trans_quant_param() to convert to INT64." | ||
| 1353 | + ) | ||
| 1354 | + | ||
| 1355 | + | ||
| 1356 | +def _auto_alloc_scaling_tile_hook(self, call: ast.Call, kwargs: dict) -> None: | ||
| 1357 | + """Pre-hook: validate a user-prepared Scaling tile when scale is a Tile (per-channel quantization). | ||
| 1358 | + | ||
| 1359 | + Per-channel quantization requires a user-prepared deqTensor tile: the user | ||
| 1360 | + builds a Scaling tile (MemorySpace.Scaling, [1, N] INT64), owns the data | ||
| 1361 | + flow (load -> move -> sync MTE1->FIX before the store/move), and passes it | ||
| 1362 | + as ``scale``. This hook only validates it — no auto-allocation of | ||
| 1363 | + Scaling/Mat tiles and no sync events are emitted. The validated tile stays | ||
| 1364 | + in the ``scale`` kwarg and is resolved by ``_resolve_scale_param`` in the | ||
| 1365 | + builder to the store_fp/move_fp operand. | ||
| 1366 | + | ||
| 1367 | + A GM Tensor scale is rejected at parse time: the automatic per-channel path | ||
| 1368 | + (auto-allocated Mat intermediate + auto sync events) has been removed; users | ||
| 1369 | + must prepare the Scaling tile themselves. | ||
| 1370 | + | ||
| 1371 | + Scale tile shape constraint: | ||
| 1372 | + - Hardware FixPipe deqTensor only supports per-column scaling: scale tile must be | ||
| 1373 | + ``[1, N]`` (row == 1), with ``N % 16 == 0`` (128B alignment) and ``N <= 512`` (4KB | ||
| 1374 | + fixpipe buffer). ``[N, 1]`` per-row scaling is rejected here with a clear error | ||
| 1375 | + (hardware would otherwise fail compilation with "TMov: row must be 1"). | ||
| 1376 | + | ||
| 1377 | + FP32 scale tile limitation: | ||
| 1378 | + - Only INT64 scale tiles are supported; FP32 scale tensors must be converted | ||
| 1379 | + on the host side via ``torch_npu.npu_trans_quant_param`` before being loaded | ||
| 1380 | + into the Scaling tile. | ||
| 1381 | + """ | ||
| 1382 | + scale = kwargs.get("scale") | ||
| 1383 | + if scale is None: | ||
| 1384 | + return | ||
| 1385 | + if not isinstance(scale, Expr): | ||
| 1386 | + return | ||
| 1387 | + scale_type = getattr(scale, "type", None) | ||
| 1388 | + | ||
| 1389 | + if isinstance(scale_type, _ir_core.TileType): | ||
| 1390 | + mem = getattr(getattr(scale_type, "memref", None), "memory_space", None) | ||
| 1391 | + if mem != MemorySpace.Scaling: | ||
| 1392 | + raise ValueError( | ||
| 1393 | + f"scale Tile must be allocated in MemorySpace.Scaling for per-channel quantization, got {mem}" | ||
| 1394 | + ) | ||
| 1395 | + fp_shape_ints = _static_shape_ints(scale_type.shape, "scale tile") | ||
| 1396 | + _validate_fp_shape_dtype(fp_shape_ints, scale_type.dtype, "scale tile") | ||
| 1397 | + return | ||
| 1398 | + | ||
| 1399 | + if isinstance(scale_type, _ir_core.TensorType): | ||
| 1400 | + raise ValueError( | ||
| 1401 | + "scale Tensor is not supported for per-channel quantization — pass a " | ||
| 1402 | + "user-prepared Scaling Tile (MemorySpace.Scaling, shape [1, N], INT64) " | ||
| 1403 | + "instead, and ensure it is ready (load -> move -> sync MTE1->FIX) before " | ||
| 1404 | + "the store/move" | ||
| 1405 | + ) | ||
| 1406 | + | ||
| 1407 | + return # scalar / runtime bits -> handled by _resolve_scale_param | ||
| 1408 | + | ||
| 1409 | + | ||
| 1220 | # --------------------------------------------------------------------------- | 1410 | # --------------------------------------------------------------------------- |
| 1221 | # Builder helpers for merged interfaces | 1411 | # Builder helpers for merged interfaces |
| 1222 | # --------------------------------------------------------------------------- | 1412 | # --------------------------------------------------------------------------- |
| @@ -1317,7 +1507,7 @@ register_table( | |||
| 1317 | { | 1507 | { |
| 1318 | # args + kwargs -> builder | 1508 | # args + kwargs -> builder |
| 1319 | "store_fp": OpSpec(builder=_ir_store_fp), | 1509 | "store_fp": OpSpec(builder=_ir_store_fp), |
| 1320 | - "move": OpSpec(builder=_ir_move), | 1510 | + "move": OpSpec(builder=_ir_move, pre_hooks=[_auto_alloc_scaling_tile_hook]), |
| 1321 | "insert": OpSpec(builder=_ir_insert), | 1511 | "insert": OpSpec(builder=_ir_insert), |
| 1322 | "getval": OpSpec(builder=_ir_getval), | 1512 | "getval": OpSpec(builder=_ir_getval), |
| 1323 | "setval": OpSpec(builder=_ir_setval), | 1513 | "setval": OpSpec(builder=_ir_setval), |
| @@ -1349,11 +1539,11 @@ register_table( | |||
| 1349 | "expand_mul": OpSpec(builder=_ir_expand_mul), | 1539 | "expand_mul": OpSpec(builder=_ir_expand_mul), |
| 1350 | "expand_sub": OpSpec(builder=_ir_expand_sub), | 1540 | "expand_sub": OpSpec(builder=_ir_expand_sub), |
| 1351 | "expand_div": OpSpec(builder=_ir_expand_div), | 1541 | "expand_div": OpSpec(builder=_ir_expand_div), |
| 1352 | - # args + kwargs + order hook (load) / order hook (store) | 1542 | + # args + kwargs + order hook (load) / order hook + scaling tile hook (store) |
| 1353 | "load": OpSpec(builder=_ir_load, pre_hooks=[_resolve_order_kwarg]), | 1543 | "load": OpSpec(builder=_ir_load, pre_hooks=[_resolve_order_kwarg]), |
| 1354 | "load_tile": OpSpec(builder=_ir_load_tile, pre_hooks=[_resolve_order_kwarg]), | 1544 | "load_tile": OpSpec(builder=_ir_load_tile, pre_hooks=[_resolve_order_kwarg]), |
| 1355 | - "store": OpSpec(builder=_ir_store, pre_hooks=[_resolve_order_kwarg]), | 1545 | + "store": OpSpec(builder=_ir_store, pre_hooks=[_auto_alloc_scaling_tile_hook, _resolve_order_kwarg]), |
| 1356 | - "store_tile": OpSpec(builder=_ir_store_tile, pre_hooks=[_resolve_order_kwarg]), | 1546 | + "store_tile": OpSpec(builder=_ir_store_tile, pre_hooks=[_auto_alloc_scaling_tile_hook, _resolve_order_kwarg]), |
| 1357 | # kwargs only | 1547 | # kwargs only |
| 1358 | "set_mask_count": OpSpec(builder=_ir_set_mask_count, parse_args=False), | 1548 | "set_mask_count": OpSpec(builder=_ir_set_mask_count, parse_args=False), |
| 1359 | "set_mask_norm": OpSpec(builder=_ir_set_mask_norm, parse_args=False), | 1549 | "set_mask_norm": OpSpec(builder=_ir_set_mask_norm, parse_args=False), |
| @@ -119,8 +119,7 @@ def store( | |||
| 119 | offsets: Offset, | 119 | offsets: Offset, |
| 120 | *, | 120 | *, |
| 121 | relu_pre_mode: Optional[ReluPreMode] = None, | 121 | relu_pre_mode: Optional[ReluPreMode] = None, |
| 122 | - pre_quant_scalar: Optional[int] = None, | 122 | + scale: Optional[Union[float, Scalar, Tile]] = None, |
| 123 | - fp_tile: Optional[Tile] = None, | ||
| 124 | order: Optional[List[int]] = None, | 123 | order: Optional[List[int]] = None, |
| 125 | atomic: AtomicType = AtomicType.AtomicNone, | 124 | atomic: AtomicType = AtomicType.AtomicNone, |
| 126 | phase: Optional[STPhase] = None, | 125 | phase: Optional[STPhase] = None, |
| @@ -131,17 +130,32 @@ def store( | |||
| 131 | dst_tensor: Destination Tensor (global memory) | 130 | dst_tensor: Destination Tensor (global memory) |
| 132 | src_tile: Source Tile (on-chip buffer) | 131 | src_tile: Source Tile (on-chip buffer) |
| 133 | offsets: Element-level offset per axis, e.g. ``[row, col]`` or ``[b, n, sq, sk]`` | 132 | offsets: Element-level offset per axis, e.g. ``[row, col]`` or ``[b, n, sq, sk]`` |
| 134 | - relu_pre_mode: Optional ReLU fusion — ``pl.ReluPreMode.NormalRelu``; mutually exclusive with ``fp_tile`` | 133 | + relu_pre_mode: Optional ReLU fusion — ``pl.ReluPreMode.NormalRelu`` |
| 135 | - pre_quant_scalar: Optional pre-quantization scalar (i64 bit pattern); mutually exclusive with ``fp_tile`` | 134 | + scale: Optional fixpipe quantization scale. |
| 136 | - fp_tile: Optional fixpipe quantization Tile; enables ``store_fp`` path, | 135 | + ``float`` or runtime scalar → per-tensor quantization (deqScalar path); |
| 137 | - mutually exclusive with ``relu_pre_mode``, ``pre_quant_scalar``, and ``phase`` | 136 | + a runtime **FP32** scalar is auto-reinterpreted as its IEEE-754 bit |
| 137 | + pattern (codegen bitcast), so pass the raw float value; a runtime | ||
| 138 | + **INT32/INT64** scalar must carry the pre-encoded float32 bit pattern | ||
| 139 | + (``struct.pack("!f", scale)``). Other runtime scalar dtypes | ||
| 140 | + (FP16/BF16/unsigned/narrower ints) are rejected at parse time. | ||
| 141 | + ``Tile`` (INT64, MemorySpace.Scaling, shape ``[1, N]``) → per-channel quantization with a | ||
| 142 | + **user-prepared deqTensor tile**; the framework reuses it directly (no auto-allocation, | ||
| 143 | + no sync insertion) — the user owns the data flow and must ensure the tile is ready | ||
| 144 | + (load → move → sync MTE1→FIX) before the store. | ||
| 145 | + Hardware requires ``[1, N]`` (row == 1, per-column), ``N % 16 == 0`` and ``N <= 512`` — | ||
| 146 | + ``[N, 1]`` per-row scaling is NOT supported. | ||
| 147 | + ``None`` → no fixpipe quantization. | ||
| 148 | + Quantization direction (quantize vs dequantize) is determined by ``dst_tensor`` dtype: | ||
| 149 | + INT8 → quantize; FP16 → dequantize (from INT32 L0C). Unsupported scale combos — | ||
| 150 | + UINT8 output, and FP32/INT32 → BF16 output — are rejected at parse time | ||
| 151 | + (hardware fixpipe has no unsigned requantization and only dequantizes INT32→FP16). | ||
| 138 | order: Optional, which axes of the Tensor the Tile dimensions map to. | 152 | order: Optional, which axes of the Tensor the Tile dimensions map to. |
| 139 | When the Tensor has more dimensions than the Tile, this specifies the mapping. | 153 | When the Tensor has more dimensions than the Tile, this specifies the mapping. |
| 140 | E.g. ``order=[0, 2]`` means Tile dim 0 → Tensor axis 0, Tile dim 1 → Tensor axis 2. | 154 | E.g. ``order=[0, 2]`` means Tile dim 0 → Tensor axis 0, Tile dim 1 → Tensor axis 2. |
| 141 | Default: last N axes of the Tensor (N = Tile ndim) | 155 | Default: last N axes of the Tensor (N = Tile ndim) |
| 142 | atomic: Atomic write mode — ``pl.AtomicType.AtomicNone`` (overwrite) or | 156 | atomic: Atomic write mode — ``pl.AtomicType.AtomicNone`` (overwrite) or |
| 143 | ``pl.AtomicType.AtomicAdd`` (atomic accumulate) | 157 | ``pl.AtomicType.AtomicAdd`` (atomic accumulate) |
| 144 | - phase: Fixpipe drain phase — ``pl.STPhase.Partial`` or ``pl.STPhase.Final``; mutually exclusive with ``fp_tile`` | 158 | + phase: Fixpipe drain phase — ``pl.STPhase.Partial`` or ``pl.STPhase.Final`` |
| 145 | """ | 159 | """ |
| 146 | 160 | ||
| 147 | 161 | ||
| @@ -152,8 +166,7 @@ def store_tile( | |||
| 152 | tile_offsets: Offset, | 166 | tile_offsets: Offset, |
| 153 | *, | 167 | *, |
| 154 | relu_pre_mode: Optional[ReluPreMode] = None, | 168 | relu_pre_mode: Optional[ReluPreMode] = None, |
| 155 | - pre_quant_scalar: Optional[int] = None, | 169 | + scale: Optional[Union[float, Scalar, Tile]] = None, |
| 156 | - fp_tile: Optional[Tile] = None, | ||
| 157 | order: Optional[List[int]] = None, | 170 | order: Optional[List[int]] = None, |
| 158 | atomic: AtomicType = AtomicType.AtomicNone, | 171 | atomic: AtomicType = AtomicType.AtomicNone, |
| 159 | phase: Optional[STPhase] = None, | 172 | phase: Optional[STPhase] = None, |
| @@ -165,17 +178,28 @@ def store_tile( | |||
| 165 | src_tile: Source Tile (on-chip buffer) | 178 | src_tile: Source Tile (on-chip buffer) |
| 166 | tile_offsets: Tile-block index, e.g. ``[tile_row, tile_col]``; | 179 | tile_offsets: Tile-block index, e.g. ``[tile_row, tile_col]``; |
| 167 | internally multiplied by tile shape to get element offsets | 180 | internally multiplied by tile shape to get element offsets |
| 168 | - relu_pre_mode: Optional ReLU fusion — ``pl.ReluPreMode.NormalRelu``; mutually exclusive with ``fp_tile`` | 181 | + relu_pre_mode: Optional ReLU fusion — ``pl.ReluPreMode.NormalRelu`` |
| 169 | - pre_quant_scalar: Optional pre-quantization scalar (i64 bit pattern); mutually exclusive with ``fp_tile`` | 182 | + scale: Optional fixpipe quantization scale. |
| 170 | - fp_tile: Optional fixpipe quantization Tile; enables ``store_fp`` path, | 183 | + ``float`` or runtime scalar → per-tensor quantization (deqScalar path); |
| 171 | - mutually exclusive with ``relu_pre_mode``, ``pre_quant_scalar``, and ``phase`` | 184 | + a runtime **FP32** scalar is auto-reinterpreted as its IEEE-754 bit |
| 185 | + pattern (codegen bitcast), so pass the raw float value; a runtime | ||
| 186 | + **INT32/INT64** scalar must carry the pre-encoded float32 bit pattern | ||
| 187 | + (``struct.pack("!f", scale)``). Other runtime scalar dtypes | ||
| 188 | + (FP16/BF16/unsigned/narrower ints) are rejected at parse time. | ||
| 189 | + ``Tile`` (INT64, MemorySpace.Scaling, shape ``[1, N]``) → per-channel quantization with a | ||
| 190 | + **user-prepared deqTensor tile**; the framework reuses it directly (no auto-allocation, | ||
| 191 | + no sync insertion) — the user owns the data flow and must ensure the tile is ready | ||
| 192 | + (load → move → sync MTE1→FIX) before the store. | ||
| 193 | + Hardware requires ``[1, N]`` (row == 1, per-column), ``N % 16 == 0`` and ``N <= 512`` — | ||
| 194 | + ``[N, 1]`` per-row scaling is NOT supported. | ||
| 195 | + ``None`` → no fixpipe quantization. | ||
| 172 | order: Optional, which axes of the Tensor the Tile dimensions map to. | 196 | order: Optional, which axes of the Tensor the Tile dimensions map to. |
| 173 | When the Tensor has more dimensions than the Tile, this specifies the mapping. | 197 | When the Tensor has more dimensions than the Tile, this specifies the mapping. |
| 174 | E.g. ``order=[0, 2]`` means Tile dim 0 → Tensor axis 0, Tile dim 1 → Tensor axis 2. | 198 | E.g. ``order=[0, 2]`` means Tile dim 0 → Tensor axis 0, Tile dim 1 → Tensor axis 2. |
| 175 | Default: last N axes of the Tensor (N = Tile ndim) | 199 | Default: last N axes of the Tensor (N = Tile ndim) |
| 176 | atomic: Atomic write mode — ``pl.AtomicType.AtomicNone`` (overwrite) or | 200 | atomic: Atomic write mode — ``pl.AtomicType.AtomicNone`` (overwrite) or |
| 177 | ``pl.AtomicType.AtomicAdd`` (atomic accumulate) | 201 | ``pl.AtomicType.AtomicAdd`` (atomic accumulate) |
| 178 | - phase: Fixpipe drain phase — ``pl.STPhase.Partial`` or ``pl.STPhase.Final``; mutually exclusive with ``fp_tile`` | 202 | + phase: Fixpipe drain phase — ``pl.STPhase.Partial`` or ``pl.STPhase.Final`` |
| 179 | """ | 203 | """ |
| 180 | 204 | ||
| 181 | 205 | ||
| @@ -187,8 +211,7 @@ def move( | |||
| 187 | *, | 211 | *, |
| 188 | acc_to_vec_mode: Optional[AccToVecMode] = None, | 212 | acc_to_vec_mode: Optional[AccToVecMode] = None, |
| 189 | relu_pre_mode: Optional[ReluPreMode] = None, | 213 | relu_pre_mode: Optional[ReluPreMode] = None, |
| 190 | - pre_quant_scalar: Optional[int] = None, | 214 | + scale: Optional[Union[float, Scalar, Tile]] = None, |
| 191 | - fp_tile: Optional[Tile] = None, | ||
| 192 | ) -> None: | 215 | ) -> None: |
| 193 | """Move data between on-chip Tiles (tile↔tile, no GM access). | 216 | """Move data between on-chip Tiles (tile↔tile, no GM access). |
| 194 | 217 | ||
| @@ -209,9 +232,7 @@ def move( | |||
| 209 | 232 | ||
| 210 | - ``acc_to_vec_mode``: Acc→Vec conversion mode (single/dual split M/N) | 233 | - ``acc_to_vec_mode``: Acc→Vec conversion mode (single/dual split M/N) |
| 211 | - ``relu_pre_mode``: ReLU activation before destination | 234 | - ``relu_pre_mode``: ReLU activation before destination |
| 212 | - - ``pre_quant_scalar``: pre-quantization scalar (mutually exclusive with ``fp_tile``) | 235 | + - ``scale``: fixpipe quantization scale (per-tensor or per-channel) |
| 213 | - - ``fp_tile``: fixpipe quantization tile, enables ``move_fp`` path | ||
| 214 | - (mutually exclusive with ``pre_quant_scalar``; single-mode only) | ||
| 215 | 236 | ||
| 216 | Args: | 237 | Args: |
| 217 | dst_tile: Destination Tile | 238 | dst_tile: Destination Tile |
| @@ -221,9 +242,20 @@ def move( | |||
| 221 | ``pl.AccToVecMode.DualModeSplitM``, ``pl.AccToVecMode.DualModeSplitN``; | 242 | ``pl.AccToVecMode.DualModeSplitM``, ``pl.AccToVecMode.DualModeSplitN``; |
| 222 | only meaningful when src is Acc and dst is Vec | 243 | only meaningful when src is Acc and dst is Vec |
| 223 | relu_pre_mode: Optional ReLU fusion — ``pl.ReluPreMode.NormalRelu`` | 244 | relu_pre_mode: Optional ReLU fusion — ``pl.ReluPreMode.NormalRelu`` |
| 224 | - pre_quant_scalar: Optional pre-quantization scalar; mutually exclusive with ``fp_tile`` | 245 | + scale: Optional fixpipe quantization scale. |
| 225 | - fp_tile: Optional fixpipe quantization Tile; enables ``move_fp`` path, | 246 | + ``float`` or runtime scalar → per-tensor quantization (deqScalar path); |
| 226 | - mutually exclusive with ``pre_quant_scalar`` | 247 | + a runtime **FP32** scalar is auto-reinterpreted as its IEEE-754 bit |
| 248 | + pattern (codegen bitcast), so pass the raw float value; a runtime | ||
| 249 | + **INT32/INT64** scalar must carry the pre-encoded float32 bit pattern | ||
| 250 | + (``struct.pack("!f", scale)``). Other runtime scalar dtypes | ||
| 251 | + (FP16/BF16/unsigned/narrower ints) are rejected at parse time. | ||
| 252 | + ``Tile`` (INT64, MemorySpace.Scaling, shape ``[1, N]``) → per-channel quantization with a | ||
| 253 | + **user-prepared deqTensor tile**; the framework reuses it directly (no auto-allocation, | ||
| 254 | + no sync insertion) — the user owns the data flow and must ensure the tile is ready | ||
| 255 | + (load → move → sync MTE1→FIX) before the move. | ||
| 256 | + Hardware requires ``[1, N]`` (row == 1, per-column), ``N % 16 == 0`` and ``N <= 512`` — | ||
| 257 | + ``[N, 1]`` per-row scaling is NOT supported. | ||
| 258 | + ``None`` → no fixpipe quantization. | ||
| 227 | """ | 259 | """ |
| 228 | 260 | ||
| 229 | 261 | ||
| @@ -1,149 +0,0 @@ | |||
| 1 | -# Copyright (c) 2025-2026 Huawei Technologies Co., Ltd. | ||
| 2 | -# This program is free software, you can redistribute it and/or modify it under the terms and conditions of | ||
| 3 | -# CANN Open Software License Agreement Version 2.0 (the "License"). | ||
| 4 | -# Please refer to the License for details. You may not use this file except in compliance with the License. | ||
| 5 | -# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | ||
| 6 | -# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | ||
| 7 | -# See LICENSE in the root of the software repository for the full text of the License. | ||
| 8 | -# ----------------------------------------------------------------------------------------------------------- | ||
| 9 | - | ||
| 10 | -"""Frontend runtime example for pl.move(..., pre_quant_scalar=...) on A5 CCE. | ||
| 11 | - | ||
| 12 | -Scalar-dequant counterpart of test_move_fp_cce.py (which uses the per-channel fp_tile path). | ||
| 13 | -This exercises the L0C->UB (Acc->Vec) fixpipe dequant via TMOV with a SCALAR scale, on A5 only | ||
| 14 | -(the L0C->UB quant path lives in arch35/copy_l0c_to_ub_impl.h, gated by PTO_NPU_ARCH_A5; a3 has | ||
| 15 | -no such path). | ||
| 16 | - | ||
| 17 | -deqScalar low 32 bits = float32 bit-pattern of the scale (scale=2.0f -> 0x40000000). The signed-int8 | ||
| 18 | -flag (bit 46) is re-derived in CCE codegen from the destination tile dtype (MakeBlockOutMoveCodegenCCE), | ||
| 19 | -so the caller passes only the low 32 bits and negatives quantize correctly to signed int8 instead of | ||
| 20 | -saturating to 0. | ||
| 21 | -""" | ||
| 22 | - | ||
| 23 | -import logging | ||
| 24 | -import os | ||
| 25 | -import struct | ||
| 26 | - | ||
| 27 | -import pypto_pro.language as pl | ||
| 28 | -import pytest | ||
| 29 | -import torch | ||
| 30 | - | ||
| 31 | -ST_DEVICE_ID = int(os.environ.get("TILE_FWK_DEVICE_ID", 0)) | ||
| 32 | -ST_DEVICE = f"npu:{ST_DEVICE_ID}" | ||
| 33 | - | ||
| 34 | - | ||
| 35 | -FP_SCALE_VALUE = 2.0 | ||
| 36 | -DEQ_SCALAR_BITS = struct.unpack("!I", struct.pack("!f", FP_SCALE_VALUE))[0] # 0x40000000 | ||
| 37 | - | ||
| 38 | - | ||
| 39 | -def _make_q(device: str) -> torch.Tensor: | ||
| 40 | - # Includes negatives on purpose: validates signed-int8 dequant keeps the sign (-3*2=-6, not 0). | ||
| 41 | - row = torch.tensor([-3.0, -2.0, -1.0, 0.0, 1.0, 2.0, 3.0, 4.0], device=device, dtype=torch.float32).repeat(8) | ||
| 42 | - return row.unsqueeze(0).repeat(64, 1) | ||
| 43 | - | ||
| 44 | - | ||
| 45 | -def _make_k(device: str) -> torch.Tensor: | ||
| 46 | - return torch.eye(64, device=device, dtype=torch.float32) | ||
| 47 | - | ||
| 48 | - | ||
| 49 | -@pl.jit() | ||
| 50 | -def deq_scalar_move_fp32_to_int8_kernel( | ||
| 51 | - q: pl.Tensor[[64, 64], pl.DT_FP32], | ||
| 52 | - k: pl.Tensor[[64, 64], pl.DT_FP32], | ||
| 53 | - move_out: pl.Tensor[[64, 64], pl.DT_INT8], | ||
| 54 | -): | ||
| 55 | - vec_type = pl.TileType(shape=[64, 64], dtype=pl.DT_INT8, target_memory=pl.MemorySpace.Vec) | ||
| 56 | - vec_tile = pl.make_tile(vec_type, addr=0x0000, size=4096) | ||
| 57 | - | ||
| 58 | - with pl.section_cube(): | ||
| 59 | - mat_type = pl.TileType(shape=[64, 64], dtype=pl.DT_FP32, target_memory=pl.MemorySpace.Mat, layout=pl.NZ) | ||
| 60 | - q_mat = pl.make_tile(mat_type, addr=0x0000, size=16384) | ||
| 61 | - k_mat = pl.make_tile(mat_type, addr=0x4000, size=16384) | ||
| 62 | - | ||
| 63 | - left_type = pl.TileType(shape=[64, 64], dtype=pl.DT_FP32, target_memory=pl.MemorySpace.Left, layout=pl.NZ) | ||
| 64 | - q_left = pl.make_tile(left_type, addr=0x0000, size=16384) | ||
| 65 | - | ||
| 66 | - right_type = pl.TileType( | ||
| 67 | - shape=[64, 64], | ||
| 68 | - dtype=pl.DT_FP32, | ||
| 69 | - target_memory=pl.MemorySpace.Right, | ||
| 70 | - layout=pl.ZN, | ||
| 71 | - ) | ||
| 72 | - k_right = pl.make_tile(right_type, addr=0x0000, size=16384) | ||
| 73 | - | ||
| 74 | - acc_type = pl.TileType( | ||
| 75 | - shape=[64, 64], | ||
| 76 | - dtype=pl.DT_FP32, | ||
| 77 | - target_memory=pl.MemorySpace.Acc, | ||
| 78 | - layout=pl.NZ, | ||
| 79 | - fractal=1024, | ||
| 80 | - ) | ||
| 81 | - acc = pl.make_tile(acc_type, addr=0x0000, size=16384) | ||
| 82 | - | ||
| 83 | - pl.load(q_mat, q, [0, 0]) | ||
| 84 | - pl.load(k_mat, k, [0, 0]) | ||
| 85 | - | ||
| 86 | - pl.system.sync_src(set_pipe=pl.PipeType.MTE2, wait_pipe=pl.PipeType.MTE1, event_id=0) | ||
| 87 | - pl.system.sync_dst(set_pipe=pl.PipeType.MTE2, wait_pipe=pl.PipeType.MTE1, event_id=0) | ||
| 88 | - | ||
| 89 | - pl.move(q_left, q_mat) | ||
| 90 | - pl.move(k_right, k_mat) | ||
| 91 | - | ||
| 92 | - pl.system.sync_src(set_pipe=pl.PipeType.MTE1, wait_pipe=pl.PipeType.M, event_id=0) | ||
| 93 | - pl.system.sync_dst(set_pipe=pl.PipeType.MTE1, wait_pipe=pl.PipeType.M, event_id=0) | ||
| 94 | - | ||
| 95 | - pl.matmul(acc, q_left, k_right) | ||
| 96 | - | ||
| 97 | - pl.system.sync_src(set_pipe=pl.PipeType.M, wait_pipe=pl.PipeType.FIX, event_id=0) | ||
| 98 | - pl.system.sync_dst(set_pipe=pl.PipeType.M, wait_pipe=pl.PipeType.FIX, event_id=0) | ||
| 99 | - | ||
| 100 | - # Scalar dequant on the L0C->UB move: TMOV with preQuant scalar (sign flag added in codegen). | ||
| 101 | - pl.move(vec_tile, acc, pre_quant_scalar=DEQ_SCALAR_BITS, acc_to_vec_mode=pl.AccToVecMode.SingleModeVec0) | ||
| 102 | - pl.system.set_cross_core(pipe=pl.PipeType.FIX, event_id=0) | ||
| 103 | - | ||
| 104 | - with pl.section_vector(): | ||
| 105 | - sub_id = pl.get_subblock_idx() | ||
| 106 | - pl.system.wait_cross_core(pipe=pl.PipeType.MTE3, event_id=0) | ||
| 107 | - if sub_id == 0: | ||
| 108 | - pl.store(move_out, vec_tile, [0, 0]) | ||
| 109 | - pl.system.bar_all() | ||
| 110 | - | ||
| 111 | - | ||
| 112 | - | ||
| 113 | -@pytest.mark.soc("950") | ||
| 114 | -def test_deq_scalar_move_fp32_to_int8(): | ||
| 115 | - device = ST_DEVICE | ||
| 116 | - torch.npu.set_device(device) | ||
| 117 | - | ||
| 118 | - device_name = torch.npu.get_device_name() | ||
| 119 | - if "Ascend950" not in device_name: | ||
| 120 | - logging.info("Current device is %s, skip.", device_name) | ||
| 121 | - return | ||
| 122 | - | ||
| 123 | - q = _make_q(device) | ||
| 124 | - k = _make_k(device) | ||
| 125 | - move_out = torch.zeros((64, 64), device=device, dtype=torch.int8) | ||
| 126 | - | ||
| 127 | - deq_scalar_move_fp32_to_int8_kernel(q, k, move_out) | ||
| 128 | - torch.npu.synchronize() | ||
| 129 | - | ||
| 130 | - raw_ref = torch.matmul(q, k) | ||
| 131 | - expected_out = torch.clamp(torch.round(raw_ref * FP_SCALE_VALUE), -128, 127).to(torch.int8) | ||
| 132 | - | ||
| 133 | - logging.info("***********cce q input (top-left 8x8)***********") | ||
| 134 | - logging.info("%s", q[:8, :8]) | ||
| 135 | - logging.info("***********cce deq scalar bits (hex)***********") | ||
| 136 | - logging.info("0x%X (scale=%s)", DEQ_SCALAR_BITS, FP_SCALE_VALUE) | ||
| 137 | - logging.info("***********cce expected move deq_scalar int8 output***********") | ||
| 138 | - logging.info("%s", expected_out[:8, :8]) | ||
| 139 | - logging.info("***********cce move deq_scalar int8 output (top-left 8x8)***********") | ||
| 140 | - logging.info("%s", move_out[:8, :8]) | ||
| 141 | - | ||
| 142 | - torch.testing.assert_close(move_out.to(torch.int32), expected_out.to(torch.int32), rtol=0, atol=0) | ||
| 143 | - logging.info("cce move deq_scalar output matches expectation.") | ||
| 144 | - | ||
| 145 | - | ||
| 146 | -if __name__ == "__main__": | ||
| 147 | - logging.basicConfig(level=logging.INFO, format="%(message)s") | ||
| 148 | - test_deq_scalar_move_fp32_to_int8() | ||
| 149 | - logging.info("\nAll tests passed!") | ||
| @@ -1,153 +0,0 @@ | |||
| 1 | -# Copyright (c) 2025-2026 Huawei Technologies Co., Ltd. | ||
| 2 | -# This program is free software, you can redistribute it and/or modify it under the terms and conditions of | ||
| 3 | -# CANN Open Software License Agreement Version 2.0 (the "License"). | ||
| 4 | -# Please refer to the License for details. You may not use this file except in compliance with the License. | ||
| 5 | -# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | ||
| 6 | -# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | ||
| 7 | -# See LICENSE in the root of the software repository for the full text of the License. | ||
| 8 | -# ----------------------------------------------------------------------------------------------------------- | ||
| 9 | - | ||
| 10 | -"""Frontend runtime example for pl.store(..., pre_quant_scalar=...) on A5 CCE. | ||
| 11 | - | ||
| 12 | -Exercises the *scalar* fixpipe dequant path (deqScalar) — the counterpart to the | ||
| 13 | -per-channel ``fp_tile`` path in test_store_fp_cce.py. Until now no kernel test | ||
| 14 | -drove ``pre_quant_scalar``; this UT validates L0C(FP32) -> GM(int8) quant with a | ||
| 15 | -scalar scale. | ||
| 16 | - | ||
| 17 | -Encoding note (copy_l0c_to_gm_impl.h:44-47): the framework clears bit46 and | ||
| 18 | -auto-sets the signed-int8 flag from the *output* dtype, so the caller passes only | ||
| 19 | -the float32 bit-pattern of the scale (low 32 bits). For scale=2.0f that is | ||
| 20 | -0x40000000, which fits the 32-bit IR attr. | ||
| 21 | -""" | ||
| 22 | - | ||
| 23 | -import logging | ||
| 24 | -import os | ||
| 25 | -import struct | ||
| 26 | - | ||
| 27 | -import pypto_pro.language as pl | ||
| 28 | -import pytest | ||
| 29 | -import torch | ||
| 30 | - | ||
| 31 | -ST_DEVICE_ID = int(os.environ.get("TILE_FWK_DEVICE_ID", 0)) | ||
| 32 | -ST_DEVICE = f"npu:{ST_DEVICE_ID}" | ||
| 33 | - | ||
| 34 | - | ||
| 35 | -FP_SCALE_VALUE = 2.0 | ||
| 36 | -# deqScalar low 32 bits = float32 bit-pattern of the scale. For scale=2.0f -> 0x40000000. | ||
| 37 | -# | ||
| 38 | -# Signed-int8 flag (bit 46): the CCE codegen now re-derives bit46 from the OUTPUT dtype | ||
| 39 | -# (backend_cce_block_out_ops.cpp MakeBlockOutStoreCodegenCCE): when the destination is | ||
| 40 | -# signed INT8 it emits preQuant = (scale & ~(1<<46)) | (1<<46), mirroring TStoreExecute in | ||
| 41 | -# copy_l0c_to_gm_impl.h. So the caller passes only the low-32-bit scale here and the sign flag | ||
| 42 | -# is added automatically — this is why negative L0C values now quantize correctly to signed int8 | ||
| 43 | -# instead of saturating to 0 (the bug this fix addresses). The 32-bit IR attr / pybind boundary | ||
| 44 | -# truncation no longer matters because the high bit is reconstructed in codegen. | ||
| 45 | -DEQ_SCALAR_BITS = struct.unpack("!I", struct.pack("!f", FP_SCALE_VALUE))[0] # 0x40000000 | ||
| 46 | - | ||
| 47 | - | ||
| 48 | -def _make_q(device: str) -> torch.Tensor: | ||
| 49 | - # Includes negatives on purpose: validates that signed-int8 dequant keeps the sign. | ||
| 50 | - row = torch.tensor([-3.0, -2.0, -1.0, 0.0, 1.0, 2.0, 3.0, 4.0], device=device, dtype=torch.float32).repeat(8) | ||
| 51 | - return row.unsqueeze(0).repeat(64, 1) | ||
| 52 | - | ||
| 53 | - | ||
| 54 | -def _make_k(device: str) -> torch.Tensor: | ||
| 55 | - return torch.eye(64, device=device, dtype=torch.float32) | ||
| 56 | - | ||
| 57 | - | ||
| 58 | -@pl.jit() | ||
| 59 | -def deq_scalar_store_fp32_to_int8_kernel( | ||
| 60 | - q: pl.Tensor[[64, 64], pl.DT_FP32], | ||
| 61 | - k: pl.Tensor[[64, 64], pl.DT_FP32], | ||
| 62 | - raw_out: pl.Tensor[[64, 64], pl.DT_FP32], | ||
| 63 | - deq_out: pl.Tensor[[64, 64], pl.DT_INT8], | ||
| 64 | -): | ||
| 65 | - with pl.section_cube(): | ||
| 66 | - mat_type = pl.TileType(shape=[64, 64], dtype=pl.DT_FP32, target_memory=pl.MemorySpace.Mat, layout=pl.NZ) | ||
| 67 | - q_mat = pl.make_tile(mat_type, addr=0x0000, size=16384) | ||
| 68 | - k_mat = pl.make_tile(mat_type, addr=0x4000, size=16384) | ||
| 69 | - | ||
| 70 | - left_type = pl.TileType(shape=[64, 64], dtype=pl.DT_FP32, target_memory=pl.MemorySpace.Left, layout=pl.NZ) | ||
| 71 | - q_left = pl.make_tile(left_type, addr=0x0000, size=16384) | ||
| 72 | - | ||
| 73 | - right_type = pl.TileType( | ||
| 74 | - shape=[64, 64], | ||
| 75 | - dtype=pl.DT_FP32, | ||
| 76 | - target_memory=pl.MemorySpace.Right, | ||
| 77 | - layout=pl.ZN, | ||
| 78 | - ) | ||
| 79 | - k_right = pl.make_tile(right_type, addr=0x0000, size=16384) | ||
| 80 | - | ||
| 81 | - acc_type = pl.TileType( | ||
| 82 | - shape=[64, 64], | ||
| 83 | - dtype=pl.DT_FP32, | ||
| 84 | - target_memory=pl.MemorySpace.Acc, | ||
| 85 | - layout=pl.NZ, | ||
| 86 | - fractal=1024, | ||
| 87 | - ) | ||
| 88 | - acc = pl.make_tile(acc_type, addr=0x0000, size=16384) | ||
| 89 | - | ||
| 90 | - pl.load(q_mat, q, [0, 0]) | ||
| 91 | - pl.load(k_mat, k, [0, 0]) | ||
| 92 | - | ||
| 93 | - pl.system.sync_src(set_pipe=pl.PipeType.MTE2, wait_pipe=pl.PipeType.MTE1, event_id=0) | ||
| 94 | - pl.system.sync_dst(set_pipe=pl.PipeType.MTE2, wait_pipe=pl.PipeType.MTE1, event_id=0) | ||
| 95 | - | ||
| 96 | - pl.move(q_left, q_mat) | ||
| 97 | - pl.move(k_right, k_mat) | ||
| 98 | - pl.system.sync_src(set_pipe=pl.PipeType.MTE1, wait_pipe=pl.PipeType.M, event_id=0) | ||
| 99 | - pl.system.sync_dst(set_pipe=pl.PipeType.MTE1, wait_pipe=pl.PipeType.M, event_id=0) | ||
| 100 | - | ||
| 101 | - pl.matmul(acc, q_left, k_right) | ||
| 102 | - | ||
| 103 | - pl.system.sync_src(set_pipe=pl.PipeType.M, wait_pipe=pl.PipeType.FIX, event_id=0) | ||
| 104 | - pl.system.sync_dst(set_pipe=pl.PipeType.M, wait_pipe=pl.PipeType.FIX, event_id=0) | ||
| 105 | - # Reference path: raw FP32 acc -> GM (no quant). | ||
| 106 | - pl.store(raw_out, acc, [0, 0]) | ||
| 107 | - # Scalar dequant path: acc -> GM int8 with deqScalar = float32(2.0) bit-pattern. | ||
| 108 | - pl.store(deq_out, acc, [0, 0], pre_quant_scalar=DEQ_SCALAR_BITS) | ||
| 109 | - pl.system.bar_all() | ||
| 110 | - | ||
| 111 | - | ||
| 112 | - | ||
| 113 | -@pytest.mark.soc("950") | ||
| 114 | -def test_deq_scalar_store_fp32_to_int8(): | ||
| 115 | - device = ST_DEVICE | ||
| 116 | - torch.npu.set_device(device) | ||
| 117 | - | ||
| 118 | - device_name = torch.npu.get_device_name() | ||
| 119 | - if "Ascend950" not in device_name: | ||
| 120 | - logging.info("Current device is %s, skip.", device_name) | ||
| 121 | - return | ||
| 122 | - | ||
| 123 | - q = _make_q(device) | ||
| 124 | - k = _make_k(device) | ||
| 125 | - raw_out = torch.zeros((64, 64), device=device, dtype=torch.float32) | ||
| 126 | - deq_out = torch.zeros((64, 64), device=device, dtype=torch.int8) | ||
| 127 | - | ||
| 128 | - deq_scalar_store_fp32_to_int8_kernel(q, k, raw_out, deq_out) | ||
| 129 | - torch.npu.synchronize() | ||
| 130 | - | ||
| 131 | - raw_ref = torch.matmul(q, k) | ||
| 132 | - expected_deq = torch.clamp(torch.round(raw_ref * FP_SCALE_VALUE), -128, 127).to(torch.int8) | ||
| 133 | - | ||
| 134 | - logging.info("***********cce q input (top-left 8x8)***********") | ||
| 135 | - logging.info("%s", q[:8, :8]) | ||
| 136 | - logging.info("***********cce deq scalar bits (hex)***********") | ||
| 137 | - logging.info("0x%X (scale=%s)", DEQ_SCALAR_BITS, FP_SCALE_VALUE) | ||
| 138 | - logging.info("***********cce raw acc->gm output (top-left 8x8)***********") | ||
| 139 | - logging.info("%s", raw_out[:8, :8]) | ||
| 140 | - logging.info("***********cce expected deq_scalar int8 output***********") | ||
| 141 | - logging.info("%s", expected_deq[:8, :8]) | ||
| 142 | - logging.info("***********cce deq_scalar int8 output (top-left 8x8)***********") | ||
| 143 | - logging.info("%s", deq_out[:8, :8]) | ||
| 144 | - | ||
| 145 | - torch.testing.assert_close(raw_out, raw_ref, rtol=1e-2, atol=1e-2) | ||
| 146 | - torch.testing.assert_close(deq_out.to(torch.int32), expected_deq.to(torch.int32), rtol=0, atol=0) | ||
| 147 | - logging.info("cce raw store and store deq_scalar outputs both match expectations.") | ||
| 148 | - | ||
| 149 | - | ||
| 150 | -if __name__ == "__main__": | ||
| 151 | - logging.basicConfig(level=logging.INFO, format="%(message)s") | ||
| 152 | - test_deq_scalar_store_fp32_to_int8() | ||
| 153 | - logging.info("\nAll tests passed!") | ||
| @@ -1,143 +0,0 @@ | |||
| 1 | -# Copyright (c) 2025-2026 Huawei Technologies Co., Ltd. | ||
| 2 | -# This program is free software, you can redistribute it and/or modify it under the terms and conditions of | ||
| 3 | -# CANN Open Software License Agreement Version 2.0 (the "License"). | ||
| 4 | -# Please refer to the License for details. You may not use this file except in compliance with the License. | ||
| 5 | -# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | ||
| 6 | -# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | ||
| 7 | -# See LICENSE in the root of the software repository for the full text of the License. | ||
| 8 | -# ----------------------------------------------------------------------------------------------------------- | ||
| 9 | - | ||
| 10 | -"""Frontend runtime example for fixpipe scalar dequant with a DYNAMIC (runtime) scale on A5 CCE. | ||
| 11 | - | ||
| 12 | -Unlike the other test_deq_scalar_* tests (which pass pre_quant_scalar as a compile-time int | ||
| 13 | -constant), here the scale is a runtime kernel argument `scale_bits: pl.DT_INT32`, | ||
| 14 | -provided at launch time. This validates the operand refactor: pre_quant_scalar is now a | ||
| 15 | -positional operand (not a compile-time attr), so the scale can be decided at runtime. | ||
| 16 | - | ||
| 17 | -The scalar carries the low 32 bits = the float32 bit-pattern of the scale (same encoding as the | ||
| 18 | -constant tests). The CCE codegen adds the signed-int8 bit46 flag from the output dtype at runtime, | ||
| 19 | -so negatives still requantize with the sign preserved. | ||
| 20 | -""" | ||
| 21 | - | ||
| 22 | -import logging | ||
| 23 | -import os | ||
| 24 | -import struct | ||
| 25 | - | ||
| 26 | -import pypto_pro.language as pl | ||
| 27 | -import pytest | ||
| 28 | -import torch | ||
| 29 | - | ||
| 30 | -ST_DEVICE_ID = int(os.environ.get("TILE_FWK_DEVICE_ID", 0)) | ||
| 31 | -ST_DEVICE = f"npu:{ST_DEVICE_ID}" | ||
| 32 | - | ||
| 33 | - | ||
| 34 | -FP_SCALE_VALUE = 2.0 | ||
| 35 | - | ||
| 36 | - | ||
| 37 | -def _scale_bits(scale: float) -> int: | ||
| 38 | - # Low 32 bits = float32 bit-pattern of the scale (scale=2.0 -> 0x40000000). | ||
| 39 | - return struct.unpack("!I", struct.pack("!f", scale))[0] | ||
| 40 | - | ||
| 41 | - | ||
| 42 | -def _make_q(device: str) -> torch.Tensor: | ||
| 43 | - # Includes negatives to validate signed-int8 dequant keeps the sign (-3*2=-6, not 0). | ||
| 44 | - row = torch.tensor([-3.0, -2.0, -1.0, 0.0, 1.0, 2.0, 3.0, 4.0], device=device, dtype=torch.float32).repeat(8) | ||
| 45 | - return row.unsqueeze(0).repeat(64, 1) | ||
| 46 | - | ||
| 47 | - | ||
| 48 | -def _make_k(device: str) -> torch.Tensor: | ||
| 49 | - return torch.eye(64, device=device, dtype=torch.float32) | ||
| 50 | - | ||
| 51 | - | ||
| 52 | -@pl.jit() | ||
| 53 | -def deq_scalar_dynamic_cce_kernel( | ||
| 54 | - q: pl.Tensor[[64, 64], pl.DT_FP32], | ||
| 55 | - k: pl.Tensor[[64, 64], pl.DT_FP32], | ||
| 56 | - deq_out: pl.Tensor[[64, 64], pl.DT_INT8], | ||
| 57 | - scale_bits: pl.DT_INT32, | ||
| 58 | -): | ||
| 59 | - with pl.section_cube(): | ||
| 60 | - mat_type = pl.TileType(shape=[64, 64], dtype=pl.DT_FP32, target_memory=pl.MemorySpace.Mat, layout=pl.NZ) | ||
| 61 | - q_mat = pl.make_tile(mat_type, addr=0x0000, size=16384) | ||
| 62 | - k_mat = pl.make_tile(mat_type, addr=0x4000, size=16384) | ||
| 63 | - | ||
| 64 | - left_type = pl.TileType(shape=[64, 64], dtype=pl.DT_FP32, target_memory=pl.MemorySpace.Left, layout=pl.NZ) | ||
| 65 | - q_left = pl.make_tile(left_type, addr=0x0000, size=16384) | ||
| 66 | - | ||
| 67 | - right_type = pl.TileType( | ||
| 68 | - shape=[64, 64], | ||
| 69 | - dtype=pl.DT_FP32, | ||
| 70 | - target_memory=pl.MemorySpace.Right, | ||
| 71 | - layout=pl.ZN, | ||
| 72 | - ) | ||
| 73 | - k_right = pl.make_tile(right_type, addr=0x0000, size=16384) | ||
| 74 | - | ||
| 75 | - acc_type = pl.TileType( | ||
| 76 | - shape=[64, 64], | ||
| 77 | - dtype=pl.DT_FP32, | ||
| 78 | - target_memory=pl.MemorySpace.Acc, | ||
| 79 | - layout=pl.NZ, | ||
| 80 | - fractal=1024, | ||
| 81 | - ) | ||
| 82 | - acc = pl.make_tile(acc_type, addr=0x0000, size=16384) | ||
| 83 | - | ||
| 84 | - pl.load(q_mat, q, [0, 0]) | ||
| 85 | - pl.load(k_mat, k, [0, 0]) | ||
| 86 | - | ||
| 87 | - pl.system.sync_src(set_pipe=pl.PipeType.MTE2, wait_pipe=pl.PipeType.MTE1, event_id=0) | ||
| 88 | - pl.system.sync_dst(set_pipe=pl.PipeType.MTE2, wait_pipe=pl.PipeType.MTE1, event_id=0) | ||
| 89 | - | ||
| 90 | - pl.move(q_left, q_mat) | ||
| 91 | - pl.move(k_right, k_mat) | ||
| 92 | - pl.system.sync_src(set_pipe=pl.PipeType.MTE1, wait_pipe=pl.PipeType.M, event_id=0) | ||
| 93 | - pl.system.sync_dst(set_pipe=pl.PipeType.MTE1, wait_pipe=pl.PipeType.M, event_id=0) | ||
| 94 | - | ||
| 95 | - pl.matmul(acc, q_left, k_right) | ||
| 96 | - | ||
| 97 | - pl.system.sync_src(set_pipe=pl.PipeType.M, wait_pipe=pl.PipeType.FIX, event_id=0) | ||
| 98 | - pl.system.sync_dst(set_pipe=pl.PipeType.M, wait_pipe=pl.PipeType.FIX, event_id=0) | ||
| 99 | - # DYNAMIC scale: pre_quant_scalar is the runtime kernel arg, not a compile-time constant. | ||
| 100 | - pl.store(deq_out, acc, [0, 0], pre_quant_scalar=scale_bits) | ||
| 101 | - pl.system.bar_all() | ||
| 102 | - | ||
| 103 | - | ||
| 104 | - | ||
| 105 | -@pytest.mark.soc("950") | ||
| 106 | -def test_deq_scalar_dynamic_cce(): | ||
| 107 | - device = ST_DEVICE | ||
| 108 | - torch.npu.set_device(device) | ||
| 109 | - | ||
| 110 | - device_name = torch.npu.get_device_name() | ||
| 111 | - if "Ascend950" not in device_name: | ||
| 112 | - logging.info("Current device is %s, skip.", device_name) | ||
| 113 | - return | ||
| 114 | - | ||
| 115 | - q = _make_q(device) | ||
| 116 | - k = _make_k(device) | ||
| 117 | - deq_out = torch.zeros((64, 64), device=device, dtype=torch.int8) | ||
| 118 | - | ||
| 119 | - scale_bits = _scale_bits(FP_SCALE_VALUE) # runtime value, computed on host | ||
| 120 | - | ||
| 121 | - deq_scalar_dynamic_cce_kernel(q, k, deq_out, scale_bits) | ||
| 122 | - torch.npu.synchronize() | ||
| 123 | - | ||
| 124 | - raw_ref = torch.matmul(q, k) | ||
| 125 | - expected_deq = torch.clamp(torch.round(raw_ref * FP_SCALE_VALUE), -128, 127).to(torch.int8) | ||
| 126 | - | ||
| 127 | - logging.info("***********cce q input (top-left 8x8)***********") | ||
| 128 | - logging.info("%s", q[:8, :8]) | ||
| 129 | - logging.info("***********cce dynamic scale bits (hex)***********") | ||
| 130 | - logging.info("0x%X (scale=%s, passed at runtime)", scale_bits, FP_SCALE_VALUE) | ||
| 131 | - logging.info("***********cce expected deq int8 output***********") | ||
| 132 | - logging.info("%s", expected_deq[:8, :8]) | ||
| 133 | - logging.info("***********cce dynamic-scale deq int8 output (top-left 8x8)***********") | ||
| 134 | - logging.info("%s", deq_out[:8, :8]) | ||
| 135 | - | ||
| 136 | - torch.testing.assert_close(deq_out.to(torch.int32), expected_deq.to(torch.int32), rtol=0, atol=0) | ||
| 137 | - logging.info("cce dynamic-scale deq_scalar output matches expectation.") | ||
| 138 | - | ||
| 139 | - | ||
| 140 | -if __name__ == "__main__": | ||
| 141 | - logging.basicConfig(level=logging.INFO, format="%(message)s") | ||
| 142 | - test_deq_scalar_dynamic_cce() | ||
| 143 | - logging.info("\nAll tests passed!") | ||
| @@ -1,144 +0,0 @@ | |||
| 1 | -# Copyright (c) 2025-2026 Huawei Technologies Co., Ltd. | ||
| 2 | -# This program is free software, you can redistribute it and/or modify it under the terms and conditions of | ||
| 3 | -# CANN Open Software License Agreement Version 2.0 (the "License"). | ||
| 4 | -# Please refer to the License for details. You may not use this file except in compliance with the License. | ||
| 5 | -# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | ||
| 6 | -# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | ||
| 7 | -# See LICENSE in the root of the software repository for the full text of the License. | ||
| 8 | -# ----------------------------------------------------------------------------------------------------------- | ||
| 9 | - | ||
| 10 | -"""Frontend runtime example for int32->half fixpipe dequant (DEQF16) on A5 CCE. | ||
| 11 | - | ||
| 12 | -This is the mainstream dequant scenario: int8 x int8 matmul accumulates to int32 in L0C | ||
| 13 | -(the quant-domain integer), then fixpipe multiplies by a scalar scale during the L0C->GM | ||
| 14 | -copy-out, producing half. Mirrors mainline test_operator_fixpipe.cpp 's322f16_scalar' | ||
| 15 | -(QuantMode_t::DEQF16); PyPTO supports it via copy_l0c_to_gm_impl.h supportedQuantMode | ||
| 16 | -(tileData int32 && globalData half). | ||
| 17 | - | ||
| 18 | -deqScalar encoding: reuse the float32 bit-pattern of the scale (scale=2.0f -> 0x40000000), | ||
| 19 | -same low-32-bit form that the validated FP32->int8 path uses, since both go through the | ||
| 20 | -same pto::TSTORE(dst, src, preQuantScalar). If int32->half (DEQF16) turns out to need a | ||
| 21 | -different scalar encoding, the on-device output will reveal it and we adjust here. | ||
| 22 | -""" | ||
| 23 | - | ||
| 24 | -import logging | ||
| 25 | -import os | ||
| 26 | -import struct | ||
| 27 | - | ||
| 28 | -import pypto_pro.language as pl | ||
| 29 | -import pytest | ||
| 30 | -import torch | ||
| 31 | - | ||
| 32 | -ST_DEVICE_ID = int(os.environ.get("TILE_FWK_DEVICE_ID", 0)) | ||
| 33 | -ST_DEVICE = f"npu:{ST_DEVICE_ID}" | ||
| 34 | - | ||
| 35 | - | ||
| 36 | -FP_SCALE_VALUE = 2.0 | ||
| 37 | -DEQ_SCALAR_BITS = struct.unpack("!I", struct.pack("!f", FP_SCALE_VALUE))[0] # 0x40000000 | ||
| 38 | - | ||
| 39 | - | ||
| 40 | -def _make_q(device: str) -> torch.Tensor: | ||
| 41 | - # int8 inputs incl. negatives; matmul with int8 identity keeps values, so int32 L0C == q. | ||
| 42 | - row = torch.tensor([-3, -2, -1, 0, 1, 2, 3, 4], device=device, dtype=torch.int8).repeat(8) | ||
| 43 | - return row.unsqueeze(0).repeat(64, 1) | ||
| 44 | - | ||
| 45 | - | ||
| 46 | -def _make_k(device: str) -> torch.Tensor: | ||
| 47 | - return torch.eye(64, device=device, dtype=torch.int8) | ||
| 48 | - | ||
| 49 | - | ||
| 50 | -@pl.jit() | ||
| 51 | -def deq_scalar_store_int32_to_half_kernel( | ||
| 52 | - q: pl.Tensor[[64, 64], pl.DT_INT8], | ||
| 53 | - k: pl.Tensor[[64, 64], pl.DT_INT8], | ||
| 54 | - deq_out: pl.Tensor[[64, 64], pl.DT_FP16], | ||
| 55 | -): | ||
| 56 | - with pl.section_cube(): | ||
| 57 | - mat_type = pl.TileType(shape=[64, 64], dtype=pl.DT_INT8, target_memory=pl.MemorySpace.Mat, layout=pl.NZ) | ||
| 58 | - q_mat = pl.make_tile(mat_type, addr=0x0000, size=4096) | ||
| 59 | - k_mat = pl.make_tile(mat_type, addr=0x2000, size=4096) | ||
| 60 | - | ||
| 61 | - left_type = pl.TileType(shape=[64, 64], dtype=pl.DT_INT8, target_memory=pl.MemorySpace.Left, layout=pl.NZ) | ||
| 62 | - q_left = pl.make_tile(left_type, addr=0x0000, size=4096) | ||
| 63 | - | ||
| 64 | - right_type = pl.TileType( | ||
| 65 | - shape=[64, 64], | ||
| 66 | - dtype=pl.DT_INT8, | ||
| 67 | - target_memory=pl.MemorySpace.Right, | ||
| 68 | - layout=pl.ZN, | ||
| 69 | - ) | ||
| 70 | - k_right = pl.make_tile(right_type, addr=0x0000, size=4096) | ||
| 71 | - | ||
| 72 | - acc_type = pl.TileType( | ||
| 73 | - shape=[64, 64], | ||
| 74 | - dtype=pl.DT_INT32, | ||
| 75 | - target_memory=pl.MemorySpace.Acc, | ||
| 76 | - layout=pl.NZ, | ||
| 77 | - fractal=1024, | ||
| 78 | - ) | ||
| 79 | - acc = pl.make_tile(acc_type, addr=0x0000, size=16384) | ||
| 80 | - | ||
| 81 | - pl.load(q_mat, q, [0, 0]) | ||
| 82 | - pl.load(k_mat, k, [0, 0]) | ||
| 83 | - | ||
| 84 | - pl.system.sync_src(set_pipe=pl.PipeType.MTE2, wait_pipe=pl.PipeType.MTE1, event_id=0) | ||
| 85 | - pl.system.sync_dst(set_pipe=pl.PipeType.MTE2, wait_pipe=pl.PipeType.MTE1, event_id=0) | ||
| 86 | - | ||
| 87 | - pl.move(q_left, q_mat) | ||
| 88 | - pl.move(k_right, k_mat) | ||
| 89 | - pl.system.sync_src(set_pipe=pl.PipeType.MTE1, wait_pipe=pl.PipeType.M, event_id=0) | ||
| 90 | - pl.system.sync_dst(set_pipe=pl.PipeType.MTE1, wait_pipe=pl.PipeType.M, event_id=0) | ||
| 91 | - | ||
| 92 | - pl.matmul(acc, q_left, k_right) | ||
| 93 | - | ||
| 94 | - pl.system.sync_src(set_pipe=pl.PipeType.M, wait_pipe=pl.PipeType.FIX, event_id=0) | ||
| 95 | - pl.system.sync_dst(set_pipe=pl.PipeType.M, wait_pipe=pl.PipeType.FIX, event_id=0) | ||
| 96 | - # int32 L0C -> half GM with scalar dequant (DEQF16). Caller passes low-32-bit scale. | ||
| 97 | - pl.store(deq_out, acc, [0, 0], pre_quant_scalar=DEQ_SCALAR_BITS) | ||
| 98 | - pl.system.bar_all() | ||
| 99 | - | ||
| 100 | - | ||
| 101 | - | ||
| 102 | -@pytest.mark.soc("950") | ||
| 103 | -def test_deq_scalar_store_int32_to_half(): | ||
| 104 | - device = ST_DEVICE | ||
| 105 | - torch.npu.set_device(device) | ||
| 106 | - | ||
| 107 | - device_name = torch.npu.get_device_name() | ||
| 108 | - if "Ascend950" not in device_name: | ||
| 109 | - logging.info("Current device is %s, skip.", device_name) | ||
| 110 | - return | ||
| 111 | - | ||
| 112 | - q = _make_q(device) | ||
| 113 | - k = _make_k(device) | ||
| 114 | - deq_out = torch.zeros((64, 64), device=device, dtype=torch.float16) | ||
| 115 | - | ||
| 116 | - deq_scalar_store_int32_to_half_kernel(q, k, deq_out) | ||
| 117 | - torch.npu.synchronize() | ||
| 118 | - | ||
| 119 | - # int32 matmul (quant-domain), then dequant by scale -> half. | ||
| 120 | - # NOTE: torch matmul on NPU rejects int32 (cube only supports float types), so compute the | ||
| 121 | - # golden on CPU. k is the identity matrix, so matmul(q, k) == q; we still do the explicit | ||
| 122 | - # matmul on CPU to keep the reference faithful rather than assuming the identity shortcut. | ||
| 123 | - raw_ref = torch.matmul(q.cpu().to(torch.int32), k.cpu().to(torch.int32)) | ||
| 124 | - expected_deq = (raw_ref.to(torch.float32) * FP_SCALE_VALUE).to(torch.float16).to(device) | ||
| 125 | - | ||
| 126 | - logging.info("***********cce q input int8 (top-left 8x8)***********") | ||
| 127 | - logging.info("%s", q[:8, :8]) | ||
| 128 | - logging.info("***********cce deq scalar bits (hex)***********") | ||
| 129 | - logging.info("0x%X (scale=%s)", DEQ_SCALAR_BITS, FP_SCALE_VALUE) | ||
| 130 | - logging.info("***********cce int32 matmul (quant-domain, top-left 8x8)***********") | ||
| 131 | - logging.info("%s", raw_ref[:8, :8]) | ||
| 132 | - logging.info("***********cce expected deq half output***********") | ||
| 133 | - logging.info("%s", expected_deq[:8, :8]) | ||
| 134 | - logging.info("***********cce deq half output (top-left 8x8)***********") | ||
| 135 | - logging.info("%s", deq_out[:8, :8]) | ||
| 136 | - | ||
| 137 | - torch.testing.assert_close(deq_out, expected_deq, rtol=1e-3, atol=1e-3) | ||
| 138 | - logging.info("cce int32->half deq_scalar output matches expectation.") | ||
| 139 | - | ||
| 140 | - | ||
| 141 | -if __name__ == "__main__": | ||
| 142 | - logging.basicConfig(level=logging.INFO, format="%(message)s") | ||
| 143 | - test_deq_scalar_store_int32_to_half() | ||
| 144 | - logging.info("\nAll tests passed!") | ||
| @@ -1,141 +0,0 @@ | |||
| 1 | -# Copyright (c) 2025-2026 Huawei Technologies Co., Ltd. | ||
| 2 | -# This program is free software, you can redistribute it and/or modify it under the terms and conditions of | ||
| 3 | -# CANN Open Software License Agreement Version 2.0 (the "License"). | ||
| 4 | -# Please refer to the License for details. You may not use this file except in compliance with the License. | ||
| 5 | -# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | ||
| 6 | -# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | ||
| 7 | -# See LICENSE in the root of the software repository for the full text of the License. | ||
| 8 | -# ----------------------------------------------------------------------------------------------------------- | ||
| 9 | - | ||
| 10 | -"""Frontend runtime example for int32->int8 fixpipe requant (REQ8) on A5 CCE. | ||
| 11 | - | ||
| 12 | -int8 x int8 matmul accumulates to int32 in L0C, then fixpipe applies a scalar scale during | ||
| 13 | -copy-out and writes signed int8 (requantization). Mirrors mainline test_operator_fixpipe.cpp | ||
| 14 | -'s322s8_scalar' (QuantMode_t::REQ8). Companion of test_deq_scalar_store_int32_to_half.py (DEQF16) — | ||
| 15 | -same int8-matmul→int32-L0C front, only the output dtype differs (int8 instead of half). | ||
| 16 | - | ||
| 17 | -Signed-int8 output: the CCE codegen re-derives bit46 (signed flag) from the INT8 output dtype, | ||
| 18 | -so negatives requantize with the sign preserved (-3*2=-6, not 0). Caller passes only the | ||
| 19 | -low-32-bit scale (float32 bit-pattern, scale=2.0f -> 0x40000000). | ||
| 20 | -""" | ||
| 21 | - | ||
| 22 | -import logging | ||
| 23 | -import os | ||
| 24 | -import struct | ||
| 25 | - | ||
| 26 | -import pypto_pro.language as pl | ||
| 27 | -import pytest | ||
| 28 | -import torch | ||
| 29 | - | ||
| 30 | -ST_DEVICE_ID = int(os.environ.get("TILE_FWK_DEVICE_ID", 0)) | ||
| 31 | -ST_DEVICE = f"npu:{ST_DEVICE_ID}" | ||
| 32 | - | ||
| 33 | - | ||
| 34 | -FP_SCALE_VALUE = 2.0 | ||
| 35 | -DEQ_SCALAR_BITS = struct.unpack("!I", struct.pack("!f", FP_SCALE_VALUE))[0] # 0x40000000 | ||
| 36 | - | ||
| 37 | - | ||
| 38 | -def _make_q(device: str) -> torch.Tensor: | ||
| 39 | - # int8 inputs incl. negatives; matmul with int8 identity keeps values, so int32 L0C == q. | ||
| 40 | - row = torch.tensor([-3, -2, -1, 0, 1, 2, 3, 4], device=device, dtype=torch.int8).repeat(8) | ||
| 41 | - return row.unsqueeze(0).repeat(64, 1) | ||
| 42 | - | ||
| 43 | - | ||
| 44 | -def _make_k(device: str) -> torch.Tensor: | ||
| 45 | - return torch.eye(64, device=device, dtype=torch.int8) | ||
| 46 | - | ||
| 47 | - | ||
| 48 | -@pl.jit() | ||
| 49 | -def deq_scalar_store_int32_to_int8_kernel( | ||
| 50 | - q: pl.Tensor[[64, 64], pl.DT_INT8], | ||
| 51 | - k: pl.Tensor[[64, 64], pl.DT_INT8], | ||
| 52 | - deq_out: pl.Tensor[[64, 64], pl.DT_INT8], | ||
| 53 | -): | ||
| 54 | - with pl.section_cube(): | ||
| 55 | - mat_type = pl.TileType(shape=[64, 64], dtype=pl.DT_INT8, target_memory=pl.MemorySpace.Mat, layout=pl.NZ) | ||
| 56 | - q_mat = pl.make_tile(mat_type, addr=0x0000, size=4096) | ||
| 57 | - k_mat = pl.make_tile(mat_type, addr=0x2000, size=4096) | ||
| 58 | - | ||
| 59 | - left_type = pl.TileType(shape=[64, 64], dtype=pl.DT_INT8, target_memory=pl.MemorySpace.Left, layout=pl.NZ) | ||
| 60 | - q_left = pl.make_tile(left_type, addr=0x0000, size=4096) | ||
| 61 | - | ||
| 62 | - right_type = pl.TileType( | ||
| 63 | - shape=[64, 64], | ||
| 64 | - dtype=pl.DT_INT8, | ||
| 65 | - target_memory=pl.MemorySpace.Right, | ||
| 66 | - layout=pl.ZN, | ||
| 67 | - ) | ||
| 68 | - k_right = pl.make_tile(right_type, addr=0x0000, size=4096) | ||
| 69 | - | ||
| 70 | - acc_type = pl.TileType( | ||
| 71 | - shape=[64, 64], | ||
| 72 | - dtype=pl.DT_INT32, | ||
| 73 | - target_memory=pl.MemorySpace.Acc, | ||
| 74 | - layout=pl.NZ, | ||
| 75 | - fractal=1024, | ||
| 76 | - ) | ||
| 77 | - acc = pl.make_tile(acc_type, addr=0x0000, size=16384) | ||
| 78 | - | ||
| 79 | - pl.load(q_mat, q, [0, 0]) | ||
| 80 | - pl.load(k_mat, k, [0, 0]) | ||
| 81 | - | ||
| 82 | - pl.system.sync_src(set_pipe=pl.PipeType.MTE2, wait_pipe=pl.PipeType.MTE1, event_id=0) | ||
| 83 | - pl.system.sync_dst(set_pipe=pl.PipeType.MTE2, wait_pipe=pl.PipeType.MTE1, event_id=0) | ||
| 84 | - | ||
| 85 | - pl.move(q_left, q_mat) | ||
| 86 | - pl.move(k_right, k_mat) | ||
| 87 | - pl.system.sync_src(set_pipe=pl.PipeType.MTE1, wait_pipe=pl.PipeType.M, event_id=0) | ||
| 88 | - pl.system.sync_dst(set_pipe=pl.PipeType.MTE1, wait_pipe=pl.PipeType.M, event_id=0) | ||
| 89 | - | ||
| 90 | - pl.matmul(acc, q_left, k_right) | ||
| 91 | - | ||
| 92 | - pl.system.sync_src(set_pipe=pl.PipeType.M, wait_pipe=pl.PipeType.FIX, event_id=0) | ||
| 93 | - pl.system.sync_dst(set_pipe=pl.PipeType.M, wait_pipe=pl.PipeType.FIX, event_id=0) | ||
| 94 | - # int32 L0C -> int8 GM with scalar requant (REQ8). Caller passes low-32-bit scale; | ||
| 95 | - # CCE codegen adds the signed-int8 flag (bit46) from the INT8 output dtype. | ||
| 96 | - pl.store(deq_out, acc, [0, 0], pre_quant_scalar=DEQ_SCALAR_BITS) | ||
| 97 | - pl.system.bar_all() | ||
| 98 | - | ||
| 99 | - | ||
| 100 | - | ||
| 101 | -@pytest.mark.soc("950") | ||
| 102 | -def test_deq_scalar_store_int32_to_int8(): | ||
| 103 | - device = ST_DEVICE | ||
| 104 | - torch.npu.set_device(device) | ||
| 105 | - | ||
| 106 | - device_name = torch.npu.get_device_name() | ||
| 107 | - if "Ascend950" not in device_name: | ||
| 108 | - logging.info("Current device is %s, skip.", device_name) | ||
| 109 | - return | ||
| 110 | - | ||
| 111 | - q = _make_q(device) | ||
| 112 | - k = _make_k(device) | ||
| 113 | - deq_out = torch.zeros((64, 64), device=device, dtype=torch.int8) | ||
| 114 | - | ||
| 115 | - deq_scalar_store_int32_to_int8_kernel(q, k, deq_out) | ||
| 116 | - torch.npu.synchronize() | ||
| 117 | - | ||
| 118 | - # int32 matmul (quant-domain) on CPU (NPU cube rejects int32), then requant by scale -> int8. | ||
| 119 | - raw_ref = torch.matmul(q.cpu().to(torch.int32), k.cpu().to(torch.int32)) | ||
| 120 | - expected_deq = torch.clamp(torch.round(raw_ref.to(torch.float32) * FP_SCALE_VALUE), -128, 127).to(torch.int8) | ||
| 121 | - expected_deq = expected_deq.to(device) | ||
| 122 | - | ||
| 123 | - logging.info("***********cce q input int8 (top-left 8x8)***********") | ||
| 124 | - logging.info("%s", q[:8, :8]) | ||
| 125 | - logging.info("***********cce deq scalar bits (hex)***********") | ||
| 126 | - logging.info("0x%X (scale=%s)", DEQ_SCALAR_BITS, FP_SCALE_VALUE) | ||
| 127 | - logging.info("***********cce int32 matmul (quant-domain, top-left 8x8)***********") | ||
| 128 | - logging.info("%s", raw_ref[:8, :8]) | ||
| 129 | - logging.info("***********cce expected requant int8 output***********") | ||
| 130 | - logging.info("%s", expected_deq[:8, :8]) | ||
| 131 | - logging.info("***********cce requant int8 output (top-left 8x8)***********") | ||
| 132 | - logging.info("%s", deq_out[:8, :8]) | ||
| 133 | - | ||
| 134 | - torch.testing.assert_close(deq_out.to(torch.int32), expected_deq.to(torch.int32), rtol=0, atol=0) | ||
| 135 | - logging.info("cce int32->int8 requant deq_scalar output matches expectation.") | ||
| 136 | - | ||
| 137 | - | ||
| 138 | -if __name__ == "__main__": | ||
| 139 | - logging.basicConfig(level=logging.INFO, format="%(message)s") | ||
| 140 | - test_deq_scalar_store_int32_to_int8() | ||
| 141 | - logging.info("\nAll tests passed!") | ||
| @@ -0,0 +1,131 @@ | |||
| 1 | +# Copyright (c) 2026 Huawei Technologies Co., Ltd. | ||
| 2 | +# This program is free software, you can redistribute it and/or modify it under the terms and conditions of | ||
| 3 | +# CANN Open Software License Agreement Version 2.0 (the "License"). | ||
| 4 | +# Please refer to the License for details. You may not use this file except in compliance with the License. | ||
| 5 | +# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | ||
| 6 | +# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | ||
| 7 | +# See LICENSE in the root of the software repository for the full text of the License. | ||
| 8 | +# ----------------------------------------------------------------------------------------------------------- | ||
| 9 | + | ||
| 10 | +"""P2 supplement: 编译期 float scale 路径的值域测试 | ||
| 11 | + | ||
| 12 | +设计文档的核心接口是 ``scale=2.0``(编译期 float,走 ``_encode_deq_scalar`` 位编码)。 | ||
| 13 | +原有 P2 值域测试全部走运行时 Expr 路径,本文件补充编译期 float scale 的 | ||
| 14 | +正 / 负 / 零 / 单位 / 分数 / 极小 / 极大值测试,直接验证 ``_encode_deq_scalar``。 | ||
| 15 | +""" | ||
| 16 | + | ||
| 17 | +import logging | ||
| 18 | +import os | ||
| 19 | + | ||
| 20 | +import pypto_pro.language as pl | ||
| 21 | +import pytest | ||
| 22 | +import torch | ||
| 23 | + | ||
| 24 | +ST_DEVICE_ID = int(os.environ.get("TILE_FWK_DEVICE_ID", 0)) | ||
| 25 | +ST_DEVICE = f"npu:{ST_DEVICE_ID}" | ||
| 26 | + | ||
| 27 | + | ||
| 28 | +def _make_q(device: str, pattern: str) -> torch.Tensor: | ||
| 29 | + if pattern == "all_positive": | ||
| 30 | + return torch.arange(1, 65, dtype=torch.float32, device=device).unsqueeze(0).repeat(64, 1) | ||
| 31 | + if pattern == "all_negative": | ||
| 32 | + return torch.arange(-64, 0, dtype=torch.float32, device=device).unsqueeze(0).repeat(64, 1) | ||
| 33 | + if pattern == "all_zeros": | ||
| 34 | + return torch.zeros((64, 64), dtype=torch.float32, device=device) | ||
| 35 | + if pattern == "large_magnitude": | ||
| 36 | + base = torch.tensor([1000.0, -1000.0, 5000.0, -5000.0], dtype=torch.float32, device=device) | ||
| 37 | + return base.unsqueeze(0).repeat(64, 16) | ||
| 38 | + row = torch.tensor([-3.0, -2.0, -1.0, 0.0, 1.0, 2.0, 3.0, 4.0], device=device, dtype=torch.float32).repeat(8) | ||
| 39 | + return row.unsqueeze(0).repeat(64, 1) | ||
| 40 | + | ||
| 41 | + | ||
| 42 | +def _make_k(device: str) -> torch.Tensor: | ||
| 43 | + return torch.eye(64, device=device, dtype=torch.float32) | ||
| 44 | + | ||
| 45 | + | ||
| 46 | +def _make_ct_kernel(scale_value: float): | ||
| 47 | + """Factory: FP32->INT8 store kernel with a compile-time float scale literal.""" | ||
| 48 | + | ||
| 49 | + @pl.jit(name=f"ct_float_scale_{scale_value}") | ||
| 50 | + def kernel( | ||
| 51 | + q: pl.Tensor[[64, 64], pl.DT_FP32], | ||
| 52 | + k: pl.Tensor[[64, 64], pl.DT_FP32], | ||
| 53 | + quant_out: pl.Tensor[[64, 64], pl.DT_INT8], | ||
| 54 | + ): | ||
| 55 | + with pl.section_cube(): | ||
| 56 | + mat_type = pl.TileType(shape=[64, 64], dtype=pl.DT_FP32, target_memory=pl.MemorySpace.Mat, layout=pl.NZ) | ||
| 57 | + q_mat = pl.make_tile(mat_type, addr=0x0000, size=16384) | ||
| 58 | + k_mat = pl.make_tile(mat_type, addr=0x4000, size=16384) | ||
| 59 | + | ||
| 60 | + left_type = pl.TileType(shape=[64, 64], dtype=pl.DT_FP32, target_memory=pl.MemorySpace.Left, layout=pl.NZ) | ||
| 61 | + q_left = pl.make_tile(left_type, addr=0x0000, size=16384) | ||
| 62 | + | ||
| 63 | + right_type = pl.TileType(shape=[64, 64], dtype=pl.DT_FP32, target_memory=pl.MemorySpace.Right, layout=pl.ZN) | ||
| 64 | + k_right = pl.make_tile(right_type, addr=0x0000, size=16384) | ||
| 65 | + | ||
| 66 | + acc_type = pl.TileType( | ||
| 67 | + shape=[64, 64], dtype=pl.DT_FP32, target_memory=pl.MemorySpace.Acc, layout=pl.NZ, fractal=1024 | ||
| 68 | + ) | ||
| 69 | + acc = pl.make_tile(acc_type, addr=0x0000, size=16384) | ||
| 70 | + | ||
| 71 | + pl.load(q_mat, q, [0, 0]) | ||
| 72 | + pl.load(k_mat, k, [0, 0]) | ||
| 73 | + pl.system.sync_src(set_pipe=pl.PipeType.MTE2, wait_pipe=pl.PipeType.MTE1, event_id=0) | ||
| 74 | + pl.system.sync_dst(set_pipe=pl.PipeType.MTE2, wait_pipe=pl.PipeType.MTE1, event_id=0) | ||
| 75 | + | ||
| 76 | + pl.move(q_left, q_mat) | ||
| 77 | + pl.move(k_right, k_mat) | ||
| 78 | + pl.system.sync_src(set_pipe=pl.PipeType.MTE1, wait_pipe=pl.PipeType.M, event_id=0) | ||
| 79 | + pl.system.sync_dst(set_pipe=pl.PipeType.MTE1, wait_pipe=pl.PipeType.M, event_id=0) | ||
| 80 | + | ||
| 81 | + pl.matmul(acc, q_left, k_right) | ||
| 82 | + pl.system.sync_src(set_pipe=pl.PipeType.M, wait_pipe=pl.PipeType.FIX, event_id=0) | ||
| 83 | + pl.system.sync_dst(set_pipe=pl.PipeType.M, wait_pipe=pl.PipeType.FIX, event_id=0) | ||
| 84 | + | ||
| 85 | + pl.store(quant_out, acc, [0, 0], scale=scale_value) | ||
| 86 | + pl.system.bar_all() | ||
| 87 | + | ||
| 88 | + return kernel | ||
| 89 | + | ||
| 90 | + | ||
| 91 | +# scale 值域:编译期 float | ||
| 92 | +# 输入通过 matmul(q, k)(k=eye),因此输出 == q,便于 golden 计算 | ||
| 93 | + | ||
| 94 | + | ||
| 95 | +@pytest.mark.soc("950") | ||
| 96 | +@pytest.mark.parametrize( | ||
| 97 | + "scale_value,pattern", | ||
| 98 | + [ | ||
| 99 | + (2.0, "mixed"), | ||
| 100 | + (-1.0, "mixed"), | ||
| 101 | + (0.0, "mixed"), | ||
| 102 | + (1.0, "mixed"), | ||
| 103 | + (0.5, "mixed"), | ||
| 104 | + (1e-6, "large_magnitude"), | ||
| 105 | + (1e6, "mixed"), | ||
| 106 | + ], | ||
| 107 | + ids=["positive", "negative", "zero", "unit", "fraction", "very_small", "very_large"], | ||
| 108 | +) | ||
| 109 | +def test_ct_float_scale_value_range(scale_value, pattern): | ||
| 110 | + """编译期 float scale 值域:与 clamp(round(x * scale)) golden 对比""" | ||
| 111 | + device = ST_DEVICE | ||
| 112 | + torch.npu.set_device(device) | ||
| 113 | + if "Ascend950" not in torch.npu.get_device_name(): | ||
| 114 | + pytest.skip(f"Current device is {torch.npu.get_device_name()}") | ||
| 115 | + | ||
| 116 | + kernel = _make_ct_kernel(scale_value) | ||
| 117 | + q = _make_q(device, pattern) | ||
| 118 | + k = _make_k(device) | ||
| 119 | + quant_out = torch.zeros((64, 64), device=device, dtype=torch.int8) | ||
| 120 | + | ||
| 121 | + kernel(q, k, quant_out) | ||
| 122 | + torch.npu.synchronize() | ||
| 123 | + | ||
| 124 | + raw_ref = torch.matmul(q, k) | ||
| 125 | + expected = torch.clamp(torch.round(raw_ref * scale_value), -128, 127).to(torch.int8) | ||
| 126 | + torch.testing.assert_close(quant_out.to(torch.int32), expected.to(torch.int32), rtol=0, atol=0) | ||
| 127 | + logging.info("test_ct_float_scale_value_range(scale=%s, pattern=%s) passed.", scale_value, pattern) | ||
| 128 | + | ||
| 129 | + | ||
| 130 | +if __name__ == "__main__": | ||
| 131 | + pytest.main([__file__, "-v"]) | ||
| @@ -0,0 +1,351 @@ | |||
| 1 | +# Copyright (c) 2025-2026 Huawei Technologies Co., Ltd. | ||
| 2 | +# This program is free software, you can redistribute it and/or modify it under the terms and conditions of | ||
| 3 | +# CANN Open Software License Agreement Version 2.0 (the "License"). | ||
| 4 | +# Please refer to the License for details. You may not use this file except in compliance with the License. | ||
| 5 | +# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | ||
| 6 | +# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | ||
| 7 | +# See LICENSE in the root of the software repository for the full text of the License. | ||
| 8 | +# ----------------------------------------------------------------------------------------------------------- | ||
| 9 | + | ||
| 10 | +"""Scale dtype validation tests for per-channel quantization (scale=Tile). | ||
| 11 | + | ||
| 12 | +Per-channel quantization requires a user-prepared Scaling Tile (INT64). Tests | ||
| 13 | +verify that: | ||
| 14 | +1. FP32 / FP16 / INT32 Scaling tiles raise clear errors with conversion guidance | ||
| 15 | +2. An INT64 Scaling tile works correctly (baseline) | ||
| 16 | + | ||
| 17 | +Note: the GM Tensor scale rejection is covered by | ||
| 18 | +test_scale_error_handling::test_err_scale_tensor_rejected. | ||
| 19 | +""" | ||
| 20 | + | ||
| 21 | +import logging | ||
| 22 | +import os | ||
| 23 | + | ||
| 24 | +import pypto_pro.language as pl | ||
| 25 | +from pypto_pro.language.parser.diagnostics._exceptions import ParserSyntaxError | ||
| 26 | +import pytest | ||
| 27 | +import torch | ||
| 28 | +import torch_npu | ||
| 29 | + | ||
| 30 | +ST_DEVICE_ID = int(os.environ.get("TILE_FWK_DEVICE_ID", 0)) | ||
| 31 | +ST_DEVICE = f"npu:{ST_DEVICE_ID}" | ||
| 32 | + | ||
| 33 | + | ||
| 34 | +FP_SCALE_VALUE = 2.0 | ||
| 35 | + | ||
| 36 | + | ||
| 37 | +def _make_q(device: str) -> torch.Tensor: | ||
| 38 | + row = torch.tensor([-3.0, -2.0, -1.0, 0.0, 1.0, 2.0, 3.0, 4.0], device=device, dtype=torch.float32).repeat(8) | ||
| 39 | + return row.unsqueeze(0).repeat(64, 1) | ||
| 40 | + | ||
| 41 | + | ||
| 42 | +def _make_k(device: str) -> torch.Tensor: | ||
| 43 | + return torch.eye(64, device=device, dtype=torch.float32) | ||
| 44 | + | ||
| 45 | + | ||
| 46 | +# ============================================================================ | ||
| 47 | +# Test 1: FP32 Scaling tile should raise clear error | ||
| 48 | +# ============================================================================ | ||
| 49 | + | ||
| 50 | + | ||
| 51 | +@pl.jit() | ||
| 52 | +def fp32_scale_kernel( | ||
| 53 | + q: pl.Tensor[[64, 64], pl.DT_FP32], | ||
| 54 | + k: pl.Tensor[[64, 64], pl.DT_FP32], | ||
| 55 | + out: pl.Tensor[[64, 64], pl.DT_INT8], | ||
| 56 | +): | ||
| 57 | + """Kernel with FP32 Scaling tile (should fail at parse time).""" | ||
| 58 | + with pl.section_cube(): | ||
| 59 | + mat_type = pl.TileType(shape=[64, 64], dtype=pl.DT_FP32, target_memory=pl.MemorySpace.Mat, layout=pl.NZ) | ||
| 60 | + q_mat = pl.make_tile(mat_type, addr=0x0000, size=16384) | ||
| 61 | + k_mat = pl.make_tile(mat_type, addr=0x4000, size=16384) | ||
| 62 | + | ||
| 63 | + left_type = pl.TileType(shape=[64, 64], dtype=pl.DT_FP32, target_memory=pl.MemorySpace.Left, layout=pl.NZ) | ||
| 64 | + q_left = pl.make_tile(left_type, addr=0x0000, size=16384) | ||
| 65 | + | ||
| 66 | + right_type = pl.TileType(shape=[64, 64], dtype=pl.DT_FP32, target_memory=pl.MemorySpace.Right, layout=pl.ZN) | ||
| 67 | + k_right = pl.make_tile(right_type, addr=0x0000, size=16384) | ||
| 68 | + | ||
| 69 | + acc_type = pl.TileType( | ||
| 70 | + shape=[64, 64], dtype=pl.DT_FP32, target_memory=pl.MemorySpace.Acc, layout=pl.NZ, fractal=1024 | ||
| 71 | + ) | ||
| 72 | + acc = pl.make_tile(acc_type, addr=0x0000, size=16384) | ||
| 73 | + | ||
| 74 | + fp_type = pl.TileType(shape=[1, 64], dtype=pl.DT_FP32, target_memory=pl.MemorySpace.Scaling) | ||
| 75 | + fp_tile = pl.make_tile(fp_type, addr=0x0000, size=256) | ||
| 76 | + | ||
| 77 | + pl.load(q_mat, q, [0, 0]) | ||
| 78 | + pl.load(k_mat, k, [0, 0]) | ||
| 79 | + pl.system.sync_src(set_pipe=pl.PipeType.MTE2, wait_pipe=pl.PipeType.MTE1, event_id=0) | ||
| 80 | + pl.system.sync_dst(set_pipe=pl.PipeType.MTE2, wait_pipe=pl.PipeType.MTE1, event_id=0) | ||
| 81 | + | ||
| 82 | + pl.move(q_left, q_mat) | ||
| 83 | + pl.move(k_right, k_mat) | ||
| 84 | + pl.system.sync_src(set_pipe=pl.PipeType.MTE1, wait_pipe=pl.PipeType.M, event_id=0) | ||
| 85 | + pl.system.sync_dst(set_pipe=pl.PipeType.MTE1, wait_pipe=pl.PipeType.M, event_id=0) | ||
| 86 | + | ||
| 87 | + pl.matmul(acc, q_left, k_right) | ||
| 88 | + pl.system.sync_src(set_pipe=pl.PipeType.M, wait_pipe=pl.PipeType.FIX, event_id=0) | ||
| 89 | + pl.system.sync_dst(set_pipe=pl.PipeType.M, wait_pipe=pl.PipeType.FIX, event_id=0) | ||
| 90 | + | ||
| 91 | + # This should raise ValueError at parse time | ||
| 92 | + pl.store(out, acc, [0, 0], scale=fp_tile) | ||
| 93 | + pl.system.bar_all() | ||
| 94 | + | ||
| 95 | + | ||
| 96 | +@pytest.mark.soc("950") | ||
| 97 | +def test_err_scale_tile_fp32(): | ||
| 98 | + """Validate that FP32 Scaling tile raises clear error with conversion guidance.""" | ||
| 99 | + device = ST_DEVICE | ||
| 100 | + torch.npu.set_device(device) | ||
| 101 | + | ||
| 102 | + device_name = torch.npu.get_device_name() | ||
| 103 | + if "Ascend950" not in device_name: | ||
| 104 | + logging.info("Current device is %s, skip.", device_name) | ||
| 105 | + return | ||
| 106 | + | ||
| 107 | + q = _make_q(device) | ||
| 108 | + k = _make_k(device) | ||
| 109 | + out = torch.zeros((64, 64), device=device, dtype=torch.int8) | ||
| 110 | + | ||
| 111 | + with pytest.raises(ParserSyntaxError, match=r"scale tile dtype FP32 is not supported.*npu_trans_quant_param"): | ||
| 112 | + fp32_scale_kernel(q, k, out) | ||
| 113 | + | ||
| 114 | + logging.info("test_err_scale_tile_fp32 passed: FP32 Scaling tile raises clear error.") | ||
| 115 | + | ||
| 116 | + | ||
| 117 | +# ============================================================================ | ||
| 118 | +# Test 3: FP16 Scaling tile should raise error | ||
| 119 | +# ============================================================================ | ||
| 120 | + | ||
| 121 | + | ||
| 122 | +@pl.jit() | ||
| 123 | +def fp16_scale_kernel( | ||
| 124 | + q: pl.Tensor[[64, 64], pl.DT_FP32], | ||
| 125 | + k: pl.Tensor[[64, 64], pl.DT_FP32], | ||
| 126 | + out: pl.Tensor[[64, 64], pl.DT_INT8], | ||
| 127 | +): | ||
| 128 | + """Kernel with FP16 Scaling tile (should fail at parse time).""" | ||
| 129 | + with pl.section_cube(): | ||
| 130 | + mat_type = pl.TileType(shape=[64, 64], dtype=pl.DT_FP32, target_memory=pl.MemorySpace.Mat, layout=pl.NZ) | ||
| 131 | + q_mat = pl.make_tile(mat_type, addr=0x0000, size=16384) | ||
| 132 | + k_mat = pl.make_tile(mat_type, addr=0x4000, size=16384) | ||
| 133 | + | ||
| 134 | + left_type = pl.TileType(shape=[64, 64], dtype=pl.DT_FP32, target_memory=pl.MemorySpace.Left, layout=pl.NZ) | ||
| 135 | + q_left = pl.make_tile(left_type, addr=0x0000, size=16384) | ||
| 136 | + | ||
| 137 | + right_type = pl.TileType(shape=[64, 64], dtype=pl.DT_FP32, target_memory=pl.MemorySpace.Right, layout=pl.ZN) | ||
| 138 | + k_right = pl.make_tile(right_type, addr=0x0000, size=16384) | ||
| 139 | + | ||
| 140 | + acc_type = pl.TileType( | ||
| 141 | + shape=[64, 64], dtype=pl.DT_FP32, target_memory=pl.MemorySpace.Acc, layout=pl.NZ, fractal=1024 | ||
| 142 | + ) | ||
| 143 | + acc = pl.make_tile(acc_type, addr=0x0000, size=16384) | ||
| 144 | + | ||
| 145 | + fp_type = pl.TileType(shape=[1, 64], dtype=pl.DT_FP16, target_memory=pl.MemorySpace.Scaling) | ||
| 146 | + fp_tile = pl.make_tile(fp_type, addr=0x0000, size=128) | ||
| 147 | + | ||
| 148 | + pl.load(q_mat, q, [0, 0]) | ||
| 149 | + pl.load(k_mat, k, [0, 0]) | ||
| 150 | + pl.system.sync_src(set_pipe=pl.PipeType.MTE2, wait_pipe=pl.PipeType.MTE1, event_id=0) | ||
| 151 | + pl.system.sync_dst(set_pipe=pl.PipeType.MTE2, wait_pipe=pl.PipeType.MTE1, event_id=0) | ||
| 152 | + | ||
| 153 | + pl.move(q_left, q_mat) | ||
| 154 | + pl.move(k_right, k_mat) | ||
| 155 | + pl.system.sync_src(set_pipe=pl.PipeType.MTE1, wait_pipe=pl.PipeType.M, event_id=0) | ||
| 156 | + pl.system.sync_dst(set_pipe=pl.PipeType.MTE1, wait_pipe=pl.PipeType.M, event_id=0) | ||
| 157 | + | ||
| 158 | + pl.matmul(acc, q_left, k_right) | ||
| 159 | + pl.system.sync_src(set_pipe=pl.PipeType.M, wait_pipe=pl.PipeType.FIX, event_id=0) | ||
| 160 | + pl.system.sync_dst(set_pipe=pl.PipeType.M, wait_pipe=pl.PipeType.FIX, event_id=0) | ||
| 161 | + | ||
| 162 | + pl.store(out, acc, [0, 0], scale=fp_tile) | ||
| 163 | + pl.system.bar_all() | ||
| 164 | + | ||
| 165 | + | ||
| 166 | +@pytest.mark.soc("950") | ||
| 167 | +def test_err_scale_tile_fp16(): | ||
| 168 | + """Validate that FP16 Scaling tile raises appropriate error.""" | ||
| 169 | + device = ST_DEVICE | ||
| 170 | + torch.npu.set_device(device) | ||
| 171 | + | ||
| 172 | + device_name = torch.npu.get_device_name() | ||
| 173 | + if "Ascend950" not in device_name: | ||
| 174 | + logging.info("Current device is %s, skip.", device_name) | ||
| 175 | + return | ||
| 176 | + | ||
| 177 | + q = _make_q(device) | ||
| 178 | + k = _make_k(device) | ||
| 179 | + out = torch.zeros((64, 64), device=device, dtype=torch.int8) | ||
| 180 | + | ||
| 181 | + with pytest.raises(ParserSyntaxError, match=r"scale tile dtype must be INT64"): | ||
| 182 | + fp16_scale_kernel(q, k, out) | ||
| 183 | + | ||
| 184 | + logging.info("test_err_scale_tile_fp16 passed: FP16 Scaling tile raises error.") | ||
| 185 | + | ||
| 186 | + | ||
| 187 | +# ============================================================================ | ||
| 188 | +# Test 4: INT32 Scaling tile should raise error | ||
| 189 | +# ============================================================================ | ||
| 190 | + | ||
| 191 | + | ||
| 192 | +@pl.jit() | ||
| 193 | +def int32_scale_kernel( | ||
| 194 | + q: pl.Tensor[[64, 64], pl.DT_FP32], | ||
| 195 | + k: pl.Tensor[[64, 64], pl.DT_FP32], | ||
| 196 | + out: pl.Tensor[[64, 64], pl.DT_INT8], | ||
| 197 | +): | ||
| 198 | + """Kernel with INT32 Scaling tile (should fail at parse time).""" | ||
| 199 | + with pl.section_cube(): | ||
| 200 | + mat_type = pl.TileType(shape=[64, 64], dtype=pl.DT_FP32, target_memory=pl.MemorySpace.Mat, layout=pl.NZ) | ||
| 201 | + q_mat = pl.make_tile(mat_type, addr=0x0000, size=16384) | ||
| 202 | + k_mat = pl.make_tile(mat_type, addr=0x4000, size=16384) | ||
| 203 | + | ||
| 204 | + left_type = pl.TileType(shape=[64, 64], dtype=pl.DT_FP32, target_memory=pl.MemorySpace.Left, layout=pl.NZ) | ||
| 205 | + q_left = pl.make_tile(left_type, addr=0x0000, size=16384) | ||
| 206 | + | ||
| 207 | + right_type = pl.TileType(shape=[64, 64], dtype=pl.DT_FP32, target_memory=pl.MemorySpace.Right, layout=pl.ZN) | ||
| 208 | + k_right = pl.make_tile(right_type, addr=0x0000, size=16384) | ||
| 209 | + | ||
| 210 | + acc_type = pl.TileType( | ||
| 211 | + shape=[64, 64], dtype=pl.DT_FP32, target_memory=pl.MemorySpace.Acc, layout=pl.NZ, fractal=1024 | ||
| 212 | + ) | ||
| 213 | + acc = pl.make_tile(acc_type, addr=0x0000, size=16384) | ||
| 214 | + | ||
| 215 | + fp_type = pl.TileType(shape=[1, 64], dtype=pl.DT_INT32, target_memory=pl.MemorySpace.Scaling) | ||
| 216 | + fp_tile = pl.make_tile(fp_type, addr=0x0000, size=256) | ||
| 217 | + | ||
| 218 | + pl.load(q_mat, q, [0, 0]) | ||
| 219 | + pl.load(k_mat, k, [0, 0]) | ||
| 220 | + pl.system.sync_src(set_pipe=pl.PipeType.MTE2, wait_pipe=pl.PipeType.MTE1, event_id=0) | ||
| 221 | + pl.system.sync_dst(set_pipe=pl.PipeType.MTE2, wait_pipe=pl.PipeType.MTE1, event_id=0) | ||
| 222 | + | ||
| 223 | + pl.move(q_left, q_mat) | ||
| 224 | + pl.move(k_right, k_mat) | ||
| 225 | + pl.system.sync_src(set_pipe=pl.PipeType.MTE1, wait_pipe=pl.PipeType.M, event_id=0) | ||
| 226 | + pl.system.sync_dst(set_pipe=pl.PipeType.MTE1, wait_pipe=pl.PipeType.M, event_id=0) | ||
| 227 | + | ||
| 228 | + pl.matmul(acc, q_left, k_right) | ||
| 229 | + pl.system.sync_src(set_pipe=pl.PipeType.M, wait_pipe=pl.PipeType.FIX, event_id=0) | ||
| 230 | + pl.system.sync_dst(set_pipe=pl.PipeType.M, wait_pipe=pl.PipeType.FIX, event_id=0) | ||
| 231 | + | ||
| 232 | + pl.store(out, acc, [0, 0], scale=fp_tile) | ||
| 233 | + pl.system.bar_all() | ||
| 234 | + | ||
| 235 | + | ||
| 236 | +@pytest.mark.soc("950") | ||
| 237 | +def test_err_scale_tile_int32(): | ||
| 238 | + """Validate that INT32 Scaling tile raises appropriate error.""" | ||
| 239 | + device = ST_DEVICE | ||
| 240 | + torch.npu.set_device(device) | ||
| 241 | + | ||
| 242 | + device_name = torch.npu.get_device_name() | ||
| 243 | + if "Ascend950" not in device_name: | ||
| 244 | + logging.info("Current device is %s, skip.", device_name) | ||
| 245 | + return | ||
| 246 | + | ||
| 247 | + q = _make_q(device) | ||
| 248 | + k = _make_k(device) | ||
| 249 | + out = torch.zeros((64, 64), device=device, dtype=torch.int8) | ||
| 250 | + | ||
| 251 | + with pytest.raises(ParserSyntaxError, match=r"scale tile dtype must be INT64"): | ||
| 252 | + int32_scale_kernel(q, k, out) | ||
| 253 | + | ||
| 254 | + logging.info("test_err_scale_tile_int32 passed: INT32 Scaling tile raises error.") | ||
| 255 | + | ||
| 256 | + | ||
| 257 | +# ============================================================================ | ||
| 258 | +# Test 5: FP32 scale manually converted to INT64 tile works correctly | ||
| 259 | +# ============================================================================ | ||
| 260 | + | ||
| 261 | + | ||
| 262 | +@pl.jit() | ||
| 263 | +def int64_scale_kernel( | ||
| 264 | + q: pl.Tensor[[64, 64], pl.DT_FP32], | ||
| 265 | + k: pl.Tensor[[64, 64], pl.DT_FP32], | ||
| 266 | + fp_params: pl.Tensor[[1, 64], pl.DT_INT64], | ||
| 267 | + out: pl.Tensor[[64, 64], pl.DT_INT8], | ||
| 268 | +): | ||
| 269 | + """Kernel with a user-prepared INT64 Scaling tile (correct usage).""" | ||
| 270 | + with pl.section_cube(): | ||
| 271 | + mat_type = pl.TileType(shape=[64, 64], dtype=pl.DT_FP32, target_memory=pl.MemorySpace.Mat, layout=pl.NZ) | ||
| 272 | + q_mat = pl.make_tile(mat_type, addr=0x0000, size=16384) | ||
| 273 | + k_mat = pl.make_tile(mat_type, addr=0x4000, size=16384) | ||
| 274 | + | ||
| 275 | + fp_mat_type = pl.TileType(shape=[1, 64], dtype=pl.DT_INT64, target_memory=pl.MemorySpace.Mat, layout=pl.ND) | ||
| 276 | + fp_mat = pl.make_tile(fp_mat_type, addr=0x8000, size=512) | ||
| 277 | + | ||
| 278 | + left_type = pl.TileType(shape=[64, 64], dtype=pl.DT_FP32, target_memory=pl.MemorySpace.Left, layout=pl.NZ) | ||
| 279 | + q_left = pl.make_tile(left_type, addr=0x0000, size=16384) | ||
| 280 | + | ||
| 281 | + right_type = pl.TileType(shape=[64, 64], dtype=pl.DT_FP32, target_memory=pl.MemorySpace.Right, layout=pl.ZN) | ||
| 282 | + k_right = pl.make_tile(right_type, addr=0x0000, size=16384) | ||
| 283 | + | ||
| 284 | + acc_type = pl.TileType( | ||
| 285 | + shape=[64, 64], dtype=pl.DT_FP32, target_memory=pl.MemorySpace.Acc, layout=pl.NZ, fractal=1024 | ||
| 286 | + ) | ||
| 287 | + acc = pl.make_tile(acc_type, addr=0x0000, size=16384) | ||
| 288 | + | ||
| 289 | + fp_type = pl.TileType(shape=[1, 64], dtype=pl.DT_INT64, target_memory=pl.MemorySpace.Scaling) | ||
| 290 | + fp_tile = pl.make_tile(fp_type, addr=0x0000, size=512) | ||
| 291 | + | ||
| 292 | + pl.load(q_mat, q, [0, 0]) | ||
| 293 | + pl.load(k_mat, k, [0, 0]) | ||
| 294 | + pl.load(fp_mat, fp_params, [0, 0]) | ||
| 295 | + pl.system.sync_src(set_pipe=pl.PipeType.MTE2, wait_pipe=pl.PipeType.MTE1, event_id=0) | ||
| 296 | + pl.system.sync_dst(set_pipe=pl.PipeType.MTE2, wait_pipe=pl.PipeType.MTE1, event_id=0) | ||
| 297 | + | ||
| 298 | + pl.move(q_left, q_mat) | ||
| 299 | + pl.move(k_right, k_mat) | ||
| 300 | + pl.system.sync_src(set_pipe=pl.PipeType.MTE1, wait_pipe=pl.PipeType.M, event_id=0) | ||
| 301 | + pl.system.sync_dst(set_pipe=pl.PipeType.MTE1, wait_pipe=pl.PipeType.M, event_id=0) | ||
| 302 | + | ||
| 303 | + pl.matmul(acc, q_left, k_right) | ||
| 304 | + pl.system.sync_src(set_pipe=pl.PipeType.M, wait_pipe=pl.PipeType.FIX, event_id=0) | ||
| 305 | + pl.system.sync_dst(set_pipe=pl.PipeType.M, wait_pipe=pl.PipeType.FIX, event_id=0) | ||
| 306 | + | ||
| 307 | + # user-owned data flow: move scale into Scaling tile, sync MTE1->FIX | ||
| 308 | + pl.move(fp_tile, fp_mat) | ||
| 309 | + pl.system.sync_src(set_pipe=pl.PipeType.MTE1, wait_pipe=pl.PipeType.FIX, event_id=1) | ||
| 310 | + pl.system.sync_dst(set_pipe=pl.PipeType.MTE1, wait_pipe=pl.PipeType.FIX, event_id=1) | ||
| 311 | + | ||
| 312 | + pl.store(out, acc, [0, 0], scale=fp_tile) | ||
| 313 | + pl.system.bar_all() | ||
| 314 | + | ||
| 315 | + | ||
| 316 | +@pytest.mark.soc("950") | ||
| 317 | +def test_per_channel_fp32_manual_conversion(): | ||
| 318 | + """Validate that a manually converted FP32→INT64 scale tile works correctly.""" | ||
| 319 | + device = ST_DEVICE | ||
| 320 | + torch.npu.set_device(device) | ||
| 321 | + | ||
| 322 | + device_name = torch.npu.get_device_name() | ||
| 323 | + if "Ascend950" not in device_name: | ||
| 324 | + logging.info("Current device is %s, skip.", device_name) | ||
| 325 | + return | ||
| 326 | + | ||
| 327 | + q = _make_q(device) | ||
| 328 | + k = _make_k(device) | ||
| 329 | + | ||
| 330 | + # Manual conversion: FP32 → INT64 using npu_trans_quant_param | ||
| 331 | + scale_fp32 = torch.full((1, 64), FP_SCALE_VALUE, device=device, dtype=torch.float32) | ||
| 332 | + scale_int64 = torch_npu.npu_trans_quant_param(scale_fp32) | ||
| 333 | + | ||
| 334 | + out = torch.zeros((64, 64), device=device, dtype=torch.int8) | ||
| 335 | + | ||
| 336 | + int64_scale_kernel(q, k, scale_int64, out) | ||
| 337 | + torch.npu.synchronize() | ||
| 338 | + | ||
| 339 | + raw_ref = torch.matmul(q, k) | ||
| 340 | + expected = torch.clamp(torch.round(raw_ref * FP_SCALE_VALUE), -128, 127).to(torch.int8) | ||
| 341 | + | ||
| 342 | + torch.testing.assert_close(out.to(torch.int32), expected.to(torch.int32), rtol=0, atol=0) | ||
| 343 | + logging.info("test_per_channel_fp32_manual_conversion passed: FP32→INT64 manual conversion works.") | ||
| 344 | + | ||
| 345 | + | ||
| 346 | +if __name__ == "__main__": | ||
| 347 | + test_err_scale_tile_fp32() | ||
| 348 | + test_err_scale_tile_fp16() | ||
| 349 | + test_err_scale_tile_int32() | ||
| 350 | + test_per_channel_fp32_manual_conversion() | ||
| 351 | + logging.info("\nAll tests passed!") | ||
| @@ -0,0 +1,488 @@ | |||
| 1 | +# Copyright (c) 2026 Huawei Technologies Co., Ltd. | ||
| 2 | +# This program is free software, you can redistribute it and/or modify it under the terms and conditions of | ||
| 3 | +# CANN Open Software License Agreement Version 2.0 (the "License"). | ||
| 4 | +# Please refer to the License for details. You may not use this file except in compliance with the License. | ||
| 5 | +# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | ||
| 6 | +# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | ||
| 7 | +# See LICENSE in the root of the software repository for the full text of the License. | ||
| 8 | +# ----------------------------------------------------------------------------------------------------------- | ||
| 9 | + | ||
| 10 | +"""P5: 参数互斥与错误处理测试 | ||
| 11 | + | ||
| 12 | +验证 scale 参数的错误处理和互斥校验: | ||
| 13 | +1. per-channel 互斥校验(与 relu/phase/dual-mode 的互斥,scale=Tile) | ||
| 14 | +2. scale 类型错误(非法类型) | ||
| 15 | +3. scale=Tensor 拒绝(Tensor 自动路径已移除) | ||
| 16 | +4. per-channel 维度错误(1D/3D/0D tile、[N,1]、col 未对齐) | ||
| 17 | +5. 旧参数废弃验证(pre_quant_scalar/fp_tile) | ||
| 18 | + | ||
| 19 | +错误在 kernel 首次调用(lazy 编译、AST 解析)时触发。hook/builder 抛出的 | ||
| 20 | +ValueError/TypeError 会被 parse_target_program 包装为 ParserSyntaxError, | ||
| 21 | +因此这里统一断言 ParserSyntaxError 并匹配其 message 原文。 | ||
| 22 | +""" | ||
| 23 | + | ||
| 24 | +import pypto_pro.language as pl | ||
| 25 | +from pypto_pro.language.parser.diagnostics._exceptions import ParserSyntaxError, UnsupportedFeatureError | ||
| 26 | +import pytest | ||
| 27 | +import torch | ||
| 28 | + | ||
| 29 | + | ||
| 30 | +def _mkl() -> "pl.TileType": | ||
| 31 | + return pl.TileType(shape=[64, 64], dtype=pl.DT_FP32, target_memory=pl.MemorySpace.Acc, layout=pl.NZ, fractal=1024) | ||
| 32 | + | ||
| 33 | + | ||
| 34 | +def _make_acc(): | ||
| 35 | + return pl.make_tile(_mkl(), addr=0x0000, size=16384) | ||
| 36 | + | ||
| 37 | + | ||
| 38 | + | ||
| 39 | +def _make_qk() -> tuple[torch.Tensor, torch.Tensor]: | ||
| 40 | + device = "cpu" | ||
| 41 | + q = torch.randn(64, 64, dtype=torch.float32, device=device) | ||
| 42 | + k = torch.eye(64, dtype=torch.float32, device=device) | ||
| 43 | + return q, k | ||
| 44 | + | ||
| 45 | + | ||
| 46 | +# ============================================================================ | ||
| 47 | +# 1. per-channel 互斥校验(scale=Tile) | ||
| 48 | +# ============================================================================ | ||
| 49 | + | ||
| 50 | + | ||
| 51 | +@pytest.mark.soc("950") | ||
| 52 | +def test_err_per_channel_with_relu(): | ||
| 53 | + """per-channel scale 不能与 relu_pre_mode 同时使用""" | ||
| 54 | + | ||
| 55 | + @pl.jit() | ||
| 56 | + def kernel( | ||
| 57 | + q: pl.Tensor[[64, 64], pl.DT_FP32], | ||
| 58 | + k: pl.Tensor[[64, 64], pl.DT_FP32], | ||
| 59 | + out: pl.Tensor[[64, 64], pl.DT_INT8], | ||
| 60 | + ): | ||
| 61 | + with pl.section_cube(): | ||
| 62 | + acc = _make_acc() | ||
| 63 | + fp_type = pl.TileType(shape=[1, 64], dtype=pl.DT_INT64, target_memory=pl.MemorySpace.Scaling) | ||
| 64 | + fp_tile = pl.make_tile(fp_type, addr=0x0000, size=512) | ||
| 65 | + pl.store(out, acc, [0, 0], scale=fp_tile, relu_pre_mode=pl.ReluPreMode.NormalRelu) | ||
| 66 | + | ||
| 67 | + q, k = _make_qk() | ||
| 68 | + out = torch.zeros(64, 64, dtype=torch.int8) | ||
| 69 | + with pytest.raises(ParserSyntaxError, match="cannot be used together with relu_pre_mode"): | ||
| 70 | + kernel(q, k, out) | ||
| 71 | + | ||
| 72 | + | ||
| 73 | +@pytest.mark.soc("950") | ||
| 74 | +def test_err_per_channel_with_phase(): | ||
| 75 | + """per-channel scale 不能与 phase 同时使用""" | ||
| 76 | + | ||
| 77 | + @pl.jit() | ||
| 78 | + def kernel( | ||
| 79 | + q: pl.Tensor[[64, 64], pl.DT_FP32], | ||
| 80 | + k: pl.Tensor[[64, 64], pl.DT_FP32], | ||
| 81 | + out: pl.Tensor[[64, 64], pl.DT_INT8], | ||
| 82 | + ): | ||
| 83 | + with pl.section_cube(): | ||
| 84 | + acc = _make_acc() | ||
| 85 | + fp_type = pl.TileType(shape=[1, 64], dtype=pl.DT_INT64, target_memory=pl.MemorySpace.Scaling) | ||
| 86 | + fp_tile = pl.make_tile(fp_type, addr=0x0000, size=512) | ||
| 87 | + pl.store(out, acc, [0, 0], scale=fp_tile, phase=pl.STPhase.Partial) | ||
| 88 | + | ||
| 89 | + q, k = _make_qk() | ||
| 90 | + out = torch.zeros(64, 64, dtype=torch.int8) | ||
| 91 | + with pytest.raises(ParserSyntaxError, match="cannot be combined with phase"): | ||
| 92 | + kernel(q, k, out) | ||
| 93 | + | ||
| 94 | + | ||
| 95 | +@pytest.mark.soc("950") | ||
| 96 | +def test_err_scale_tensor_rejected(): | ||
| 97 | + """scale 传 GM Tensor 应在解析期被拒绝(Tensor 自动路径已移除)""" | ||
| 98 | + | ||
| 99 | + @pl.jit() | ||
| 100 | + def kernel( | ||
| 101 | + q: pl.Tensor[[64, 64], pl.DT_FP32], | ||
| 102 | + k: pl.Tensor[[64, 64], pl.DT_FP32], | ||
| 103 | + scale_tensor: pl.Tensor[[1, 64], pl.DT_INT64], | ||
| 104 | + out: pl.Tensor[[64, 64], pl.DT_INT8], | ||
| 105 | + ): | ||
| 106 | + with pl.section_cube(): | ||
| 107 | + acc = _make_acc() | ||
| 108 | + pl.store(out, acc, [0, 0], scale=scale_tensor) | ||
| 109 | + | ||
| 110 | + q, k = _make_qk() | ||
| 111 | + scale_tensor = torch.zeros(1, 64, dtype=torch.int64) | ||
| 112 | + out = torch.zeros(64, 64, dtype=torch.int8) | ||
| 113 | + with pytest.raises(ParserSyntaxError, match="scale Tensor is not supported for per-channel quantization"): | ||
| 114 | + kernel(q, k, scale_tensor, out) | ||
| 115 | + | ||
| 116 | + | ||
| 117 | +@pytest.mark.soc("950") | ||
| 118 | +def test_err_scale_uint8_output(): | ||
| 119 | + """scale 量化到 UINT8 输出不被硬件支持,应在解析期被拒绝(而非设备 507015)""" | ||
| 120 | + | ||
| 121 | + @pl.jit() | ||
| 122 | + def kernel( | ||
| 123 | + q: pl.Tensor[[64, 64], pl.DT_FP32], | ||
| 124 | + k: pl.Tensor[[64, 64], pl.DT_FP32], | ||
| 125 | + out: pl.Tensor[[64, 64], pl.DT_UINT8], | ||
| 126 | + ): | ||
| 127 | + with pl.section_cube(): | ||
| 128 | + acc = _make_acc() | ||
| 129 | + pl.store(out, acc, [0, 0], scale=2.0) | ||
| 130 | + | ||
| 131 | + q, k = _make_qk() | ||
| 132 | + out = torch.zeros(64, 64, dtype=torch.uint8) | ||
| 133 | + with pytest.raises(ParserSyntaxError, match="UINT8"): | ||
| 134 | + kernel(q, k, out) | ||
| 135 | + | ||
| 136 | + | ||
| 137 | +@pytest.mark.soc("950") | ||
| 138 | +def test_err_scale_fp32_to_bf16(): | ||
| 139 | + """FP32→BF16 带 scale 不被硬件支持(仅支持无 scale 截断),应在解析期拒绝""" | ||
| 140 | + | ||
| 141 | + @pl.jit() | ||
| 142 | + def kernel( | ||
| 143 | + q: pl.Tensor[[64, 64], pl.DT_FP32], | ||
| 144 | + k: pl.Tensor[[64, 64], pl.DT_FP32], | ||
| 145 | + out: pl.Tensor[[64, 64], pl.DT_BF16], | ||
| 146 | + ): | ||
| 147 | + with pl.section_cube(): | ||
| 148 | + acc = _make_acc() | ||
| 149 | + pl.store(out, acc, [0, 0], scale=2.0) | ||
| 150 | + | ||
| 151 | + q, k = _make_qk() | ||
| 152 | + out = torch.zeros(64, 64, dtype=torch.bfloat16) | ||
| 153 | + with pytest.raises(ParserSyntaxError, match="BF16"): | ||
| 154 | + kernel(q, k, out) | ||
| 155 | + | ||
| 156 | + | ||
| 157 | +@pytest.mark.soc("950") | ||
| 158 | +def test_err_scale_int32_to_bf16(): | ||
| 159 | + """INT32→BF16 带 scale 不被硬件支持(硬件只支持 INT32→FP16 反量化),应在解析期拒绝""" | ||
| 160 | + | ||
| 161 | + @pl.jit() | ||
| 162 | + def kernel( | ||
| 163 | + q: pl.Tensor[[64, 64], pl.DT_INT8], | ||
| 164 | + k: pl.Tensor[[64, 64], pl.DT_INT8], | ||
| 165 | + out: pl.Tensor[[64, 64], pl.DT_BF16], | ||
| 166 | + ): | ||
| 167 | + with pl.section_cube(): | ||
| 168 | + acc_type = pl.TileType( | ||
| 169 | + shape=[64, 64], dtype=pl.DT_INT32, target_memory=pl.MemorySpace.Acc, layout=pl.NZ, fractal=1024 | ||
| 170 | + ) | ||
| 171 | + acc = pl.make_tile(acc_type, addr=0x0000, size=16384) | ||
| 172 | + pl.store(out, acc, [0, 0], scale=0.01) | ||
| 173 | + | ||
| 174 | + q = torch.randint(-8, 8, (64, 64), dtype=torch.int8) | ||
| 175 | + k = torch.eye(64, dtype=torch.int8) | ||
| 176 | + out = torch.zeros(64, 64, dtype=torch.bfloat16) | ||
| 177 | + with pytest.raises(ParserSyntaxError, match="BF16"): | ||
| 178 | + kernel(q, k, out) | ||
| 179 | + | ||
| 180 | + | ||
| 181 | +@pytest.mark.soc("950") | ||
| 182 | +def test_err_scale_tile_not_scaling(): | ||
| 183 | + """scale 传非 Scaling 空间的 Tile 应在解析期被拒绝""" | ||
| 184 | + | ||
| 185 | + @pl.jit() | ||
| 186 | + def kernel( | ||
| 187 | + q: pl.Tensor[[64, 64], pl.DT_FP32], | ||
| 188 | + k: pl.Tensor[[64, 64], pl.DT_FP32], | ||
| 189 | + out: pl.Tensor[[64, 64], pl.DT_INT8], | ||
| 190 | + ): | ||
| 191 | + with pl.section_cube(): | ||
| 192 | + acc = _make_acc() | ||
| 193 | + mat_type = pl.TileType(shape=[1, 64], dtype=pl.DT_INT64, target_memory=pl.MemorySpace.Mat, layout=pl.ND) | ||
| 194 | + mat_tile = pl.make_tile(mat_type, addr=0x8000, size=512) | ||
| 195 | + pl.store(out, acc, [0, 0], scale=mat_tile) | ||
| 196 | + | ||
| 197 | + q, k = _make_qk() | ||
| 198 | + out = torch.zeros(64, 64, dtype=torch.int8) | ||
| 199 | + with pytest.raises(ParserSyntaxError, match="MemorySpace.Scaling"): | ||
| 200 | + kernel(q, k, out) | ||
| 201 | + | ||
| 202 | + | ||
| 203 | +@pytest.mark.soc("950") | ||
| 204 | +def test_err_per_channel_move_dual_mode(): | ||
| 205 | + """per-channel scale 在 move 时只支持 single-mode""" | ||
| 206 | + | ||
| 207 | + @pl.jit() | ||
| 208 | + def kernel( | ||
| 209 | + q: pl.Tensor[[64, 64], pl.DT_FP32], | ||
| 210 | + k: pl.Tensor[[64, 64], pl.DT_FP32], | ||
| 211 | + out: pl.Tensor[[64, 64], pl.DT_INT8], | ||
| 212 | + ): | ||
| 213 | + vec_type = pl.TileType(shape=[64, 64], dtype=pl.DT_INT8, target_memory=pl.MemorySpace.Vec) | ||
| 214 | + vec_tile = pl.make_tile(vec_type, addr=0x0000, size=4096) | ||
| 215 | + with pl.section_cube(): | ||
| 216 | + acc = _make_acc() | ||
| 217 | + fp_type = pl.TileType(shape=[1, 64], dtype=pl.DT_INT64, target_memory=pl.MemorySpace.Scaling) | ||
| 218 | + fp_tile = pl.make_tile(fp_type, addr=0x0000, size=512) | ||
| 219 | + pl.move(vec_tile, acc, scale=fp_tile, acc_to_vec_mode=pl.AccToVecMode.DualModeSplitM) | ||
| 220 | + | ||
| 221 | + q, k = _make_qk() | ||
| 222 | + out = torch.zeros(64, 64, dtype=torch.int8) | ||
| 223 | + with pytest.raises(ParserSyntaxError, match="only supports single-mode"): | ||
| 224 | + kernel(q, k, out) | ||
| 225 | + | ||
| 226 | + | ||
| 227 | +# ============================================================================ | ||
| 228 | +# 2. scale 类型错误 | ||
| 229 | +# ============================================================================ | ||
| 230 | + | ||
| 231 | + | ||
| 232 | +@pytest.mark.soc("950") | ||
| 233 | +def test_err_scale_string(): | ||
| 234 | + """scale 不能是字符串""" | ||
| 235 | + | ||
| 236 | + @pl.jit() | ||
| 237 | + def kernel( | ||
| 238 | + q: pl.Tensor[[64, 64], pl.DT_FP32], | ||
| 239 | + k: pl.Tensor[[64, 64], pl.DT_FP32], | ||
| 240 | + out: pl.Tensor[[64, 64], pl.DT_INT8], | ||
| 241 | + ): | ||
| 242 | + with pl.section_cube(): | ||
| 243 | + acc = _make_acc() | ||
| 244 | + pl.store(out, acc, [0, 0], scale="invalid") | ||
| 245 | + | ||
| 246 | + q, k = _make_qk() | ||
| 247 | + out = torch.zeros(64, 64, dtype=torch.int8) | ||
| 248 | + with pytest.raises(ParserSyntaxError, match="scale must be"): | ||
| 249 | + kernel(q, k, out) | ||
| 250 | + | ||
| 251 | + | ||
| 252 | +@pytest.mark.soc("950") | ||
| 253 | +def test_err_scale_list(): | ||
| 254 | + """scale 不能是列表""" | ||
| 255 | + | ||
| 256 | + @pl.jit() | ||
| 257 | + def kernel( | ||
| 258 | + q: pl.Tensor[[64, 64], pl.DT_FP32], | ||
| 259 | + k: pl.Tensor[[64, 64], pl.DT_FP32], | ||
| 260 | + out: pl.Tensor[[64, 64], pl.DT_INT8], | ||
| 261 | + ): | ||
| 262 | + with pl.section_cube(): | ||
| 263 | + acc = _make_acc() | ||
| 264 | + pl.store(out, acc, [0, 0], scale=[1.0, 2.0]) | ||
| 265 | + | ||
| 266 | + q, k = _make_qk() | ||
| 267 | + out = torch.zeros(64, 64, dtype=torch.int8) | ||
| 268 | + with pytest.raises(ParserSyntaxError, match="scale must be"): | ||
| 269 | + kernel(q, k, out) | ||
| 270 | + | ||
| 271 | + | ||
| 272 | +@pytest.mark.soc("950") | ||
| 273 | +def test_err_scale_dict(): | ||
| 274 | + """scale 不能是字典""" | ||
| 275 | + # 注意:dict 字面量在 AST 解析阶段就抛 UnsupportedFeatureError(早于 | ||
| 276 | + # _resolve_scale_param 的类型检查),故此处断言 UnsupportedFeatureError。 | ||
| 277 | + | ||
| 278 | + @pl.jit() | ||
| 279 | + def kernel( | ||
| 280 | + q: pl.Tensor[[64, 64], pl.DT_FP32], | ||
| 281 | + k: pl.Tensor[[64, 64], pl.DT_FP32], | ||
| 282 | + out: pl.Tensor[[64, 64], pl.DT_INT8], | ||
| 283 | + ): | ||
| 284 | + with pl.section_cube(): | ||
| 285 | + acc = _make_acc() | ||
| 286 | + pl.store(out, acc, [0, 0], scale={"value": 2.0}) | ||
| 287 | + | ||
| 288 | + q, k = _make_qk() | ||
| 289 | + out = torch.zeros(64, 64, dtype=torch.int8) | ||
| 290 | + with pytest.raises(UnsupportedFeatureError, match="Unsupported expression type"): | ||
| 291 | + kernel(q, k, out) | ||
| 292 | + | ||
| 293 | + | ||
| 294 | +@pytest.mark.soc("950") | ||
| 295 | +def test_err_scale_none_type(): | ||
| 296 | + """scale 不能是自定义对象""" | ||
| 297 | + | ||
| 298 | + @pl.jit() | ||
| 299 | + def kernel( | ||
| 300 | + q: pl.Tensor[[64, 64], pl.DT_FP32], | ||
| 301 | + k: pl.Tensor[[64, 64], pl.DT_FP32], | ||
| 302 | + out: pl.Tensor[[64, 64], pl.DT_INT8], | ||
| 303 | + ): | ||
| 304 | + with pl.section_cube(): | ||
| 305 | + acc = _make_acc() | ||
| 306 | + pl.store(out, acc, [0, 0], scale=object()) | ||
| 307 | + | ||
| 308 | + | ||
| 309 | +@pytest.mark.soc("950") | ||
| 310 | +def test_err_scale_unsupported_scalar_dtype(): | ||
| 311 | + """运行时标量只支持 FP32 / INT32 / INT64,FP16/BF16 等其余 dtype 应在解析期拒绝""" | ||
| 312 | + | ||
| 313 | + @pl.jit() | ||
| 314 | + def kernel( | ||
| 315 | + q: pl.Tensor[[64, 64], pl.DT_FP32], | ||
| 316 | + k: pl.Tensor[[64, 64], pl.DT_FP32], | ||
| 317 | + scale_val: pl.DT_FP16, | ||
| 318 | + out: pl.Tensor[[64, 64], pl.DT_INT8], | ||
| 319 | + ): | ||
| 320 | + with pl.section_cube(): | ||
| 321 | + acc = _make_acc() | ||
| 322 | + pl.store(out, acc, [0, 0], scale=scale_val) | ||
| 323 | + | ||
| 324 | + q, k = _make_qk() | ||
| 325 | + scale_val = torch.tensor(2.0, dtype=torch.float16) | ||
| 326 | + out = torch.zeros(64, 64, dtype=torch.int8) | ||
| 327 | + with pytest.raises(ParserSyntaxError, match="scale runtime scalar dtype fp16 is not supported"): | ||
| 328 | + kernel(q, k, scale_val, out) | ||
| 329 | + | ||
| 330 | + | ||
| 331 | +# ============================================================================ | ||
| 332 | +# 3. per-channel 维度错误(scale=Tile) | ||
| 333 | +# ============================================================================ | ||
| 334 | + | ||
| 335 | + | ||
| 336 | +@pytest.mark.soc("950") | ||
| 337 | +def test_err_per_channel_1d_tile(): | ||
| 338 | + """per-channel scale tile 必须是 2D,不能是 1D""" | ||
| 339 | + | ||
| 340 | + @pl.jit() | ||
| 341 | + def kernel( | ||
| 342 | + q: pl.Tensor[[64, 64], pl.DT_FP32], | ||
| 343 | + k: pl.Tensor[[64, 64], pl.DT_FP32], | ||
| 344 | + out: pl.Tensor[[64, 64], pl.DT_INT8], | ||
| 345 | + ): | ||
| 346 | + with pl.section_cube(): | ||
| 347 | + acc = _make_acc() | ||
| 348 | + fp_type = pl.TileType(shape=[64], dtype=pl.DT_INT64, target_memory=pl.MemorySpace.Scaling) | ||
| 349 | + fp_tile = pl.make_tile(fp_type, addr=0x0000, size=512) | ||
| 350 | + pl.store(out, acc, [0, 0], scale=fp_tile) | ||
| 351 | + | ||
| 352 | + q, k = _make_qk() | ||
| 353 | + out = torch.zeros(64, 64, dtype=torch.int8) | ||
| 354 | + with pytest.raises(ParserSyntaxError, match="scale tile must be 2D"): | ||
| 355 | + kernel(q, k, out) | ||
| 356 | + | ||
| 357 | + | ||
| 358 | +@pytest.mark.soc("950") | ||
| 359 | +def test_err_per_channel_3d_tile(): | ||
| 360 | + """per-channel scale tile 必须是 2D,不能是 3D""" | ||
| 361 | + | ||
| 362 | + @pl.jit() | ||
| 363 | + def kernel( | ||
| 364 | + q: pl.Tensor[[64, 64], pl.DT_FP32], | ||
| 365 | + k: pl.Tensor[[64, 64], pl.DT_FP32], | ||
| 366 | + out: pl.Tensor[[64, 64], pl.DT_INT8], | ||
| 367 | + ): | ||
| 368 | + with pl.section_cube(): | ||
| 369 | + acc = _make_acc() | ||
| 370 | + fp_type = pl.TileType(shape=[1, 64, 1], dtype=pl.DT_INT64, target_memory=pl.MemorySpace.Scaling) | ||
| 371 | + fp_tile = pl.make_tile(fp_type, addr=0x0000, size=512) | ||
| 372 | + pl.store(out, acc, [0, 0], scale=fp_tile) | ||
| 373 | + | ||
| 374 | + q, k = _make_qk() | ||
| 375 | + out = torch.zeros(64, 64, dtype=torch.int8) | ||
| 376 | + with pytest.raises(ParserSyntaxError, match="scale tile must be 2D"): | ||
| 377 | + kernel(q, k, out) | ||
| 378 | + | ||
| 379 | + | ||
| 380 | +@pytest.mark.soc("950") | ||
| 381 | +def test_err_per_channel_0d_tile(): | ||
| 382 | + """per-channel scale tile 必须是 2D,不能是 0D scalar""" | ||
| 383 | + | ||
| 384 | + @pl.jit() | ||
| 385 | + def kernel( | ||
| 386 | + q: pl.Tensor[[64, 64], pl.DT_FP32], | ||
| 387 | + k: pl.Tensor[[64, 64], pl.DT_FP32], | ||
| 388 | + out: pl.Tensor[[64, 64], pl.DT_INT8], | ||
| 389 | + ): | ||
| 390 | + with pl.section_cube(): | ||
| 391 | + acc = _make_acc() | ||
| 392 | + fp_type = pl.TileType(shape=[], dtype=pl.DT_INT64, target_memory=pl.MemorySpace.Scaling) | ||
| 393 | + fp_tile = pl.make_tile(fp_type, addr=0x0000, size=512) | ||
| 394 | + pl.store(out, acc, [0, 0], scale=fp_tile) | ||
| 395 | + | ||
| 396 | + q, k = _make_qk() | ||
| 397 | + out = torch.zeros(64, 64, dtype=torch.int8) | ||
| 398 | + with pytest.raises(ParserSyntaxError, match="requires non-empty shape|must be 2D"): | ||
| 399 | + kernel(q, k, out) | ||
| 400 | + | ||
| 401 | + | ||
| 402 | +@pytest.mark.soc("950") | ||
| 403 | +def test_err_per_channel_n1_tile(): | ||
| 404 | + """[N, 1] 逐行 scale 不被硬件 FixPipe 支持,应在解析期被拒绝""" | ||
| 405 | + | ||
| 406 | + @pl.jit() | ||
| 407 | + def kernel( | ||
| 408 | + q: pl.Tensor[[64, 64], pl.DT_FP32], | ||
| 409 | + k: pl.Tensor[[64, 64], pl.DT_FP32], | ||
| 410 | + out: pl.Tensor[[64, 64], pl.DT_INT8], | ||
| 411 | + ): | ||
| 412 | + with pl.section_cube(): | ||
| 413 | + acc = _make_acc() | ||
| 414 | + fp_type = pl.TileType(shape=[64, 1], dtype=pl.DT_INT64, target_memory=pl.MemorySpace.Scaling) | ||
| 415 | + fp_tile = pl.make_tile(fp_type, addr=0x0000, size=512) | ||
| 416 | + pl.store(out, acc, [0, 0], scale=fp_tile) | ||
| 417 | + | ||
| 418 | + q, k = _make_qk() | ||
| 419 | + out = torch.zeros(64, 64, dtype=torch.int8) | ||
| 420 | + with pytest.raises(ParserSyntaxError, match=r"shape \[1, N\].*row == 1"): | ||
| 421 | + kernel(q, k, out) | ||
| 422 | + | ||
| 423 | + | ||
| 424 | +@pytest.mark.soc("950") | ||
| 425 | +def test_err_per_channel_col_not_aligned(): | ||
| 426 | + """[1, N] 的 N 必须为 16 的倍数(128B 对齐),否则应在解析期被拒绝""" | ||
| 427 | + | ||
| 428 | + @pl.jit() | ||
| 429 | + def kernel( | ||
| 430 | + q: pl.Tensor[[64, 64], pl.DT_FP32], | ||
| 431 | + k: pl.Tensor[[64, 64], pl.DT_FP32], | ||
| 432 | + out: pl.Tensor[[64, 64], pl.DT_INT8], | ||
| 433 | + ): | ||
| 434 | + with pl.section_cube(): | ||
| 435 | + acc = _make_acc() | ||
| 436 | + fp_type = pl.TileType(shape=[1, 8], dtype=pl.DT_INT64, target_memory=pl.MemorySpace.Scaling) | ||
| 437 | + fp_tile = pl.make_tile(fp_type, addr=0x0000, size=512) | ||
| 438 | + pl.store(out, acc, [0, 0], scale=fp_tile) | ||
| 439 | + | ||
| 440 | + q, k = _make_qk() | ||
| 441 | + out = torch.zeros(64, 64, dtype=torch.int8) | ||
| 442 | + with pytest.raises(ParserSyntaxError, match="multiple of 16"): | ||
| 443 | + kernel(q, k, out) | ||
| 444 | + | ||
| 445 | + | ||
| 446 | +# ============================================================================ | ||
| 447 | +# 4. 旧参数废弃验证 | ||
| 448 | +# ============================================================================ | ||
| 449 | + | ||
| 450 | + | ||
| 451 | +@pytest.mark.soc("950") | ||
| 452 | +def test_err_legacy_pre_quant_scalar(): | ||
| 453 | + """旧参数 pre_quant_scalar 已废弃,应抛出 TypeError""" | ||
| 454 | + | ||
| 455 | + @pl.jit() | ||
| 456 | + def kernel( | ||
| 457 | + q: pl.Tensor[[64, 64], pl.DT_FP32], | ||
| 458 | + k: pl.Tensor[[64, 64], pl.DT_FP32], | ||
| 459 | + out: pl.Tensor[[64, 64], pl.DT_INT8], | ||
| 460 | + ): | ||
| 461 | + with pl.section_cube(): | ||
| 462 | + acc = _make_acc() | ||
| 463 | + pl.store(out, acc, [0, 0], pre_quant_scalar=0x40000000) | ||
| 464 | + | ||
| 465 | + q, k = _make_qk() | ||
| 466 | + out = torch.zeros(64, 64, dtype=torch.int8) | ||
| 467 | + with pytest.raises(ParserSyntaxError, match="unexpected keyword argument.*pre_quant_scalar"): | ||
| 468 | + kernel(q, k, out) | ||
| 469 | + | ||
| 470 | + | ||
| 471 | +@pytest.mark.soc("950") | ||
| 472 | +def test_err_legacy_fp_tile(): | ||
| 473 | + """旧参数 fp_tile 已废弃,应抛出 TypeError(per-channel 统一走 scale= 入口)""" | ||
| 474 | + | ||
| 475 | + @pl.jit() | ||
| 476 | + def kernel( | ||
| 477 | + q: pl.Tensor[[64, 64], pl.DT_FP32], | ||
| 478 | + k: pl.Tensor[[64, 64], pl.DT_FP32], | ||
| 479 | + out: pl.Tensor[[64, 64], pl.DT_INT8], | ||
| 480 | + ): | ||
| 481 | + with pl.section_cube(): | ||
| 482 | + acc = _make_acc() | ||
| 483 | + pl.store(out, acc, [0, 0], fp_tile=acc) | ||
| 484 | + | ||
| 485 | + q, k = _make_qk() | ||
| 486 | + out = torch.zeros(64, 64, dtype=torch.int8) | ||
| 487 | + with pytest.raises(ParserSyntaxError, match="unexpected keyword argument.*fp_tile"): | ||
| 488 | + kernel(q, k, out) | ||
Rpython/tests/st/pypto_pro/frontend/datacopy/test_deq_scalar_move_fp32_to_int8_dynamic.py→python/tests/st/pypto_pro/frontend/datacopy/test_scale_param.py+193-51
| @@ -1,4 +1,4 @@ | |||
| 1 | -# Copyright (c) 2025-2026 Huawei Technologies Co., Ltd. | 1 | +# Copyright (c) 2026 Huawei Technologies Co., Ltd. |
| 2 | # This program is free software, you can redistribute it and/or modify it under the terms and conditions of | 2 | # This program is free software, you can redistribute it and/or modify it under the terms and conditions of |
| 3 | # CANN Open Software License Agreement Version 2.0 (the "License"). | 3 | # CANN Open Software License Agreement Version 2.0 (the "License"). |
| 4 | # Please refer to the License for details. You may not use this file except in compliance with the License. | 4 | # Please refer to the License for details. You may not use this file except in compliance with the License. |
| @@ -7,16 +7,19 @@ | |||
| 7 | # See LICENSE in the root of the software repository for the full text of the License. | 7 | # See LICENSE in the root of the software repository for the full text of the License. |
| 8 | # ----------------------------------------------------------------------------------------------------------- | 8 | # ----------------------------------------------------------------------------------------------------------- |
| 9 | 9 | ||
| 10 | -"""Frontend runtime example for L0C->UB scalar dequant with a DYNAMIC (runtime) scale on A5 CCE. | 10 | +"""Comprehensive test suite for the unified ``scale`` parameter in pl.store/pl.move. |
| 11 | 11 | ||
| 12 | -Dynamic-scale counterpart of test_deq_scalar_move_fp32_to_int8.py. The scale is a runtime kernel | 12 | +Validates the new fixpipe quantization API where ``scale`` replaces the legacy |
| 13 | -argument `scale_bits: pl.DT_INT32` passed at launch. This is the only test that exercises | 13 | +``pre_quant_scalar`` and ``fp_tile`` parameters. |
| 14 | -the MOVE path's own runtime sign-bit bit-op emit AND the move operand type-dispatch with a runtime | ||
| 15 | -scalar coexisting with acc_to_vec_mode (store's dynamic test does not cover the move codegen). | ||
| 16 | 14 | ||
| 17 | -The scalar carries the low 32 bits = the float32 bit-pattern of the scale; CCE codegen adds the | 15 | +Scenarios covered: |
| 18 | -signed-int8 bit46 flag from the output tile dtype at runtime, so negatives keep their sign. | 16 | +1. Per-tensor store with float scale (FP32 -> INT8) |
| 19 | -A5 only (the L0C->UB quant path lives in arch35/copy_l0c_to_ub_impl.h, gated by PTO_NPU_ARCH_A5). | 17 | +2. Per-tensor store with random input (non-deterministic round alignment) |
| 18 | +3. Per-tensor move with float scale (Acc -> Vec, FP32 -> INT8) | ||
| 19 | +4. Dynamic (runtime) scale via Expr | ||
| 20 | + | ||
| 21 | +Note: ReLU fusion is covered by test_scale_relu_fusion / | ||
| 22 | +test_scale_precision_alignment::test_golden_per_tensor_relu (atol=0). | ||
| 20 | """ | 23 | """ |
| 21 | 24 | ||
| 22 | import logging | 25 | import logging |
| @@ -34,13 +37,7 @@ ST_DEVICE = f"npu:{ST_DEVICE_ID}" | |||
| 34 | FP_SCALE_VALUE = 2.0 | 37 | FP_SCALE_VALUE = 2.0 |
| 35 | 38 | ||
| 36 | 39 | ||
| 37 | -def _scale_bits(scale: float) -> int: | ||
| 38 | - # Low 32 bits = float32 bit-pattern of the scale (scale=2.0 -> 0x40000000). | ||
| 39 | - return struct.unpack("!I", struct.pack("!f", scale))[0] | ||
| 40 | - | ||
| 41 | - | ||
| 42 | def _make_q(device: str) -> torch.Tensor: | 40 | def _make_q(device: str) -> torch.Tensor: |
| 43 | - # Includes negatives to validate signed-int8 dequant keeps the sign (-3*2=-6, not 0). | ||
| 44 | row = torch.tensor([-3.0, -2.0, -1.0, 0.0, 1.0, 2.0, 3.0, 4.0], device=device, dtype=torch.float32).repeat(8) | 41 | row = torch.tensor([-3.0, -2.0, -1.0, 0.0, 1.0, 2.0, 3.0, 4.0], device=device, dtype=torch.float32).repeat(8) |
| 45 | return row.unsqueeze(0).repeat(64, 1) | 42 | return row.unsqueeze(0).repeat(64, 1) |
| 46 | 43 | ||
| @@ -50,11 +47,52 @@ def _make_k(device: str) -> torch.Tensor: | |||
| 50 | 47 | ||
| 51 | 48 | ||
| 52 | @pl.jit() | 49 | @pl.jit() |
| 53 | -def deq_scalar_move_dynamic_cce_kernel( | 50 | +def scale_store_kernel( |
| 51 | + q: pl.Tensor[[64, 64], pl.DT_FP32], | ||
| 52 | + k: pl.Tensor[[64, 64], pl.DT_FP32], | ||
| 53 | + raw_out: pl.Tensor[[64, 64], pl.DT_FP32], | ||
| 54 | + quant_out: pl.Tensor[[64, 64], pl.DT_INT8], | ||
| 55 | +): | ||
| 56 | + with pl.section_cube(): | ||
| 57 | + mat_type = pl.TileType(shape=[64, 64], dtype=pl.DT_FP32, target_memory=pl.MemorySpace.Mat, layout=pl.NZ) | ||
| 58 | + q_mat = pl.make_tile(mat_type, addr=0x0000, size=16384) | ||
| 59 | + k_mat = pl.make_tile(mat_type, addr=0x4000, size=16384) | ||
| 60 | + | ||
| 61 | + left_type = pl.TileType(shape=[64, 64], dtype=pl.DT_FP32, target_memory=pl.MemorySpace.Left, layout=pl.NZ) | ||
| 62 | + q_left = pl.make_tile(left_type, addr=0x0000, size=16384) | ||
| 63 | + | ||
| 64 | + right_type = pl.TileType(shape=[64, 64], dtype=pl.DT_FP32, target_memory=pl.MemorySpace.Right, layout=pl.ZN) | ||
| 65 | + k_right = pl.make_tile(right_type, addr=0x0000, size=16384) | ||
| 66 | + | ||
| 67 | + acc_type = pl.TileType( | ||
| 68 | + shape=[64, 64], dtype=pl.DT_FP32, target_memory=pl.MemorySpace.Acc, layout=pl.NZ, fractal=1024 | ||
| 69 | + ) | ||
| 70 | + acc = pl.make_tile(acc_type, addr=0x0000, size=16384) | ||
| 71 | + | ||
| 72 | + pl.load(q_mat, q, [0, 0]) | ||
| 73 | + pl.load(k_mat, k, [0, 0]) | ||
| 74 | + pl.system.sync_src(set_pipe=pl.PipeType.MTE2, wait_pipe=pl.PipeType.MTE1, event_id=0) | ||
| 75 | + pl.system.sync_dst(set_pipe=pl.PipeType.MTE2, wait_pipe=pl.PipeType.MTE1, event_id=0) | ||
| 76 | + | ||
| 77 | + pl.move(q_left, q_mat) | ||
| 78 | + pl.move(k_right, k_mat) | ||
| 79 | + pl.system.sync_src(set_pipe=pl.PipeType.MTE1, wait_pipe=pl.PipeType.M, event_id=0) | ||
| 80 | + pl.system.sync_dst(set_pipe=pl.PipeType.MTE1, wait_pipe=pl.PipeType.M, event_id=0) | ||
| 81 | + | ||
| 82 | + pl.matmul(acc, q_left, k_right) | ||
| 83 | + pl.system.sync_src(set_pipe=pl.PipeType.M, wait_pipe=pl.PipeType.FIX, event_id=0) | ||
| 84 | + pl.system.sync_dst(set_pipe=pl.PipeType.M, wait_pipe=pl.PipeType.FIX, event_id=0) | ||
| 85 | + | ||
| 86 | + pl.store(raw_out, acc, [0, 0]) | ||
| 87 | + pl.store(quant_out, acc, [0, 0], scale=FP_SCALE_VALUE) | ||
| 88 | + pl.system.bar_all() | ||
| 89 | + | ||
| 90 | + | ||
| 91 | +@pl.jit() | ||
| 92 | +def scale_move_kernel( | ||
| 54 | q: pl.Tensor[[64, 64], pl.DT_FP32], | 93 | q: pl.Tensor[[64, 64], pl.DT_FP32], |
| 55 | k: pl.Tensor[[64, 64], pl.DT_FP32], | 94 | k: pl.Tensor[[64, 64], pl.DT_FP32], |
| 56 | move_out: pl.Tensor[[64, 64], pl.DT_INT8], | 95 | move_out: pl.Tensor[[64, 64], pl.DT_INT8], |
| 57 | - scale_bits: pl.DT_INT32, | ||
| 58 | ): | 96 | ): |
| 59 | vec_type = pl.TileType(shape=[64, 64], dtype=pl.DT_INT8, target_memory=pl.MemorySpace.Vec) | 97 | vec_type = pl.TileType(shape=[64, 64], dtype=pl.DT_INT8, target_memory=pl.MemorySpace.Vec) |
| 60 | vec_tile = pl.make_tile(vec_type, addr=0x0000, size=4096) | 98 | vec_tile = pl.make_tile(vec_type, addr=0x0000, size=4096) |
| @@ -67,43 +105,29 @@ def deq_scalar_move_dynamic_cce_kernel( | |||
| 67 | left_type = pl.TileType(shape=[64, 64], dtype=pl.DT_FP32, target_memory=pl.MemorySpace.Left, layout=pl.NZ) | 105 | left_type = pl.TileType(shape=[64, 64], dtype=pl.DT_FP32, target_memory=pl.MemorySpace.Left, layout=pl.NZ) |
| 68 | q_left = pl.make_tile(left_type, addr=0x0000, size=16384) | 106 | q_left = pl.make_tile(left_type, addr=0x0000, size=16384) |
| 69 | 107 | ||
| 70 | - right_type = pl.TileType( | 108 | + right_type = pl.TileType(shape=[64, 64], dtype=pl.DT_FP32, target_memory=pl.MemorySpace.Right, layout=pl.ZN) |
| 71 | - shape=[64, 64], | ||
| 72 | - dtype=pl.DT_FP32, | ||
| 73 | - target_memory=pl.MemorySpace.Right, | ||
| 74 | - layout=pl.ZN, | ||
| 75 | - ) | ||
| 76 | k_right = pl.make_tile(right_type, addr=0x0000, size=16384) | 109 | k_right = pl.make_tile(right_type, addr=0x0000, size=16384) |
| 77 | 110 | ||
| 78 | acc_type = pl.TileType( | 111 | acc_type = pl.TileType( |
| 79 | - shape=[64, 64], | 112 | + shape=[64, 64], dtype=pl.DT_FP32, target_memory=pl.MemorySpace.Acc, layout=pl.NZ, fractal=1024 |
| 80 | - dtype=pl.DT_FP32, | ||
| 81 | - target_memory=pl.MemorySpace.Acc, | ||
| 82 | - layout=pl.NZ, | ||
| 83 | - fractal=1024, | ||
| 84 | ) | 113 | ) |
| 85 | acc = pl.make_tile(acc_type, addr=0x0000, size=16384) | 114 | acc = pl.make_tile(acc_type, addr=0x0000, size=16384) |
| 86 | 115 | ||
| 87 | pl.load(q_mat, q, [0, 0]) | 116 | pl.load(q_mat, q, [0, 0]) |
| 88 | pl.load(k_mat, k, [0, 0]) | 117 | pl.load(k_mat, k, [0, 0]) |
| 89 | - | ||
| 90 | pl.system.sync_src(set_pipe=pl.PipeType.MTE2, wait_pipe=pl.PipeType.MTE1, event_id=0) | 118 | pl.system.sync_src(set_pipe=pl.PipeType.MTE2, wait_pipe=pl.PipeType.MTE1, event_id=0) |
| 91 | pl.system.sync_dst(set_pipe=pl.PipeType.MTE2, wait_pipe=pl.PipeType.MTE1, event_id=0) | 119 | pl.system.sync_dst(set_pipe=pl.PipeType.MTE2, wait_pipe=pl.PipeType.MTE1, event_id=0) |
| 92 | 120 | ||
| 93 | pl.move(q_left, q_mat) | 121 | pl.move(q_left, q_mat) |
| 94 | pl.move(k_right, k_mat) | 122 | pl.move(k_right, k_mat) |
| 95 | - | ||
| 96 | pl.system.sync_src(set_pipe=pl.PipeType.MTE1, wait_pipe=pl.PipeType.M, event_id=0) | 123 | pl.system.sync_src(set_pipe=pl.PipeType.MTE1, wait_pipe=pl.PipeType.M, event_id=0) |
| 97 | pl.system.sync_dst(set_pipe=pl.PipeType.MTE1, wait_pipe=pl.PipeType.M, event_id=0) | 124 | pl.system.sync_dst(set_pipe=pl.PipeType.MTE1, wait_pipe=pl.PipeType.M, event_id=0) |
| 98 | 125 | ||
| 99 | pl.matmul(acc, q_left, k_right) | 126 | pl.matmul(acc, q_left, k_right) |
| 100 | - | ||
| 101 | pl.system.sync_src(set_pipe=pl.PipeType.M, wait_pipe=pl.PipeType.FIX, event_id=0) | 127 | pl.system.sync_src(set_pipe=pl.PipeType.M, wait_pipe=pl.PipeType.FIX, event_id=0) |
| 102 | pl.system.sync_dst(set_pipe=pl.PipeType.M, wait_pipe=pl.PipeType.FIX, event_id=0) | 128 | pl.system.sync_dst(set_pipe=pl.PipeType.M, wait_pipe=pl.PipeType.FIX, event_id=0) |
| 103 | 129 | ||
| 104 | - # DYNAMIC scale on the L0C->UB move: pre_quant_scalar is the runtime kernel arg, coexisting | 130 | + pl.move(vec_tile, acc, scale=FP_SCALE_VALUE, acc_to_vec_mode=pl.AccToVecMode.SingleModeVec0) |
| 105 | - # with acc_to_vec_mode (exercises move's operand type-dispatch + runtime sign-bit emit). | ||
| 106 | - pl.move(vec_tile, acc, pre_quant_scalar=scale_bits, acc_to_vec_mode=pl.AccToVecMode.SingleModeVec0) | ||
| 107 | pl.system.set_cross_core(pipe=pl.PipeType.FIX, event_id=0) | 131 | pl.system.set_cross_core(pipe=pl.PipeType.FIX, event_id=0) |
| 108 | 132 | ||
| 109 | with pl.section_vector(): | 133 | with pl.section_vector(): |
| @@ -114,9 +138,110 @@ def deq_scalar_move_dynamic_cce_kernel( | |||
| 114 | pl.system.bar_all() | 138 | pl.system.bar_all() |
| 115 | 139 | ||
| 116 | 140 | ||
| 141 | +@pl.jit() | ||
| 142 | +def scale_dynamic_kernel( | ||
| 143 | + q: pl.Tensor[[64, 64], pl.DT_FP32], | ||
| 144 | + k: pl.Tensor[[64, 64], pl.DT_FP32], | ||
| 145 | + quant_out: pl.Tensor[[64, 64], pl.DT_INT8], | ||
| 146 | + scale_bits: pl.DT_INT32, | ||
| 147 | +): | ||
| 148 | + with pl.section_cube(): | ||
| 149 | + mat_type = pl.TileType(shape=[64, 64], dtype=pl.DT_FP32, target_memory=pl.MemorySpace.Mat, layout=pl.NZ) | ||
| 150 | + q_mat = pl.make_tile(mat_type, addr=0x0000, size=16384) | ||
| 151 | + k_mat = pl.make_tile(mat_type, addr=0x4000, size=16384) | ||
| 152 | + | ||
| 153 | + left_type = pl.TileType(shape=[64, 64], dtype=pl.DT_FP32, target_memory=pl.MemorySpace.Left, layout=pl.NZ) | ||
| 154 | + q_left = pl.make_tile(left_type, addr=0x0000, size=16384) | ||
| 155 | + | ||
| 156 | + right_type = pl.TileType(shape=[64, 64], dtype=pl.DT_FP32, target_memory=pl.MemorySpace.Right, layout=pl.ZN) | ||
| 157 | + k_right = pl.make_tile(right_type, addr=0x0000, size=16384) | ||
| 158 | + | ||
| 159 | + acc_type = pl.TileType( | ||
| 160 | + shape=[64, 64], dtype=pl.DT_FP32, target_memory=pl.MemorySpace.Acc, layout=pl.NZ, fractal=1024 | ||
| 161 | + ) | ||
| 162 | + acc = pl.make_tile(acc_type, addr=0x0000, size=16384) | ||
| 163 | + | ||
| 164 | + pl.load(q_mat, q, [0, 0]) | ||
| 165 | + pl.load(k_mat, k, [0, 0]) | ||
| 166 | + pl.system.sync_src(set_pipe=pl.PipeType.MTE2, wait_pipe=pl.PipeType.MTE1, event_id=0) | ||
| 167 | + pl.system.sync_dst(set_pipe=pl.PipeType.MTE2, wait_pipe=pl.PipeType.MTE1, event_id=0) | ||
| 168 | + | ||
| 169 | + pl.move(q_left, q_mat) | ||
| 170 | + pl.move(k_right, k_mat) | ||
| 171 | + pl.system.sync_src(set_pipe=pl.PipeType.MTE1, wait_pipe=pl.PipeType.M, event_id=0) | ||
| 172 | + pl.system.sync_dst(set_pipe=pl.PipeType.MTE1, wait_pipe=pl.PipeType.M, event_id=0) | ||
| 173 | + | ||
| 174 | + pl.matmul(acc, q_left, k_right) | ||
| 175 | + pl.system.sync_src(set_pipe=pl.PipeType.M, wait_pipe=pl.PipeType.FIX, event_id=0) | ||
| 176 | + pl.system.sync_dst(set_pipe=pl.PipeType.M, wait_pipe=pl.PipeType.FIX, event_id=0) | ||
| 177 | + | ||
| 178 | + pl.store(quant_out, acc, [0, 0], scale=scale_bits) | ||
| 179 | + pl.system.bar_all() | ||
| 180 | + | ||
| 117 | 181 | ||
| 118 | @pytest.mark.soc("950") | 182 | @pytest.mark.soc("950") |
| 119 | -def test_deq_scalar_move_dynamic_cce(): | 183 | +def test_scale_store_per_tensor(): |
| 184 | + device = ST_DEVICE | ||
| 185 | + torch.npu.set_device(device) | ||
| 186 | + | ||
| 187 | + device_name = torch.npu.get_device_name() | ||
| 188 | + if "Ascend950" not in device_name: | ||
| 189 | + logging.info("Current device is %s, skip.", device_name) | ||
| 190 | + return | ||
| 191 | + | ||
| 192 | + q = _make_q(device) | ||
| 193 | + k = _make_k(device) | ||
| 194 | + raw_out = torch.zeros((64, 64), device=device, dtype=torch.float32) | ||
| 195 | + quant_out = torch.zeros((64, 64), device=device, dtype=torch.int8) | ||
| 196 | + | ||
| 197 | + scale_store_kernel(q, k, raw_out, quant_out) | ||
| 198 | + torch.npu.synchronize() | ||
| 199 | + | ||
| 200 | + raw_ref = torch.matmul(q, k) | ||
| 201 | + expected_quant = torch.clamp(torch.round(raw_ref * FP_SCALE_VALUE), -128, 127).to(torch.int8) | ||
| 202 | + | ||
| 203 | + torch.testing.assert_close(raw_out, raw_ref, rtol=1e-2, atol=1e-2) | ||
| 204 | + torch.testing.assert_close(quant_out.to(torch.int32), expected_quant.to(torch.int32), rtol=0, atol=0) | ||
| 205 | + logging.info("test_scale_store_per_tensor passed.") | ||
| 206 | + | ||
| 207 | + | ||
| 208 | +@pytest.mark.soc("950") | ||
| 209 | +def test_scale_store_random_input(): | ||
| 210 | + """随机输入 per-tensor 量化:golden = clamp(round(raw_ref * scale))。 | ||
| 211 | + | ||
| 212 | + 与 k=eye 的确定性用例互补:随机数据下 matmul 累加顺序与 torch 不同, | ||
| 213 | + 且在 round 边界(x.5)处设备/torch 可能翻 1,故量化输出用 atol=1, | ||
| 214 | + 原始输出(未量化)用相对容差验证 matmul 本身。 | ||
| 215 | + """ | ||
| 216 | + | ||
| 217 | + device = ST_DEVICE | ||
| 218 | + torch.npu.set_device(device) | ||
| 219 | + | ||
| 220 | + device_name = torch.npu.get_device_name() | ||
| 221 | + if "Ascend950" not in device_name: | ||
| 222 | + logging.info("Current device is %s, skip.", device_name) | ||
| 223 | + return | ||
| 224 | + | ||
| 225 | + q = torch.randn(64, 64, dtype=torch.float32, device=device) | ||
| 226 | + k = torch.randn(64, 64, dtype=torch.float32, device=device) | ||
| 227 | + raw_out = torch.zeros((64, 64), device=device, dtype=torch.float32) | ||
| 228 | + quant_out = torch.zeros((64, 64), device=device, dtype=torch.int8) | ||
| 229 | + | ||
| 230 | + scale_store_kernel(q, k, raw_out, quant_out) | ||
| 231 | + torch.npu.synchronize() | ||
| 232 | + | ||
| 233 | + raw_ref = torch.matmul(q, k) | ||
| 234 | + expected_quant = torch.clamp(torch.round(raw_ref * FP_SCALE_VALUE), -128, 127).to(torch.int8) | ||
| 235 | + | ||
| 236 | + # 随机数据下 matmul 累加误差(vs torch)远小于 1 LSB,但为稳健起见原始输出用相对容差 | ||
| 237 | + torch.testing.assert_close(raw_out, raw_ref, rtol=1e-2, atol=1e-2) | ||
| 238 | + # 量化输出:round 边界(x.5)处允许 ±1 LSB 翻转 | ||
| 239 | + torch.testing.assert_close(quant_out.to(torch.int32), expected_quant.to(torch.int32), rtol=0, atol=1) | ||
| 240 | + logging.info("test_scale_store_random_input passed.") | ||
| 241 | + | ||
| 242 | + | ||
| 243 | +@pytest.mark.soc("950") | ||
| 244 | +def test_scale_move_per_tensor(): | ||
| 120 | device = ST_DEVICE | 245 | device = ST_DEVICE |
| 121 | torch.npu.set_device(device) | 246 | torch.npu.set_device(device) |
| 122 | 247 | ||
| @@ -129,28 +254,45 @@ def test_deq_scalar_move_dynamic_cce(): | |||
| 129 | k = _make_k(device) | 254 | k = _make_k(device) |
| 130 | move_out = torch.zeros((64, 64), device=device, dtype=torch.int8) | 255 | move_out = torch.zeros((64, 64), device=device, dtype=torch.int8) |
| 131 | 256 | ||
| 132 | - scale_bits = _scale_bits(FP_SCALE_VALUE) # runtime value, computed on host | 257 | + scale_move_kernel(q, k, move_out) |
| 133 | - | ||
| 134 | - deq_scalar_move_dynamic_cce_kernel(q, k, move_out, scale_bits) | ||
| 135 | torch.npu.synchronize() | 258 | torch.npu.synchronize() |
| 136 | 259 | ||
| 137 | raw_ref = torch.matmul(q, k) | 260 | raw_ref = torch.matmul(q, k) |
| 138 | - expected_out = torch.clamp(torch.round(raw_ref * FP_SCALE_VALUE), -128, 127).to(torch.int8) | 261 | + expected = torch.clamp(torch.round(raw_ref * FP_SCALE_VALUE), -128, 127).to(torch.int8) |
| 139 | 262 | ||
| 140 | - logging.info("***********cce q input (top-left 8x8)***********") | 263 | + torch.testing.assert_close(move_out.to(torch.int32), expected.to(torch.int32), rtol=0, atol=0) |
| 141 | - logging.info("%s", q[:8, :8]) | 264 | + logging.info("test_scale_move_per_tensor passed.") |
| 142 | - logging.info("***********cce dynamic scale bits (hex)***********") | ||
| 143 | - logging.info("0x%X (scale=%s, passed at runtime)", scale_bits, FP_SCALE_VALUE) | ||
| 144 | - logging.info("***********cce expected move deq int8 output***********") | ||
| 145 | - logging.info("%s", expected_out[:8, :8]) | ||
| 146 | - logging.info("***********cce dynamic-scale move deq int8 output (top-left 8x8)***********") | ||
| 147 | - logging.info("%s", move_out[:8, :8]) | ||
| 148 | 265 | ||
| 149 | - torch.testing.assert_close(move_out.to(torch.int32), expected_out.to(torch.int32), rtol=0, atol=0) | 266 | + |
| 150 | - logging.info("cce dynamic-scale move deq_scalar output matches expectation.") | 267 | +@pytest.mark.soc("950") |
| 268 | +def test_scale_dynamic(): | ||
| 269 | + device = ST_DEVICE | ||
| 270 | + torch.npu.set_device(device) | ||
| 271 | + | ||
| 272 | + device_name = torch.npu.get_device_name() | ||
| 273 | + if "Ascend950" not in device_name: | ||
| 274 | + logging.info("Current device is %s, skip.", device_name) | ||
| 275 | + return | ||
| 276 | + | ||
| 277 | + q = _make_q(device) | ||
| 278 | + k = _make_k(device) | ||
| 279 | + quant_out = torch.zeros((64, 64), device=device, dtype=torch.int8) | ||
| 280 | + | ||
| 281 | + scale_bits = struct.unpack("!I", struct.pack("!f", FP_SCALE_VALUE))[0] | ||
| 282 | + | ||
| 283 | + scale_dynamic_kernel(q, k, quant_out, scale_bits) | ||
| 284 | + torch.npu.synchronize() | ||
| 285 | + | ||
| 286 | + raw_ref = torch.matmul(q, k) | ||
| 287 | + expected = torch.clamp(torch.round(raw_ref * FP_SCALE_VALUE), -128, 127).to(torch.int8) | ||
| 288 | + | ||
| 289 | + torch.testing.assert_close(quant_out.to(torch.int32), expected.to(torch.int32), rtol=0, atol=0) | ||
| 290 | + logging.info("test_scale_dynamic passed.") | ||
| 151 | 291 | ||
| 152 | 292 | ||
| 153 | if __name__ == "__main__": | 293 | if __name__ == "__main__": |
| 154 | - logging.basicConfig(level=logging.INFO, format="%(message)s") | 294 | + test_scale_store_per_tensor() |
| 155 | - test_deq_scalar_move_dynamic_cce() | 295 | + test_scale_store_random_input() |
| 296 | + test_scale_move_per_tensor() | ||
| 297 | + test_scale_dynamic() | ||
| 156 | logging.info("\nAll tests passed!") | 298 | logging.info("\nAll tests passed!") |
Rpython/tests/st/pypto_pro/frontend/datacopy/test_move_fp.py→python/tests/st/pypto_pro/frontend/datacopy/test_scale_relu_fusion.py+184-79
这个地方枚举的应该是宏