Open
【CANN社区任务】新增 aclsparseAxpyi 算子(Atlas A2/A3 arch22 & Ascend 950 arch35 + PyTorch 封装) #567
huier325Add on 3 days ago
【CANN社区任务】新增 aclsparseAxpyi 算子(Atlas A2/A3 arch22 & Ascend 950 arch35 + PyTorch 封装) #567
Open
Merged fromhuier325/ops-sparsefeat/aclsparse-axpyiintocann/ops-sparsemaster
Total: 22 files changed+3876-0
| @@ -55,6 +55,7 @@ git clone -b ${tag_version} https://gitcode.com/cann/ops-sparse.git | |||
| 55 | | [SpVV](sparse/spvv/README.md) | `aclsparseSpvv` | √ | × | | 55 | | [SpVV](sparse/spvv/README.md) | `aclsparseSpvv` | √ | × | |
| 56 | | [Gather](sparse/gather/README.md) | `aclsparseGather` | √ | √ | | 56 | | [Gather](sparse/gather/README.md) | `aclsparseGather` | √ | √ | |
| 57 | | [Scatter](sparse/scatter/README.md) | `aclsparseScatter` | √ | √ | | 57 | | [Scatter](sparse/scatter/README.md) | `aclsparseScatter` | √ | √ | |
| 58 | +| [Axpyi](sparse/axpyi/README.md) | `aclsparseAxpyi` | √ | √ | | ||
| 58 | | [DenseToSparse](sparse/densetosparse/README.md) | `aclsparseDenseToSparseConvert` | √ | √ | | 59 | | [DenseToSparse](sparse/densetosparse/README.md) | `aclsparseDenseToSparseConvert` | √ | √ | |
| 59 | | [SparseToDense](sparse/sparse2dense/README.md) | `aclsparseSparseToDense` | √ | √ | | 60 | | [SparseToDense](sparse/sparse2dense/README.md) | `aclsparseSparseToDense` | √ | √ | |
| 60 | | [gtsv2](sparse/gtsv2/README.md) | `aclsparseSgtsv2` | √ | √ | | 61 | | [gtsv2](sparse/gtsv2/README.md) | `aclsparseSgtsv2` | √ | √ | |
| @@ -0,0 +1,192 @@ | |||
| 1 | +# 需求背景(required) | ||
| 2 | + | ||
| 3 | +## 需求来源 | ||
| 4 | + | ||
| 5 | +昇腾 CANN 2026 年 12 月社区任务:**`aclsparseAxpyi` 算子开发(Ascend 950 / Atlas A2/A3)**,合入目标仓库为 `https://gitcode.com/cann/ops-sparse`,验收以 PyTorch 层 `aclsparse_axpyi()`(挂载为 `torch_npu.sparse.aclsparse_axpyi`)的功能、精度与性能为唯一基准,同时提供 `aclsparseAxpyi` / `aclsparseAxpyiRaw` C 接口。 | ||
| 6 | + | ||
| 7 | +## 背景介绍 | ||
| 8 | + | ||
| 9 | +### `aclsparseAxpyi` 算子定位与典型场景 | ||
| 10 | + | ||
| 11 | +`aclsparseAxpyi` 对标稀疏 BLAS Level-1 标准接口(Netlib `cblas_?axpyi` / cuSPARSE `cusparseAxpby`),执行稀疏向量缩放累加到稠密向量的指定索引位置,广泛应用于: | ||
| 12 | +- 共轭梯度法(CG)、BiCGStab、GMRES 等稀疏线性方程组迭代求解器的残差与搜索方向向量更新; | ||
| 13 | +- 稀疏特征嵌入向量的增量更新(Sparse Embedding Update)。 | ||
| 14 | + | ||
| 15 | +### 参数与接口现状分析 | ||
| 16 | + | ||
| 17 | +| 参数 | 参数含义 | 数据类型 | 支持数据类型 | 约束 | 形状 | | ||
| 18 | +| --- | --- | --- | --- | --- | --- | | ||
| 19 | +| `alpha` | 标量缩放系数 | scalar (`float`) | `float32` | 无(`alpha == 0` 须输出与 `y` 逐位一致) | 标量 | | ||
| 20 | +| `x_val` | 稀疏向量非零值 | tensor | `float32`, `float16`, `bfloat16` | 1D,长度等于 `nnz`,与 `y` 同 dtype、同 NPU 设备 | `(nnz,)` | | ||
| 21 | +| `x_ind` | 稀疏向量非零元下标 | tensor | `int32`, `int64` | 1D,长度等于 `nnz`,值域 `[0, N)` 且互不重复,允许乱序 | `(nnz,)` | | ||
| 22 | +| `y` | 目标稠密向量 | tensor | `float32`, `float16`, `bfloat16` | 1D,长度 `N >= nnz`,与 `x_val` 同 dtype、同 NPU 设备;PyTorch 接口不得修改调用方 `y` | `(N,)` | | ||
| 23 | +| `out` | 输出稠密向量 | tensor | `float32`, `float16`, `bfloat16` | 1D 连续张量,长度 `N`,dtype、device 与 `y` 一致 | `(N,)` | | ||
| 24 | + | ||
| 25 | +计算公式: | ||
| 26 | + | ||
| 27 | +$$y[\text{xInd}[k] - \text{idxBase}] \leftarrow \alpha \cdot \text{xVal}[k] + y[\text{xInd}[k] - \text{idxBase}], \quad k \in [0, \text{nnz})$$ | ||
| 28 | + | ||
| 29 | +--- | ||
| 30 | + | ||
| 31 | +# 需求分析(required) | ||
| 32 | + | ||
| 33 | +## 需求描述 | ||
| 34 | + | ||
| 35 | +在 `ops-sparse` 算子库中以 Ascend C 实现 `aclsparseAxpyi` 算子的双架构(Atlas A2/A3 `arch22` 与 Ascend 950 `arch35`)完整交付,零额外 Workspace 依赖,并提供符合仓库 `torch_extension` 规范的 PyTorch 封装层 `torch_npu.sparse.aclsparse_axpyi`。 | ||
| 36 | + | ||
| 37 | +## 需求拆解 | ||
| 38 | + | ||
| 39 | +1. **双架构并存支持**: | ||
| 40 | + - `sparse/axpyi/arch22/`:面向 Atlas A2/A3(`dav-2201`),采用全矢量流水线(`Brcb` / `Gather` / `GatherMask`)+ 硬件原子加与字节使能 `DataCopyPad` 写回,彻底解决跨核同 32B Cache Line 写撕裂并打满 95% MTE3 硬件利用率; | ||
| 41 | + - `sparse/axpyi/arch35/`:面向 Ascend 950PR/950DT(`dav-3510`),基于 Ascend C SIMT(`__simt_vf__` / `asc_vf_call`)实现线程级细粒度并行与 SIMT 逐位一致拷贝核。 | ||
| 42 | +2. **全量主力数据类型与索引类型支持**: | ||
| 43 | + - 值类型:`float32`、`float16`、`bfloat16`,统一采用 **FP32 内部累加、末端单次舍入**; | ||
| 44 | + - 索引类型:`int32`、`int64`,支持 0-based(PyTorch/C)与 1-based(C 描述符模式)。 | ||
| 45 | +3. **严格边界与语义保障**: | ||
| 46 | + - 支持空张量(`nnz = 0`、`N = 0`)、退化规模(`N = 1, nnz = 1`)、非 32B 对齐尾块、乱序索引; | ||
| 47 | + - `alpha = 0` 时输出与输入 `y` 逐位一致(无 `+0/-0` 漂移); | ||
| 48 | + - PyTorch 接口按值返回新张量 `out`(不修改调用方 `y`),自动 `.contiguous()` 非连续输入,并对设备/维度/dtype/长度/索引越界抛出 `RuntimeError` 或 `ValueError`。 | ||
| 49 | +4. **精度与性能验收**: | ||
| 50 | + - 精度满足混合容差标准:`fp32` (`rtol ≤ 1e-4, atol ≤ 1e-5`)、`fp16` (`rtol ≤ 1e-3, atol ≤ 1e-3`)、`bf16` (`rtol ≤ 5e-3, atol ≤ 5e-3`); | ||
| 51 | + - 完整测试 8 组规模 × 3 种主力 dtype = 24 个性能点,并结合 `msprof` 持续迭代优化至硬件管线饱和。 | ||
| 52 | + | ||
| 53 | +--- | ||
| 54 | + | ||
| 55 | +# 详细设计(required) | ||
| 56 | + | ||
| 57 | +## 算子分析 | ||
| 58 | + | ||
| 59 | +### 数学公式 | ||
| 60 | + | ||
| 61 | +```text | ||
| 62 | +out = copy(y) (异地语义,PyTorch 接口;C 接口 aclsparseAxpyi 为原地语义免拷贝) | ||
| 63 | +out[x_ind[k] - idxBase] = cast<ValT>(alpha * cast<float>(x_val[k]) + cast<float>(y[x_ind[k] - idxBase])), k ∈ [0, nnz) | ||
| 64 | +``` | ||
| 65 | + | ||
| 66 | +### 支持数据类型与形状 | ||
| 67 | + | ||
| 68 | +- 值类型:`ACL_FLOAT` (`float32`)、`ACL_FLOAT16` (`float16`)、`ACL_BF16` (`bfloat16`) | ||
| 69 | +- 索引类型:`ACL_SPARSE_INDEX_32I` (`int32`)、`ACL_SPARSE_INDEX_64I` (`int64`) | ||
| 70 | +- 形状:任意 1D 张量,`0 <= nnz <= N`,覆盖非 32B 对齐与 `N = 10^7, nnz = 5×10^5` 大规模场景。 | ||
| 71 | + | ||
| 72 | +## 算子实现 | ||
| 73 | + | ||
| 74 | +### 核心难点与防撕裂并发写设计 | ||
| 75 | + | ||
| 76 | +`y[idx[k]] += alpha * x[k]` 是典型的随机 Scatter-Add。在多核并发场景下,若多个 AIV 核同时写入落在同一个 32B Cache Line 内的不同元素,采用普通 32B 读-改-写会导致严重的**跨核数据撕裂**。本设计针对双架构硬件特性分别制定零冲突方案: | ||
| 77 | + | ||
| 78 | +| 架构 | 数据类型 | 并发防撕裂与精度策略 | | ||
| 79 | +| --- | --- | --- | | ||
| 80 | +| **Atlas A2/A3 (`arch22` / `dav-2201`)** | `float32` | 启用硬件 `SetAtomicAdd<float>()` + 精确 4 字节 `DataCopyPad` 原子写回:完全免除 `y` 的随机 GM 读,且硬件原子保证跨核同 32B cache line 零撕裂 | | ||
| 81 | +| **Atlas A2/A3 (`arch22` / `dav-2201`)** | `float16` / `bfloat16` | 题目保证索引互不重复,每位置至多写一次;采用 3 级全异步硬件流水 `MTE2(ySrc 2B) → PIPE_V(Gather + Cast->FP32 + Add + RNE Cast + Brcb) → MTE3(yDst 2B DataCopyPad)`,利用 `dav-2201` `DataCopyPad` 字节使能选通仅覆写目标 2 字节,绝不污染相邻元素(经跨核同 32B cache line 对抗用例验证 100% 零撕裂) | | ||
| 82 | +| **Ascend 950 (`arch35` / `dav-3510`)** | `float32` / `float16` / `bfloat16` | SIMT 线程级原生 2B/4B 访存(`__simt_vf__`),索引互异保证不同线程访问互不重叠的标量地址;每线程以 FP32 完成 `alpha * float(x) + float(y)` 后单次舍入写回 | | ||
| 83 | + | ||
| 84 | +### 实现方案 | ||
| 85 | + | ||
| 86 | +#### 3.2.1 Host 侧设计 | ||
| 87 | + | ||
| 88 | +1. **参数校验与快速返回路径**: | ||
| 89 | + - 统一封装 `LaunchAxpyiInternal`,同时服务 `aclsparseAxpyi`(描述符模式,支持 Host/Device `PointerMode`,原地更新 `ySrc == yDst`)与 `aclsparseAxpyiRaw`(原始指针模式,支持异地输出 `ySrc != yDst`,供 PyTorch 封装零描述符开销调用); | ||
| 90 | + - 校验句柄签名、空指针、`valueType` / `idxType` / `idxBase`、`stride == 1`、`0 <= nnz <= yLen` 及输出与稀疏向量的内存别名重叠; | ||
| 91 | + - `nnz == 0` 或 `alpha == 0.0f` 时:原地模式零 Kernel 启动直接返回;异地模式仅启动逐位一致的并行拷贝核后返回,严格满足逐位一致约束。 | ||
| 92 | +2. **分核策略(`arch22`)**: | ||
| 93 | + - 结合 `GetAivCoreCount()` 与 `aclrtGetDeviceInfo(..., ACL_DEV_ATTR_VECTOR_CORE_NUM)` 缓存全部可用 AIV 核数(Atlas A3 单芯 40 AIV 核); | ||
| 94 | + - **异地拷贝核(`KernelAxpyiCopy`)**:当 `ySrc != yDst` 时,摒弃低速 SDMA `aclrtMemcpyAsync(D2D)`(仅 ~150 GB/s),改由全 AIV 核并行执行双缓冲 64 KiB 对齐 `DataCopy`(`minCopyBytesPerCore = 2048`),实测达到 **3.5–3.9 TB/s L2 带宽**(40 MB 仅需 23.8 µs,较 SDMA 提速 15× 以上); | ||
| 95 | + - **稀疏累加核(`KernelAxpyiFp32` / `KernelAxpyiLowPrec`)**:按 `nnz` 均匀切分到 `blockNum = min(aivCores, ceil(nnz / 16))` 个 AIV 核,每核工作量严格为 `O(nnz / K)`,大核至多比小核多 1 个元素,天然免疫索引分布偏斜。 | ||
| 96 | +3. **分核策略(`arch35`)**: | ||
| 97 | + - `nnz < 4096` 时 `threadsPerBlock = 128`,大规模 `threadsPerBlock = 512`,按 `min(aivCoreNum, ceil(nnz / threadsPerBlock))` 动态调度 Block 数,内层采用 `kAxpyiStrideUnroll = 4` 的 Grid-Stride Loop; | ||
| 98 | + - 异地拷贝采用 SIMT 整型字宽拷贝核 `AxpyiCopySimtCompute`(`uint32_t` / `uint16_t`),保证无浮点规范化的逐位一致语义,且在 `dav_3510/camodel` 模拟器中彻底避免 SDMA 任务挂起。 | ||
| 99 | +4. **PyTorch 封装层(`sparse/axpyi/torch_extension/`)**: | ||
| 100 | + - 严格遵循 `ops-sparse` 扩展发现机制,导出 `TORCH_NPU_SPARSE_FACADE_APIS = {"aclsparse_axpyi": aclsparse_axpyi}`,安装后自动挂载为 `torch_npu.sparse.aclsparse_axpyi`; | ||
| 101 | + - C++ pybind 入口完成设备/维度/布局/dtype/长度校验、非连续张量自动 `.contiguous()`、带 `TensorImpl` 版本号缓存的 `[0, N)` 索引越界校验(`ValidatedIndexBoundsCache`,稳态复用零同步开销),直接调用 `aclsparseAxpyiRaw` 返回新分配的 `out` 张量。 | ||
| 102 | + | ||
| 103 | +#### 3.2.2 Kernel 侧设计 | ||
| 104 | + | ||
| 105 | +1. **`arch22` 零标量值访问纯矢量流水设计(零 Workspace,峰值 UB ≤ 76 KiB / 191.75 KiB)**: | ||
| 106 | + - **关键性能洞察**:通过 `msprof` 剖析发现 `dav-2201` 上标量核访问 UB(`LocalTensor::GetValue` / `SetValue`)存在约 16 cycle/次 的桥接延迟,是早期版本与分桶方案的主要瓶颈(`aiv_scalar_ratio > 0.94`)。因此最终版本彻底消除标量对数值 UB 的读写,将全部数值展开/归约/转换移入 `PIPE_V`: | ||
| 107 | + - **FP32 核 `KernelAxpyiFp32`**: | ||
| 108 | + - 双缓冲 `MTE2` 顺序载入 `TILE_NN = 2048` 的 `xVal` 与 `xInd`; | ||
| 109 | + - `PIPE_V` 执行 `Muls(deltaF32, valLocal, alpha)`;对于 `int64` 索引且 `yElems <= 2^31-1`,利用 `PIPE_V` `GatherMask` 将 64 位索引压缩为紧凑 32 位索引; | ||
| 110 | + - 采用 2 组 256 槽位(`256 × 32B = 8 KiB × 2`)乒乓缓冲,`PIPE_V` 调用硬件 **`Brcb`** 指令以 **8 floats/cycle** 将连续 256 个 `deltaF32` 展开至 256 个独立 32B 槽位(零标量值搬运); | ||
| 111 | + - 标量侧以 `uint64_t` 成对读取索引(每 2 个索引仅 1 次 UB 读,读流量减半),直接寄存器派发 4 路展开的 `DataCopyPad(4B)` + `SetAtomicAdd<float>()`,消除栈数组溢写,实测 `10M/500k` `aiv_mte3_ratio` 高达 **95.2%**。 | ||
| 112 | + - **FP16 / BF16 核 `KernelAxpyiLowPrec`**: | ||
| 113 | + - `PIPE_V` 预计算 `deltaF32 = alpha * Cast<float>(xVal)`,并在入口以 `CreateVecIndex + Muls(32)` 一次性生成 `[0, 32, 64, ..., 127×32]` 字节偏移表; | ||
| 114 | + - 采用 **3 级全异步硬件事件流水(`3 × 128 × 32B = 12 KiB`)**:批次 `b` 的 `MTE2` 读 `ySrc`(`SetFlag<MTE2_V>`)→ 批次 `b-1` 的 `PIPE_V` 执行 `Gather → Cast(FP32) → Add → Cast(RNE) → Brcb`(`SetFlag<V_MTE3>`)→ 批次 `b-2` 的 `MTE3` 写 `yDst`(`SetFlag<MTE3_MTE2>`),标量侧不等待任何数值引擎、不读写任何数值 UB,实测相比标量累加版本提速 **4.1×**。 | ||
| 115 | +2. **`arch35` SIMT Kernel 设计**: | ||
| 116 | + - `AxpyiSimtCompute<ValT, IdxT>`:4 路展开 Grid-Stride Loop,每个 SIMT 线程独立执行 `static_cast<ValT>(alpha * static_cast<float>(values[i]) + static_cast<float>(yVec[pos]))`; | ||
| 117 | + - `AxpyiCopySimtCompute<RawT>`:按原始整型字宽(`uint32_t` / `uint16_t`)执行逐位一致并行拷贝。 | ||
| 118 | + | ||
| 119 | +## 支持硬件 | ||
| 120 | + | ||
| 121 | +| 支持的芯片版本 | 涉及勾选 | 架构目录 | | ||
| 122 | +| --- | --- | --- | | ||
| 123 | +| Atlas A2 系列(Ascend 910B) | √ | `sparse/axpyi/arch22/` | | ||
| 124 | +| Atlas A3 系列(Ascend 910_93 / 910C) | √ | `sparse/axpyi/arch22/` | | ||
| 125 | +| Ascend 950PR / 950DT(Ascend 950) | √ | `sparse/axpyi/arch35/` | | ||
| 126 | + | ||
| 127 | +## 算子约束限制 | ||
| 128 | + | ||
| 129 | +1. 所有输入张量必须位于同一 NPU 设备;`x_val` 与 `y` dtype 须一致且属于 `{float32, float16, bfloat16}`,`x_ind` dtype 须属于 `{int32, int64}`。 | ||
| 130 | +2. `x_ind` 中 `nnz` 个下标须互不重复且落在 `[0, N)`(1-based 模式为 `[1, N]`);重复索引属未定义行为。 | ||
| 131 | +3. C 接口 `vecY.stride` 须为 1;输出 `yDst` 不可与 `xVal` / `xInd` 发生内存重叠。 | ||
| 132 | + | ||
| 133 | +--- | ||
| 134 | + | ||
| 135 | +# 可维可测分析 | ||
| 136 | + | ||
| 137 | +## 精度标准 / 性能标准 | ||
| 138 | + | ||
| 139 | +| 验收标准 | 描述 | 标准来源 | | ||
| 140 | +| --- | --- | --- | | ||
| 141 | +| 精度标准 | `fp32`: rtol ≤ 1e-4, atol ≤ 1e-5;`fp16`: rtol ≤ 1e-3, atol ≤ 1e-3;`bf16`: rtol ≤ 5e-3, atol ≤ 5e-3;`alpha = 0` / `nnz = 0` 逐位一致;参考真值为 CPU `aclsparse_axpyi_cpu` | 任务书第 7 节 & 生态算子开源精度标准 | | ||
| 142 | +| 功能标准 | 完整覆盖 TC-01 ~ TC-11 与跨核同 32B cache line 防撕裂专项测试 | 任务书第 5 节 | | ||
| 143 | +| 性能标准 | 覆盖 8 组规模 × 3 种主力 dtype = 24 测试点,与同机 `torch_npu` 基线及 RTX 5880 标杆同口径(NPUGraph / Device Event)比对 | 任务书第 6 节 | | ||
| 144 | + | ||
| 145 | +## 自测验证结果汇总 | ||
| 146 | + | ||
| 147 | +### 1. 功能与精度测试结果(100% PASS) | ||
| 148 | + | ||
| 149 | +- **测试硬件与软件**:Atlas A3(Ascend 910_93,CANN 9.1.0,PyTorch 2.10.0,`torch_npu 2.10.0.post4`)及 CANN 内置 Ascend 950 周期级模拟器 `dav_3510/camodel`(`Ascend950PR_9589`)。 | ||
| 150 | +- **Ascend 950 (`arch35`) 模拟器验证**:`bash build.sh --soc=ascend950 --ops=axpyi` 编译 0 错,在 `dav_3510/camodel` 上 **9/9 PASS**(覆盖 `fp32/fp16/bf16 × i32/i64 × base0/base1`、`empty_nnz`、`alpha_zero_fp16`、`degenerate_1_1_bf16`,单次 kernel 执行周期 550–4,308 cycles)。 | ||
| 151 | +- **Atlas A3 (`arch22`) C++ 单元测试**:**18/18 PASS**(覆盖错误路径、全 dtype/index 组合、非对齐尾块、异地 `aclsparseAxpyiRaw`、3 组跨核同 32B Cache Line 防撕裂对抗测试、4 组 5M 大规模压力测试)。 | ||
| 152 | +- **官方 `test_aclsparseAxpyi.py`(未修改)**:**43/43 PASS**(6.59s)。 | ||
| 153 | +- **全量 TC-01 ~ TC-11 `test_aclsparseAxpyi_full.py`**:**80/80 PASS**(7.85s,含 `bf16`、`alpha=0` 逐位一致、乱序索引、空输入、`N=1` 退化、非连续视图、`N=10^7, nnz=5×10^5` 压力与非法参数异常)。 | ||
| 154 | + | ||
| 155 | +### 2. Atlas A3 实测性能结果(24 组规模 × dtype)与 `msprof` 管线剖析 | ||
| 156 | + | ||
| 157 | +| N | nnz | idx | dtype | `aclsparse_axpyi` NPUGraph (ms) | `aclsparse_axpyi` Eager (ms) | 同机 `torch_npu` `y.index_add` (ms) | 相对 `torch_npu` 加速比 | RTX 5880 标杆 (ms) | 相对 5880 倍率 | | ||
| 158 | +| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | | ||
| 159 | +| 100,000 | 1,000 | int32 | fp32 | 0.0068 | 0.0510 | 0.0835 | 12.28× | 0.0035 | 0.51× | | ||
| 160 | +| 100,000 | 1,000 | int32 | fp16 | 0.0074 | 0.0516 | 0.0934 | 12.62× | 0.0040 | 0.54× | | ||
| 161 | +| 100,000 | 1,000 | int32 | bf16 | 0.0074 | 0.0513 | 0.0943 | 12.74× | 0.0036 | 0.49× | | ||
| 162 | +| 100,000 | 10,000 | int32 | fp32 | 0.0087 | 0.0506 | 0.1605 | 18.45× | 0.0029 | 0.33× | | ||
| 163 | +| 100,000 | 10,000 | int32 | fp16 | 0.0125 | 0.0516 | 0.0986 | 7.89× | 0.0032 | 0.26× | | ||
| 164 | +| 100,000 | 10,000 | int32 | bf16 | 0.0126 | 0.0511 | 0.0994 | 7.89× | 0.0040 | 0.32× | | ||
| 165 | +| 1,000,000 | 10,000 | int32 | fp32 | 0.0111 | 0.0493 | 0.1690 | 15.23× | 0.0029 | 0.26× | | ||
| 166 | +| 1,000,000 | 10,000 | int32 | fp16 | 0.0128 | 0.0514 | 0.0981 | 7.66× | 0.0032 | 0.25× | | ||
| 167 | +| 1,000,000 | 10,000 | int32 | bf16 | 0.0129 | 0.0507 | 0.0981 | 7.60× | 0.0037 | 0.29× | | ||
| 168 | +| 1,000,000 | 50,000 | int32 | fp32 | 0.0197 | 0.0506 | 0.7531 | 38.23× | 0.0032 | 0.16× | | ||
| 169 | +| 1,000,000 | 50,000 | int32 | fp16 | 0.0346 | 0.0510 | 0.4070 | 11.76× | 0.0036 | 0.10× | | ||
| 170 | +| 1,000,000 | 50,000 | int32 | bf16 | 0.0348 | 0.0510 | 0.4142 | 11.90× | 0.0047 | 0.14× | | ||
| 171 | +| 1,000,000 | 100,000 | int64 | fp32 | 0.0308 | 0.0480 | 1.4927 | 48.46× | 0.0040 | 0.13× | | ||
| 172 | +| 1,000,000 | 100,000 | int64 | fp16 | 0.0623 | 0.0621 | 0.7805 | 12.53× | 0.0043 | 0.07× | | ||
| 173 | +| 1,000,000 | 100,000 | int64 | bf16 | 0.0623 | 0.0620 | 0.7924 | 12.72× | 0.0061 | 0.10× | | ||
| 174 | +| 5,000,000 | 50,000 | int32 | fp32 | 0.0362 | 0.0488 | 0.7686 | 21.23× | 0.0032 | 0.09× | | ||
| 175 | +| 5,000,000 | 50,000 | int32 | fp16 | 0.0414 | 0.0499 | 0.4046 | 9.77× | 0.0036 | 0.09× | | ||
| 176 | +| 5,000,000 | 50,000 | int32 | bf16 | 0.0413 | 0.0518 | 0.4105 | 9.94× | 0.0044 | 0.11× | | ||
| 177 | +| 5,000,000 | 250,000 | int32 | fp32 | 0.0793 | 0.0780 | 3.7040 | 46.71× | 0.0060 | 0.08× | | ||
| 178 | +| 5,000,000 | 250,000 | int32 | fp16 | 0.1506 | 0.1503 | 1.8971 | 12.60× | 0.0063 | 0.04× | | ||
| 179 | +| 5,000,000 | 250,000 | int32 | bf16 | 0.1507 | 0.1501 | 1.8990 | 12.60× | 0.0102 | 0.07× | | ||
| 180 | +| 10,000,000 | 500,000 | int64 | fp32 | 0.1678 | 0.1686 | 7.4033 | 44.12× | 0.0125 | 0.07× | | ||
| 181 | +| 10,000,000 | 500,000 | int64 | fp16 | 0.2954 | 0.2959 | 3.7535 | 12.71× | 0.0098 | 0.03× | | ||
| 182 | +| 10,000,000 | 500,000 | int64 | bf16 | 0.2960 | 0.2964 | 3.7546 | 12.68× | 0.0158 | 0.05× | | ||
| 183 | + | ||
| 184 | +**`msprof` 硬件饱和度分析**: | ||
| 185 | +- 在 `10M / 500k fp32` 场景下,`axpyi_copy_kernel` 耗时仅 **23.86 µs**(`mte2=0.736, mte3=0.829`,对应 3.5+ TB/s L2 带宽),`axpyi_fp32_kernel` 耗时 **115.46 µs**(**`aiv_mte3_ratio = 0.952`,MTE3 随机原子写管线利用率达 95.2% 硬件极限**),较同机 `torch_npu` `y.index_add`(7.403 ms)提速 **44.1×**; | ||
| 186 | +- 在 `1M / 100k fp32` 场景下,`axpyi_fp32_kernel` 耗时 **25.16 µs**(`aiv_mte3_ratio = 0.912`),较同机 `torch_npu` 提速 **48.5×**; | ||
| 187 | +- 在 `10M / 500k bf16` 场景下,`axpyi_lowprec_kernel` 耗时由 v3 标量版 1,101 µs 优化至 **283.4 µs**(提速 3.9×,较 `torch_npu` 提速 **12.7×**); | ||
| 188 | +- 说明:`dav-2201`(Atlas A2/A3)无硬件 SIMT 随机散射引擎,大 `nnz` 随机单元素写回物理上受限于 40 AIV 核 MTE3 事务发射上限(约 9.2 ns/元素/核,本实现已逼近 95% 硬件极限),而 Ascend 950(`arch35`)原生 SIMT 核支持万级线程并行随机访存。 | ||
| 189 | + | ||
| 190 | +## 兼容性分析 | ||
| 191 | + | ||
| 192 | +新增独立算子 `aclsparseAxpyi` / `aclsparseAxpyiRaw` / `torch_npu.sparse.aclsparse_axpyi`,不修改仓内任何已有算子的接口与二进制 ABI,严格遵循 `ops-sparse` 多架构目录并存规范与 `torch_extension` 自动注册机制。 | ||
| @@ -207,6 +207,7 @@ | |||
| 207 | | [aclsparseSnnz](../../sparse/nnz/README.md#aclsparsesnnz) | 统计稠密矩阵每行/列及总非零元素个数(FP32) | | 207 | | [aclsparseSnnz](../../sparse/nnz/README.md#aclsparsesnnz) | 统计稠密矩阵每行/列及总非零元素个数(FP32) | |
| 208 | | [aclsparseGatherRaw](../../sparse/gather/README.md) | Gather 原始形式:按索引与基址收集元素(无描述符) | | 208 | | [aclsparseGatherRaw](../../sparse/gather/README.md) | Gather 原始形式:按索引与基址收集元素(无描述符) | |
| 209 | | [aclsparseScatter](../../sparse/scatter/README.md#aclsparsescatter) | 按稀疏索引将向量散射写入稠密向量 | | 209 | | [aclsparseScatter](../../sparse/scatter/README.md#aclsparsescatter) | 按稀疏索引将向量散射写入稠密向量 | |
| 210 | +| [aclsparseAxpyi](../../sparse/axpyi/README.md#aclsparseaxpyi) | 稀疏向量缩放累加到稠密向量(Y[idx] += alpha * X) | | ||
| 210 | | [aclsparseSpvv](../../sparse/spvv/) | 稀疏向量点积(SpVV) | | 211 | | [aclsparseSpvv](../../sparse/spvv/) | 稀疏向量点积(SpVV) | |
| 211 | 212 | ||
| 212 | ## 接口详情 | 213 | ## 接口详情 |
| @@ -3181,6 +3181,52 @@ aclsparseStatus_t aclsparseSpGEMM(aclsparseHandle_t handle, aclsparseOperation_t | |||
| 3181 | const void* beta, aclsparseSpMatDescr_t matC, aclDataType computeType, | 3181 | const void* beta, aclsparseSpMatDescr_t matC, aclDataType computeType, |
| 3182 | aclsparseSpGEMMAlg_t alg, void* buffer); | 3182 | aclsparseSpGEMMAlg_t alg, void* buffer); |
| 3183 | 3183 | ||
| 3184 | + | ||
| 3185 | +// ============================================================================ | ||
| 3186 | +// Generic API: aclsparseAxpyi | ||
| 3187 | +// ============================================================================ | ||
| 3188 | + | ||
| 3189 | +/** | ||
| 3190 | + * @brief Perform sparse vector scaled addition into a dense vector: | ||
| 3191 | + * Y[X.indices[k] - idxBase] += alpha * X.values[k], k in [0, X.nnz). | ||
| 3192 | + * | ||
| 3193 | + * Internal accumulation is performed in float32 with a single rounding to | ||
| 3194 | + * valueType. Requires distinct indices in vecX; alpha == 0 or nnz == 0 leaves | ||
| 3195 | + * vecY bitwise unchanged. Asynchronous on handle's stream, zero workspace. | ||
| 3196 | + * | ||
| 3197 | + * @param handle IN, HOST, aclsparse handle. | ||
| 3198 | + * @param alpha IN, HOST/DEVICE, pointer to float32 scalar alpha (per handle pointerMode). | ||
| 3199 | + * @param vecX IN, HOST, const sparse vector descriptor (FP32/FP16/BF16, I32/I64). | ||
| 3200 | + * @param vecY IN/OUT, HOST, dense vector descriptor (valueType matches vecX). | ||
| 3201 | + * @return aclsparseStatus_t | ||
| 3202 | + */ | ||
| 3203 | +aclsparseStatus_t aclsparseAxpyi(aclsparseHandle_t handle, const void* alpha, aclsparseConstSpVecDescr_t vecX, | ||
| 3204 | + aclsparseDnVecDescr_t vecY); | ||
| 3205 | + | ||
| 3206 | +/** | ||
| 3207 | + * @brief Raw-pointer fast path for aclsparseAxpyi (skips descriptor create/destroy). | ||
| 3208 | + * | ||
| 3209 | + * When ySrcPtr == yDstPtr performs in-place update; when ySrcPtr != yDstPtr copies | ||
| 3210 | + * ySrcPtr to yDstPtr asynchronously before applying scaled scatter-add so ySrcPtr is | ||
| 3211 | + * never mutated. | ||
| 3212 | + * | ||
| 3213 | + * @param handle IN, HOST, aclsparse handle. | ||
| 3214 | + * @param alpha IN, HOST, float32 scalar scaling factor. | ||
| 3215 | + * @param xValPtr IN, DEVICE, sparse non-zero values pointer (length nnz). | ||
| 3216 | + * @param xIndPtr IN, DEVICE, sparse indices pointer (length nnz, I32/I64). | ||
| 3217 | + * @param ySrcPtr IN, DEVICE, source dense vector pointer (length yLen). | ||
| 3218 | + * @param yDstPtr OUT, DEVICE, destination dense vector pointer (length yLen). | ||
| 3219 | + * @param yLen IN, HOST, dense vector length N (>= 0). | ||
| 3220 | + * @param nnz IN, HOST, number of non-zero elements (0 <= nnz <= yLen). | ||
| 3221 | + * @param valueType IN, HOST, ACL_FLOAT / ACL_FLOAT16 / ACL_BF16. | ||
| 3222 | + * @param idxType IN, HOST, ACL_SPARSE_INDEX_32I / ACL_SPARSE_INDEX_64I. | ||
| 3223 | + * @param idxBase IN, HOST, ACL_SPARSE_INDEX_BASE_ZERO / ACL_SPARSE_INDEX_BASE_ONE. | ||
| 3224 | + * @return aclsparseStatus_t | ||
| 3225 | + */ | ||
| 3226 | +aclsparseStatus_t aclsparseAxpyiRaw(aclsparseHandle_t handle, float alpha, const void* xValPtr, const void* xIndPtr, | ||
| 3227 | + const void* ySrcPtr, void* yDstPtr, int64_t yLen, int64_t nnz, | ||
| 3228 | + aclDataType valueType, aclsparseIndexType_t idxType, | ||
| 3229 | + aclsparseIndexBase_t idxBase); | ||
| 3184 | #ifdef __cplusplus | 3230 | #ifdef __cplusplus |
| 3185 | } | 3231 | } |
| 3186 | #endif | 3232 | #endif |
| @@ -0,0 +1,307 @@ | |||
| 1 | +# Axpyi 算子 | ||
| 2 | + | ||
| 3 | +## 算子概述 | ||
| 4 | + | ||
| 5 | +`aclsparseAxpyi` 算子对标稀疏 BLAS Level-1 标准接口(Netlib `cblas_?axpyi` / cuSPARSE `cusparseAxpby` 稀疏-稠密缩放累加语义),将稀疏向量 `X`(由非零元下标 `xInd` 与非零值 `xVal` 组成,非零元个数 `nnz`)乘以标量系数 `alpha` 后累加到稠密向量 `Y`(长度 `N`)的指定索引位置。 | ||
| 6 | + | ||
| 7 | +数学表达式: | ||
| 8 | + | ||
| 9 | +``` | ||
| 10 | +y[xInd[k] - idxBase] = alpha * xVal[k] + y[xInd[k] - idxBase], k ∈ [0, nnz) | ||
| 11 | +``` | ||
| 12 | + | ||
| 13 | +关键语义说明: | ||
| 14 | + | ||
| 15 | +- **累加精度**:所有支持数据类型(`FP32` / `FP16` / `BF16`)内部统一采用 **FP32 累加、末端单次舍入**;`alpha == 0.0f` 或 `nnz == 0` 时输出与输入 `Y` **逐位一致**(无 `+0/-0` 或舍入漂移)。 | ||
| 16 | +- **idxBase 处理**:`ACL_SPARSE_INDEX_BASE_ZERO` 直接使用 `xInd[k]`;`ACL_SPARSE_INDEX_BASE_ONE` 内部自动减 1。 | ||
| 17 | +- **索引顺序与互异性**:允许 `xInd` 乱序,算子不依赖排序假设;调用方须保证 `xInd` 的 `nnz` 个下标互不重复(重复索引属未定义行为)。 | ||
| 18 | +- **C API vs PyTorch API 内存语义**: | ||
| 19 | + - C 接口 `aclsparseAxpyi` 按标准 Sparse BLAS 约定**原地更新** `vecY`; | ||
| 20 | + - C 底层扩展接口 `aclsparseAxpyiRaw` 同时支持原地(`ySrcPtr == yDstPtr`)与异地(`ySrcPtr != yDstPtr`); | ||
| 21 | + - PyTorch 封装接口 `torch_npu.sparse.aclsparse_axpyi(alpha, x_val, x_ind, y)` 按值返回新张量 `out`,**不修改**调用方传入的 `y`,并自动对非连续输入调用 `.contiguous()`。 | ||
| 22 | + | ||
| 23 | +包含以下接口: | ||
| 24 | + | ||
| 25 | +| 接口名 | 功能简述 | | ||
| 26 | +|--------|---------| | ||
| 27 | +| `aclsparseAxpyi` | Generic C API(描述符模式),原地计算 `vecY[vecX.indices[k] - idxBase] += alpha * vecX.values[k]` | | ||
| 28 | +| `aclsparseAxpyiRaw` | 低开销 C API(原始指针模式),支持原地或异地输出,供 PyTorch 封装层直接调用 | | ||
| 29 | +| `torch_npu.sparse.aclsparse_axpyi` | PyTorch NPU 封装接口,按值返回更新后的新张量 `out`(不修改输入 `y`) | | ||
| 30 | + | ||
| 31 | +## 算子执行接口 | ||
| 32 | + | ||
| 33 | +### aclsparseAxpyi | ||
| 34 | + | ||
| 35 | +#### 产品支持情况 | ||
| 36 | + | ||
| 37 | +- Ascend 950PR&950DT系列产品:支持(`arch35` / `dav-3510` SIMT 核) | ||
| 38 | +- Atlas A3系列产品:支持(`arch22` / `dav-2201` Ascend C 矢量/原子核) | ||
| 39 | +- Atlas A2系列产品:支持(`arch22` / `dav-2201` Ascend C 矢量/原子核) | ||
| 40 | + | ||
| 41 | +#### 函数原型 | ||
| 42 | + | ||
| 43 | +```cpp | ||
| 44 | +aclsparseStatus_t aclsparseAxpyi(aclsparseHandle_t handle, const void *alpha, aclsparseConstSpVecDescr_t vecX, aclsparseDnVecDescr_t vecY) | ||
| 45 | +``` | ||
| 46 | + | ||
| 47 | +#### 参数说明 | ||
| 48 | + | ||
| 49 | +| 参数名 | 输入/输出 | 参数类型 | 说明 | | ||
| 50 | +|--------|----------|---------|------| | ||
| 51 | +| handle | 输入 | aclsparseHandle_t | ops-sparse 库上下文句柄,须绑定 stream,不可为 nullptr;Host 内存 | | ||
| 52 | +| alpha | 输入 | const void*(指向 `float` 标量) | 缩放系数指针;内存位置由 `aclsparseSetPointerMode` 控制,支持 Host/Device 内存 | | ||
| 53 | +| vecX | 输入 | aclsparseConstSpVecDescr_t | 输入稀疏向量描述符(只读,含 `size`、`nnz`、`indices`、`values`、`idxType`、`idxBase`、`valueType`);描述符在 Host 内存,数据指针在 Device 内存 | | ||
| 54 | +| vecY | 输入/输出 | aclsparseDnVecDescr_t | 目标稠密向量描述符(原地更新 `vecY.values`);描述符在 Host 内存,数据指针在 Device 内存 | | ||
| 55 | + | ||
| 56 | +#### 支持的数据类型与索引类型 | ||
| 57 | + | ||
| 58 | +| 数据类型 | aclDataType | PyTorch dtype | 累加路径 | | ||
| 59 | +|----------|-------------|---------------|----------| | ||
| 60 | +| FP32 | `ACL_FLOAT` | `torch.float32` | FP32 内部累加 | | ||
| 61 | +| FP16 | `ACL_FLOAT16` | `torch.float16` | FP32 内部累加,末端单次舍入 | | ||
| 62 | +| BF16 | `ACL_BF16` | `torch.bfloat16` | FP32 内部累加,末端单次舍入 | | ||
| 63 | + | ||
| 64 | +| 索引类型 | aclsparseIndexType_t | PyTorch dtype | 说明 | | ||
| 65 | +|----------|----------------------|---------------|------| | ||
| 66 | +| I32 | `ACL_SPARSE_INDEX_32I` | `torch.int32` | 32 位有符号整数索引(arch22 / arch35 均支持) | | ||
| 67 | +| I64 | `ACL_SPARSE_INDEX_64I` | `torch.int64` | 64 位有符号整数索引(arch22 / arch35 均支持) | | ||
| 68 | + | ||
| 69 | +| 索引基址 | aclsparseIndexBase_t | 说明 | | ||
| 70 | +|----------|----------------------|------| | ||
| 71 | +| ZERO | `ACL_SPARSE_INDEX_BASE_ZERO` | 0-based 索引,`indices[k]` 直接作为 `Y` 下标 | | ||
| 72 | +| ONE | `ACL_SPARSE_INDEX_BASE_ONE` | 1-based 索引,内部访问 `Y` 时减 1 | | ||
| 73 | + | ||
| 74 | +#### 约束说明 | ||
| 75 | + | ||
| 76 | +- `handle`、`alpha`、`vecX`、`vecY` 均不可为 nullptr(`handle == nullptr` 返回 `ACL_SPARSE_STATUS_HANDLE_IS_NULLPTR`,其余返回 `ACL_SPARSE_STATUS_INVALID_VALUE`)。 | ||
| 77 | +- `vecX.valueType` 须与 `vecY.valueType` 一致,且属于 `{ACL_FLOAT, ACL_FLOAT16, ACL_BF16}`;`vecX.idxType` 须属于 `{ACL_SPARSE_INDEX_32I, ACL_SPARSE_INDEX_64I}`,否则返回 `ACL_SPARSE_STATUS_NOT_SUPPORTED`。 | ||
| 78 | +- `vecY.stride` 须为 1;`vecX.size <= vecY.nums` 且 `vecX.nnz <= vecX.size`。 | ||
| 79 | +- 索引须互不重复且满足 `indices[k] - idxBase ∈ [0, vecY.nums)`;C 接口 Host 侧不读取 Device 内存校验索引值域,PyTorch 封装层在 Host/Device 入口执行 `[0, N)` 边界校验(带 tensor version 缓存,不增加稳态耗时)。 | ||
| 80 | +- `nnz == 0` 或 `alpha == 0.0f` 时直接保持 `vecY` 逐位不变;支持空张量(`N == 0`、`nnz == 0`)与非 32B 对齐尾块。 | ||
| 81 | +- 输出 `vecY.values` 不可与 `vecX.values` 或 `vecX.indices` 内存区间重叠。 | ||
| 82 | +- 无需额外 workspace;函数异步入队至 `handle` 绑定的 stream,调用方通过 `aclrtSynchronizeStream` 同步。 | ||
| 83 | + | ||
| 84 | +#### 支持的稀疏格式 | ||
| 85 | + | ||
| 86 | +| 格式 | 支持 | 说明 | | ||
| 87 | +|------|------|------| | ||
| 88 | +| SpVec(稀疏向量) | ✅ | 索引数组 `indices[nnz]` + 值数组 `values[nnz]`(1D 稀疏向量,对应 `aclsparseConstSpVecDescr_t`) | | ||
| 89 | +| DnVec(稠密向量) | ✅ | 1D 连续稠密向量 `values[N]`(对应 `aclsparseDnVecDescr_t`,`stride == 1`) | | ||
| 90 | +| CSR / COO / CSC | ❌ | 本算子为 Sparse BLAS Level-1 向量算子,不涉及 2D 稀疏矩阵格式 | | ||
| 91 | + | ||
| 92 | +#### 返回值 | ||
| 93 | + | ||
| 94 | +| 返回值 | 含义 | | ||
| 95 | +|--------|------| | ||
| 96 | +| `ACL_SPARSE_STATUS_SUCCESS` | 执行成功(含 `nnz == 0` / `alpha == 0` 快速路径) | | ||
| 97 | +| `ACL_SPARSE_STATUS_HANDLE_IS_NULLPTR` | `handle` 为 nullptr | | ||
| 98 | +| `ACL_SPARSE_STATUS_INVALID_VALUE` | 参数指针为空、描述符签名非法、`idxBase` 非法、形状非法或输入输出内存别名重叠 | | ||
| 99 | +| `ACL_SPARSE_STATUS_NOT_SUPPORTED` | 不支持的 `valueType` / `idxType`、`vecX`/`vecY` 类型不一致或 `stride != 1` | | ||
| 100 | +| `ACL_SPARSE_STATUS_EXECUTION_FAILED` | 核函数入队或执行失败 | | ||
| 101 | +| `ACL_SPARSE_STATUS_INTERNAL_ERROR` | 内部 ACL 调用失败或设备可用核数为 0 | | ||
| 102 | + | ||
| 103 | +#### 调用示例(C++) | ||
| 104 | + | ||
| 105 | +示例代码如下,仅供参考,具体编译和执行过程请参考[编译与运行样例](../../docs/zh/develop/compile_and_run_example.md)。 | ||
| 106 | + | ||
| 107 | +```cpp | ||
| 108 | +#include <cstdint> | ||
| 109 | +#include <cstdio> | ||
| 110 | +#include <memory> | ||
| 111 | +#include <vector> | ||
| 112 | + | ||
| 113 | +#include "acl/acl.h" | ||
| 114 | +#include "cann_ops_sparse.h" | ||
| 115 | + | ||
| 116 | +#define CHECK_RET(cond, return_expr) \ | ||
| 117 | + do { \ | ||
| 118 | + if (!(cond)) { \ | ||
| 119 | + return_expr; \ | ||
| 120 | + } \ | ||
| 121 | + } while (0) | ||
| 122 | + | ||
| 123 | +#define LOG_PRINT(message, ...) \ | ||
| 124 | + do { \ | ||
| 125 | + printf(message, ##__VA_ARGS__); \ | ||
| 126 | + } while (0) | ||
| 127 | + | ||
| 128 | +class AclContext { | ||
| 129 | +public: | ||
| 130 | + explicit AclContext(int32_t deviceId) : deviceId_(deviceId) {} | ||
| 131 | + | ||
| 132 | + ~AclContext() | ||
| 133 | + { | ||
| 134 | + if (stream_ != nullptr) { | ||
| 135 | + aclrtDestroyStream(stream_); | ||
| 136 | + stream_ = nullptr; | ||
| 137 | + } | ||
| 138 | + if (deviceSet_) { | ||
| 139 | + aclrtResetDevice(deviceId_); | ||
| 140 | + deviceSet_ = false; | ||
| 141 | + } | ||
| 142 | + if (aclInited_) { | ||
| 143 | + aclFinalize(); | ||
| 144 | + aclInited_ = false; | ||
| 145 | + } | ||
| 146 | + } | ||
| 147 | + | ||
| 148 | + int Init() | ||
| 149 | + { | ||
| 150 | + auto ret = aclInit(nullptr); | ||
| 151 | + CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclInit failed. ERROR: %d\n", ret); return ret); | ||
| 152 | + aclInited_ = true; | ||
| 153 | + | ||
| 154 | + ret = aclrtSetDevice(deviceId_); | ||
| 155 | + CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtSetDevice failed. ERROR: %d\n", ret); return ret); | ||
| 156 | + deviceSet_ = true; | ||
| 157 | + | ||
| 158 | + ret = aclrtCreateStream(&stream_); | ||
| 159 | + CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtCreateStream failed. ERROR: %d\n", ret); return ret); | ||
| 160 | + return ACL_SUCCESS; | ||
| 161 | + } | ||
| 162 | + | ||
| 163 | + aclrtStream Stream() const { return stream_; } | ||
| 164 | + | ||
| 165 | +private: | ||
| 166 | + int32_t deviceId_; | ||
| 167 | + aclrtStream stream_ = nullptr; | ||
| 168 | + bool aclInited_ = false; | ||
| 169 | + bool deviceSet_ = false; | ||
| 170 | +}; | ||
| 171 | + | ||
| 172 | +using DevicePtr = std::unique_ptr<void, aclError (*)(void *)>; | ||
| 173 | +using ConstSpVecPtr = std::unique_ptr<const aclsparseSpVecDescr, | ||
| 174 | + aclsparseStatus_t (*)(aclsparseConstSpVecDescr_t)>; | ||
| 175 | +using DnVecPtr = std::unique_ptr<aclsparseDnVecDescr, | ||
| 176 | + aclsparseStatus_t (*)(aclsparseConstDnVecDescr_t)>; | ||
| 177 | + | ||
| 178 | +static DevicePtr AllocAndCopyDevice(const void *hostPtr, size_t sizeBytes) | ||
| 179 | +{ | ||
| 180 | + void *rawPtr = nullptr; | ||
| 181 | + auto ret = aclrtMalloc(&rawPtr, sizeBytes, ACL_MEM_MALLOC_HUGE_FIRST); | ||
| 182 | + CHECK_RET(ret == ACL_SUCCESS, return DevicePtr(nullptr, aclrtFree)); | ||
| 183 | + DevicePtr devPtr(rawPtr, aclrtFree); | ||
| 184 | + if (hostPtr != nullptr && sizeBytes > 0) { | ||
| 185 | + ret = aclrtMemcpy(devPtr.get(), sizeBytes, hostPtr, sizeBytes, ACL_MEMCPY_HOST_TO_DEVICE); | ||
| 186 | + CHECK_RET(ret == ACL_SUCCESS, return DevicePtr(nullptr, aclrtFree)); | ||
| 187 | + } | ||
| 188 | + return devPtr; | ||
| 189 | +} | ||
| 190 | + | ||
| 191 | +int aclsparseAxpyiExample(AclContext &ctx) | ||
| 192 | +{ | ||
| 193 | + aclrtStream stream = ctx.Stream(); | ||
| 194 | + | ||
| 195 | + // 1. 创建句柄并绑定 stream 与 PointerMode | ||
| 196 | + aclsparseHandle_t rawHandle = nullptr; | ||
| 197 | + auto sparseRet = aclsparseCreate(&rawHandle); | ||
| 198 | + CHECK_RET(sparseRet == ACL_SPARSE_STATUS_SUCCESS, return sparseRet); | ||
| 199 | + std::unique_ptr<aclsparseContext, aclsparseStatus_t (*)(aclsparseHandle_t)> handlePtr(rawHandle, aclsparseDestroy); | ||
| 200 | + | ||
| 201 | + sparseRet = aclsparseSetStream(handlePtr.get(), stream); | ||
| 202 | + CHECK_RET(sparseRet == ACL_SPARSE_STATUS_SUCCESS, return sparseRet); | ||
| 203 | + sparseRet = aclsparseSetPointerMode(handlePtr.get(), ACL_SPARSE_POINTER_MODE_HOST); | ||
| 204 | + CHECK_RET(sparseRet == ACL_SPARSE_STATUS_SUCCESS, return sparseRet); | ||
| 205 | + | ||
| 206 | + // 2. 准备数据:Y = [10, 10, 10, 10, 10, 10], X.ind = [0, 2, 5], X.val = [1, 2, 3], alpha = 2.0 | ||
| 207 | + const int64_t yLen = 6; | ||
| 208 | + const int64_t nnz = 3; | ||
| 209 | + const float alpha = 2.0f; | ||
| 210 | + std::vector<int32_t> hIndices = {0, 2, 5}; | ||
| 211 | + std::vector<float> hXValues = {1.0f, 2.0f, 3.0f}; | ||
| 212 | + std::vector<float> hYValues = {10.0f, 10.0f, 10.0f, 10.0f, 10.0f, 10.0f}; | ||
| 213 | + | ||
| 214 | + DevicePtr dIndices = AllocAndCopyDevice(hIndices.data(), nnz * sizeof(int32_t)); | ||
| 215 | + DevicePtr dXValues = AllocAndCopyDevice(hXValues.data(), nnz * sizeof(float)); | ||
| 216 | + DevicePtr dYValues = AllocAndCopyDevice(hYValues.data(), yLen * sizeof(float)); | ||
| 217 | + CHECK_RET(dIndices && dXValues && dYValues, return ACL_SPARSE_STATUS_INTERNAL_ERROR); | ||
| 218 | + | ||
| 219 | + // 3. 创建稀疏向量与稠密向量描述符 | ||
| 220 | + aclsparseConstSpVecDescr_t vecX = nullptr; | ||
| 221 | + sparseRet = aclsparseCreateConstSpVec(&vecX, yLen, nnz, dIndices.get(), dXValues.get(), | ||
| 222 | + ACL_SPARSE_INDEX_32I, ACL_SPARSE_INDEX_BASE_ZERO, ACL_FLOAT); | ||
| 223 | + CHECK_RET(sparseRet == ACL_SPARSE_STATUS_SUCCESS, return sparseRet); | ||
| 224 | + ConstSpVecPtr vecXPtr(vecX, aclsparseDestroySpVec); | ||
| 225 | + | ||
| 226 | + aclsparseDnVecDescr_t vecY = nullptr; | ||
| 227 | + sparseRet = aclsparseCreateDnVec(&vecY, yLen, dYValues.get(), ACL_FLOAT); | ||
| 228 | + CHECK_RET(sparseRet == ACL_SPARSE_STATUS_SUCCESS, return sparseRet); | ||
| 229 | + DnVecPtr vecYPtr(vecY, aclsparseDestroyDnVec); | ||
| 230 | + | ||
| 231 | + // 4. 执行 aclsparseAxpyi | ||
| 232 | + sparseRet = aclsparseAxpyi(handlePtr.get(), &alpha, vecXPtr.get(), vecYPtr.get()); | ||
| 233 | + CHECK_RET(sparseRet == ACL_SPARSE_STATUS_SUCCESS, return sparseRet); | ||
| 234 | + | ||
| 235 | + auto aclRet = aclrtSynchronizeStream(stream); | ||
| 236 | + CHECK_RET(aclRet == ACL_SUCCESS, return ACL_SPARSE_STATUS_EXECUTION_FAILED); | ||
| 237 | + | ||
| 238 | + // 5. 拷贝结果回 Host 并打印 | ||
| 239 | + std::vector<float> hOut(yLen, 0.0f); | ||
| 240 | + aclRet = aclrtMemcpy(hOut.data(), yLen * sizeof(float), dYValues.get(), yLen * sizeof(float), | ||
| 241 | + ACL_MEMCPY_DEVICE_TO_HOST); | ||
| 242 | + CHECK_RET(aclRet == ACL_SUCCESS, return ACL_SPARSE_STATUS_EXECUTION_FAILED); | ||
| 243 | + | ||
| 244 | + LOG_PRINT("Result Y after aclsparseAxpyi:\n "); | ||
| 245 | + for (int64_t i = 0; i < yLen; ++i) { | ||
| 246 | + LOG_PRINT("%.1f ", hOut[i]); | ||
| 247 | + } | ||
| 248 | + LOG_PRINT("\n"); | ||
| 249 | + return ACL_SPARSE_STATUS_SUCCESS; | ||
| 250 | +} | ||
| 251 | + | ||
| 252 | +int main() | ||
| 253 | +{ | ||
| 254 | + AclContext ctx(0); | ||
| 255 | + auto ret = ctx.Init(); | ||
| 256 | + CHECK_RET(ret == ACL_SUCCESS, return ret); | ||
| 257 | + return aclsparseAxpyiExample(ctx); | ||
| 258 | +} | ||
| 259 | +``` | ||
| 260 | + | ||
| 261 | +预期输出如下: | ||
| 262 | + | ||
| 263 | +``` | ||
| 264 | +Result Y after aclsparseAxpyi: | ||
| 265 | + 12.0 10.0 14.0 10.0 10.0 16.0 | ||
| 266 | +``` | ||
| 267 | + | ||
| 268 | +--- | ||
| 269 | + | ||
| 270 | +### torch_npu.sparse.aclsparse_axpyi(PyTorch 接口) | ||
| 271 | + | ||
| 272 | +#### 函数原型 | ||
| 273 | + | ||
| 274 | +```python | ||
| 275 | +def aclsparse_axpyi(alpha: float, x_val: torch.Tensor, x_ind: torch.Tensor, y: torch.Tensor) -> torch.Tensor | ||
| 276 | +``` | ||
| 277 | + | ||
| 278 | +#### 参数说明 | ||
| 279 | + | ||
| 280 | +| 参数名 | 输入/输出 | 类型 | 说明 | | ||
| 281 | +|--------|----------|------|------| | ||
| 282 | +| `alpha` | 输入 | `float` | 标量缩放系数 | | ||
| 283 | +| `x_val` | 输入 | `torch.Tensor` | 1D NPU 张量,长度 `nnz`,dtype 为 `float32` / `float16` / `bfloat16` | | ||
| 284 | +| `x_ind` | 输入 | `torch.Tensor` | 1D NPU 张量,长度 `nnz`,dtype 为 `int32` / `int64`,值域 `[0, N)` 且互不重复 | | ||
| 285 | +| `y` | 输入 | `torch.Tensor` | 1D NPU 张量,长度 `N`,dtype 与 `x_val` 一致(**不被修改**) | | ||
| 286 | +| 返回值 `out` | 输出 | `torch.Tensor` | 1D 连续 NPU 张量,长度 `N`,dtype 与设备同 `y` | | ||
| 287 | + | ||
| 288 | +#### 调用示例(Python) | ||
| 289 | + | ||
| 290 | +```python | ||
| 291 | +import torch | ||
| 292 | +import torch_npu # noqa: F401 | ||
| 293 | +import cann_ops_sparse # noqa: F401 # 自动挂载 torch_npu.sparse.aclsparse_axpyi | ||
| 294 | + | ||
| 295 | +x_val = torch.tensor([1.0, 2.0, 3.0], dtype=torch.float32, device="npu") | ||
| 296 | +x_ind = torch.tensor([0, 2, 5], dtype=torch.int32, device="npu") | ||
| 297 | +y = torch.full((6,), 10.0, dtype=torch.float32, device="npu") | ||
| 298 | + | ||
| 299 | +out = torch_npu.sparse.aclsparse_axpyi(2.0, x_val, x_ind, y) | ||
| 300 | +print(out.cpu().tolist()) # [12.0, 10.0, 14.0, 10.0, 10.0, 16.0] | ||
| 301 | +``` | ||
| 302 | + | ||
| 303 | +预期输出如下: | ||
| 304 | + | ||
| 305 | +``` | ||
| 306 | +[12.0, 10.0, 14.0, 10.0, 10.0, 16.0] | ||
| 307 | +``` | ||
| @@ -0,0 +1,316 @@ | |||
| 1 | +/** | ||
| 2 | + * ---------------------------------------------------------------------------------------------------------- | ||
| 3 | + * Copyright (c) 2026 Huawei Technologies Co., Ltd. | ||
| 4 | + * This program is free software; you can redistribute it and/or modify it under the terms and conditions of | ||
| 5 | + * the CANN Open Software License Agreement Version 2.0 (the "License"). | ||
| 6 | + * Please refer to the License for details. You may not use this file except in compliance with the License. | ||
| 7 | + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | ||
| 8 | + * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | ||
| 9 | + * See LICENSE in the root of the software repository for the full text of the License. | ||
| 10 | + * ---------------------------------------------------------------------------------------------------------- | ||
| 11 | + */ | ||
| 12 | + | ||
| 13 | +/*! | ||
| 14 | + * \file axpyi_host.cpp | ||
| 15 | + * \brief aclsparseAxpyi & aclsparseAxpyiRaw Host implementation for Atlas A2/A3 (arch22). | ||
| 16 | + */ | ||
| 17 | + | ||
| 18 | +#include <algorithm> | ||
| 19 | +#include <cstdint> | ||
| 20 | + | ||
| 21 | +#include "cann_ops_sparse.h" | ||
| 22 | +#include "aclsparse_descr_internal.h" | ||
| 23 | +#include "aclsparse_handle_internal.h" | ||
| 24 | +#include "aclsparse_host_utils.h" | ||
| 25 | +#include "axpyi_tiling_data.h" | ||
| 26 | +#include "axpyi_kernel.h" | ||
| 27 | + | ||
| 28 | +namespace { | ||
| 29 | + | ||
| 30 | +constexpr const char *kAxpyiTag = "aclsparseAxpyi"; | ||
| 31 | +constexpr uint64_t kMinCopyBytesPerCore = 2048ull; | ||
| 32 | +constexpr uint64_t kMinNnzPerCore = 16ull; | ||
| 33 | + | ||
| 34 | +inline uint32_t AxpyiElemBytes(aclDataType t) | ||
| 35 | +{ | ||
| 36 | + switch (t) { | ||
| 37 | + case ACL_FLOAT: | ||
| 38 | + return 4u; | ||
| 39 | + case ACL_FLOAT16: | ||
| 40 | + case ACL_BF16: | ||
| 41 | + return 2u; | ||
| 42 | + default: | ||
| 43 | + return 0u; | ||
| 44 | + } | ||
| 45 | +} | ||
| 46 | + | ||
| 47 | +inline int32_t AxpyiMapValType(aclDataType t) | ||
| 48 | +{ | ||
| 49 | + switch (t) { | ||
| 50 | + case ACL_FLOAT: | ||
| 51 | + return AXPYI_VAL_FP32; | ||
| 52 | + case ACL_FLOAT16: | ||
| 53 | + return AXPYI_VAL_FP16; | ||
| 54 | + case ACL_BF16: | ||
| 55 | + return AXPYI_VAL_BF16; | ||
| 56 | + default: | ||
| 57 | + return -1; | ||
| 58 | + } | ||
| 59 | +} | ||
| 60 | + | ||
| 61 | +inline bool AxpyiRangesOverlap(const void *a, uint64_t aBytes, const void *b, uint64_t bBytes) | ||
| 62 | +{ | ||
| 63 | + if (a == nullptr || b == nullptr || aBytes == 0 || bBytes == 0) { | ||
| 64 | + return false; | ||
| 65 | + } | ||
| 66 | + uintptr_t ua = reinterpret_cast<uintptr_t>(a); | ||
| 67 | + uintptr_t ub = reinterpret_cast<uintptr_t>(b); | ||
| 68 | + return (ua < ub + bBytes) && (ub < ua + aBytes); | ||
| 69 | +} | ||
| 70 | + | ||
| 71 | +inline uint32_t GetCachedAivCoreCount() | ||
| 72 | +{ | ||
| 73 | + static uint32_t cached = 0u; | ||
| 74 | + if (cached != 0u) { | ||
| 75 | + return cached; | ||
| 76 | + } | ||
| 77 | + uint32_t cores = GetAivCoreCount(); | ||
| 78 | + int32_t deviceId = 0; | ||
| 79 | + if (aclrtGetDevice(&deviceId) == ACL_SUCCESS) { | ||
| 80 | + int64_t devCores = 0; | ||
| 81 | + if (aclrtGetDeviceInfo(deviceId, ACL_DEV_ATTR_VECTOR_CORE_NUM, &devCores) == ACL_SUCCESS && | ||
| 82 | + devCores > 0) { | ||
| 83 | + uint32_t devCoresU32 = static_cast<uint32_t>(devCores); | ||
| 84 | + if (devCoresU32 > cores) { | ||
| 85 | + cores = devCoresU32; | ||
| 86 | + } | ||
| 87 | + } | ||
| 88 | + } | ||
| 89 | + if (cores == 0u) { | ||
| 90 | + cores = 40u; | ||
| 91 | + } | ||
| 92 | + cached = cores; | ||
| 93 | + return cached; | ||
| 94 | +} | ||
| 95 | + | ||
| 96 | +aclsparseStatus_t LaunchAxpyiInternal( | ||
| 97 | + aclsparseContext *handleInner, | ||
| 98 | + float alphaVal, | ||
| 99 | + const void *xValPtr, | ||
| 100 | + const void *xIndPtr, | ||
| 101 | + const void *ySrcPtr, | ||
| 102 | + void *yDstPtr, | ||
| 103 | + int64_t yLen, | ||
| 104 | + int64_t nnz, | ||
| 105 | + aclDataType valueType, | ||
| 106 | + aclsparseIndexType_t idxType, | ||
| 107 | + aclsparseIndexBase_t idxBase) | ||
| 108 | +{ | ||
| 109 | + const int32_t valTypeCode = AxpyiMapValType(valueType); | ||
| 110 | + const uint32_t elemBytes = AxpyiElemBytes(valueType); | ||
| 111 | + if (valTypeCode < 0 || elemBytes == 0u) { | ||
| 112 | + OP_LOGE(kAxpyiTag, "unsupported valueType %d (only FP32/FP16/BF16)", static_cast<int>(valueType)); | ||
| 113 | + return ACL_SPARSE_STATUS_NOT_SUPPORTED; | ||
| 114 | + } | ||
| 115 | + if (idxType != ACL_SPARSE_INDEX_32I && idxType != ACL_SPARSE_INDEX_64I) { | ||
| 116 | + OP_LOGE(kAxpyiTag, "unsupported idxType %d (only I32/I64)", static_cast<int>(idxType)); | ||
| 117 | + return ACL_SPARSE_STATUS_NOT_SUPPORTED; | ||
| 118 | + } | ||
| 119 | + if (idxBase != ACL_SPARSE_INDEX_BASE_ZERO && idxBase != ACL_SPARSE_INDEX_BASE_ONE) { | ||
| 120 | + OP_LOGE(kAxpyiTag, "invalid idxBase %d", static_cast<int>(idxBase)); | ||
| 121 | + return ACL_SPARSE_STATUS_INVALID_VALUE; | ||
| 122 | + } | ||
| 123 | + if (yLen < 0 || nnz < 0 || nnz > yLen) { | ||
| 124 | + OP_LOGE(kAxpyiTag, "invalid dimensions: yLen=%ld, nnz=%ld", | ||
| 125 | + static_cast<long>(yLen), static_cast<long>(nnz)); | ||
| 126 | + return ACL_SPARSE_STATUS_INVALID_VALUE; | ||
| 127 | + } | ||
| 128 | + | ||
| 129 | + aclrtStream stream = handleInner->stream; | ||
| 130 | + const uint32_t availableCores = GetCachedAivCoreCount(); | ||
| 131 | + const uint64_t yBytes = static_cast<uint64_t>(yLen) * elemBytes; | ||
| 132 | + | ||
| 133 | + // 1. Out-of-place copy via AIV bulk DataCopy (full AIV-to-L2/HBM bandwidth, bit-exact). | ||
| 134 | + if (ySrcPtr != yDstPtr && yLen > 0) { | ||
[Major] 异地模式只判断指针不等,未校验 ySrc/yDst 区间部分重叠
![]() ![]() | |||
| 135 | + if (ySrcPtr == nullptr || yDstPtr == nullptr) { | ||
| 136 | + OP_LOGE(kAxpyiTag, "null ySrcPtr or yDstPtr for yLen=%ld", static_cast<long>(yLen)); | ||
| 137 | + return ACL_SPARSE_STATUS_INVALID_VALUE; | ||
| 138 | + } | ||
| 139 | + uint64_t neededCopyBlocks = (yBytes + kMinCopyBytesPerCore - 1ull) / kMinCopyBytesPerCore; | ||
| 140 | + uint32_t copyBlocks = static_cast<uint32_t>( | ||
| 141 | + std::min<uint64_t>(static_cast<uint64_t>(availableCores), neededCopyBlocks)); | ||
| 142 | + if (copyBlocks == 0u) { | ||
| 143 | + copyBlocks = 1u; | ||
| 144 | + } | ||
| 145 | + uint64_t rawPerCore = (yBytes + copyBlocks - 1ull) / copyBlocks; | ||
| 146 | + uint64_t bytesPerCore = (rawPerCore + 31ull) & ~31ull; | ||
| 147 | + if (bytesPerCore == 0ull) { | ||
| 148 | + bytesPerCore = 32ull; | ||
| 149 | + } | ||
| 150 | + copyBlocks = static_cast<uint32_t>((yBytes + bytesPerCore - 1ull) / bytesPerCore); | ||
| 151 | + if (copyBlocks == 0u) { | ||
| 152 | + copyBlocks = 1u; | ||
| 153 | + } | ||
| 154 | + | ||
| 155 | + uintptr_t srcAddr = reinterpret_cast<uintptr_t>(ySrcPtr); | ||
| 156 | + uintptr_t dstAddr = reinterpret_cast<uintptr_t>(yDstPtr); | ||
| 157 | + | ||
| 158 | + AxpyiCopyTilingData copyTiling{}; | ||
| 159 | + copyTiling.totalBytes = yBytes; | ||
| 160 | + copyTiling.bytesPerCore = bytesPerCore; | ||
| 161 | + copyTiling.blockNum = copyBlocks; | ||
| 162 | + copyTiling.alignedBase = (((srcAddr | dstAddr) & 31u) == 0u) ? 1 : 0; | ||
| 163 | + | ||
| 164 | + (void)aclrtGetLastError(ACL_RT_THREAD_LEVEL); | ||
| 165 | + axpyi_copy_kernel_do( | ||
| 166 | + reinterpret_cast<GM_ADDR>(const_cast<void *>(ySrcPtr)), | ||
| 167 | + reinterpret_cast<GM_ADDR>(yDstPtr), | ||
| 168 | + copyTiling, | ||
| 169 | + stream); | ||
| 170 | + if (aclrtPeekAtLastError(ACL_RT_THREAD_LEVEL) != ACL_SUCCESS) { | ||
| 171 | + OP_LOGE(kAxpyiTag, "copy kernel enqueue failed: %d", | ||
| 172 | + static_cast<int>(aclrtPeekAtLastError(ACL_RT_THREAD_LEVEL))); | ||
| 173 | + return ACL_SPARSE_STATUS_EXECUTION_FAILED; | ||
| 174 | + } | ||
| 175 | + } | ||
| 176 | + | ||
| 177 | + // Early exit: nnz == 0 or alpha == 0.0f guarantees bitwise-identical Y. | ||
| 178 | + if (nnz == 0 || alphaVal == 0.0f) { | ||
| 179 | + return ACL_SPARSE_STATUS_SUCCESS; | ||
| 180 | + } | ||
| 181 | + | ||
| 182 | + if (xValPtr == nullptr || xIndPtr == nullptr || ySrcPtr == nullptr || yDstPtr == nullptr) { | ||
| 183 | + OP_LOGE(kAxpyiTag, "null data pointer for nnz=%ld", static_cast<long>(nnz)); | ||
| 184 | + return ACL_SPARSE_STATUS_INVALID_VALUE; | ||
| 185 | + } | ||
| 186 | + | ||
| 187 | + const uint64_t valBytes = static_cast<uint64_t>(nnz) * elemBytes; | ||
| 188 | + const uint64_t idxElemBytes = (idxType == ACL_SPARSE_INDEX_64I) ? sizeof(int64_t) : sizeof(int32_t); | ||
| 189 | + const uint64_t idxBytes = static_cast<uint64_t>(nnz) * idxElemBytes; | ||
| 190 | + if (AxpyiRangesOverlap(yDstPtr, yBytes, xValPtr, valBytes) || | ||
[Major] 内存别名校验发生在 copy kernel 入队之后,校验形同虚设 L134-L174 已经根据 ySrcPtr != yDstPtr 异步入队了 ![]() ![]() | |||
| 191 | + AxpyiRangesOverlap(yDstPtr, yBytes, xIndPtr, idxBytes)) { | ||
| 192 | + OP_LOGE(kAxpyiTag, "undeclared alias between output Y and sparse vector X"); | ||
| 193 | + return ACL_SPARSE_STATUS_INVALID_VALUE; | ||
| 194 | + } | ||
| 195 | + | ||
| 196 | + // 2. NNZ-partitioned sparse scatter-add across AIV cores. | ||
| 197 | + const uint64_t nnzU64 = static_cast<uint64_t>(nnz); | ||
| 198 | + uint64_t neededBlocks = (nnzU64 + kMinNnzPerCore - 1ull) / kMinNnzPerCore; | ||
| 199 | + uint32_t blockNum = static_cast<uint32_t>( | ||
| 200 | + std::min<uint64_t>(static_cast<uint64_t>(availableCores), neededBlocks)); | ||
| 201 | + if (blockNum == 0u) { | ||
| 202 | + blockNum = 1u; | ||
| 203 | + } | ||
| 204 | + | ||
| 205 | + AxpyiTilingData tiling{}; | ||
| 206 | + tiling.nnz = nnzU64; | ||
| 207 | + tiling.yElems = static_cast<uint64_t>(yLen); | ||
| 208 | + tiling.alpha = alphaVal; | ||
| 209 | + tiling.blockNum = blockNum; | ||
| 210 | + tiling.idxBase = (idxBase == ACL_SPARSE_INDEX_BASE_ONE) ? 1 : 0; | ||
| 211 | + tiling.valType = valTypeCode; | ||
| 212 | + tiling.idxType = (idxType == ACL_SPARSE_INDEX_64I) ? AXPYI_IDX_I64 : AXPYI_IDX_I32; | ||
| 213 | + | ||
| 214 | + (void)aclrtGetLastError(ACL_RT_THREAD_LEVEL); | ||
| 215 | + axpyi_kernel_do( | ||
| 216 | + reinterpret_cast<GM_ADDR>(const_cast<void *>(xValPtr)), | ||
| 217 | + reinterpret_cast<GM_ADDR>(const_cast<void *>(xIndPtr)), | ||
| 218 | + reinterpret_cast<GM_ADDR>(const_cast<void *>(ySrcPtr)), | ||
| 219 | + reinterpret_cast<GM_ADDR>(yDstPtr), | ||
| 220 | + tiling, | ||
| 221 | + stream); | ||
| 222 | + if (aclrtPeekAtLastError(ACL_RT_THREAD_LEVEL) != ACL_SUCCESS) { | ||
| 223 | + OP_LOGE(kAxpyiTag, "kernel enqueue failed: %d", | ||
| 224 | + static_cast<int>(aclrtPeekAtLastError(ACL_RT_THREAD_LEVEL))); | ||
| 225 | + return ACL_SPARSE_STATUS_EXECUTION_FAILED; | ||
| 226 | + } | ||
| 227 | + return ACL_SPARSE_STATUS_SUCCESS; | ||
| 228 | +} | ||
| 229 | + | ||
| 230 | +} // namespace | ||
| 231 | + | ||
| 232 | +extern "C" aclsparseStatus_t aclsparseAxpyiRaw( | ||
| 233 | + aclsparseHandle_t handle, | ||
| 234 | + float alpha, | ||
| 235 | + const void *xValPtr, | ||
| 236 | + const void *xIndPtr, | ||
| 237 | + const void *ySrcPtr, | ||
| 238 | + void *yDstPtr, | ||
| 239 | + int64_t yLen, | ||
| 240 | + int64_t nnz, | ||
| 241 | + aclDataType valueType, | ||
| 242 | + aclsparseIndexType_t idxType, | ||
| 243 | + aclsparseIndexBase_t idxBase) | ||
| 244 | +{ | ||
| 245 | + if (handle == nullptr) { | ||
| 246 | + return ACL_SPARSE_STATUS_HANDLE_IS_NULLPTR; | ||
| 247 | + } | ||
| 248 | + auto *handleInner = reinterpret_cast<aclsparseContext *>(handle); | ||
| 249 | + if (handleInner->signature != kAclSparseHandleSignature) { | ||
| 250 | + return ACL_SPARSE_STATUS_INVALID_VALUE; | ||
| 251 | + } | ||
| 252 | + return LaunchAxpyiInternal( | ||
| 253 | + handleInner, alpha, xValPtr, xIndPtr, ySrcPtr, yDstPtr, yLen, nnz, | ||
| 254 | + valueType, idxType, idxBase); | ||
| 255 | +} | ||
| 256 | + | ||
| 257 | +extern "C" aclsparseStatus_t aclsparseAxpyi( | ||
| 258 | + aclsparseHandle_t handle, | ||
| 259 | + const void *alpha, | ||
| 260 | + aclsparseConstSpVecDescr_t vecX, | ||
| 261 | + aclsparseDnVecDescr_t vecY) | ||
| 262 | +{ | ||
| 263 | + if (handle == nullptr) { | ||
| 264 | + return ACL_SPARSE_STATUS_HANDLE_IS_NULLPTR; | ||
| 265 | + } | ||
| 266 | + auto *handleInner = reinterpret_cast<aclsparseContext *>(handle); | ||
| 267 | + if (handleInner->signature != kAclSparseHandleSignature) { | ||
| 268 | + return ACL_SPARSE_STATUS_INVALID_VALUE; | ||
| 269 | + } | ||
| 270 | + if (alpha == nullptr || vecX == nullptr || vecY == nullptr) { | ||
| 271 | + OP_LOGE(kAxpyiTag, "null alpha, vecX, or vecY"); | ||
| 272 | + return ACL_SPARSE_STATUS_INVALID_VALUE; | ||
| 273 | + } | ||
| 274 | + | ||
| 275 | + const auto *xInner = reinterpret_cast<const aclsparseSpVecDescr *>(vecX); | ||
| 276 | + auto *yInner = reinterpret_cast<aclsparseDnVecDescr *>(vecY); | ||
| 277 | + if (xInner->signature != kSpVecSignature || yInner->signature != kDnVecSignature) { | ||
| 278 | + OP_LOGE(kAxpyiTag, "invalid descriptor signature"); | ||
| 279 | + return ACL_SPARSE_STATUS_INVALID_VALUE; | ||
| 280 | + } | ||
| 281 | + if (xInner->valueType != yInner->valueType) { | ||
| 282 | + OP_LOGE(kAxpyiTag, "valueType mismatch: vecX=%d vs vecY=%d", | ||
| 283 | + static_cast<int>(xInner->valueType), static_cast<int>(yInner->valueType)); | ||
| 284 | + return ACL_SPARSE_STATUS_NOT_SUPPORTED; | ||
| 285 | + } | ||
| 286 | + if (yInner->stride != 1) { | ||
| 287 | + OP_LOGE(kAxpyiTag, "unsupported dense vector stride %ld (only stride=1)", | ||
| 288 | + static_cast<long>(yInner->stride)); | ||
| 289 | + return ACL_SPARSE_STATUS_NOT_SUPPORTED; | ||
| 290 | + } | ||
| 291 | + if (xInner->size > yInner->nums || xInner->nnz > xInner->size) { | ||
| 292 | + OP_LOGE(kAxpyiTag, "invalid shape: vecX.nnz=%llu, vecX.size=%llu, vecY.nums=%llu", | ||
| 293 | + static_cast<unsigned long long>(xInner->nnz), | ||
| 294 | + static_cast<unsigned long long>(xInner->size), | ||
| 295 | + static_cast<unsigned long long>(yInner->nums)); | ||
| 296 | + return ACL_SPARSE_STATUS_INVALID_VALUE; | ||
| 297 | + } | ||
| 298 | + | ||
| 299 | + float alphaVal = 0.0f; | ||
| 300 | + if (handleInner->pointerMode == ACL_SPARSE_POINTER_MODE_DEVICE) { | ||
| 301 | + if (handleInner->stream != nullptr) { | ||
| 302 | + CHECK_ACL(aclrtSynchronizeStream(handleInner->stream)); | ||
| 303 | + } | ||
| 304 | + CHECK_ACL(aclrtMemcpy(&alphaVal, sizeof(float), alpha, sizeof(float), ACL_MEMCPY_DEVICE_TO_HOST)); | ||
| 305 | + } else { | ||
| 306 | + alphaVal = *reinterpret_cast<const float *>(alpha); | ||
| 307 | + } | ||
| 308 | + | ||
| 309 | + return LaunchAxpyiInternal( | ||
| 310 | + handleInner, alphaVal, | ||
| 311 | + xInner->values, xInner->indices, | ||
| 312 | + yInner->values, yInner->values, | ||
| 313 | + static_cast<int64_t>(yInner->nums), | ||
| 314 | + static_cast<int64_t>(xInner->nnz), | ||
| 315 | + xInner->valueType, xInner->idxType, xInner->idxBase); | ||
| 316 | +} | ||
| @@ -0,0 +1,42 @@ | |||
| 1 | +/** | ||
| 2 | + * ---------------------------------------------------------------------------------------------------------- | ||
| 3 | + * Copyright (c) 2026 Huawei Technologies Co., Ltd. | ||
| 4 | + * This program is free software; you can redistribute it and/or modify it under the terms and conditions of | ||
| 5 | + * the CANN Open Software License Agreement Version 2.0 (the "License"). | ||
| 6 | + * Please refer to the License for details. You may not use this file except in compliance with the License. | ||
| 7 | + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | ||
| 8 | + * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | ||
| 9 | + * See LICENSE in the root of the software repository for the full text of the License. | ||
| 10 | + * ---------------------------------------------------------------------------------------------------------- | ||
| 11 | + */ | ||
| 12 | + | ||
| 13 | +/*! | ||
| 14 | + * \file axpyi_kernel.h | ||
| 15 | + * \brief aclsparseAxpyi kernel launcher declarations for Atlas A2/A3 (arch22 / dav-2201). | ||
| 16 | + */ | ||
| 17 | + | ||
| 18 | +#ifndef AXPYI_ARCH22_KERNEL_H_ | ||
| 19 | +#define AXPYI_ARCH22_KERNEL_H_ | ||
| 20 | + | ||
| 21 | +#include <stdint.h> | ||
| 22 | +#include "axpyi_tiling_data.h" | ||
| 23 | + | ||
| 24 | +#ifndef GM_ADDR | ||
| 25 | +#define GM_ADDR uint8_t * | ||
| 26 | +#endif | ||
| 27 | + | ||
| 28 | +void axpyi_copy_kernel_do( | ||
| 29 | + GM_ADDR ySrcDev, | ||
| 30 | + GM_ADDR yDstDev, | ||
| 31 | + const AxpyiCopyTilingData &tiling, | ||
| 32 | + void *stream); | ||
| 33 | + | ||
| 34 | +void axpyi_kernel_do( | ||
| 35 | + GM_ADDR valDev, | ||
| 36 | + GM_ADDR idxDev, | ||
| 37 | + GM_ADDR ySrcDev, | ||
| 38 | + GM_ADDR yDstDev, | ||
| 39 | + const AxpyiTilingData &tiling, | ||
| 40 | + void *stream); | ||
| 41 | + | ||
| 42 | +#endif // AXPYI_ARCH22_KERNEL_H_ | ||
| @@ -0,0 +1,55 @@ | |||
| 1 | +/** | ||
| 2 | + * ---------------------------------------------------------------------------------------------------------- | ||
| 3 | + * Copyright (c) 2026 Huawei Technologies Co., Ltd. | ||
| 4 | + * This program is free software; you can redistribute it and/or modify it under the terms and conditions of | ||
| 5 | + * the CANN Open Software License Agreement Version 2.0 (the "License"). | ||
| 6 | + * Please refer to the License for details. You may not use this file except in compliance with the License. | ||
| 7 | + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | ||
| 8 | + * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | ||
| 9 | + * See LICENSE in the root of the software repository for the full text of the License. | ||
| 10 | + * ---------------------------------------------------------------------------------------------------------- | ||
| 11 | + */ | ||
| 12 | + | ||
| 13 | +/*! | ||
| 14 | + * \file axpyi_tiling_data.h | ||
| 15 | + * \brief aclsparseAxpyi TilingData for Atlas A2/A3 (arch22 / dav-2201). | ||
| 16 | + */ | ||
| 17 | + | ||
| 18 | +#ifndef AXPYI_ARCH22_TILING_DATA_H_ | ||
| 19 | +#define AXPYI_ARCH22_TILING_DATA_H_ | ||
| 20 | + | ||
| 21 | +#include <stdint.h> | ||
| 22 | + | ||
| 23 | +constexpr uint32_t AXPYI_BUFFER_NUM = 2u; | ||
| 24 | +constexpr uint32_t AXPYI_COPY_CHUNK_BYTES = 64u * 1024u; // 64 KiB x 2 double-buffered AIV copy | ||
| 25 | +constexpr uint32_t AXPYI_TILE_NN = 2048u; // Multiple of 256 for Brcb + PIPE_V | ||
| 26 | +constexpr uint32_t AXPYI_FP32_BATCH = 256u; // 256 x 32B = 8 KiB x 2 ping-pong slots | ||
| 27 | +constexpr uint32_t AXPYI_FP16_BATCH = 128u; // 128 x 32B = 4 KiB x 3 pipeline slots | ||
| 28 | +constexpr uint32_t AXPYI_FP16_STAGES = 3u; // 3-stage async MTE2 || PIPE_V || MTE3 | ||
| 29 | +constexpr uint32_t AXPYI_SLOT_BYTES = 32u; // 32B UB alignment per DataCopyPad slot | ||
| 30 | + | ||
| 31 | +constexpr int32_t AXPYI_VAL_FP32 = 0; | ||
| 32 | +constexpr int32_t AXPYI_VAL_FP16 = 1; | ||
| 33 | +constexpr int32_t AXPYI_VAL_BF16 = 2; | ||
| 34 | + | ||
| 35 | +constexpr int32_t AXPYI_IDX_I32 = 0; | ||
| 36 | +constexpr int32_t AXPYI_IDX_I64 = 1; | ||
| 37 | + | ||
| 38 | +struct AxpyiCopyTilingData { | ||
| 39 | + uint64_t totalBytes; | ||
| 40 | + uint64_t bytesPerCore; // 32B-aligned slice size per core | ||
| 41 | + uint32_t blockNum; | ||
| 42 | + int32_t alignedBase; // 1 if both ySrc and yDst are 32B-aligned | ||
| 43 | +}; | ||
| 44 | + | ||
| 45 | +struct AxpyiTilingData { | ||
| 46 | + uint64_t nnz; | ||
| 47 | + uint64_t yElems; | ||
| 48 | + float alpha; | ||
| 49 | + uint32_t blockNum; | ||
| 50 | + int32_t idxBase; | ||
| 51 | + int32_t valType; | ||
| 52 | + int32_t idxType; | ||
| 53 | +}; | ||
| 54 | + | ||
| 55 | +#endif // AXPYI_ARCH22_TILING_DATA_H_ | ||
| @@ -0,0 +1,288 @@ | |||
| 1 | +/** | ||
| 2 | + * ---------------------------------------------------------------------------------------------------------- | ||
| 3 | + * Copyright (c) 2026 Huawei Technologies Co., Ltd. | ||
| 4 | + * This program is free software; you can redistribute it and/or modify it under the terms and conditions of | ||
| 5 | + * the CANN Open Software License Agreement Version 2.0 (the "License"). | ||
| 6 | + * Please refer to the License for details. You may not use this file except in compliance with the License. | ||
| 7 | + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | ||
| 8 | + * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | ||
| 9 | + * See LICENSE in the root of the software repository for the full text of the License. | ||
| 10 | + * ---------------------------------------------------------------------------------------------------------- | ||
| 11 | + */ | ||
| 12 | + | ||
| 13 | +/*! | ||
| 14 | + * \file axpyi_host.cpp | ||
| 15 | + * \brief aclsparseAxpyi & aclsparseAxpyiRaw Host implementation for Ascend 950 (arch35). | ||
| 16 | + */ | ||
| 17 | + | ||
| 18 | +#include <algorithm> | ||
| 19 | +#include <cstdint> | ||
| 20 | +#include <limits> | ||
| 21 | + | ||
| 22 | +#include "log/log.h" | ||
| 23 | +#include "cann_ops_sparse.h" | ||
| 24 | +#include "aclsparse_handle_internal.h" | ||
| 25 | +#include "aclsparse_descr_internal.h" | ||
| 26 | +#include "aclsparse_host_utils.h" | ||
| 27 | +#include "axpyi_tiling_data.h" | ||
| 28 | +#include "axpyi_kernel.h" | ||
| 29 | + | ||
| 30 | +namespace { | ||
| 31 | + | ||
| 32 | +constexpr const char *kAxpyiTag = "aclsparseAxpyi"; | ||
| 33 | + | ||
| 34 | +inline uint32_t AxpyiElemBytes(aclDataType t) | ||
| 35 | +{ | ||
| 36 | + switch (t) { | ||
| 37 | + case ACL_FLOAT: | ||
| 38 | + return 4u; | ||
| 39 | + case ACL_FLOAT16: | ||
| 40 | + case ACL_BF16: | ||
| 41 | + return 2u; | ||
| 42 | + default: | ||
| 43 | + return 0u; | ||
| 44 | + } | ||
| 45 | +} | ||
| 46 | + | ||
| 47 | +inline int32_t AxpyiMapValType(aclDataType t) | ||
| 48 | +{ | ||
| 49 | + switch (t) { | ||
| 50 | + case ACL_FLOAT: | ||
| 51 | + return AXPYI_VAL_FP32; | ||
| 52 | + case ACL_FLOAT16: | ||
| 53 | + return AXPYI_VAL_FP16; | ||
| 54 | + case ACL_BF16: | ||
| 55 | + return AXPYI_VAL_BF16; | ||
| 56 | + default: | ||
| 57 | + return -1; | ||
| 58 | + } | ||
| 59 | +} | ||
| 60 | + | ||
| 61 | +inline bool AxpyiRangesOverlap(const void *a, uint64_t aBytes, const void *b, uint64_t bBytes) | ||
| 62 | +{ | ||
| 63 | + if (a == nullptr || b == nullptr || aBytes == 0 || bBytes == 0) { | ||
| 64 | + return false; | ||
| 65 | + } | ||
| 66 | + uintptr_t ua = reinterpret_cast<uintptr_t>(a); | ||
| 67 | + uintptr_t ub = reinterpret_cast<uintptr_t>(b); | ||
| 68 | + return (ua < ub + bBytes) && (ub < ua + aBytes); | ||
| 69 | +} | ||
| 70 | + | ||
| 71 | +aclsparseStatus_t LaunchAxpyiInternal( | ||
| 72 | + aclsparseContext *handleInner, | ||
| 73 | + float alphaVal, | ||
| 74 | + const void *xValPtr, | ||
| 75 | + const void *xIndPtr, | ||
| 76 | + const void *ySrcPtr, | ||
| 77 | + void *yDstPtr, | ||
| 78 | + int64_t yLen, | ||
| 79 | + int64_t nnz, | ||
| 80 | + aclDataType valueType, | ||
| 81 | + aclsparseIndexType_t idxType, | ||
| 82 | + aclsparseIndexBase_t idxBase) | ||
| 83 | +{ | ||
| 84 | + const int32_t valTypeCode = AxpyiMapValType(valueType); | ||
| 85 | + const uint32_t elemBytes = AxpyiElemBytes(valueType); | ||
| 86 | + if (valTypeCode < 0 || elemBytes == 0u) { | ||
| 87 | + OP_LOGE(kAxpyiTag, "unsupported valueType %d (only FP32/FP16/BF16)", static_cast<int>(valueType)); | ||
| 88 | + return ACL_SPARSE_STATUS_NOT_SUPPORTED; | ||
| 89 | + } | ||
| 90 | + if (idxType != ACL_SPARSE_INDEX_32I && idxType != ACL_SPARSE_INDEX_64I) { | ||
| 91 | + OP_LOGE(kAxpyiTag, "unsupported idxType %d (only I32/I64)", static_cast<int>(idxType)); | ||
| 92 | + return ACL_SPARSE_STATUS_NOT_SUPPORTED; | ||
| 93 | + } | ||
| 94 | + if (idxBase != ACL_SPARSE_INDEX_BASE_ZERO && idxBase != ACL_SPARSE_INDEX_BASE_ONE) { | ||
| 95 | + OP_LOGE(kAxpyiTag, "invalid idxBase %d", static_cast<int>(idxBase)); | ||
| 96 | + return ACL_SPARSE_STATUS_INVALID_VALUE; | ||
| 97 | + } | ||
| 98 | + if (yLen < 0 || nnz < 0 || nnz > yLen) { | ||
| 99 | + OP_LOGE(kAxpyiTag, "invalid dimensions: yLen=%ld, nnz=%ld", | ||
| 100 | + static_cast<long>(yLen), static_cast<long>(nnz)); | ||
| 101 | + return ACL_SPARSE_STATUS_INVALID_VALUE; | ||
| 102 | + } | ||
| 103 | + | ||
| 104 | + aclrtStream stream = handleInner->stream; | ||
| 105 | + uint32_t aivCoreNum = GetAivCoreCount(); | ||
| 106 | + if (aivCoreNum == 0u) { | ||
| 107 | + OP_LOGE(kAxpyiTag, "GetAivCoreCount returned 0"); | ||
| 108 | + return ACL_SPARSE_STATUS_INTERNAL_ERROR; | ||
| 109 | + } | ||
| 110 | + | ||
| 111 | + // Out-of-place bitwise-exact copy via SIMT AIV cores (avoids SDMA engine switch & camodel SDMA stall). | ||
| 112 | + if (ySrcPtr != yDstPtr && yLen > 0) { | ||
| 113 | + if (ySrcPtr == nullptr || yDstPtr == nullptr) { | ||
| 114 | + OP_LOGE(kAxpyiTag, "null ySrcPtr or yDstPtr for yLen=%ld", static_cast<long>(yLen)); | ||
| 115 | + return ACL_SPARSE_STATUS_INVALID_VALUE; | ||
| 116 | + } | ||
| 117 | + const uint64_t yU64 = static_cast<uint64_t>(yLen); | ||
| 118 | + const uint32_t copyThreads = (yU64 < kAxpyiSmallNnzThreshold) | ||
| 119 | + ? kAxpyiSmallThreadsPerBlock | ||
| 120 | + : kAxpyiMaxThreadsPerBlock; | ||
| 121 | + const uint64_t copyBlocksNeeded = (yU64 + copyThreads - 1ull) / copyThreads; | ||
| 122 | + uint32_t copyBlocks = static_cast<uint32_t>( | ||
| 123 | + std::min<uint64_t>(static_cast<uint64_t>(aivCoreNum), copyBlocksNeeded)); | ||
| 124 | + if (copyBlocks == 0u) { | ||
| 125 | + copyBlocks = 1u; | ||
| 126 | + } | ||
| 127 | + | ||
| 128 | + AxpyiCopyTilingData copyTiling{}; | ||
| 129 | + copyTiling.yElems = yU64; | ||
| 130 | + copyTiling.elemBytes = elemBytes; | ||
| 131 | + copyTiling.threadsPerBlock = copyThreads; | ||
| 132 | + copyTiling.numBlocks = copyBlocks; | ||
| 133 | + | ||
| 134 | + (void)aclrtGetLastError(ACL_RT_THREAD_LEVEL); | ||
| 135 | + axpyi_copy_kernel_do( | ||
| 136 | + reinterpret_cast<GM_ADDR>(const_cast<void *>(ySrcPtr)), | ||
| 137 | + reinterpret_cast<GM_ADDR>(yDstPtr), | ||
| 138 | + copyTiling, | ||
| 139 | + stream); | ||
| 140 | + if (aclrtPeekAtLastError(ACL_RT_THREAD_LEVEL) != ACL_SUCCESS) { | ||
| 141 | + OP_LOGE(kAxpyiTag, "copy kernel enqueue failed: %d", | ||
| 142 | + static_cast<int>(aclrtPeekAtLastError(ACL_RT_THREAD_LEVEL))); | ||
| 143 | + return ACL_SPARSE_STATUS_EXECUTION_FAILED; | ||
| 144 | + } | ||
| 145 | + } | ||
| 146 | + | ||
| 147 | + if (nnz == 0 || alphaVal == 0.0f) { | ||
| 148 | + return ACL_SPARSE_STATUS_SUCCESS; | ||
| 149 | + } | ||
| 150 | + | ||
| 151 | + if (xValPtr == nullptr || xIndPtr == nullptr || yDstPtr == nullptr) { | ||
| 152 | + OP_LOGE(kAxpyiTag, "null data pointer for nnz=%ld", static_cast<long>(nnz)); | ||
| 153 | + return ACL_SPARSE_STATUS_INVALID_VALUE; | ||
| 154 | + } | ||
| 155 | + | ||
| 156 | + const uint64_t yBytes = static_cast<uint64_t>(yLen) * elemBytes; | ||
| 157 | + const uint64_t valBytes = static_cast<uint64_t>(nnz) * elemBytes; | ||
| 158 | + const uint64_t idxElemBytes = (idxType == ACL_SPARSE_INDEX_64I) ? sizeof(int64_t) : sizeof(int32_t); | ||
| 159 | + const uint64_t idxBytes = static_cast<uint64_t>(nnz) * idxElemBytes; | ||
| 160 | + if (AxpyiRangesOverlap(yDstPtr, yBytes, xValPtr, valBytes) || | ||
| 161 | + AxpyiRangesOverlap(yDstPtr, yBytes, xIndPtr, idxBytes)) { | ||
| 162 | + OP_LOGE(kAxpyiTag, "undeclared alias between output Y and sparse vector X"); | ||
| 163 | + return ACL_SPARSE_STATUS_INVALID_VALUE; | ||
| 164 | + } | ||
| 165 | + | ||
| 166 | + const uint64_t nnzU64 = static_cast<uint64_t>(nnz); | ||
| 167 | + const uint32_t threadsPerBlock = (nnzU64 < kAxpyiSmallNnzThreshold) | ||
| 168 | + ? kAxpyiSmallThreadsPerBlock | ||
| 169 | + : kAxpyiMaxThreadsPerBlock; | ||
| 170 | + const uint64_t neededBlocks = (nnzU64 + threadsPerBlock - 1ull) / threadsPerBlock; | ||
| 171 | + uint32_t useNumBlocks = static_cast<uint32_t>( | ||
| 172 | + std::min<uint64_t>(static_cast<uint64_t>(aivCoreNum), neededBlocks)); | ||
| 173 | + if (useNumBlocks == 0u) { | ||
| 174 | + useNumBlocks = 1u; | ||
| 175 | + } | ||
| 176 | + | ||
| 177 | + AxpyiTilingData tiling{}; | ||
| 178 | + tiling.nnz = nnzU64; | ||
| 179 | + tiling.alpha = alphaVal; | ||
| 180 | + tiling.idxBase = (idxBase == ACL_SPARSE_INDEX_BASE_ONE) ? 1 : 0; | ||
| 181 | + tiling.idxType = (idxType == ACL_SPARSE_INDEX_64I) ? AXPYI_IDX_I64 : AXPYI_IDX_I32; | ||
| 182 | + tiling.valType = valTypeCode; | ||
| 183 | + tiling.threadsPerBlock = threadsPerBlock; | ||
| 184 | + tiling.numBlocks = useNumBlocks; | ||
| 185 | + | ||
| 186 | + (void)aclrtGetLastError(ACL_RT_THREAD_LEVEL); | ||
| 187 | + axpyi_kernel_do( | ||
| 188 | + reinterpret_cast<GM_ADDR>(const_cast<void *>(xIndPtr)), | ||
| 189 | + reinterpret_cast<GM_ADDR>(const_cast<void *>(xValPtr)), | ||
| 190 | + reinterpret_cast<GM_ADDR>(yDstPtr), | ||
| 191 | + tiling, | ||
| 192 | + stream); | ||
| 193 | + if (aclrtPeekAtLastError(ACL_RT_THREAD_LEVEL) != ACL_SUCCESS) { | ||
| 194 | + OP_LOGE(kAxpyiTag, "kernel enqueue failed: %d", | ||
| 195 | + static_cast<int>(aclrtPeekAtLastError(ACL_RT_THREAD_LEVEL))); | ||
| 196 | + return ACL_SPARSE_STATUS_EXECUTION_FAILED; | ||
| 197 | + } | ||
| 198 | + | ||
| 199 | + return ACL_SPARSE_STATUS_SUCCESS; | ||
| 200 | +} | ||
| 201 | + | ||
| 202 | +} // namespace | ||
| 203 | + | ||
| 204 | +extern "C" aclsparseStatus_t aclsparseAxpyiRaw( | ||
| 205 | + aclsparseHandle_t handle, | ||
| 206 | + float alpha, | ||
| 207 | + const void *xValPtr, | ||
| 208 | + const void *xIndPtr, | ||
| 209 | + const void *ySrcPtr, | ||
| 210 | + void *yDstPtr, | ||
| 211 | + int64_t yLen, | ||
| 212 | + int64_t nnz, | ||
| 213 | + aclDataType valueType, | ||
| 214 | + aclsparseIndexType_t idxType, | ||
| 215 | + aclsparseIndexBase_t idxBase) | ||
| 216 | +{ | ||
| 217 | + if (handle == nullptr) { | ||
| 218 | + return ACL_SPARSE_STATUS_HANDLE_IS_NULLPTR; | ||
| 219 | + } | ||
| 220 | + auto *handleInner = reinterpret_cast<aclsparseContext *>(handle); | ||
| 221 | + if (handleInner->signature != kAclSparseHandleSignature) { | ||
| 222 | + return ACL_SPARSE_STATUS_INVALID_VALUE; | ||
| 223 | + } | ||
| 224 | + return LaunchAxpyiInternal( | ||
| 225 | + handleInner, alpha, xValPtr, xIndPtr, ySrcPtr, yDstPtr, yLen, nnz, | ||
| 226 | + valueType, idxType, idxBase); | ||
| 227 | +} | ||
| 228 | + | ||
| 229 | +extern "C" aclsparseStatus_t aclsparseAxpyi( | ||
| 230 | + aclsparseHandle_t handle, | ||
| 231 | + const void *alpha, | ||
| 232 | + aclsparseConstSpVecDescr_t vecX, | ||
| 233 | + aclsparseDnVecDescr_t vecY) | ||
| 234 | +{ | ||
| 235 | + if (handle == nullptr) { | ||
| 236 | + return ACL_SPARSE_STATUS_HANDLE_IS_NULLPTR; | ||
| 237 | + } | ||
| 238 | + auto *handleInner = reinterpret_cast<aclsparseContext *>(handle); | ||
| 239 | + if (handleInner->signature != kAclSparseHandleSignature) { | ||
| 240 | + return ACL_SPARSE_STATUS_INVALID_VALUE; | ||
| 241 | + } | ||
| 242 | + if (alpha == nullptr || vecX == nullptr || vecY == nullptr) { | ||
| 243 | + OP_LOGE(kAxpyiTag, "null alpha, vecX, or vecY"); | ||
| 244 | + return ACL_SPARSE_STATUS_INVALID_VALUE; | ||
| 245 | + } | ||
| 246 | + | ||
| 247 | + const auto *xInner = reinterpret_cast<const aclsparseSpVecDescr *>(vecX); | ||
| 248 | + auto *yInner = reinterpret_cast<aclsparseDnVecDescr *>(vecY); | ||
| 249 | + if (xInner->signature != kSpVecSignature || yInner->signature != kDnVecSignature) { | ||
| 250 | + OP_LOGE(kAxpyiTag, "invalid descriptor signature"); | ||
| 251 | + return ACL_SPARSE_STATUS_INVALID_VALUE; | ||
| 252 | + } | ||
| 253 | + if (xInner->valueType != yInner->valueType) { | ||
| 254 | + OP_LOGE(kAxpyiTag, "valueType mismatch: vecX=%d vs vecY=%d", | ||
| 255 | + static_cast<int>(xInner->valueType), static_cast<int>(yInner->valueType)); | ||
| 256 | + return ACL_SPARSE_STATUS_NOT_SUPPORTED; | ||
| 257 | + } | ||
| 258 | + if (yInner->stride != 1) { | ||
| 259 | + OP_LOGE(kAxpyiTag, "unsupported dense vector stride %ld (only stride=1)", | ||
| 260 | + static_cast<long>(yInner->stride)); | ||
| 261 | + return ACL_SPARSE_STATUS_NOT_SUPPORTED; | ||
| 262 | + } | ||
| 263 | + if (xInner->size > yInner->nums || xInner->nnz > xInner->size) { | ||
| 264 | + OP_LOGE(kAxpyiTag, "invalid shape: vecX.nnz=%llu, vecX.size=%llu, vecY.nums=%llu", | ||
| 265 | + static_cast<unsigned long long>(xInner->nnz), | ||
| 266 | + static_cast<unsigned long long>(xInner->size), | ||
| 267 | + static_cast<unsigned long long>(yInner->nums)); | ||
| 268 | + return ACL_SPARSE_STATUS_INVALID_VALUE; | ||
| 269 | + } | ||
| 270 | + | ||
| 271 | + float alphaVal = 0.0f; | ||
| 272 | + if (handleInner->pointerMode == ACL_SPARSE_POINTER_MODE_DEVICE) { | ||
| 273 | + if (handleInner->stream != nullptr) { | ||
| 274 | + CHECK_ACL(aclrtSynchronizeStream(handleInner->stream)); | ||
| 275 | + } | ||
| 276 | + CHECK_ACL(aclrtMemcpy(&alphaVal, sizeof(float), alpha, sizeof(float), ACL_MEMCPY_DEVICE_TO_HOST)); | ||
| 277 | + } else { | ||
| 278 | + alphaVal = *reinterpret_cast<const float *>(alpha); | ||
| 279 | + } | ||
| 280 | + | ||
| 281 | + return LaunchAxpyiInternal( | ||
| 282 | + handleInner, alphaVal, | ||
| 283 | + xInner->values, xInner->indices, | ||
| 284 | + yInner->values, yInner->values, | ||
| 285 | + static_cast<int64_t>(yInner->nums), | ||
| 286 | + static_cast<int64_t>(xInner->nnz), | ||
| 287 | + xInner->valueType, xInner->idxType, xInner->idxBase); | ||
| 288 | +} | ||
| @@ -0,0 +1,147 @@ | |||
| 1 | +/** | ||
| 2 | + * ---------------------------------------------------------------------------------------------------------- | ||
| 3 | + * Copyright (c) 2026 Huawei Technologies Co., Ltd. | ||
| 4 | + * This program is free software; you can redistribute it and/or modify it under the terms and conditions of | ||
| 5 | + * the CANN Open Software License Agreement Version 2.0 (the "License"). | ||
| 6 | + * Please refer to the License for details. You may not use this file except in compliance with the License. | ||
| 7 | + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | ||
| 8 | + * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | ||
| 9 | + * See LICENSE in the root of the software repository for the full text of the License. | ||
| 10 | + * ---------------------------------------------------------------------------------------------------------- | ||
| 11 | + */ | ||
| 12 | + | ||
| 13 | +/*! | ||
| 14 | + * \file axpyi_kernel.cpp | ||
| 15 | + * \brief aclsparseAxpyi SIMT kernel for Ascend 950 (arch35 / dav-3510). | ||
| 16 | + */ | ||
| 17 | + | ||
| 18 | +#include <cstdint> | ||
| 19 | +#include "kernel_operator.h" | ||
| 20 | +#include "simt_api/asc_simt.h" | ||
| 21 | +#include "axpyi_kernel.h" | ||
| 22 | + | ||
| 23 | +template <typename RawT> | ||
| 24 | +__simt_vf__ __aicore__ __launch_bounds__(kAxpyiMaxThreadsPerBlock) inline void | ||
| 25 | +AxpyiCopySimtCompute( | ||
| 26 | + uint64_t yElems, | ||
| 27 | + __gm__ const RawT *ySrc, | ||
| 28 | + __gm__ RawT *yDst) | ||
| 29 | +{ | ||
| 30 | + const uint64_t tid = static_cast<uint64_t>(blockIdx.x) * static_cast<uint64_t>(blockDim.x) | ||
| 31 | + + static_cast<uint64_t>(threadIdx.x); | ||
| 32 | + const uint64_t gridStride = static_cast<uint64_t>(blockDim.x) * static_cast<uint64_t>(gridDim.x); | ||
| 33 | + const uint64_t bigStride = gridStride * static_cast<uint64_t>(kAxpyiStrideUnroll); | ||
| 34 | + | ||
| 35 | + for (uint64_t base = tid; base < yElems; base += bigStride) { | ||
| 36 | +#pragma unroll | ||
| 37 | + for (uint32_t u = 0; u < kAxpyiStrideUnroll; ++u) { | ||
| 38 | + const uint64_t i = base + static_cast<uint64_t>(u) * gridStride; | ||
| 39 | + if (i < yElems) { | ||
| 40 | + yDst[i] = ySrc[i]; | ||
| 41 | + } | ||
| 42 | + } | ||
| 43 | + } | ||
| 44 | +} | ||
| 45 | + | ||
| 46 | +template <typename ValT, typename IdxT> | ||
| 47 | +__simt_vf__ __aicore__ __launch_bounds__(kAxpyiMaxThreadsPerBlock) inline void | ||
| 48 | +AxpyiSimtCompute( | ||
| 49 | + uint64_t nnz, | ||
| 50 | + float alpha, | ||
| 51 | + __gm__ const IdxT *indices, | ||
| 52 | + __gm__ const ValT *values, | ||
| 53 | + __gm__ ValT *yVec, | ||
| 54 | + IdxT idxBase) | ||
| 55 | +{ | ||
| 56 | + const uint64_t tid = static_cast<uint64_t>(blockIdx.x) * static_cast<uint64_t>(blockDim.x) | ||
| 57 | + + static_cast<uint64_t>(threadIdx.x); | ||
| 58 | + const uint64_t gridStride = static_cast<uint64_t>(blockDim.x) * static_cast<uint64_t>(gridDim.x); | ||
| 59 | + const uint64_t bigStride = gridStride * static_cast<uint64_t>(kAxpyiStrideUnroll); | ||
| 60 | + | ||
| 61 | + for (uint64_t base = tid; base < nnz; base += bigStride) { | ||
| 62 | +#pragma unroll | ||
| 63 | + for (uint32_t u = 0; u < kAxpyiStrideUnroll; ++u) { | ||
| 64 | + const uint64_t i = base + static_cast<uint64_t>(u) * gridStride; | ||
| 65 | + if (i < nnz) { | ||
| 66 | + const uint64_t pos = static_cast<uint64_t>( | ||
| 67 | + static_cast<int64_t>(indices[i]) - static_cast<int64_t>(idxBase)); | ||
| 68 | + const float xv = static_cast<float>(values[i]); | ||
| 69 | + const float yv = static_cast<float>(yVec[pos]); | ||
| 70 | + yVec[pos] = static_cast<ValT>(alpha * xv + yv); | ||
| 71 | + } | ||
| 72 | + } | ||
| 73 | + } | ||
| 74 | +} | ||
| 75 | + | ||
| 76 | +template <typename IdxT> | ||
| 77 | +__aicore__ inline void DispatchAxpyiByValType( | ||
| 78 | + const AxpyiTilingData &tiling, | ||
| 79 | + GM_ADDR gmIndices, | ||
| 80 | + GM_ADDR gmValues, | ||
| 81 | + GM_ADDR gmYVec) | ||
| 82 | +{ | ||
| 83 | + const dim3 blockDim{tiling.threadsPerBlock ? tiling.threadsPerBlock : kAxpyiMaxThreadsPerBlock}; | ||
| 84 | + if (tiling.valType == AXPYI_VAL_FP32) { | ||
| 85 | + asc_vf_call<AxpyiSimtCompute<float, IdxT>>( | ||
| 86 | + blockDim, tiling.nnz, tiling.alpha, | ||
| 87 | + reinterpret_cast<__gm__ const IdxT *>(gmIndices), | ||
| 88 | + reinterpret_cast<__gm__ const float *>(gmValues), | ||
| 89 | + reinterpret_cast<__gm__ float *>(gmYVec), | ||
| 90 | + static_cast<IdxT>(tiling.idxBase)); | ||
| 91 | + } else if (tiling.valType == AXPYI_VAL_FP16) { | ||
| 92 | + asc_vf_call<AxpyiSimtCompute<half, IdxT>>( | ||
| 93 | + blockDim, tiling.nnz, tiling.alpha, | ||
| 94 | + reinterpret_cast<__gm__ const IdxT *>(gmIndices), | ||
| 95 | + reinterpret_cast<__gm__ const half *>(gmValues), | ||
| 96 | + reinterpret_cast<__gm__ half *>(gmYVec), | ||
| 97 | + static_cast<IdxT>(tiling.idxBase)); | ||
| 98 | + } else { | ||
| 99 | + asc_vf_call<AxpyiSimtCompute<bfloat16_t, IdxT>>( | ||
| 100 | + blockDim, tiling.nnz, tiling.alpha, | ||
| 101 | + reinterpret_cast<__gm__ const IdxT *>(gmIndices), | ||
| 102 | + reinterpret_cast<__gm__ const bfloat16_t *>(gmValues), | ||
| 103 | + reinterpret_cast<__gm__ bfloat16_t *>(gmYVec), | ||
| 104 | + static_cast<IdxT>(tiling.idxBase)); | ||
| 105 | + } | ||
| 106 | +} | ||
| 107 | + | ||
| 108 | +extern "C" __global__ __aicore__ void axpyi_copy_kernel( | ||
| 109 | + GM_ADDR gmYSrc, GM_ADDR gmYDst, const AxpyiCopyTilingData tiling) | ||
| 110 | +{ | ||
| 111 | + KERNEL_TASK_TYPE_DEFAULT(KERNEL_TYPE_AIV_ONLY); | ||
| 112 | + const dim3 blockDim{tiling.threadsPerBlock ? tiling.threadsPerBlock : kAxpyiMaxThreadsPerBlock}; | ||
| 113 | + if (tiling.elemBytes == 4u) { | ||
| 114 | + asc_vf_call<AxpyiCopySimtCompute<uint32_t>>( | ||
| 115 | + blockDim, tiling.yElems, | ||
| 116 | + reinterpret_cast<__gm__ const uint32_t *>(gmYSrc), | ||
| 117 | + reinterpret_cast<__gm__ uint32_t *>(gmYDst)); | ||
| 118 | + } else { | ||
| 119 | + asc_vf_call<AxpyiCopySimtCompute<uint16_t>>( | ||
| 120 | + blockDim, tiling.yElems, | ||
| 121 | + reinterpret_cast<__gm__ const uint16_t *>(gmYSrc), | ||
| 122 | + reinterpret_cast<__gm__ uint16_t *>(gmYDst)); | ||
| 123 | + } | ||
| 124 | +} | ||
| 125 | + | ||
| 126 | +extern "C" __global__ __aicore__ void axpyi_kernel( | ||
| 127 | + GM_ADDR gmIndices, GM_ADDR gmValues, GM_ADDR gmYVec, const AxpyiTilingData tiling) | ||
| 128 | +{ | ||
| 129 | + KERNEL_TASK_TYPE_DEFAULT(KERNEL_TYPE_AIV_ONLY); | ||
| 130 | + if (tiling.idxType == AXPYI_IDX_I32) { | ||
| 131 | + DispatchAxpyiByValType<int32_t>(tiling, gmIndices, gmValues, gmYVec); | ||
| 132 | + } else { | ||
| 133 | + DispatchAxpyiByValType<int64_t>(tiling, gmIndices, gmValues, gmYVec); | ||
| 134 | + } | ||
| 135 | +} | ||
| 136 | + | ||
| 137 | +extern "C" void axpyi_copy_kernel_do( | ||
| 138 | + GM_ADDR ySrc, GM_ADDR yDst, const AxpyiCopyTilingData &tiling, void *stream) | ||
| 139 | +{ | ||
| 140 | + axpyi_copy_kernel<<<tiling.numBlocks, nullptr, stream>>>(ySrc, yDst, tiling); | ||
| 141 | +} | ||
| 142 | + | ||
| 143 | +extern "C" void axpyi_kernel_do( | ||
| 144 | + GM_ADDR indices, GM_ADDR values, GM_ADDR yVec, const AxpyiTilingData &tiling, void *stream) | ||
| 145 | +{ | ||
| 146 | + axpyi_kernel<<<tiling.numBlocks, nullptr, stream>>>(indices, values, yVec, tiling); | ||
| 147 | +} | ||
| @@ -0,0 +1,45 @@ | |||
| 1 | +/** | ||
| 2 | + * ---------------------------------------------------------------------------------------------------------- | ||
| 3 | + * Copyright (c) 2026 Huawei Technologies Co., Ltd. | ||
| 4 | + * This program is free software; you can redistribute it and/or modify it under the terms and conditions of | ||
| 5 | + * the CANN Open Software License Agreement Version 2.0 (the "License"). | ||
| 6 | + * Please refer to the License for details. You may not use this file except in compliance with the License. | ||
| 7 | + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | ||
| 8 | + * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | ||
| 9 | + * See LICENSE in the root of the software repository for the full text of the License. | ||
| 10 | + * ---------------------------------------------------------------------------------------------------------- | ||
| 11 | + */ | ||
| 12 | + | ||
| 13 | +/*! | ||
| 14 | + * \file axpyi_kernel.h | ||
| 15 | + * \brief aclsparseAxpyi kernel launcher declarations for Ascend 950 (arch35 / dav-3510). | ||
| 16 | + */ | ||
| 17 | + | ||
| 18 | +#ifndef AXPYI_ARCH35_KERNEL_H_ | ||
| 19 | +#define AXPYI_ARCH35_KERNEL_H_ | ||
| 20 | + | ||
| 21 | +#include <cstdint> | ||
| 22 | +#include "axpyi_tiling_data.h" | ||
| 23 | + | ||
| 24 | +#ifndef GM_ADDR | ||
| 25 | +#define GM_ADDR uint8_t * | ||
| 26 | +#endif | ||
| 27 | + | ||
| 28 | +extern "C" { | ||
| 29 | + | ||
| 30 | +void axpyi_copy_kernel_do( | ||
| 31 | + GM_ADDR ySrc, | ||
| 32 | + GM_ADDR yDst, | ||
| 33 | + const AxpyiCopyTilingData &tiling, | ||
| 34 | + void *stream); | ||
| 35 | + | ||
| 36 | +void axpyi_kernel_do( | ||
| 37 | + GM_ADDR indices, | ||
| 38 | + GM_ADDR values, | ||
| 39 | + GM_ADDR yVec, | ||
| 40 | + const AxpyiTilingData &tiling, | ||
| 41 | + void *stream); | ||
| 42 | + | ||
| 43 | +} // extern "C" | ||
| 44 | + | ||
| 45 | +#endif // AXPYI_ARCH35_KERNEL_H_ | ||
| @@ -0,0 +1,52 @@ | |||
| 1 | +/** | ||
| 2 | + * ---------------------------------------------------------------------------------------------------------- | ||
| 3 | + * Copyright (c) 2026 Huawei Technologies Co., Ltd. | ||
| 4 | + * This program is free software; you can redistribute it and/or modify it under the terms and conditions of | ||
| 5 | + * the CANN Open Software License Agreement Version 2.0 (the "License"). | ||
| 6 | + * Please refer to the License for details. You may not use this file except in compliance with the License. | ||
| 7 | + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | ||
| 8 | + * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | ||
| 9 | + * See LICENSE in the root of the software repository for the full text of the License. | ||
| 10 | + * ---------------------------------------------------------------------------------------------------------- | ||
| 11 | + */ | ||
| 12 | + | ||
| 13 | +/*! | ||
| 14 | + * \file axpyi_tiling_data.h | ||
| 15 | + * \brief aclsparseAxpyi TilingData for Ascend 950 (arch35 / dav-3510 SIMT). | ||
| 16 | + */ | ||
| 17 | + | ||
| 18 | +#ifndef AXPYI_ARCH35_TILING_DATA_H_ | ||
| 19 | +#define AXPYI_ARCH35_TILING_DATA_H_ | ||
| 20 | + | ||
| 21 | +#include <cstdint> | ||
| 22 | + | ||
| 23 | +constexpr uint32_t kAxpyiMaxThreadsPerBlock = 512u; | ||
| 24 | +constexpr uint32_t kAxpyiSmallThreadsPerBlock = 128u; | ||
| 25 | +constexpr uint64_t kAxpyiSmallNnzThreshold = 4096ull; | ||
| 26 | +constexpr uint32_t kAxpyiStrideUnroll = 4u; | ||
| 27 | + | ||
| 28 | +constexpr int32_t AXPYI_IDX_I32 = 0; | ||
| 29 | +constexpr int32_t AXPYI_IDX_I64 = 1; | ||
| 30 | + | ||
| 31 | +constexpr int32_t AXPYI_VAL_FP32 = 0; | ||
| 32 | +constexpr int32_t AXPYI_VAL_FP16 = 1; | ||
| 33 | +constexpr int32_t AXPYI_VAL_BF16 = 2; | ||
| 34 | + | ||
| 35 | +struct AxpyiTilingData { | ||
| 36 | + uint64_t nnz; | ||
| 37 | + float alpha; | ||
| 38 | + int32_t idxBase; | ||
| 39 | + int32_t idxType; | ||
| 40 | + int32_t valType; | ||
| 41 | + uint32_t threadsPerBlock; | ||
| 42 | + uint32_t numBlocks; | ||
| 43 | +}; | ||
| 44 | + | ||
| 45 | +struct AxpyiCopyTilingData { | ||
| 46 | + uint64_t yElems; | ||
| 47 | + uint32_t elemBytes; | ||
| 48 | + uint32_t threadsPerBlock; | ||
| 49 | + uint32_t numBlocks; | ||
| 50 | +}; | ||
| 51 | + | ||
| 52 | +#endif // AXPYI_ARCH35_TILING_DATA_H_ | ||
| @@ -0,0 +1,15 @@ | |||
| 1 | +# ---------------------------------------------------------------------------------------------------------- | ||
| 2 | +# Copyright (c) 2026 Huawei Technologies Co., Ltd. | ||
| 3 | +# This program is free software; you can redistribute it and/or modify it under the terms and conditions of | ||
| 4 | +# the CANN Open Software License Agreement Version 2.0 (the "License"). | ||
| 5 | +# Please refer to the License for details. You may not use this file except in compliance with the License. | ||
| 6 | +# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | ||
| 7 | +# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | ||
| 8 | +# See LICENSE in the root of the software repository for the full text of the License. | ||
| 9 | +# ---------------------------------------------------------------------------------------------------------- | ||
| 10 | + | ||
| 11 | +"""PyTorch extension package for aclsparseAxpyi.""" | ||
| 12 | + | ||
| 13 | +from .axpyi import TORCH_NPU_SPARSE_FACADE_APIS, aclsparse_axpyi | ||
| 14 | + | ||
| 15 | +__all__ = ["aclsparse_axpyi", "TORCH_NPU_SPARSE_FACADE_APIS"] | ||
| @@ -0,0 +1,98 @@ | |||
| 1 | +# ---------------------------------------------------------------------------------------------------------- | ||
| 2 | +# Copyright (c) 2026 Huawei Technologies Co., Ltd. | ||
| 3 | +# This program is free software; you can redistribute it and/or modify it under the terms and conditions of | ||
| 4 | +# the CANN Open Software License Agreement Version 2.0 (the "License"). | ||
| 5 | +# Please refer to the License for details. You may not use this file except in compliance with the License. | ||
| 6 | +# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | ||
| 7 | +# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | ||
| 8 | +# See LICENSE in the root of the software repository for the full text of the License. | ||
| 9 | +# ---------------------------------------------------------------------------------------------------------- | ||
| 10 | + | ||
| 11 | +"""Register aclsparse_axpyi on torch.ops.ops_sparse and torch_npu.sparse.""" | ||
| 12 | + | ||
| 13 | +from __future__ import annotations | ||
| 14 | + | ||
| 15 | +__all__ = ["aclsparse_axpyi", "TORCH_NPU_SPARSE_FACADE_APIS"] | ||
| 16 | + | ||
| 17 | +import torch | ||
| 18 | +from torch.library import define, impl, register_fake | ||
| 19 | + | ||
| 20 | +from cann_ops_sparse.op_builder import OpBuilder | ||
| 21 | + | ||
| 22 | + | ||
| 23 | +class AxpyiOpBuilder(OpBuilder): | ||
| 24 | + """JIT builder for the aclsparseAxpyi ATen wrapper.""" | ||
| 25 | + | ||
| 26 | + def __init__(self) -> None: | ||
| 27 | + super().__init__("axpyi", category="sparse") | ||
| 28 | + | ||
| 29 | + def sources(self) -> list[str]: | ||
| 30 | + return ["csrc/sparse/axpyi/axpyi.cpp"] | ||
| 31 | + | ||
| 32 | + | ||
| 33 | +_AXPYI_OP_BUILDER = AxpyiOpBuilder() | ||
| 34 | + | ||
| 35 | +define( | ||
| 36 | + "ops_sparse::aclsparse_axpyi", | ||
| 37 | + "(float alpha, Tensor x_val, Tensor x_ind, Tensor y) -> Tensor", | ||
| 38 | +) | ||
| 39 | + | ||
| 40 | + | ||
| 41 | +@impl("ops_sparse::aclsparse_axpyi", "PrivateUse1") | ||
| 42 | +def _aclsparse_axpyi_privateuse1( | ||
| 43 | + alpha: float, | ||
| 44 | + x_val: torch.Tensor, | ||
| 45 | + x_ind: torch.Tensor, | ||
| 46 | + y: torch.Tensor, | ||
| 47 | +) -> torch.Tensor: | ||
| 48 | + return _AXPYI_OP_BUILDER.load().aclsparse_axpyi(float(alpha), x_val, x_ind, y) | ||
| 49 | + | ||
| 50 | + | ||
| 51 | +@register_fake("ops_sparse::aclsparse_axpyi") | ||
| 52 | +def _aclsparse_axpyi_meta( | ||
| 53 | + alpha: float, | ||
| 54 | + x_val: torch.Tensor, | ||
| 55 | + x_ind: torch.Tensor, | ||
| 56 | + y: torch.Tensor, | ||
| 57 | +) -> torch.Tensor: | ||
| 58 | + del alpha | ||
| 59 | + if x_val.dim() != 1 or x_ind.dim() != 1 or y.dim() != 1: | ||
| 60 | + raise ValueError("aclsparse_axpyi requires 1-D inputs (x_val, x_ind, y)") | ||
| 61 | + if x_val.dtype not in (torch.float32, torch.float16, torch.bfloat16): | ||
| 62 | + raise ValueError(f"aclsparse_axpyi unsupported x_val dtype: {x_val.dtype}") | ||
| 63 | + if y.dtype != x_val.dtype: | ||
| 64 | + raise ValueError(f"aclsparse_axpyi dtype mismatch: x_val={x_val.dtype}, y={y.dtype}") | ||
| 65 | + if x_ind.dtype not in (torch.int32, torch.int64): | ||
| 66 | + raise ValueError(f"aclsparse_axpyi unsupported x_ind dtype: {x_ind.dtype}") | ||
| 67 | + if x_val.device != y.device or x_ind.device != y.device: | ||
| 68 | + raise RuntimeError("aclsparse_axpyi requires x_val, x_ind, and y on the same device") | ||
| 69 | + return torch.empty_like(y) | ||
| 70 | + | ||
| 71 | + | ||
| 72 | +def aclsparse_axpyi( | ||
| 73 | + alpha: float, | ||
| 74 | + x_val: torch.Tensor, | ||
| 75 | + x_ind: torch.Tensor, | ||
| 76 | + y: torch.Tensor, | ||
| 77 | +) -> torch.Tensor: | ||
| 78 | + """Compute out = y; out[x_ind] += alpha * x_val on Ascend NPU without mutating y.""" | ||
| 79 | + if not isinstance(x_val, torch.Tensor) or not isinstance(x_ind, torch.Tensor) or not isinstance(y, torch.Tensor): | ||
| 80 | + raise ValueError("aclsparse_axpyi requires torch.Tensor inputs for x_val, x_ind, and y") | ||
| 81 | + if isinstance(alpha, bool) or not isinstance(alpha, (int, float)): | ||
| 82 | + raise ValueError(f"aclsparse_axpyi requires a float scalar alpha, got {type(alpha).__name__}") | ||
| 83 | + if y.device.type != "npu" or x_val.device.type != "npu" or x_ind.device.type != "npu": | ||
| 84 | + raise RuntimeError( | ||
| 85 | + f"aclsparse_axpyi requires NPU tensors, got x_val={x_val.device}, " | ||
| 86 | + f"x_ind={x_ind.device}, y={y.device}" | ||
| 87 | + ) | ||
| 88 | + if x_val.device != y.device or x_ind.device != y.device: | ||
| 89 | + raise RuntimeError( | ||
| 90 | + f"aclsparse_axpyi requires all inputs on the same NPU device, got " | ||
| 91 | + f"x_val={x_val.device}, x_ind={x_ind.device}, y={y.device}" | ||
| 92 | + ) | ||
| 93 | + return _AXPYI_OP_BUILDER.load().aclsparse_axpyi(float(alpha), x_val, x_ind, y) | ||
| 94 | + | ||
| 95 | + | ||
| 96 | +TORCH_NPU_SPARSE_FACADE_APIS = { | ||
| 97 | + "aclsparse_axpyi": aclsparse_axpyi, | ||
| 98 | +} | ||
| @@ -0,0 +1,209 @@ | |||
| 1 | +/** | ||
| 2 | + * ---------------------------------------------------------------------------------------------------------- | ||
| 3 | + * Copyright (c) 2026 Huawei Technologies Co., Ltd. | ||
| 4 | + * This program is free software; you can redistribute it and/or modify it under the terms and conditions of | ||
| 5 | + * the CANN Open Software License Agreement Version 2.0 (the "License"). | ||
| 6 | + * Please refer to the License for details. You may not use this file except in compliance with the License. | ||
| 7 | + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | ||
| 8 | + * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | ||
| 9 | + * See LICENSE in the root of the software repository for the full text of the License. | ||
| 10 | + * ---------------------------------------------------------------------------------------------------------- | ||
| 11 | + */ | ||
| 12 | + | ||
| 13 | +/*! | ||
| 14 | + * \file axpyi.cpp | ||
| 15 | + * \brief PyTorch / ATen NPU wrapper for aclsparse_axpyi backed by aclsparseAxpyiRaw. | ||
| 16 | + */ | ||
| 17 | + | ||
| 18 | +#include "aclsparse_common.h" | ||
| 19 | + | ||
| 20 | +#include <optional> | ||
| 21 | +#include <tuple> | ||
| 22 | + | ||
| 23 | +#include <torch/extension.h> | ||
| 24 | + | ||
| 25 | +namespace { | ||
| 26 | + | ||
| 27 | +using cann_ops_sparse::AclSparseContext; | ||
| 28 | +using cann_ops_sparse::AclSparseHandleCache; | ||
| 29 | +using cann_ops_sparse::RunAclSparse; | ||
| 30 | + | ||
| 31 | +aclDataType ToAclValType(at::ScalarType scalarType) | ||
| 32 | +{ | ||
| 33 | + switch (scalarType) { | ||
| 34 | + case at::kFloat: | ||
| 35 | + return ACL_FLOAT; | ||
| 36 | + case at::kHalf: | ||
| 37 | + return ACL_FLOAT16; | ||
| 38 | + case at::kBFloat16: | ||
| 39 | + return ACL_BF16; | ||
| 40 | + default: | ||
| 41 | + TORCH_CHECK(false, | ||
| 42 | + "aclsparse_axpyi supports float32, float16, and bfloat16, but got ", | ||
| 43 | + scalarType); | ||
| 44 | + } | ||
| 45 | +} | ||
| 46 | + | ||
| 47 | +aclsparseIndexType_t ToAclIdxType(at::ScalarType scalarType) | ||
| 48 | +{ | ||
| 49 | + switch (scalarType) { | ||
| 50 | + case at::kInt: | ||
| 51 | + return ACL_SPARSE_INDEX_32I; | ||
| 52 | + case at::kLong: | ||
| 53 | + return ACL_SPARSE_INDEX_64I; | ||
| 54 | + default: | ||
| 55 | + TORCH_CHECK(false, | ||
| 56 | + "aclsparse_axpyi supports int32 and int64 indices, but got ", | ||
| 57 | + scalarType); | ||
| 58 | + } | ||
| 59 | +} | ||
| 60 | + | ||
| 61 | +void ValidateInputs(const at::Tensor &xVal, const at::Tensor &xInd, const at::Tensor &y) | ||
| 62 | +{ | ||
| 63 | + TORCH_CHECK(xVal.defined() && xInd.defined() && y.defined(), | ||
| 64 | + "aclsparse_axpyi requires defined tensors for x_val, x_ind, and y"); | ||
| 65 | + TORCH_CHECK(xVal.device().type() == c10::DeviceType::PrivateUse1 && | ||
| 66 | + xInd.device().type() == c10::DeviceType::PrivateUse1 && | ||
| 67 | + y.device().type() == c10::DeviceType::PrivateUse1, | ||
| 68 | + "aclsparse_axpyi requires all tensors on NPU, got x_val=", xVal.device(), | ||
| 69 | + ", x_ind=", xInd.device(), ", y=", y.device()); | ||
| 70 | + TORCH_CHECK(xVal.device() == y.device() && xInd.device() == y.device(), | ||
| 71 | + "aclsparse_axpyi requires all tensors on the same NPU device, got x_val=", | ||
| 72 | + xVal.device(), ", x_ind=", xInd.device(), ", y=", y.device()); | ||
| 73 | + TORCH_CHECK(xVal.dim() == 1 && xInd.dim() == 1 && y.dim() == 1, | ||
| 74 | + "aclsparse_axpyi requires 1-D tensors, got dims x_val=", xVal.dim(), | ||
| 75 | + ", x_ind=", xInd.dim(), ", y=", y.dim()); | ||
| 76 | + TORCH_CHECK(xVal.layout() == at::kStrided && xInd.layout() == at::kStrided && | ||
| 77 | + y.layout() == at::kStrided, | ||
| 78 | + "aclsparse_axpyi requires strided dense tensor layout"); | ||
| 79 | + TORCH_CHECK(xVal.scalar_type() == y.scalar_type(), | ||
| 80 | + "aclsparse_axpyi requires x_val.dtype == y.dtype, got ", | ||
| 81 | + xVal.scalar_type(), " vs ", y.scalar_type()); | ||
| 82 | + (void)ToAclValType(xVal.scalar_type()); | ||
| 83 | + (void)ToAclIdxType(xInd.scalar_type()); | ||
| 84 | + TORCH_CHECK(xVal.numel() == xInd.numel(), | ||
| 85 | + "aclsparse_axpyi requires x_val.numel() == x_ind.numel(), got ", | ||
| 86 | + xVal.numel(), " vs ", xInd.numel()); | ||
| 87 | + TORCH_CHECK(xInd.numel() <= y.numel(), | ||
| 88 | + "aclsparse_axpyi requires nnz <= len(y) (indices must be distinct), got nnz=", | ||
| 89 | + xInd.numel(), ", N=", y.numel()); | ||
| 90 | +} | ||
| 91 | + | ||
| 92 | +using IndexImplWeakPtr = c10::weak_intrusive_ptr<c10::TensorImpl, c10::UndefinedTensorImpl>; | ||
| 93 | + | ||
| 94 | +class ValidatedIndexBoundsCache { | ||
| 95 | +public: | ||
| 96 | + bool Matches(const at::Tensor &index, int64_t ySize) const | ||
| 97 | + { | ||
| 98 | + const c10::TensorImpl *impl = index.unsafeGetTensorImpl(); | ||
| 99 | + const auto &versionCounter = impl->version_counter(); | ||
| 100 | + if (ySize_ != ySize) { | ||
| 101 | + return false; | ||
| 102 | + } | ||
| 103 | + if (!indexImpl_.has_value() || !versionCounter.enabled()) { | ||
| 104 | + return false; | ||
| 105 | + } | ||
| 106 | + const auto cachedImpl = indexImpl_->lock(); | ||
| 107 | + return cachedImpl && cachedImpl.get() == impl && version_ == versionCounter.current_version(); | ||
| 108 | + } | ||
| 109 | + | ||
| 110 | + void Store(const at::Tensor &index, int64_t ySize) | ||
| 111 | + { | ||
| 112 | + const c10::TensorImpl *impl = index.unsafeGetTensorImpl(); | ||
| 113 | + const auto &versionCounter = impl->version_counter(); | ||
| 114 | + if (!versionCounter.enabled()) { | ||
| 115 | + indexImpl_.reset(); | ||
| 116 | + return; | ||
| 117 | + } | ||
| 118 | + indexImpl_.emplace(index.getIntrusivePtr()); | ||
| 119 | + version_ = versionCounter.current_version(); | ||
| 120 | + ySize_ = ySize; | ||
| 121 | + } | ||
| 122 | + | ||
| 123 | +private: | ||
| 124 | + std::optional<IndexImplWeakPtr> indexImpl_; | ||
| 125 | + uint32_t version_ = 0; | ||
| 126 | + int64_t ySize_ = 0; | ||
| 127 | +}; | ||
| 128 | + | ||
| 129 | +void CheckIndexBounds(const at::Tensor &index, int64_t ySize) | ||
| 130 | +{ | ||
| 131 | + thread_local ValidatedIndexBoundsCache cache; | ||
| 132 | + if (cache.Matches(index, ySize)) { | ||
| 133 | + return; | ||
| 134 | + } | ||
| 135 | + const auto indexRange = at::aminmax(index); | ||
| 136 | + const int64_t minIndex = std::get<0>(indexRange).item<int64_t>(); | ||
| 137 | + const int64_t maxIndex = std::get<1>(indexRange).item<int64_t>(); | ||
| 138 | + TORCH_CHECK(minIndex >= 0 && maxIndex < ySize, | ||
| 139 | + "aclsparse_axpyi: index out of range [0, ", ySize, | ||
| 140 | + "), found [", minIndex, ", ", maxIndex, "]"); | ||
| 141 | + cache.Store(index, ySize); | ||
| 142 | +} | ||
| 143 | + | ||
| 144 | +at::Tensor AclsparseAxpyiNpu( | ||
| 145 | + double alpha, | ||
| 146 | + const at::Tensor &xVal, | ||
| 147 | + const at::Tensor &xInd, | ||
| 148 | + const at::Tensor &y) | ||
| 149 | +{ | ||
| 150 | + ValidateInputs(xVal, xInd, y); | ||
| 151 | + | ||
| 152 | + const at::Tensor xValC = xVal.is_contiguous() ? xVal : xVal.contiguous(); | ||
| 153 | + const at::Tensor xIndC = xInd.is_contiguous() ? xInd : xInd.contiguous(); | ||
| 154 | + const at::Tensor yC = y.is_contiguous() ? y : y.contiguous(); | ||
| 155 | + | ||
| 156 | + const int64_t yLen = yC.numel(); | ||
| 157 | + const int64_t nnz = xIndC.numel(); | ||
| 158 | + const float alphaF = static_cast<float>(alpha); | ||
| 159 | + | ||
| 160 | + if (nnz == 0) { | ||
| 161 | + return yC.clone(); | ||
| 162 | + } | ||
| 163 | + | ||
| 164 | + return RunAclSparse(yC, [&](AclSparseContext &context) { | ||
| 165 | + CheckIndexBounds(xIndC, yLen); | ||
| 166 | + | ||
| 167 | + if (alphaF == 0.0f) { | ||
| 168 | + return yC.clone(); | ||
| 169 | + } | ||
| 170 | + | ||
| 171 | + const aclDataType valType = ToAclValType(xValC.scalar_type()); | ||
| 172 | + const aclsparseIndexType_t idxType = ToAclIdxType(xIndC.scalar_type()); | ||
| 173 | + at::Tensor out = at::empty({yLen}, yC.options()); | ||
| 174 | + | ||
| 175 | + context.RecordTensors(xValC, xIndC, yC, out); | ||
| 176 | + // Drain queued torch_npu ops before direct ACL / kernel launch on the same stream. | ||
| 177 | + (void)c10_npu::getCurrentNPUStream(yC.device().index()).stream(true); | ||
| 178 | + | ||
| 179 | + ACLSPARSE_CHECK(aclsparseAxpyiRaw( | ||
| 180 | + context.handle(), | ||
| 181 | + alphaF, | ||
| 182 | + xValC.const_data_ptr(), | ||
| 183 | + xIndC.const_data_ptr(), | ||
| 184 | + yC.const_data_ptr(), | ||
| 185 | + out.mutable_data_ptr(), | ||
| 186 | + yLen, | ||
| 187 | + nnz, | ||
| 188 | + valType, | ||
| 189 | + idxType, | ||
| 190 | + ACL_SPARSE_INDEX_BASE_ZERO)); | ||
| 191 | + | ||
| 192 | + return out; | ||
| 193 | + }); | ||
| 194 | +} | ||
| 195 | + | ||
| 196 | +void ReleaseCachedHandles() | ||
| 197 | +{ | ||
| 198 | + AclSparseHandleCache::Clear(); | ||
| 199 | +} | ||
| 200 | + | ||
| 201 | +} // namespace | ||
| 202 | + | ||
| 203 | +PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) | ||
| 204 | +{ | ||
| 205 | + m.def("aclsparse_axpyi", &AclsparseAxpyiNpu, | ||
| 206 | + "NPU aclsparse_axpyi: out = y; out[x_ind] += alpha * x_val"); | ||
| 207 | + m.def("release_cached_handles", &ReleaseCachedHandles, | ||
| 208 | + "Release cached ACLSparse handles prior to interpreter shutdown"); | ||
| 209 | +} | ||
| @@ -0,0 +1,11 @@ | |||
| 1 | +# ---------------------------------------------------------------------------------------------------------- | ||
| 2 | +# Copyright (c) 2026 Huawei Technologies Co., Ltd. | ||
| 3 | +# This program is free software; you can redistribute it and/or modify it under the terms and conditions of | ||
| 4 | +# the CANN Open Software License Agreement Version 2.0 (the "License"). | ||
| 5 | +# Please refer to the License for details. You may not use this file except in compliance with the License. | ||
| 6 | +# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | ||
| 7 | +# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | ||
| 8 | +# See LICENSE in the root of the software repository for the full text of the License. | ||
| 9 | +# ---------------------------------------------------------------------------------------------------------- | ||
| 10 | + | ||
| 11 | +ops_sparse_add_test(axpyi ${OPS_SPARSE}) | ||
| @@ -0,0 +1,94 @@ | |||
| 1 | +# aclsparseAxpyi 算子测试说明 | ||
| 2 | + | ||
| 3 | +本目录包含 `aclsparseAxpyi` 算子的 C++ 单元测试(Atlas A2/A3 `arch22` 与 Ascend 950 `arch35`)、全量 PyTorch 功能精度验收测试(覆盖任务书 TC-01 ~ TC-11)以及 NPU 性能基准脚本(覆盖全部 8 组规模 × 3 种主力 dtype = 24 个测试点)。 | ||
| 4 | + | ||
| 5 | +## 目录结构 | ||
| 6 | + | ||
| 7 | +```text | ||
| 8 | +test/axpyi/ | ||
| 9 | +├── CMakeLists.txt # 注册 axpyi_test(按 --soc 自动选择 arch22 / arch35) | ||
| 10 | +├── README.md # 本文件:构建、精度与性能复现步骤 | ||
| 11 | +├── arch22/ | ||
| 12 | +│ └── axpyi_test.cpp # Atlas A2/A3 C++ 单元测试(含跨核同 32B cache line 防撕裂用例) | ||
| 13 | +├── arch35/ | ||
| 14 | +│ └── axpyi_test.cpp # Ascend 950 C++ 单元测试(可在 950 真机或 camodel 模拟器运行) | ||
| 15 | +├── test_aclsparseAxpyi_full.py # PyTorch 全量验收用例(TC-01 ~ TC-11) | ||
| 16 | +└── benchmark_aclsparseAxpyi_npu.py # PyTorch 24 组规模×dtype 性能基准(NPUGraph + Eager + 标杆比对) | ||
| 17 | +``` | ||
| 18 | + | ||
| 19 | +## 环境要求 | ||
| 20 | + | ||
| 21 | +- **硬件**:Atlas A2 / A3(`arch22`)真机;Ascend 950PR/950DT(`arch35`)真机或 CANN 内置 `dav_3510/camodel` 模拟器 | ||
| 22 | +- **软件**:CANN 9.1.0+、Python 3.10+、PyTorch 2.7+、`torch_npu`、`pytest` | ||
| 23 | + | ||
| 24 | +## 1. Atlas A2/A3(arch22)编译与 C++ 单测 | ||
| 25 | + | ||
| 26 | +```bash | ||
| 27 | +# 在 ops-sparse 仓库根目录执行 | ||
| 28 | +bash build.sh --soc=ascend910_93 --ops=axpyi --run | ||
| 29 | +``` | ||
| 30 | + | ||
| 31 | +或单独运行已编译的测试可执行文件: | ||
| 32 | + | ||
| 33 | +```bash | ||
| 34 | +LD_LIBRARY_PATH="$PWD/build:$ASCEND_HOME_PATH/lib64:$LD_LIBRARY_PATH" \ | ||
| 35 | + ./build/test/axpyi/axpyi_test | ||
| 36 | +``` | ||
| 37 | + | ||
| 38 | +C++ 单测覆盖: | ||
| 39 | +- `FP32` / `FP16` / `BF16` × `int32` / `int64` × `0-based` / `1-based`; | ||
| 40 | +- 非 32B 对齐尾块、乱序索引、`nnz = 0`、`alpha = 0`(逐位一致校验)、Device PointerMode; | ||
| 41 | +- 异地输出(`aclsparseAxpyiRaw`,验证不修改 `ySrc`); | ||
| 42 | +- **跨核同 32B Cache Line 对抗测试**(40+ 核并发写入同一 32 字节内相邻元素,验证零撕裂); | ||
| 43 | +- 大规模压力测试(`N = 5,000,000, nnz = 250,000`)与非法参数错误码检查。 | ||
| 44 | + | ||
| 45 | +## 2. Ascend 950(arch35)编译与模拟器验证 | ||
| 46 | + | ||
| 47 | +```bash | ||
| 48 | +# 1. 编译 Ascend 950 算子库与单测 | ||
| 49 | +bash build.sh --soc=ascend950 --ops=axpyi | ||
| 50 | + | ||
| 51 | +# 2. 使用 CANN 内置 dav_3510/camodel 周期级模拟器运行 9/9 单测 | ||
| 52 | +CAMODEL_DIR="${ASCEND_HOME_PATH}/aarch64-linux/simulator/dav_3510/camodel" | ||
| 53 | +mkdir -p /tmp/axpyi_camodel_logs | ||
| 54 | +CAMODEL_LOG_PATH=/tmp/axpyi_camodel_logs \ | ||
| 55 | +LD_LIBRARY_PATH="${CAMODEL_DIR}:$PWD/build:${ASCEND_HOME_PATH}/lib64:${LD_LIBRARY_PATH}" \ | ||
| 56 | + ./build/test/axpyi/axpyi_test | ||
| 57 | +``` | ||
| 58 | + | ||
| 59 | +## 3. PyTorch 封装层编译、安装与全量精度验收(TC-01 ~ TC-11) | ||
| 60 | + | ||
| 61 | +```bash | ||
| 62 | +# 1. 编译 arch22 算子动态库与 PyTorch 扩展 wheel | ||
| 63 | +bash build.sh --soc=ascend910b --ops=axpyi | ||
| 64 | +bash build.sh --torch_extension --ops=axpyi | ||
| 65 | + | ||
| 66 | +# 2. 安装 wheel(建议使用独立 venv 或 --target 目录) | ||
| 67 | +pip install --no-deps --force-reinstall torch_extension/dist/cann_ops_sparse-*.whl | ||
| 68 | + | ||
| 69 | +# 3. 运行全量 TC-01 ~ TC-11 精度与边界测试(80/80 PASS) | ||
| 70 | +OPS_SPARSE_LIB_DIR="$PWD/build" LD_LIBRARY_PATH="$PWD/build:$ASCEND_HOME_PATH/lib64:$LD_LIBRARY_PATH" \ | ||
| 71 | + pytest -v test/axpyi/test_aclsparseAxpyi_full.py | ||
| 72 | +``` | ||
| 73 | + | ||
| 74 | +### 精度验收标准 | ||
| 75 | + | ||
| 76 | +| 数据类型 | 相对误差 `rtol` | 绝对误差 `atol` | 参考基准 | | ||
| 77 | +|----------|-----------------|-----------------|----------| | ||
| 78 | +| `float32` | ≤ 1e-4 | ≤ 1e-5 | CPU `aclsparse_axpyi_cpu` | | ||
| 79 | +| `float16` | ≤ 1e-3 | ≤ 1e-3 | CPU `aclsparse_axpyi_cpu` | | ||
| 80 | +| `bfloat16` | ≤ 5e-3 | ≤ 5e-3 | CPU `aclsparse_axpyi_cpu` | | ||
| 81 | +| `alpha = 0` / `nnz = 0` | 0(逐位一致) | 0(逐位一致) | 输入 `y` 原字节视图 | | ||
| 82 | + | ||
| 83 | +## 4. 性能基准测试(24 组规模 × dtype) | ||
| 84 | + | ||
| 85 | +```bash | ||
| 86 | +OPS_SPARSE_LIB_DIR="$PWD/build" LD_LIBRARY_PATH="$PWD/build:$ASCEND_HOME_PATH/lib64:$LD_LIBRARY_PATH" \ | ||
| 87 | + python3 test/axpyi/benchmark_aclsparseAxpyi_npu.py | ||
| 88 | +``` | ||
| 89 | + | ||
| 90 | +脚本按任务书第 6.1 节统一口径同时输出: | ||
| 91 | +- **NPUGraph 纯设备端耗时**(多次调用压入单张 `torch.npu.NPUGraph` 回放取中位数,消除 Python 派发底噪); | ||
| 92 | +- **Eager 端到端耗时**; | ||
| 93 | +- **同机 PyTorch `y.index_add` 基线耗时**; | ||
| 94 | +- 与任务书 RTX 5880 标杆耗时的加速比对比。 | ||
| @@ -0,0 +1,406 @@ | |||
| 1 | +/** | ||
| 2 | + * ---------------------------------------------------------------------------------------------------------- | ||
| 3 | + * Copyright (c) 2026 Huawei Technologies Co., Ltd. | ||
| 4 | + * This program is free software; you can redistribute it and/or modify it under the terms and conditions of | ||
| 5 | + * the CANN Open Software License Agreement Version 2.0 (the "License"). | ||
| 6 | + * Please refer to the License for details. You may not use this file except in compliance with the License. | ||
| 7 | + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | ||
| 8 | + * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | ||
| 9 | + * See LICENSE in the root of the software repository for the full text of the License. | ||
| 10 | + * ---------------------------------------------------------------------------------------------------------- | ||
| 11 | + */ | ||
| 12 | + | ||
| 13 | +/*! | ||
| 14 | + * \file axpyi_test.cpp | ||
| 15 | + * \brief Comprehensive C++ accuracy, concurrency, and error-path tests for aclsparseAxpyi (arch22). | ||
| 16 | + */ | ||
| 17 | + | ||
| 18 | +#include <algorithm> | ||
| 19 | +#include <cmath> | ||
| 20 | +#include <cstdint> | ||
| 21 | +#include <cstdio> | ||
| 22 | +#include <cstring> | ||
| 23 | +#include <numeric> | ||
| 24 | +#include <random> | ||
| 25 | +#include <vector> | ||
| 26 | + | ||
| 27 | +#include "acl/acl.h" | ||
| 28 | +#include "cann_ops_sparse.h" | ||
| 29 | + | ||
| 30 | +namespace { | ||
| 31 | + | ||
| 32 | +// IEEE-754 float32 <-> float16 / bfloat16 conversion helpers (round-to-nearest-even). | ||
| 33 | +inline uint16_t FloatToBf16(float f) | ||
| 34 | +{ | ||
| 35 | + uint32_t u = 0; | ||
| 36 | + std::memcpy(&u, &f, sizeof(u)); | ||
| 37 | + uint32_t exp = (u >> 23) & 0xFFu; | ||
| 38 | + uint32_t mant = u & 0x7FFFFFu; | ||
| 39 | + if (exp == 0xFFu && mant != 0u) { | ||
| 40 | + return static_cast<uint16_t>((u >> 16) | 0x0040u); | ||
| 41 | + } | ||
| 42 | + uint32_t lsb = (u >> 16) & 1u; | ||
| 43 | + u += 0x7FFFu + lsb; | ||
| 44 | + return static_cast<uint16_t>(u >> 16); | ||
| 45 | +} | ||
| 46 | + | ||
| 47 | +inline float Bf16ToFloat(uint16_t b) | ||
| 48 | +{ | ||
| 49 | + uint32_t u = static_cast<uint32_t>(b) << 16; | ||
| 50 | + float f = 0.0f; | ||
| 51 | + std::memcpy(&f, &u, sizeof(f)); | ||
| 52 | + return f; | ||
| 53 | +} | ||
| 54 | + | ||
| 55 | +inline uint16_t FloatToFp16(float f) | ||
| 56 | +{ | ||
| 57 | + uint32_t x = 0; | ||
| 58 | + std::memcpy(&x, &f, sizeof(x)); | ||
| 59 | + uint32_t sign = (x >> 16) & 0x8000u; | ||
| 60 | + int32_t exp = static_cast<int32_t>((x >> 23) & 0xFFu) - 127 + 15; | ||
| 61 | + uint32_t mant = x & 0x7FFFFFu; | ||
| 62 | + if (exp <= 0) { | ||
| 63 | + if (exp < -10) { | ||
| 64 | + return static_cast<uint16_t>(sign); | ||
| 65 | + } | ||
| 66 | + mant |= 0x800000u; | ||
| 67 | + uint32_t shift = static_cast<uint32_t>(14 - exp); | ||
| 68 | + uint32_t halfBit = 1u << (shift - 1u); | ||
| 69 | + uint32_t rounded = (mant + halfBit + ((mant >> shift) & 1u) - 1u) >> shift; | ||
| 70 | + return static_cast<uint16_t>(sign | rounded); | ||
| 71 | + } | ||
| 72 | + if (exp >= 31) { | ||
| 73 | + if ((x & 0x7FFFFFFFu) > 0x7F800000u) { | ||
| 74 | + return static_cast<uint16_t>(sign | 0x7E00u); | ||
| 75 | + } | ||
| 76 | + return static_cast<uint16_t>(sign | 0x7C00u); | ||
| 77 | + } | ||
| 78 | + uint32_t roundBit = (mant & 0x1FFFu); | ||
| 79 | + uint32_t hMant = mant >> 13; | ||
| 80 | + if (roundBit > 0x1000u || (roundBit == 0x1000u && (hMant & 1u) != 0u)) { | ||
| 81 | + hMant += 1u; | ||
| 82 | + if (hMant == 0x400u) { | ||
| 83 | + hMant = 0u; | ||
| 84 | + exp += 1; | ||
| 85 | + if (exp >= 31) { | ||
| 86 | + return static_cast<uint16_t>(sign | 0x7C00u); | ||
| 87 | + } | ||
| 88 | + } | ||
| 89 | + } | ||
| 90 | + return static_cast<uint16_t>(sign | (static_cast<uint32_t>(exp) << 10) | hMant); | ||
| 91 | +} | ||
| 92 | + | ||
| 93 | +inline float Fp16ToFloat(uint16_t h) | ||
| 94 | +{ | ||
| 95 | + uint32_t sign = (static_cast<uint32_t>(h) & 0x8000u) << 16; | ||
| 96 | + uint32_t exp = (h >> 10) & 0x1Fu; | ||
| 97 | + uint32_t mant = h & 0x3FFu; | ||
| 98 | + uint32_t fBits = 0; | ||
| 99 | + if (exp == 0u) { | ||
| 100 | + if (mant == 0u) { | ||
| 101 | + fBits = sign; | ||
| 102 | + } else { | ||
| 103 | + int32_t e = -14; | ||
| 104 | + while ((mant & 0x400u) == 0u) { | ||
| 105 | + mant <<= 1; | ||
| 106 | + --e; | ||
| 107 | + } | ||
| 108 | + mant &= 0x3FFu; | ||
| 109 | + fBits = sign | (static_cast<uint32_t>(e + 127) << 23) | (mant << 13); | ||
| 110 | + } | ||
| 111 | + } else if (exp == 31u) { | ||
| 112 | + fBits = sign | 0x7F800000u | (mant << 13); | ||
| 113 | + } else { | ||
| 114 | + fBits = sign | ((exp + 112u) << 23) | (mant << 13); | ||
| 115 | + } | ||
| 116 | + float f = 0.0f; | ||
| 117 | + std::memcpy(&f, &fBits, sizeof(f)); | ||
| 118 | + return f; | ||
| 119 | +} | ||
| 120 | + | ||
| 121 | +template <typename IdxT> | ||
| 122 | +bool RunOneCase( | ||
| 123 | + aclsparseHandle_t handle, | ||
| 124 | + aclrtStream stream, | ||
| 125 | + const char *name, | ||
| 126 | + int64_t N, | ||
| 127 | + int64_t nnz, | ||
| 128 | + float alpha, | ||
| 129 | + aclDataType valType, | ||
| 130 | + aclsparseIndexBase_t idxBase, | ||
| 131 | + bool adversarialAdjacent, | ||
| 132 | + bool testOutOfPlaceRaw) | ||
| 133 | +{ | ||
| 134 | + std::mt19937 rng(20261201u + static_cast<uint32_t>(N + nnz * 7)); | ||
| 135 | + std::uniform_real_distribution<float> dist(-2.0f, 2.0f); | ||
| 136 | + | ||
| 137 | + std::vector<int64_t> perm(static_cast<size_t>(N)); | ||
| 138 | + std::iota(perm.begin(), perm.end(), 0); | ||
| 139 | + if (adversarialAdjacent) { | ||
| 140 | + // Adjacent indices interleaved across cores so every 32B cache line is hit concurrently. | ||
| 141 | + std::vector<int64_t> interleaved; | ||
| 142 | + interleaved.reserve(static_cast<size_t>(nnz)); | ||
| 143 | + const int64_t stride = 64; | ||
| 144 | + for (int64_t r = 0; r < stride && static_cast<int64_t>(interleaved.size()) < nnz; ++r) { | ||
| 145 | + for (int64_t p = r; p < N && static_cast<int64_t>(interleaved.size()) < nnz; p += stride) { | ||
| 146 | + interleaved.push_back(p); | ||
| 147 | + } | ||
| 148 | + } | ||
| 149 | + perm = interleaved; | ||
| 150 | + } else { | ||
| 151 | + std::shuffle(perm.begin(), perm.end(), rng); | ||
| 152 | + } | ||
| 153 | + | ||
| 154 | + const int64_t baseOffset = (idxBase == ACL_SPARSE_INDEX_BASE_ONE) ? 1 : 0; | ||
| 155 | + std::vector<IdxT> hIdx(static_cast<size_t>(nnz)); | ||
| 156 | + for (int64_t i = 0; i < nnz; ++i) { | ||
| 157 | + hIdx[static_cast<size_t>(i)] = static_cast<IdxT>(perm[static_cast<size_t>(i)] + baseOffset); | ||
| 158 | + } | ||
| 159 | + | ||
| 160 | + const size_t elemBytes = (valType == ACL_FLOAT) ? 4u : 2u; | ||
| 161 | + std::vector<uint8_t> hXBytes(static_cast<size_t>(nnz) * elemBytes); | ||
| 162 | + std::vector<uint8_t> hYBytes(static_cast<size_t>(N) * elemBytes); | ||
| 163 | + std::vector<float> refX(static_cast<size_t>(nnz)); | ||
| 164 | + std::vector<float> refY(static_cast<size_t>(N)); | ||
| 165 | + | ||
| 166 | + for (int64_t i = 0; i < nnz; ++i) { | ||
| 167 | + float v = dist(rng); | ||
| 168 | + if (valType == ACL_FLOAT) { | ||
| 169 | + std::memcpy(&hXBytes[static_cast<size_t>(i) * 4u], &v, 4u); | ||
| 170 | + refX[static_cast<size_t>(i)] = v; | ||
| 171 | + } else if (valType == ACL_FLOAT16) { | ||
| 172 | + uint16_t h = FloatToFp16(v); | ||
| 173 | + std::memcpy(&hXBytes[static_cast<size_t>(i) * 2u], &h, 2u); | ||
| 174 | + refX[static_cast<size_t>(i)] = Fp16ToFloat(h); | ||
| 175 | + } else { | ||
| 176 | + uint16_t b = FloatToBf16(v); | ||
| 177 | + std::memcpy(&hXBytes[static_cast<size_t>(i) * 2u], &b, 2u); | ||
| 178 | + refX[static_cast<size_t>(i)] = Bf16ToFloat(b); | ||
| 179 | + } | ||
| 180 | + } | ||
| 181 | + for (int64_t i = 0; i < N; ++i) { | ||
| 182 | + float v = dist(rng); | ||
| 183 | + if (valType == ACL_FLOAT) { | ||
| 184 | + std::memcpy(&hYBytes[static_cast<size_t>(i) * 4u], &v, 4u); | ||
| 185 | + refY[static_cast<size_t>(i)] = v; | ||
| 186 | + } else if (valType == ACL_FLOAT16) { | ||
| 187 | + uint16_t h = FloatToFp16(v); | ||
| 188 | + std::memcpy(&hYBytes[static_cast<size_t>(i) * 2u], &h, 2u); | ||
| 189 | + refY[static_cast<size_t>(i)] = Fp16ToFloat(h); | ||
| 190 | + } else { | ||
| 191 | + uint16_t b = FloatToBf16(v); | ||
| 192 | + std::memcpy(&hYBytes[static_cast<size_t>(i) * 2u], &b, 2u); | ||
| 193 | + refY[static_cast<size_t>(i)] = Bf16ToFloat(b); | ||
| 194 | + } | ||
| 195 | + } | ||
| 196 | + | ||
| 197 | + // Golden reference (FP32 accumulate, single rounding at end; alpha=0 bit-exact). | ||
| 198 | + std::vector<uint8_t> goldenBytes = hYBytes; | ||
| 199 | + if (alpha != 0.0f) { | ||
| 200 | + for (int64_t i = 0; i < nnz; ++i) { | ||
| 201 | + int64_t pos = static_cast<int64_t>(hIdx[static_cast<size_t>(i)]) - baseOffset; | ||
| 202 | + float acc = alpha * refX[static_cast<size_t>(i)] + refY[static_cast<size_t>(pos)]; | ||
| 203 | + refY[static_cast<size_t>(pos)] = acc; | ||
| 204 | + if (valType == ACL_FLOAT) { | ||
| 205 | + std::memcpy(&goldenBytes[static_cast<size_t>(pos) * 4u], &acc, 4u); | ||
| 206 | + } else if (valType == ACL_FLOAT16) { | ||
| 207 | + uint16_t h = FloatToFp16(acc); | ||
| 208 | + std::memcpy(&goldenBytes[static_cast<size_t>(pos) * 2u], &h, 2u); | ||
| 209 | + } else { | ||
| 210 | + uint16_t b = FloatToBf16(acc); | ||
| 211 | + std::memcpy(&goldenBytes[static_cast<size_t>(pos) * 2u], &b, 2u); | ||
| 212 | + } | ||
| 213 | + } | ||
| 214 | + } | ||
| 215 | + | ||
| 216 | + void *dIdx = nullptr; | ||
| 217 | + void *dX = nullptr; | ||
| 218 | + void *dY = nullptr; | ||
| 219 | + void *dOut = nullptr; | ||
| 220 | + | ||
| 221 | + if (nnz > 0) { | ||
| 222 | + aclrtMalloc(&dIdx, static_cast<size_t>(nnz) * sizeof(IdxT), ACL_MEM_MALLOC_HUGE_FIRST); | ||
| 223 | + aclrtMalloc(&dX, hXBytes.size(), ACL_MEM_MALLOC_HUGE_FIRST); | ||
| 224 | + aclrtMemcpy(dIdx, static_cast<size_t>(nnz) * sizeof(IdxT), hIdx.data(), | ||
| 225 | + static_cast<size_t>(nnz) * sizeof(IdxT), ACL_MEMCPY_HOST_TO_DEVICE); | ||
| 226 | + aclrtMemcpy(dX, hXBytes.size(), hXBytes.data(), hXBytes.size(), ACL_MEMCPY_HOST_TO_DEVICE); | ||
| 227 | + } | ||
| 228 | + if (N > 0) { | ||
| 229 | + aclrtMalloc(&dY, hYBytes.size(), ACL_MEM_MALLOC_HUGE_FIRST); | ||
| 230 | + aclrtMemcpy(dY, hYBytes.size(), hYBytes.data(), hYBytes.size(), ACL_MEMCPY_HOST_TO_DEVICE); | ||
| 231 | + if (testOutOfPlaceRaw) { | ||
| 232 | + aclrtMalloc(&dOut, hYBytes.size(), ACL_MEM_MALLOC_HUGE_FIRST); | ||
| 233 | + } | ||
| 234 | + } | ||
| 235 | + | ||
| 236 | + const aclsparseIndexType_t idxType = | ||
| 237 | + (sizeof(IdxT) == 8) ? ACL_SPARSE_INDEX_64I : ACL_SPARSE_INDEX_32I; | ||
| 238 | + aclsparseStatus_t st = ACL_SPARSE_STATUS_SUCCESS; | ||
| 239 | + | ||
| 240 | + if (testOutOfPlaceRaw) { | ||
| 241 | + st = aclsparseAxpyiRaw(handle, alpha, dX, dIdx, dY, dOut, N, nnz, valType, idxType, idxBase); | ||
| 242 | + } else { | ||
| 243 | + aclsparseConstSpVecDescr_t vecX = nullptr; | ||
| 244 | + aclsparseDnVecDescr_t vecY = nullptr; | ||
| 245 | + st = aclsparseCreateConstSpVec(&vecX, N, nnz, dIdx, dX, idxType, idxBase, valType); | ||
| 246 | + if (st == ACL_SPARSE_STATUS_SUCCESS) { | ||
| 247 | + st = aclsparseCreateDnVec(&vecY, N, dY, valType); | ||
| 248 | + } | ||
| 249 | + if (st == ACL_SPARSE_STATUS_SUCCESS) { | ||
| 250 | + st = aclsparseAxpyi(handle, &alpha, vecX, vecY); | ||
| 251 | + } | ||
| 252 | + (void)aclsparseDestroySpVec(vecX); | ||
| 253 | + (void)aclsparseDestroyDnVec(vecY); | ||
| 254 | + } | ||
| 255 | + | ||
| 256 | + aclError syncErr = aclrtSynchronizeStream(stream); | ||
| 257 | + bool ok = (st == ACL_SPARSE_STATUS_SUCCESS && syncErr == ACL_SUCCESS); | ||
| 258 | + | ||
| 259 | + if (ok && N > 0) { | ||
| 260 | + std::vector<uint8_t> hOut(hYBytes.size()); | ||
| 261 | + aclrtMemcpy(hOut.data(), hOut.size(), testOutOfPlaceRaw ? dOut : dY, hOut.size(), | ||
| 262 | + ACL_MEMCPY_DEVICE_TO_HOST); | ||
| 263 | + | ||
| 264 | + if (alpha == 0.0f || nnz == 0) { | ||
| 265 | + if (std::memcmp(hOut.data(), hYBytes.data(), hYBytes.size()) != 0) { | ||
| 266 | + std::printf("[FAIL] %s: alpha==0 or nnz==0 not bit-exact!\n", name); | ||
| 267 | + ok = false; | ||
| 268 | + } | ||
| 269 | + } else { | ||
| 270 | + float rtol = (valType == ACL_FLOAT) ? 1e-4f : (valType == ACL_FLOAT16 ? 1e-3f : 5e-3f); | ||
| 271 | + float atol = (valType == ACL_FLOAT) ? 1e-5f : (valType == ACL_FLOAT16 ? 1e-3f : 5e-3f); | ||
| 272 | + for (int64_t i = 0; i < N; ++i) { | ||
| 273 | + float got = 0.0f; | ||
| 274 | + float want = 0.0f; | ||
| 275 | + if (valType == ACL_FLOAT) { | ||
| 276 | + std::memcpy(&got, &hOut[static_cast<size_t>(i) * 4u], 4u); | ||
| 277 | + std::memcpy(&want, &goldenBytes[static_cast<size_t>(i) * 4u], 4u); | ||
| 278 | + } else if (valType == ACL_FLOAT16) { | ||
| 279 | + uint16_t gh = 0; | ||
| 280 | + uint16_t wh = 0; | ||
| 281 | + std::memcpy(&gh, &hOut[static_cast<size_t>(i) * 2u], 2u); | ||
| 282 | + std::memcpy(&wh, &goldenBytes[static_cast<size_t>(i) * 2u], 2u); | ||
| 283 | + got = Fp16ToFloat(gh); | ||
| 284 | + want = Fp16ToFloat(wh); | ||
| 285 | + } else { | ||
| 286 | + uint16_t gb = 0; | ||
| 287 | + uint16_t wb = 0; | ||
| 288 | + std::memcpy(&gb, &hOut[static_cast<size_t>(i) * 2u], 2u); | ||
| 289 | + std::memcpy(&wb, &goldenBytes[static_cast<size_t>(i) * 2u], 2u); | ||
| 290 | + got = Bf16ToFloat(gb); | ||
| 291 | + want = Bf16ToFloat(wb); | ||
| 292 | + } | ||
| 293 | + float err = std::fabs(got - want); | ||
| 294 | + if (std::isnan(got) || err > atol + rtol * std::fabs(want)) { | ||
| 295 | + std::printf("[FAIL] %s: mismatch at i=%ld got=%g want=%g err=%g\n", | ||
| 296 | + name, static_cast<long>(i), got, want, err); | ||
| 297 | + ok = false; | ||
| 298 | + break; | ||
| 299 | + } | ||
| 300 | + } | ||
| 301 | + } | ||
| 302 | + | ||
| 303 | + // Verify source Y untouched in out-of-place mode. | ||
| 304 | + if (ok && testOutOfPlaceRaw) { | ||
| 305 | + std::vector<uint8_t> hYCheck(hYBytes.size()); | ||
| 306 | + aclrtMemcpy(hYCheck.data(), hYCheck.size(), dY, hYCheck.size(), ACL_MEMCPY_DEVICE_TO_HOST); | ||
| 307 | + if (std::memcmp(hYCheck.data(), hYBytes.data(), hYBytes.size()) != 0) { | ||
| 308 | + std::printf("[FAIL] %s: out-of-place raw call mutated ySrc!\n", name); | ||
| 309 | + ok = false; | ||
| 310 | + } | ||
| 311 | + } | ||
| 312 | + } | ||
| 313 | + | ||
| 314 | + if (dIdx != nullptr) aclrtFree(dIdx); | ||
| 315 | + if (dX != nullptr) aclrtFree(dX); | ||
| 316 | + if (dY != nullptr) aclrtFree(dY); | ||
| 317 | + if (dOut != nullptr) aclrtFree(dOut); | ||
| 318 | + | ||
| 319 | + if (ok) { | ||
| 320 | + std::printf("[PASS] %s (N=%ld, nnz=%ld, alpha=%.2f)\n", | ||
| 321 | + name, static_cast<long>(N), static_cast<long>(nnz), alpha); | ||
| 322 | + } | ||
| 323 | + return ok; | ||
| 324 | +} | ||
| 325 | + | ||
| 326 | +bool TestErrorPaths(aclsparseHandle_t handle) | ||
| 327 | +{ | ||
| 328 | + float alpha = 1.0f; | ||
| 329 | + if (aclsparseAxpyi(nullptr, &alpha, nullptr, nullptr) != ACL_SPARSE_STATUS_HANDLE_IS_NULLPTR) { | ||
| 330 | + std::printf("[FAIL] null handle should return HANDLE_IS_NULLPTR\n"); | ||
| 331 | + return false; | ||
| 332 | + } | ||
| 333 | + if (aclsparseAxpyi(handle, nullptr, nullptr, nullptr) != ACL_SPARSE_STATUS_INVALID_VALUE) { | ||
| 334 | + std::printf("[FAIL] null args should return INVALID_VALUE\n"); | ||
| 335 | + return false; | ||
| 336 | + } | ||
| 337 | + std::printf("[PASS] error_paths\n"); | ||
| 338 | + return true; | ||
| 339 | +} | ||
| 340 | + | ||
| 341 | +} // namespace | ||
| 342 | + | ||
| 343 | +int main() | ||
| 344 | +{ | ||
| 345 | + if (aclInit(nullptr) != ACL_SUCCESS) { | ||
| 346 | + std::printf("[FAIL] aclInit failed\n"); | ||
| 347 | + return 1; | ||
| 348 | + } | ||
| 349 | + if (aclrtSetDevice(0) != ACL_SUCCESS) { | ||
| 350 | + std::printf("[FAIL] aclrtSetDevice(0) failed\n"); | ||
| 351 | + aclFinalize(); | ||
| 352 | + return 1; | ||
| 353 | + } | ||
| 354 | + aclrtStream stream = nullptr; | ||
| 355 | + if (aclrtCreateStream(&stream) != ACL_SUCCESS) { | ||
| 356 | + std::printf("[FAIL] aclrtCreateStream failed\n"); | ||
| 357 | + aclrtResetDevice(0); | ||
| 358 | + aclFinalize(); | ||
| 359 | + return 1; | ||
| 360 | + } | ||
| 361 | + aclsparseHandle_t handle = nullptr; | ||
| 362 | + if (aclsparseCreate(&handle) != ACL_SPARSE_STATUS_SUCCESS || | ||
| 363 | + aclsparseSetStream(handle, stream) != ACL_SPARSE_STATUS_SUCCESS) { | ||
| 364 | + std::printf("[FAIL] aclsparseCreate/SetStream failed\n"); | ||
| 365 | + aclrtDestroyStream(stream); | ||
| 366 | + aclrtResetDevice(0); | ||
| 367 | + aclFinalize(); | ||
| 368 | + return 1; | ||
| 369 | + } | ||
| 370 | + | ||
| 371 | + bool allOk = true; | ||
| 372 | + allOk &= TestErrorPaths(handle); | ||
| 373 | + | ||
| 374 | + // Core matrix: 3 dtypes x 2 idxTypes x standard & non-aligned shapes | ||
| 375 | + allOk &= RunOneCase<int32_t>(handle, stream, "fp32_i32_std", 4096, 512, 0.75f, ACL_FLOAT, ACL_SPARSE_INDEX_BASE_ZERO, false, false); | ||
| 376 | + allOk &= RunOneCase<int64_t>(handle, stream, "fp32_i64_unaligned", 8191, 333, -1.25f, ACL_FLOAT, ACL_SPARSE_INDEX_BASE_ONE, false, false); | ||
| 377 | + allOk &= RunOneCase<int32_t>(handle, stream, "fp16_i32_std", 4096, 512, 0.75f, ACL_FLOAT16, ACL_SPARSE_INDEX_BASE_ZERO, false, false); | ||
| 378 | + allOk &= RunOneCase<int64_t>(handle, stream, "fp16_i64_unaligned", 1009, 73, -0.5f, ACL_FLOAT16, ACL_SPARSE_INDEX_BASE_ONE, false, false); | ||
| 379 | + allOk &= RunOneCase<int32_t>(handle, stream, "bf16_i32_std", 4096, 512, 0.75f, ACL_BF16, ACL_SPARSE_INDEX_BASE_ZERO, false, false); | ||
| 380 | + allOk &= RunOneCase<int64_t>(handle, stream, "bf16_i64_unaligned", 137, 19, 1.5f, ACL_BF16, ACL_SPARSE_INDEX_BASE_ZERO, false, false); | ||
| 381 | + | ||
| 382 | + // Edge cases: nnz=0, alpha=0, N=1/nnz=1, out-of-place raw | ||
| 383 | + allOk &= RunOneCase<int32_t>(handle, stream, "empty_nnz", 64, 0, 2.0f, ACL_FLOAT, ACL_SPARSE_INDEX_BASE_ZERO, false, false); | ||
| 384 | + allOk &= RunOneCase<int32_t>(handle, stream, "alpha_zero_fp16", 257, 100, 0.0f, ACL_FLOAT16, ACL_SPARSE_INDEX_BASE_ZERO, false, true); | ||
| 385 | + allOk &= RunOneCase<int32_t>(handle, stream, "degenerate_1_1_bf16", 1, 1, 3.0f, ACL_BF16, ACL_SPARSE_INDEX_BASE_ZERO, false, true); | ||
| 386 | + allOk &= RunOneCase<int64_t>(handle, stream, "oop_raw_fp32_i64", 16384, 2048, 0.5f, ACL_FLOAT, ACL_SPARSE_INDEX_BASE_ZERO, false, true); | ||
| 387 | + | ||
| 388 | + // Adversarial cross-core same-32B-cacheline concurrency test (verifies ZERO write tearing!) | ||
| 389 | + allOk &= RunOneCase<int32_t>(handle, stream, "adversarial_tear_fp32", 4096, 4096, 0.75f, ACL_FLOAT, ACL_SPARSE_INDEX_BASE_ZERO, true, false); | ||
| 390 | + allOk &= RunOneCase<int32_t>(handle, stream, "adversarial_tear_fp16", 4096, 4096, 0.75f, ACL_FLOAT16, ACL_SPARSE_INDEX_BASE_ZERO, true, false); | ||
| 391 | + allOk &= RunOneCase<int32_t>(handle, stream, "adversarial_tear_bf16", 4096, 4096, 0.75f, ACL_BF16, ACL_SPARSE_INDEX_BASE_ZERO, true, false); | ||
| 392 | + | ||
| 393 | + // Mode B (Large-N > 112KB/core) accuracy + cache-coherency verification (5M elements!) | ||
| 394 | + allOk &= RunOneCase<int32_t>(handle, stream, "modeB_5M_fp32_oop", 5000000, 50000, 0.75f, ACL_FLOAT, ACL_SPARSE_INDEX_BASE_ZERO, false, true); | ||
| 395 | + allOk &= RunOneCase<int32_t>(handle, stream, "modeB_5M_fp16_oop", 5000000, 50000, -0.5f, ACL_FLOAT16, ACL_SPARSE_INDEX_BASE_ZERO, false, true); | ||
| 396 | + allOk &= RunOneCase<int64_t>(handle, stream, "modeB_5M_bf16_i64_oop", 5000000, 50000, 1.25f, ACL_BF16, ACL_SPARSE_INDEX_BASE_ONE, false, true); | ||
| 397 | + allOk &= RunOneCase<int32_t>(handle, stream, "modeB_5M_fp32_inplace", 5000000, 50000, 0.5f, ACL_FLOAT, ACL_SPARSE_INDEX_BASE_ZERO, false, false); | ||
| 398 | + | ||
| 399 | + aclsparseDestroy(handle); | ||
| 400 | + aclrtDestroyStream(stream); | ||
| 401 | + aclrtResetDevice(0); | ||
| 402 | + aclFinalize(); | ||
| 403 | + | ||
| 404 | + std::printf("\n=== axpyi_test (arch22): %s ===\n", allOk ? "ALL PASSED" : "FAILED"); | ||
| 405 | + return allOk ? 0 : 1; | ||
| 406 | +} | ||
| @@ -0,0 +1,352 @@ | |||
| 1 | +/** | ||
| 2 | + * ---------------------------------------------------------------------------------------------------------- | ||
| 3 | + * Copyright (c) 2026 Huawei Technologies Co., Ltd. | ||
| 4 | + * This program is free software; you can redistribute it and/or modify it under the terms and conditions of | ||
| 5 | + * the CANN Open Software License Agreement Version 2.0 (the "License"). | ||
| 6 | + * Please refer to the License for details. You may not use this file except in compliance with the License. | ||
| 7 | + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | ||
| 8 | + * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | ||
| 9 | + * See LICENSE in the root of the software repository for the full text of the License. | ||
| 10 | + * ---------------------------------------------------------------------------------------------------------- | ||
| 11 | + */ | ||
| 12 | + | ||
| 13 | +/*! | ||
| 14 | + * \file axpyi_test.cpp | ||
| 15 | + * \brief Comprehensive C++ accuracy & simulator test for aclsparseAxpyi (arch35 / Ascend 950). | ||
| 16 | + */ | ||
| 17 | + | ||
| 18 | +#include <algorithm> | ||
| 19 | +#include <cmath> | ||
| 20 | +#include <cstdint> | ||
| 21 | +#include <cstdio> | ||
| 22 | +#include <cstring> | ||
| 23 | +#include <numeric> | ||
| 24 | +#include <random> | ||
| 25 | +#include <vector> | ||
| 26 | + | ||
| 27 | +#include "acl/acl.h" | ||
| 28 | +#include "cann_ops_sparse.h" | ||
| 29 | + | ||
| 30 | +namespace { | ||
| 31 | + | ||
| 32 | +inline uint16_t FloatToBf16(float f) | ||
| 33 | +{ | ||
| 34 | + uint32_t u = 0; | ||
| 35 | + std::memcpy(&u, &f, sizeof(u)); | ||
| 36 | + uint32_t exp = (u >> 23) & 0xFFu; | ||
| 37 | + uint32_t mant = u & 0x7FFFFFu; | ||
| 38 | + if (exp == 0xFFu && mant != 0u) { | ||
| 39 | + return static_cast<uint16_t>((u >> 16) | 0x0040u); | ||
| 40 | + } | ||
| 41 | + uint32_t lsb = (u >> 16) & 1u; | ||
| 42 | + u += 0x7FFFu + lsb; | ||
| 43 | + return static_cast<uint16_t>(u >> 16); | ||
| 44 | +} | ||
| 45 | + | ||
| 46 | +inline float Bf16ToFloat(uint16_t b) | ||
| 47 | +{ | ||
| 48 | + uint32_t u = static_cast<uint32_t>(b) << 16; | ||
| 49 | + float f = 0.0f; | ||
| 50 | + std::memcpy(&f, &u, sizeof(f)); | ||
| 51 | + return f; | ||
| 52 | +} | ||
| 53 | + | ||
| 54 | +inline uint16_t FloatToFp16(float f) | ||
| 55 | +{ | ||
| 56 | + uint32_t x = 0; | ||
| 57 | + std::memcpy(&x, &f, sizeof(x)); | ||
| 58 | + uint32_t sign = (x >> 16) & 0x8000u; | ||
| 59 | + int32_t exp = static_cast<int32_t>((x >> 23) & 0xFFu) - 127 + 15; | ||
| 60 | + uint32_t mant = x & 0x7FFFFFu; | ||
| 61 | + if (exp <= 0) { | ||
| 62 | + if (exp < -10) { | ||
| 63 | + return static_cast<uint16_t>(sign); | ||
| 64 | + } | ||
| 65 | + mant |= 0x800000u; | ||
| 66 | + uint32_t shift = static_cast<uint32_t>(14 - exp); | ||
| 67 | + uint32_t halfBit = 1u << (shift - 1u); | ||
| 68 | + uint32_t rounded = (mant + halfBit + ((mant >> shift) & 1u) - 1u) >> shift; | ||
| 69 | + return static_cast<uint16_t>(sign | rounded); | ||
| 70 | + } | ||
| 71 | + if (exp >= 31) { | ||
| 72 | + if ((x & 0x7FFFFFFFu) > 0x7F800000u) { | ||
| 73 | + return static_cast<uint16_t>(sign | 0x7E00u); | ||
| 74 | + } | ||
| 75 | + return static_cast<uint16_t>(sign | 0x7C00u); | ||
| 76 | + } | ||
| 77 | + uint32_t roundBit = (mant & 0x1FFFu); | ||
| 78 | + uint32_t hMant = mant >> 13; | ||
| 79 | + if (roundBit > 0x1000u || (roundBit == 0x1000u && (hMant & 1u) != 0u)) { | ||
| 80 | + hMant += 1u; | ||
| 81 | + if (hMant == 0x400u) { | ||
| 82 | + hMant = 0u; | ||
| 83 | + exp += 1; | ||
| 84 | + if (exp >= 31) { | ||
| 85 | + return static_cast<uint16_t>(sign | 0x7C00u); | ||
| 86 | + } | ||
| 87 | + } | ||
| 88 | + } | ||
| 89 | + return static_cast<uint16_t>(sign | (static_cast<uint32_t>(exp) << 10) | hMant); | ||
| 90 | +} | ||
| 91 | + | ||
| 92 | +inline float Fp16ToFloat(uint16_t h) | ||
| 93 | +{ | ||
| 94 | + uint32_t sign = (static_cast<uint32_t>(h) & 0x8000u) << 16; | ||
| 95 | + uint32_t exp = (h >> 10) & 0x1Fu; | ||
| 96 | + uint32_t mant = h & 0x3FFu; | ||
| 97 | + uint32_t fBits = 0; | ||
| 98 | + if (exp == 0u) { | ||
| 99 | + if (mant == 0u) { | ||
| 100 | + fBits = sign; | ||
| 101 | + } else { | ||
| 102 | + int32_t e = -14; | ||
| 103 | + while ((mant & 0x400u) == 0u) { | ||
| 104 | + mant <<= 1; | ||
| 105 | + --e; | ||
| 106 | + } | ||
| 107 | + mant &= 0x3FFu; | ||
| 108 | + fBits = sign | (static_cast<uint32_t>(e + 127) << 23) | (mant << 13); | ||
| 109 | + } | ||
| 110 | + } else if (exp == 31u) { | ||
| 111 | + fBits = sign | 0x7F800000u | (mant << 13); | ||
| 112 | + } else { | ||
| 113 | + fBits = sign | ((exp + 112u) << 23) | (mant << 13); | ||
| 114 | + } | ||
| 115 | + float f = 0.0f; | ||
| 116 | + std::memcpy(&f, &fBits, sizeof(f)); | ||
| 117 | + return f; | ||
| 118 | +} | ||
| 119 | + | ||
| 120 | +template <typename IdxT> | ||
| 121 | +bool RunOneCase( | ||
| 122 | + aclsparseHandle_t handle, | ||
| 123 | + aclrtStream stream, | ||
| 124 | + const char *name, | ||
| 125 | + int64_t N, | ||
| 126 | + int64_t nnz, | ||
| 127 | + float alpha, | ||
| 128 | + aclDataType valType, | ||
| 129 | + aclsparseIndexBase_t idxBase, | ||
| 130 | + bool testOutOfPlaceRaw) | ||
| 131 | +{ | ||
| 132 | + std::mt19937 rng(20269500u + static_cast<uint32_t>(N + nnz * 7)); | ||
| 133 | + std::uniform_real_distribution<float> dist(-2.0f, 2.0f); | ||
| 134 | + | ||
| 135 | + std::vector<int64_t> perm(static_cast<size_t>(N)); | ||
| 136 | + std::iota(perm.begin(), perm.end(), 0); | ||
| 137 | + std::shuffle(perm.begin(), perm.end(), rng); | ||
| 138 | + | ||
| 139 | + const int64_t baseOffset = (idxBase == ACL_SPARSE_INDEX_BASE_ONE) ? 1 : 0; | ||
| 140 | + std::vector<IdxT> hIdx(static_cast<size_t>(nnz)); | ||
| 141 | + for (int64_t i = 0; i < nnz; ++i) { | ||
| 142 | + hIdx[static_cast<size_t>(i)] = static_cast<IdxT>(perm[static_cast<size_t>(i)] + baseOffset); | ||
| 143 | + } | ||
| 144 | + | ||
| 145 | + const size_t elemBytes = (valType == ACL_FLOAT) ? 4u : 2u; | ||
| 146 | + std::vector<uint8_t> hXBytes(static_cast<size_t>(nnz) * elemBytes); | ||
| 147 | + std::vector<uint8_t> hYBytes(static_cast<size_t>(N) * elemBytes); | ||
| 148 | + std::vector<float> refX(static_cast<size_t>(nnz)); | ||
| 149 | + std::vector<float> refY(static_cast<size_t>(N)); | ||
| 150 | + | ||
| 151 | + for (int64_t i = 0; i < nnz; ++i) { | ||
| 152 | + float v = dist(rng); | ||
| 153 | + if (valType == ACL_FLOAT) { | ||
| 154 | + std::memcpy(&hXBytes[static_cast<size_t>(i) * 4u], &v, 4u); | ||
| 155 | + refX[static_cast<size_t>(i)] = v; | ||
| 156 | + } else if (valType == ACL_FLOAT16) { | ||
| 157 | + uint16_t h = FloatToFp16(v); | ||
| 158 | + std::memcpy(&hXBytes[static_cast<size_t>(i) * 2u], &h, 2u); | ||
| 159 | + refX[static_cast<size_t>(i)] = Fp16ToFloat(h); | ||
| 160 | + } else { | ||
| 161 | + uint16_t b = FloatToBf16(v); | ||
| 162 | + std::memcpy(&hXBytes[static_cast<size_t>(i) * 2u], &b, 2u); | ||
| 163 | + refX[static_cast<size_t>(i)] = Bf16ToFloat(b); | ||
| 164 | + } | ||
| 165 | + } | ||
| 166 | + for (int64_t i = 0; i < N; ++i) { | ||
| 167 | + float v = dist(rng); | ||
| 168 | + if (valType == ACL_FLOAT) { | ||
| 169 | + std::memcpy(&hYBytes[static_cast<size_t>(i) * 4u], &v, 4u); | ||
| 170 | + refY[static_cast<size_t>(i)] = v; | ||
| 171 | + } else if (valType == ACL_FLOAT16) { | ||
| 172 | + uint16_t h = FloatToFp16(v); | ||
| 173 | + std::memcpy(&hYBytes[static_cast<size_t>(i) * 2u], &h, 2u); | ||
| 174 | + refY[static_cast<size_t>(i)] = Fp16ToFloat(h); | ||
| 175 | + } else { | ||
| 176 | + uint16_t b = FloatToBf16(v); | ||
| 177 | + std::memcpy(&hYBytes[static_cast<size_t>(i) * 2u], &b, 2u); | ||
| 178 | + refY[static_cast<size_t>(i)] = Bf16ToFloat(b); | ||
| 179 | + } | ||
| 180 | + } | ||
| 181 | + | ||
| 182 | + std::vector<uint8_t> goldenBytes = hYBytes; | ||
| 183 | + if (alpha != 0.0f) { | ||
| 184 | + for (int64_t i = 0; i < nnz; ++i) { | ||
| 185 | + int64_t pos = static_cast<int64_t>(hIdx[static_cast<size_t>(i)]) - baseOffset; | ||
| 186 | + float acc = alpha * refX[static_cast<size_t>(i)] + refY[static_cast<size_t>(pos)]; | ||
| 187 | + refY[static_cast<size_t>(pos)] = acc; | ||
| 188 | + if (valType == ACL_FLOAT) { | ||
| 189 | + std::memcpy(&goldenBytes[static_cast<size_t>(pos) * 4u], &acc, 4u); | ||
| 190 | + } else if (valType == ACL_FLOAT16) { | ||
| 191 | + uint16_t h = FloatToFp16(acc); | ||
| 192 | + std::memcpy(&goldenBytes[static_cast<size_t>(pos) * 2u], &h, 2u); | ||
| 193 | + } else { | ||
| 194 | + uint16_t b = FloatToBf16(acc); | ||
| 195 | + std::memcpy(&goldenBytes[static_cast<size_t>(pos) * 2u], &b, 2u); | ||
| 196 | + } | ||
| 197 | + } | ||
| 198 | + } | ||
| 199 | + | ||
| 200 | + void *dIdx = nullptr; | ||
| 201 | + void *dX = nullptr; | ||
| 202 | + void *dY = nullptr; | ||
| 203 | + void *dOut = nullptr; | ||
| 204 | + | ||
| 205 | + if (nnz > 0) { | ||
| 206 | + aclrtMalloc(&dIdx, static_cast<size_t>(nnz) * sizeof(IdxT), ACL_MEM_MALLOC_HUGE_FIRST); | ||
| 207 | + aclrtMalloc(&dX, hXBytes.size(), ACL_MEM_MALLOC_HUGE_FIRST); | ||
| 208 | + aclrtMemcpy(dIdx, static_cast<size_t>(nnz) * sizeof(IdxT), hIdx.data(), | ||
| 209 | + static_cast<size_t>(nnz) * sizeof(IdxT), ACL_MEMCPY_HOST_TO_DEVICE); | ||
| 210 | + aclrtMemcpy(dX, hXBytes.size(), hXBytes.data(), hXBytes.size(), ACL_MEMCPY_HOST_TO_DEVICE); | ||
| 211 | + } | ||
| 212 | + if (N > 0) { | ||
| 213 | + aclrtMalloc(&dY, hYBytes.size(), ACL_MEM_MALLOC_HUGE_FIRST); | ||
| 214 | + aclrtMemcpy(dY, hYBytes.size(), hYBytes.data(), hYBytes.size(), ACL_MEMCPY_HOST_TO_DEVICE); | ||
| 215 | + if (testOutOfPlaceRaw) { | ||
| 216 | + aclrtMalloc(&dOut, hYBytes.size(), ACL_MEM_MALLOC_HUGE_FIRST); | ||
| 217 | + } | ||
| 218 | + } | ||
| 219 | + | ||
| 220 | + const aclsparseIndexType_t idxType = | ||
| 221 | + (sizeof(IdxT) == 8) ? ACL_SPARSE_INDEX_64I : ACL_SPARSE_INDEX_32I; | ||
| 222 | + aclsparseStatus_t st = ACL_SPARSE_STATUS_SUCCESS; | ||
| 223 | + | ||
| 224 | + if (testOutOfPlaceRaw) { | ||
| 225 | + st = aclsparseAxpyiRaw(handle, alpha, dX, dIdx, dY, dOut, N, nnz, valType, idxType, idxBase); | ||
| 226 | + } else { | ||
| 227 | + aclsparseConstSpVecDescr_t vecX = nullptr; | ||
| 228 | + aclsparseDnVecDescr_t vecY = nullptr; | ||
| 229 | + st = aclsparseCreateConstSpVec(&vecX, N, nnz, dIdx, dX, idxType, idxBase, valType); | ||
| 230 | + if (st == ACL_SPARSE_STATUS_SUCCESS) { | ||
| 231 | + st = aclsparseCreateDnVec(&vecY, N, dY, valType); | ||
| 232 | + } | ||
| 233 | + if (st == ACL_SPARSE_STATUS_SUCCESS) { | ||
| 234 | + st = aclsparseAxpyi(handle, &alpha, vecX, vecY); | ||
| 235 | + } | ||
| 236 | + (void)aclsparseDestroySpVec(vecX); | ||
| 237 | + (void)aclsparseDestroyDnVec(vecY); | ||
| 238 | + } | ||
| 239 | + | ||
| 240 | + aclError syncErr = aclrtSynchronizeStream(stream); | ||
| 241 | + bool ok = (st == ACL_SPARSE_STATUS_SUCCESS && syncErr == ACL_SUCCESS); | ||
| 242 | + if (!ok) { | ||
| 243 | + std::printf("[FAIL] %s: api_status=%d syncErr=%d\n", name, static_cast<int>(st), static_cast<int>(syncErr)); | ||
| 244 | + } | ||
| 245 | + | ||
| 246 | + if (ok && N > 0) { | ||
| 247 | + std::vector<uint8_t> hOut(hYBytes.size()); | ||
| 248 | + aclrtMemcpy(hOut.data(), hOut.size(), testOutOfPlaceRaw ? dOut : dY, hOut.size(), | ||
| 249 | + ACL_MEMCPY_DEVICE_TO_HOST); | ||
| 250 | + | ||
| 251 | + if (alpha == 0.0f || nnz == 0) { | ||
| 252 | + if (std::memcmp(hOut.data(), hYBytes.data(), hYBytes.size()) != 0) { | ||
| 253 | + std::printf("[FAIL] %s: alpha==0 or nnz==0 not bit-exact!\n", name); | ||
| 254 | + ok = false; | ||
| 255 | + } | ||
| 256 | + } else { | ||
| 257 | + float rtol = (valType == ACL_FLOAT) ? 1e-4f : (valType == ACL_FLOAT16 ? 1e-3f : 5e-3f); | ||
| 258 | + float atol = (valType == ACL_FLOAT) ? 1e-5f : (valType == ACL_FLOAT16 ? 1e-3f : 5e-3f); | ||
| 259 | + for (int64_t i = 0; i < N; ++i) { | ||
| 260 | + float got = 0.0f; | ||
| 261 | + float want = 0.0f; | ||
| 262 | + if (valType == ACL_FLOAT) { | ||
| 263 | + std::memcpy(&got, &hOut[static_cast<size_t>(i) * 4u], 4u); | ||
| 264 | + std::memcpy(&want, &goldenBytes[static_cast<size_t>(i) * 4u], 4u); | ||
| 265 | + } else if (valType == ACL_FLOAT16) { | ||
| 266 | + uint16_t gh = 0; | ||
| 267 | + uint16_t wh = 0; | ||
| 268 | + std::memcpy(&gh, &hOut[static_cast<size_t>(i) * 2u], 2u); | ||
| 269 | + std::memcpy(&wh, &goldenBytes[static_cast<size_t>(i) * 2u], 2u); | ||
| 270 | + got = Fp16ToFloat(gh); | ||
| 271 | + want = Fp16ToFloat(wh); | ||
| 272 | + } else { | ||
| 273 | + uint16_t gb = 0; | ||
| 274 | + uint16_t wb = 0; | ||
| 275 | + std::memcpy(&gb, &hOut[static_cast<size_t>(i) * 2u], 2u); | ||
| 276 | + std::memcpy(&wb, &goldenBytes[static_cast<size_t>(i) * 2u], 2u); | ||
| 277 | + got = Bf16ToFloat(gb); | ||
| 278 | + want = Bf16ToFloat(wb); | ||
| 279 | + } | ||
| 280 | + float err = std::fabs(got - want); | ||
| 281 | + if (std::isnan(got) || err > atol + rtol * std::fabs(want)) { | ||
| 282 | + std::printf("[FAIL] %s: mismatch at i=%ld got=%g want=%g err=%g\n", | ||
| 283 | + name, static_cast<long>(i), got, want, err); | ||
| 284 | + ok = false; | ||
| 285 | + break; | ||
| 286 | + } | ||
| 287 | + } | ||
| 288 | + } | ||
| 289 | + } | ||
| 290 | + | ||
| 291 | + if (dIdx != nullptr) aclrtFree(dIdx); | ||
| 292 | + if (dX != nullptr) aclrtFree(dX); | ||
| 293 | + if (dY != nullptr) aclrtFree(dY); | ||
| 294 | + if (dOut != nullptr) aclrtFree(dOut); | ||
| 295 | + | ||
| 296 | + if (ok) { | ||
| 297 | + std::printf("[PASS] %s (N=%ld, nnz=%ld, alpha=%.2f)\n", | ||
| 298 | + name, static_cast<long>(N), static_cast<long>(nnz), alpha); | ||
| 299 | + } | ||
| 300 | + return ok; | ||
| 301 | +} | ||
| 302 | + | ||
| 303 | +} // namespace | ||
| 304 | + | ||
| 305 | +int main() | ||
| 306 | +{ | ||
| 307 | + if (aclInit(nullptr) != ACL_SUCCESS) { | ||
| 308 | + std::printf("[FAIL] aclInit failed\n"); | ||
| 309 | + return 1; | ||
| 310 | + } | ||
| 311 | + if (aclrtSetDevice(0) != ACL_SUCCESS) { | ||
| 312 | + std::printf("[FAIL] aclrtSetDevice(0) failed\n"); | ||
| 313 | + aclFinalize(); | ||
| 314 | + return 1; | ||
| 315 | + } | ||
| 316 | + aclrtStream stream = nullptr; | ||
| 317 | + if (aclrtCreateStream(&stream) != ACL_SUCCESS) { | ||
| 318 | + std::printf("[FAIL] aclrtCreateStream failed\n"); | ||
| 319 | + aclrtResetDevice(0); | ||
| 320 | + aclFinalize(); | ||
| 321 | + return 1; | ||
| 322 | + } | ||
| 323 | + aclsparseHandle_t handle = nullptr; | ||
| 324 | + if (aclsparseCreate(&handle) != ACL_SPARSE_STATUS_SUCCESS || | ||
| 325 | + aclsparseSetStream(handle, stream) != ACL_SPARSE_STATUS_SUCCESS) { | ||
| 326 | + std::printf("[FAIL] aclsparseCreate/SetStream failed\n"); | ||
| 327 | + aclrtDestroyStream(stream); | ||
| 328 | + aclrtResetDevice(0); | ||
| 329 | + aclFinalize(); | ||
| 330 | + return 1; | ||
| 331 | + } | ||
| 332 | + | ||
| 333 | + bool allOk = true; | ||
| 334 | + // Simulator-friendly sizes covering all 6 (dtype x idxType) combos + base0/1 + edge cases. | ||
| 335 | + allOk &= RunOneCase<int32_t>(handle, stream, "fp32_i32_base0", 256, 64, 0.75f, ACL_FLOAT, ACL_SPARSE_INDEX_BASE_ZERO, false); | ||
| 336 | + allOk &= RunOneCase<int64_t>(handle, stream, "fp32_i64_base1", 137, 19, -1.25f, ACL_FLOAT, ACL_SPARSE_INDEX_BASE_ONE, false); | ||
| 337 | + allOk &= RunOneCase<int32_t>(handle, stream, "fp16_i32_base0", 256, 64, 0.75f, ACL_FLOAT16, ACL_SPARSE_INDEX_BASE_ZERO, false); | ||
| 338 | + allOk &= RunOneCase<int64_t>(handle, stream, "fp16_i64_base1", 137, 19, -0.5f, ACL_FLOAT16, ACL_SPARSE_INDEX_BASE_ONE, false); | ||
| 339 | + allOk &= RunOneCase<int32_t>(handle, stream, "bf16_i32_base0", 256, 64, 0.75f, ACL_BF16, ACL_SPARSE_INDEX_BASE_ZERO, false); | ||
| 340 | + allOk &= RunOneCase<int64_t>(handle, stream, "bf16_i64_base0", 137, 19, 1.5f, ACL_BF16, ACL_SPARSE_INDEX_BASE_ZERO, false); | ||
| 341 | + allOk &= RunOneCase<int32_t>(handle, stream, "empty_nnz", 64, 0, 2.0f, ACL_FLOAT, ACL_SPARSE_INDEX_BASE_ZERO, false); | ||
| 342 | + allOk &= RunOneCase<int32_t>(handle, stream, "alpha_zero_fp16", 64, 16, 0.0f, ACL_FLOAT16, ACL_SPARSE_INDEX_BASE_ZERO, true); | ||
| 343 | + allOk &= RunOneCase<int32_t>(handle, stream, "degenerate_1_1_bf16", 1, 1, 3.0f, ACL_BF16, ACL_SPARSE_INDEX_BASE_ZERO, true); | ||
| 344 | + | ||
| 345 | + aclsparseDestroy(handle); | ||
| 346 | + aclrtDestroyStream(stream); | ||
| 347 | + aclrtResetDevice(0); | ||
| 348 | + aclFinalize(); | ||
| 349 | + | ||
| 350 | + std::printf("\n=== axpyi_test (arch35): %s ===\n", allOk ? "ALL PASSED" : "FAILED"); | ||
| 351 | + return allOk ? 0 : 1; | ||
| 352 | +} | ||
| @@ -0,0 +1,149 @@ | |||
| 1 | +# Copyright (c) 2026 Huawei Technologies Co., Ltd. | ||
| 2 | +# All rights reserved. | ||
| 3 | +# | ||
| 4 | +# This source code is licensed under the CANN Open Software License Agreement | ||
| 5 | +# Version 2.0 (the "License"). You may not use this file except in compliance | ||
| 6 | +# with the License. You may obtain a copy of the License at | ||
| 7 | +# | ||
| 8 | +# https://gitcode.com/cann/ops-sparse/blob/master/LICENSE | ||
| 9 | +"""Benchmark aclsparse_axpyi (both NPUGraph pure device time & Eager time) vs RTX 5880.""" | ||
| 10 | + | ||
| 11 | +import argparse | ||
| 12 | +import statistics | ||
| 13 | +import torch | ||
| 14 | +import torch_npu # noqa: F401 | ||
| 15 | +import cann_ops_sparse # noqa: F401 | ||
| 16 | + | ||
| 17 | +SHAPES = [ | ||
| 18 | + (100_000, 1_000, "int32"), | ||
| 19 | + (100_000, 10_000, "int32"), | ||
| 20 | + (1_000_000, 10_000, "int32"), | ||
| 21 | + (1_000_000, 50_000, "int32"), | ||
| 22 | + (1_000_000, 100_000, "int64"), | ||
| 23 | + (5_000_000, 50_000, "int32"), | ||
| 24 | + (5_000_000, 250_000, "int32"), | ||
| 25 | + (10_000_000, 500_000, "int64"), | ||
| 26 | +] | ||
| 27 | + | ||
| 28 | +GPU_5880_MS = { | ||
| 29 | + (100_000, 1_000, "int32"): (0.0035, 0.0040, 0.0036), | ||
| 30 | + (100_000, 10_000, "int32"): (0.0029, 0.0032, 0.0040), | ||
| 31 | + (1_000_000, 10_000, "int32"): (0.0029, 0.0032, 0.0037), | ||
| 32 | + (1_000_000, 50_000, "int32"): (0.0032, 0.0036, 0.0047), | ||
| 33 | + (1_000_000, 100_000, "int64"): (0.0040, 0.0043, 0.0061), | ||
| 34 | + (5_000_000, 50_000, "int32"): (0.0032, 0.0036, 0.0044), | ||
| 35 | + (5_000_000, 250_000, "int32"): (0.0060, 0.0063, 0.0102), | ||
| 36 | + (10_000_000, 500_000, "int64"): (0.0125, 0.0098, 0.0158), | ||
| 37 | +} | ||
| 38 | + | ||
| 39 | + | ||
| 40 | +def make_distinct_indices(N, nnz, idx_dt, device): | ||
| 41 | + # Knuth golden-ratio prime (coprime to all 10^k => guaranteed distinct & uniform across [0, N)). | ||
| 42 | + step = 2654435761 | ||
| 43 | + k = torch.arange(nnz, dtype=torch.int64, device=device) | ||
| 44 | + idx = (k * step + 137) % N | ||
| 45 | + return idx.to(idx_dt) | ||
| 46 | + | ||
| 47 | + | ||
| 48 | +@torch.no_grad() | ||
| 49 | +def measure_eager_ms(fn, warmup, iters): | ||
| 50 | + for _ in range(warmup): | ||
| 51 | + fn() | ||
| 52 | + torch.npu.synchronize() | ||
| 53 | + start_ev = torch.npu.Event(enable_timing=True) | ||
| 54 | + end_ev = torch.npu.Event(enable_timing=True) | ||
| 55 | + samples = [] | ||
| 56 | + for _ in range(5): | ||
| 57 | + start_ev.record() | ||
| 58 | + for _ in range(iters): | ||
| 59 | + fn() | ||
| 60 | + end_ev.record() | ||
| 61 | + torch.npu.synchronize() | ||
| 62 | + samples.append(start_ev.elapsed_time(end_ev) / iters) | ||
| 63 | + return statistics.median(samples) | ||
| 64 | + | ||
| 65 | + | ||
| 66 | +@torch.no_grad() | ||
| 67 | +def measure_graph_ms(fn, graph_iters=50): | ||
| 68 | + """Capture multiple calls into NPUGraph (same methodology as RTX 5880 CUDA Graph in Section 6.1).""" | ||
| 69 | + # Warmup first (populates bounds cache & allocator) | ||
| 70 | + for _ in range(5): | ||
| 71 | + fn() | ||
| 72 | + torch.npu.synchronize() | ||
| 73 | + | ||
| 74 | + g = torch.npu.NPUGraph() | ||
| 75 | + with torch.npu.graph(g): | ||
| 76 | + for _ in range(graph_iters): | ||
| 77 | + fn() | ||
| 78 | + torch.npu.synchronize() | ||
| 79 | + | ||
| 80 | + # Warmup replay | ||
| 81 | + for _ in range(5): | ||
| 82 | + g.replay() | ||
| 83 | + torch.npu.synchronize() | ||
| 84 | + | ||
| 85 | + start_ev = torch.npu.Event(enable_timing=True) | ||
| 86 | + end_ev = torch.npu.Event(enable_timing=True) | ||
| 87 | + samples = [] | ||
| 88 | + for _ in range(7): | ||
| 89 | + start_ev.record() | ||
| 90 | + g.replay() | ||
| 91 | + end_ev.record() | ||
| 92 | + torch.npu.synchronize() | ||
| 93 | + samples.append(start_ev.elapsed_time(end_ev) / graph_iters) | ||
| 94 | + del g | ||
| 95 | + torch.npu.empty_cache() | ||
| 96 | + return statistics.median(samples) | ||
| 97 | + | ||
| 98 | + | ||
| 99 | +@torch.no_grad() | ||
| 100 | +def main(): | ||
| 101 | + p = argparse.ArgumentParser() | ||
| 102 | + p.add_argument("--warmup", type=int, default=15) | ||
| 103 | + p.add_argument("--iter", type=int, default=60) | ||
| 104 | + p.add_argument("--ratio-target", type=float, default=0.25) | ||
| 105 | + args = p.parse_args() | ||
| 106 | + | ||
| 107 | + device = torch.device("npu:0") | ||
| 108 | + dtypes = [("fp32", torch.float32, 0), ("fp16", torch.float16, 1), ("bf16", torch.bfloat16, 2)] | ||
| 109 | + | ||
| 110 | + print( | ||
| 111 | + f"{'N':>10} | {'nnz':>7} | {'idx':>5} | {'dt':>4} | " | ||
| 112 | + f"{'graph(ms)':>9} | {'eager(ms)':>9} | {'ref_npu':>9} | {'5880(ms)':>8} | {'g_ratio':>7} | {'pass':>4}" | ||
| 113 | + ) | ||
| 114 | + print("-" * 102) | ||
| 115 | + fails = 0 | ||
| 116 | + for N, nnz, idx_name in SHAPES: | ||
| 117 | + idx_dt = torch.int64 if idx_name == "int64" else torch.int32 | ||
| 118 | + x_ind = make_distinct_indices(N, nnz, idx_dt, device) | ||
| 119 | + x_ind_i64 = x_ind.to(torch.int64) | ||
| 120 | + for dt_name, dtype, col in dtypes: | ||
| 121 | + x_val = torch.randn(nnz, dtype=dtype, device=device) | ||
| 122 | + y = torch.randn(N, dtype=dtype, device=device) | ||
| 123 | + | ||
| 124 | + op_fn = lambda: torch_npu.sparse.aclsparse_axpyi(0.5, x_val, x_ind, y) | ||
| 125 | + ref_fn = lambda: y.index_add(0, x_ind_i64, x_val, alpha=0.5) | ||
| 126 | + | ||
| 127 | + t_eager = measure_eager_ms(op_fn, args.warmup, args.iter) | ||
| 128 | + try: | ||
| 129 | + t_graph = measure_graph_ms(op_fn, graph_iters=30) | ||
| 130 | + except Exception as e: | ||
| 131 | + print(f" [NPUGraph warn {N}/{nnz}/{dt_name}: {e}]") | ||
| 132 | + t_graph = t_eager | ||
| 133 | + t_ref = measure_eager_ms(ref_fn, 5, 20) | ||
| 134 | + t_5880 = GPU_5880_MS[(N, nnz, idx_name)][col] | ||
| 135 | + best_t = min(t_graph, t_eager) | ||
| 136 | + ratio = t_5880 / best_t if best_t > 0 else 0.0 | ||
| 137 | + ok = ratio >= args.ratio_target | ||
| 138 | + if not ok: | ||
| 139 | + fails += 1 | ||
| 140 | + print( | ||
| 141 | + f"{N:>10} | {nnz:>7} | {idx_name:>5} | {dt_name:>4} | " | ||
| 142 | + f"{t_graph:9.4f} | {t_eager:9.4f} | {t_ref:9.4f} | {t_5880:8.4f} | " | ||
| 143 | + f"{ratio:6.2f}x | {'PASS' if ok else 'FAIL'}" | ||
| 144 | + ) | ||
| 145 | + print(f"\nSummary (NPUGraph/pure-device): {24 - fails}/24 passed target >= {args.ratio_target:.2f}x 5880") | ||
| 146 | + | ||
| 147 | + | ||
| 148 | +if __name__ == "__main__": | ||
| 149 | + main() | ||


[Minor] AIV 核数缓存为非线程安全的函数内 static 且跨 device 复用
GetCachedAivCoreCount用未加锁的static uint32_t cached缓存结果,多线程首次并发调用存在数据竞争(UB);同时该缓存按进程全局保存、不区分 deviceId,多卡场景下不同设备 AIV 核数不同会返回错误核数,影响 blockNum 切分。建议改用std::once_flag/std::atomic保证线程安全,或按 deviceId 维度做缓存。