Skip to content

Integrate NPU SpMM Demo into DGL - #7912

Open
zhuqiming1025 wants to merge 330 commits into
dmlc:masterfrom
zhuqiming1025:master
Open

zhuqiming1025 wants to merge 330 commits into
dmlc:masterfrom
zhuqiming1025:master

Conversation

@zhuqiming1025

Copy link
Copy Markdown

Description

Checklist

Please feel free to remove inapplicable items for your PR.

  • The PR title starts with [$CATEGORY] (such as [NN], [Model], [Doc], [Feature]])
  • I've leverage the tools to beautify the python and c++ code.
  • The PR is complete and small, read the Google eng practice (CL equals to PR) to understand more about small PR. In DGL, we consider PRs with less than 200 lines of core code change are small (example, test and documentation could be exempted).
  • All changes have test coverage
  • Code is well-documented
  • To the best of my knowledge, examples are either not affected by this change, or have been fixed to be compatible with this change
  • Related issue is referred in this PR
  • If the PR is for a new model/paper, I've updated the example index here.

Changes

xuejiakn and others added 28 commits August 14, 2026 08:21
fix(npu): sync PyTorch NPU stream for graph-structure queries

Created-by: xuejikan11
Commit-by: xuejikan
Merged-by: knightgd
Description: ## Summary
Sync PyTorch NPU stream for graph-structure queries to fix data races.

## Files (7)
- python/dgl/_ffi/streams.py
- python/dgl/core.py
- python/dgl/heterograph.py
- src/array/array.cc
- src/array/ascend/segment_reduce.cc
- src/array/kernel.cc
- src/graph/unit_graph.cc

关联的Issue: BUPT-GAMMA#6

See merge request: AI4Science/dgl-ascend!9
feat(sddmm): add SDDMM operator with NPU-native kernels

Created-by: xuejikan11
Commit-by: xuejikan
Merged-by: knightgd
Description: ## Summary
Add SDDMM with 3 NPU-native kernels + host dispatch.

## Files (8)
- python/dgl/_sparse_ops.py
- src/array/ascend/sddmm.cc (new)
- src/array/ascend/sddmm_dot_kernel.cpp (new)
- src/array/ascend/sddmm_copy_lhs_kernel.cpp (new)
- src/array/ascend/sddmm_binary_kernel.cpp (new)
- src/array/ascend/sddmm_copy_lhs_tiling.h (new)
- src/array/ascend/sddmm_binary_tiling.h (new)
- tests/python/ascend/test_sddmm.py (new)

关联的Issue: BUPT-GAMMA#7

See merge request: AI4Science/dgl-ascend!10
feat(spmm): add unified SPMM kernel with FP32/FP16 template

Created-by: xuejikan11
Commit-by: xuejikan
Merged-by: knightgd
Description: ## Summary
Add unified SPMM kernel with template-based FP32/FP16 support.

## Files (6)
- src/array/ascend/spmm.cc (modified)
- src/array/ascend/spmm_unified_aiv_kernel.cpp (new)
- src/array/ascend/spmm_unified_maxmin_kernel.cpp (new)
- src/array/ascend/spmm_unified_sum_kernel.cpp (new)
- src/array/ascend/spmm_unified_tiling.h (new)
- tests/python/ascend/test_spmm.py (new)

关联的Issue: BUPT-GAMMA#8

See merge request: AI4Science/dgl-ascend!11
feat(edge_softmax): add edge_softmax and CSRTranspose NPU support

Created-by: xuejikan11
Commit-by: xuejikan
Merged-by: knightgd
Description: ## Summary
Add edge_softmax kernel + CSRTranspose.

## Files (5)
- src/array/ascend/edge_softmax.cc (new)
- src/array/ascend/edge_softmax_kernel.cpp (new)
- src/array/ascend/edge_softmax_tiling.h (new)
- src/array/ascend/csr_transpose.cc (new)
- tests/ascend/test_edge_softmax_npu.py (new)

关联的Issue: BUPT-GAMMA#9

See merge request: AI4Science/dgl-ascend!12
…ITCH_CUDA_ASCEND

PR BUPT-GAMMA#16 added Ascend SDDMM kernel implementations (SDDMMCsr<kDGLAscend> /
SDDMMCoo<kDGLAscend> template specializations) and changed the macro in
kernel.cc::SDDMM() from ATEN_XPU_SWITCH_CUDA to ATEN_XPU_SWITCH_CUDA_ASCEND.

However, array.cc::CSRSDDMM() and array.cc::COOSDDMM() — the lower-level
dispatch entry points called by dgl_sparse (matmul.cc::SDDMMNoAutoGrad and
BroadcastOpNoAutoGrad) — were not updated. They still use
ATEN_XPU_SWITCH_CUDA, which treats kDGLAscend as unsupported and falls
back to LOG(FATAL) at runtime.

This fix changes both CSRSDDMM and COOSDDMM in array.cc to use
ATEN_XPU_SWITCH_CUDA_ASCEND, consistent with kernel.cc.

Without this fix, dgl.sparse.SDDMM() and related operations
(BroadcastAdd/Sub/Mul/Div, SpMM backward) silently fail on NPU.
Add tests verifying that dgl.sparse.sddmm() correctly routes to Ascend
SDDMM kernels through the array.cc::CSRSDDMM/COOSDDMM dispatch path.

Before the macro fix, these calls would LOG(FATAL) with
does not support ascend device. After the fix, they route to
SDDMMCsr<kDGLAscend>/SDDMMCoo<kDGLAscend> without crash.

Tests cover:
- COO format SDDMM (no crash, shape correct)
- CSR format SDDMM (no crash, shape correct)
- Various edge counts
- Empty graph
- FP16 dtype
- Consistency: both gsddmm (kernel.cc) and dgl.sparse (array.cc) paths work
Move dgl.sparse dispatch path tests from standalone test_sddmm_sparse.py
into test_sddmm.py as TestSparseSDDMM class. Use int32 indices to avoid
NPU DLPack int64 overflow issue (unrelated to the macro fix).
…ITCH_CUDA_ASCEND

PR BUPT-GAMMA#16 (GitHub) added Ascend SDDMM kernel implementations
(SDDMMCsr<kDGLAscend> / SDDMMCoo<kDGLAscend> template specializations)
and changed the macro in kernel.cc::SDDMM() from ATEN_XPU_SWITCH_CUDA
to ATEN_XPU_SWITCH_CUDA_ASCEND.

However, array.cc::CSRSDDMM() and array.cc::COOSDDMM() -- the lower-level
dispatch entry points called by dgl_sparse (matmul.cc::SDDMMNoAutoGrad
and BroadcastOpNoAutoGrad) -- were not updated. They still use
ATEN_XPU_SWITCH_CUDA, which treats kDGLAscend as unsupported and crashes
with LOG(FATAL).

This fix changes both CSRSDDMM and COOSDDMM in array.cc to use
ATEN_XPU_SWITCH_CUDA_ASCEND, consistent with kernel.cc.

Also adds TestSparseSDDMM class to test_sddmm.py verifying dgl.sparse.sddmm
does not crash on NPU.
…end-macro

fix(sddmm): route CSRSDDMM/COOSDDMM to Ascend kernels via ATEN_XPU_SWITCH_CUDA_ASCEND
fix(sddmm): route CSRSDDMM/COOSDDMM to Ascend kernels via ATEN_XPU_SWITCH_CUDA_ASCEND

Created-by: xuejikan11
Commit-by: xuejikan11
Merged-by: knightgd
Description: ## Summary

Fix missing `ATEN_XPU_SWITCH_CUDA_ASCEND` macro in `array.cc::CSRSDDMM()` and `array.cc::COOSDDMM()`.

## Problem

PR !10 (feat/sddmm-ascend) added Ascend SDDMM kernel implementations (`SDDMMCsr<kDGLAscend>` / `SDDMMCoo<kDGLAscend>` template specializations) and changed the macro in `kernel.cc::SDDMM()` from `ATEN_XPU_SWITCH_CUDA` to `ATEN_XPU_SWITCH_CUDA_ASCEND`.

However, `array.cc::CSRSDDMM()` and `array.cc::COOSDDMM()` -- the lower-level dispatch entry points called by `dgl_sparse` (`matmul.cc::SDDMMNoAutoGrad` and `BroadcastOpNoAutoGrad`) -- were not updated. They still use `ATEN_XPU_SWITCH_CUDA`, which treats `kDGLAscend` as unsupported and crashes with `LOG(FATAL)`.

## Two dispatch paths

| Path | Entry point | Macro status | Affected APIs |
|------|-------------|-------------|---------------|
| `dgl.ops.gsddmm` | `kernel.cc::SDDMM()` | Fixed in PR !10 | gsddmm |
| `dgl.sparse.sddmm` | `array.cc::CSRSDDMM/COOSDDMM()` | **Fixed in this PR** | dgl.sparse.SDDMM, BroadcastAdd/Sub/Mul/Div, SpMM backward |

## Changes

- `src/array/array.cc`: 2 lines changed
  - `CSRSDDMM`: `ATEN_XPU_SWITCH_CUDA` -> `ATEN_XPU_SWITCH_CUDA_ASCEND`
  - `COOSDDMM`: `ATEN_XPU_SWITCH_CUDA` -> `ATEN_XPU_SWITCH_CUDA_ASCEND`
- `tests/python/ascend/test_sddmm.py`: added TestSparseSDDMM class (112 lines)
  - Verifies `dgl.sparse.sddmm()` does not crash on NPU (COO + CSR)
  - Tests shape correctness, empty graph, FP16
  - Consistency test: both `gsddmm` and `dgl.sparse` paths work

## Verification

- Build: success on Ascend 910B3 (CANN 9.0.0, torch_npu 2.7.1.post4)
- Tests: 46/46 passed (40 existing + 6 new, no regression)

```
tests/python/ascend/test_sddmm.py    46 passed
```

## 类型标签
- [x] Bug修复

See merge request: AI4Science/dgl-ascend!13
14 cases covering structural validity (sampled edges are true neighbors,
per-row count == min(fanout, degree)), deterministic exact comparison
against CPU for select-all and fanout >= degree, semantic checks (no
duplicates without replacement, edge-id mapping), unsorted COO input,
default in-edge direction (transposed COO path), statistical uniformity,
and an NPU path coverage guard. Mirrors the structure of
test_csr_row_wise_sampling_npu.py.
Route NPU COO row-wise uniform sampling to an assembly of existing
Ascend operators instead of falling through to LOG(FATAL): full-graph
COOToCSR followed by the native CSR uniform-sampling kernel. The row
ids pass straight through to the CSR kernel because the full-graph
indptr is indexed by real node ids, so the sampled output rows are
already real node ids (no Range + IndexSelect remapping).

Degenerate inputs (empty rows, empty graph, zero fanout) return an
empty COO matrix without launching kernels. The weighted path (prob or
mask given) is rejected explicitly as unsupported.
COO-format graphs do not support order='srcdst' (only CSR does), so the
CPU-side verification helpers must pick the edge order based on the
graph's created formats.
OUT_DEG_5 wrongly stated node 4 has out-degree 0 (carried over from the
in-degree table of the CSR test); edge (4,1) gives it out-degree 1. The
degree-0 assertion becomes a deterministic degree-1 check instead.
- CHECK that rows and the graph share the same dtype in the assembler
  (fails loudly instead of silently corrupting indices)
- explicit <cstdint> include instead of relying on transitive headers
- tests: empty graph (nnz == 0) and dtype-mismatch rejection
…flow

Kernel: drop row ids outside [0, num_total_rows) as empty rows instead
of indexing indptr out of bounds. Matches the CPU path, where
COOSliceRows silently discards invalid seed ids. The total row count is
passed through a new tiling entry.

Launcher: saturating check on num_rows * num_samples — overflow now
fails loudly with a CHECK instead of wrapping and under-allocating the
output buffers.

These defenses do not rely on the Python-level nodes validation; they
protect any caller that reaches the aten layer directly.
Replace the single-core scalar-GM kernel (1 of 40 vector cores, ~0.4x
CPU on 100k-row graphs) with a 40-core AIV_ONLY design:

- nnz-balanced row partitions and per-block output offsets are computed
  on the host and uploaded as GM tables (spmm rowSplit pattern); blocks
  write disjoint output ranges, no cross-block reduction
- per-row CSR windows are bulk-copied GM->UB via double-buffered VECIN
  queues, sampled with scalar reads from the DeQue'd tensor, and staged
  out through a VECOUT queue one complete Alloc/EnQue/DeQue/Free cycle
  at a time (sddmm queue discipline)
- rows whose degree exceeds the UB window fall back to direct-GM
  sampling, bounding memory for skewed graphs
- output buffers are zeroed on the launch stream before the kernel:
  DGL's allocator reuses device memory without zeroing, so slots not
  written must read as 0, not stale data from earlier launches
- table uploads use stream-ordered memcpyAsync followed by a stream
  sync, keeping stack sources alive until the copy lands

Hardware parameters are queried at runtime instead of hard-coded:
vector-core count via ACL_DEV_ATTR_VECTOR_CORE_NUM (40 on 910B, other
SoCs/vNPU instances differ) and per-core UB size via
ACL_DEV_ATTR_UBUF_PER_VECTOR_CORE (192KB on 910B, 248KB on 950PR), the
latter passed to the kernel through the tiling block.

Kernel-level speedup on a 100k-row CSR graph: ~1200ms -> 19ms (~65x).
End-to-end COO-graph sampling remains dominated by COOToCSR (~1.2s),
tracked separately.
Documents product support (runtime-queried hardware adaptation across
SoCs), design (assembly route + multi-core AIV kernel), parameter and
constraint specs, scenario coverage, and measured performance on
Ascend910B3 including the stage-by-stage breakdown (65x kernel
speedup; end-to-end bottleneck attributed to the upstream COOToCSR
conversion).
The src/array/ascend directory carries no per-operator docs by
convention (18 operators, none documented inline); a lone README next
to one file breaks that consistency. Operator documentation lives in
the top-level README and docs/ instead.
- run clang-format-18 (repo .clang-format, Google base) over the four
  new/rewritten operator files
- drop a redundant !select_all conjunct (num_samples == 0 implies it)
  in both launchers, flagged by cppcheck knownConditionTrueFalse
- simplify an always-true ternary in the UB size fallback
- passedByValue on the mat parameter is kept: it matches the upstream
  aten template signature used across every backend implementation
Add coverage dimensions the perf rewrite must hold:
- sorted/unsorted flag invariance (unified counting-sort path anchor)
- cache semantics: repeat-call consistency, address-reuse no-stale-hit,
  distinct-graph no-collision
- defense: out-of-range row id fails loudly
- multi-band large graphs (2M rows / 500k edges)
- sampling integration on COO-restricted graphs (DEBT-01 scenario)

Oracle notes: per-source degree (not per-dst bincount) with
min(fanout, out_deg) expectation; select-all cap is unbounded.
Three test-side bugs found and fixed during bring-up (int32 graph
must be CPU-built, adjacency_matrix has no transpose kwarg, bincount
axis + select-all cap). No production code changed.

38/38 on Ascend 910B3 against the pre-rewrite implementation.
Ascend SpMM kernel only supports op='copy_lhs'. NNConv's
graph.update_all(fn.u_mul_e(...), fn.sum(...)) triggers
_gspmm(op='mul', reduce='sum') which LOG(FATAL) on NPU.

Add _npu_gspmm_binary() that decomposes fused SpMM into NPU-native
ops: index_select + elementwise mul/add + segment_reduce('sum').
Add NPU interception branch in _gspmm() for op in ('mul','add')
and reduce_op=='sum'. CPU/GPU paths are unaffected.

Tested on Ascend 910B3 with MPNNModel regression/classification/reload.
20 cases / 25 parametrized expansions mirroring the uniform CSR suite:
deterministic exact-compare (select-all, fanout>degree, edge_dir=out),
structural + statistical checks for random sampling, fused-specific
semantics (renumbering, mapping reuse across layers, mapping dtype =
graph idtype), batch-write boundary cases (zero-degree rows, single
seed, empty request, fanout zero, 4100-degree hub row), and e2e hybrid
coverage (hetero graphs, exclude_edges, NPU path coverage assertions,
two-layer NeighborSampler).
… launcher

Multi-core AIV kernel (twin of the uniform CSR kernel) with fused
outputs: block-local CSR indptr, coo_rows carrying row positions, and a
compact interleaved (rid, pos) pair array for the seed mapping. All
kernel outputs are contiguous batch writes staged in UB and flushed with
DataCopyPad (no GlobalTensor scalar access); the host launcher scatters
the pairs into seed_mapping after kernel completion since AscendC has no
GM scatter primitive.

Huge-degree rows stream through window-sized segments; no-replace
sampling uses a prefix-window reservoir that reproduces algorithm R
exactly regardless of segmentation. The dispatcher routes uniform fused
sampling on NPU inputs to the new launcher and rejects weighted fused
sampling with an explicit error.
iambowen and others added 30 commits September 29, 2026 14:00
Co-authored-by: Bowen Ma<iambowen.m@qq.com>
feat(ascend): support  BFS Nodes/Edges Frontiers capabilities in dgl

Created-by: TokenDance
Commit-by: Bowen Ma
Merged-by: knightgd
Description: ## 描述

将 BFSNodesFrontiers / BFSEdgesFrontiers 两个直调算子从独立子工程接入主仓 aten 派发体系,替代并作废原独立工程 PR !36:

- **算子宿主层**:新增 `src/array/ascend/bfs_nodes_frontiers.cc` / `bfs_edges_frontiers.cc`,注册到主仓 `src/array/ascend/`,通过 aten 派发在 NPU 上自动路由到新 kernel。
- **Kernel 层**:新增 `bfs_nodes_frontiers_kernel.cpp` / `bfs_edges_frontiers_kernel.cpp`,复用平移的 `bfs_core.h`(BFS 工作区布局 `bfs_ws_layout.h`);kernel 单入口 + `dtype_bytes` 分支,规避 CANN 9.0.0 `K_TYPE_AIV` meta 注册 bug。
- **CANN 兼容**:新增 `acl_attr_compat.h`,兼容 CANN 8.3 / 8.5 头文件差异。
- **Python 侧**:沿用既有 `dgl.bfs_nodes_generator` / `dgl.bfs_edges_generator` 接口,NPU 图自动走新 kernel,无需改用户调用。
- **可靠性保留**:errflag 双保险 / SoftSyncAll / 保底开关(回退 CPU 路径)全部保留。
- **派发修正**:`src/array/array.cc` 两处 `ATEN_XPU_SWITCH` 改为 `ATEN_XPU_SWITCH_CUDA_ASCEND`,使 BFS 系列在 NPU 上可达。
- **次要改动**:`python/dgl/traversal.py` 增加 NPU 分支;多个 ascend 源文件(coo2csr / csr_row_wise_sampling_* / csr_row_wise_topk / spmm)补 include。

## 关联的Issue

- 关联 Issue:BUPT-GAMMA#31(原已关联独立工程 PR !36,本 PR 取代该独立工程 PR 完成同一需求的上库)。
- 独立工程 PR !36 作废。

## 测试

- 新增 NPU 测试:`tests/ascend/test_bfs_nodes_frontiers_npu.py` + `tests/ascend/test_bfs_edges_frontiers_npu.py`,111 个用例在 NPU 全量通过(CP3 功能验收)。
- CPU traversal 回归:`dgl.bfs_nodes_generator` / `dgl.bfs_edges_generator` 6/6 通过。
- 独立工程对照验证通过(独立工程目录 `BFSNodesFrontiers/` 不并入本 PR)。
- 性能:CP4 验收确认不劣化。

## 文档更新

- 无需额外文档更新(Python 接口未变)。

## 类型标签

- [ ] Bug修复
- [x] 新特性
- [ ] 性能优化
- [ ] 文档更新
- [ ] 其他

See merge request: AI4Science/dgl-ascend!37
- dynamic block_dim via aclrtGetDeviceInfo instead of hardcoded 1
- keep 64-bit fill value bit-exact via FullTilingData{uint64_t n, val}
- replace per-element GM SetValue with UB stamp + DataCopyPad(Ext)
- drop fake DOUBLE_BUFFER; add MTE2->MTE3 barrier for 64-bit doubling
- extend npu tests with tile/multi-core boundary sizes
feat(array): add AscendC Full operator with vectorized fill path
fix(array): add AscendC Full operator with vectorized fill path

Created-by: gxl_gyr
Commit-by: gxlgyr
Merged-by: knightgd
Description: ## Description
<!-- Brief description. Refer to the related issues if existed.
It'll be great if relevant reviewers can be assigned as well.-->

## Checklist
Please feel free to remove inapplicable items for your PR.
- [ ] The PR title starts with [$CATEGORY] (such as [NN], [Model], [Doc], [Feature]])
- [ ] I've leverage the [tools](https://docs.google.com/document/d/1iHyj7zlmygKSk5gBPsqIqL5ASPzJSPREaNT_QdsiYA4/edit) to beautify the python and c++ code.
- [ ] The PR is complete and small, read the [Google eng practice (CL equals to PR)](https://google.github.io/eng-practices/review/developer/small-cls.html) to understand more about small PR. In DGL, we consider PRs with less than 200 lines of core code change are small (example, test and documentation could be exempted).
- [ ] All changes have test coverage
- [ ] Code is well-documented
- [ ] To the best of my knowledge, examples are either not affected by this change, or have been fixed to be compatible with this change
- [ ] Related issue is referred in this PR
- [ ] If the PR is for a new model/paper, I've updated the example index [here](../examples/README.md).

## Changes
<!-- You could use following template
- [ ] Feature1, tests, (and when applicable, API doc)
- [ ] Feature2, tests, (and when applicable, API doc)
-->


See merge request: AI4Science/dgl-ascend!41
Co-authored-by: shaozengwei<zengwei19861029@163.com>
[feature] 实现单次启动的Ascend concat算子

Created-by: shaozengwei
Commit-by: shaozengwei
Merged-by: knightgd
Description: ## Description
<!-- Brief description. Refer to the related issues if existed.
It'll be great if relevant reviewers can be assigned as well.-->

## Checklist
Please feel free to remove inapplicable items for your PR.
- [ ] The PR title starts with [$CATEGORY] (such as [NN], [Model], [Doc], [Feature]])
- [ ] I've leverage the [tools](https://docs.google.com/document/d/1iHyj7zlmygKSk5gBPsqIqL5ASPzJSPREaNT_QdsiYA4/edit) to beautify the python and c++ code.
- [ ] The PR is complete and small, read the [Google eng practice (CL equals to PR)](https://google.github.io/eng-practices/review/developer/small-cls.html) to understand more about small PR. In DGL, we consider PRs with less than 200 lines of core code change are small (example, test and documentation could be exempted).
- [ ] All changes have test coverage
- [ ] Code is well-documented
- [ ] To the best of my knowledge, examples are either not affected by this change, or have been fixed to be compatible with this change
- [ ] Related issue is referred in this PR
- [ ] If the PR is for a new model/paper, I've updated the example index [here](../examples/README.md).

## Changes
<!-- You could use following template
- [ ] Feature1, tests, (and when applicable, API doc)
- [ ] Feature2, tests, (and when applicable, API doc)
-->


See merge request: AI4Science/dgl-ascend!43
…llback) + review fixes

Co-authored-by: xuejikan11<xuejikan11@noreply.gitcode.com>
fix(ascend): native kernels for Range int32 and CSRToCOO (drop CPU fallback) + review fixes

Created-by: xuejikan11
Commit-by: xuejikan11
Merged-by: knightgd
Description: ### 关联 Issue
- **BUPT-GAMMA#38** https://gitcode.com/AI4Science/dgl-ascend/issues/38 (中文说明:Range int32 / CSRToCOO 原生算子修复 + 同步性能优化)

### Summary

Native AscendC fixes replacing CPU fallbacks, plus review-driven cleanups and redundant-sync removal. 2969/2969 test_nn.py passing on 910B3 (CANN 9.0.0).

Commits:
- f4fb44fe merge upstream master + local NPU fixes (2969/2969)
- 0af850f4 address review findings P1-P3 + comment corrections
- 3b9ada45 native kernels for Range int32 and CSRToCOO (drop CPU fallback)
- 4c01d1a7 restore int32 min/max NPU workaround comments
- 50d9eb9c drop redundant aclrtSynchronizeDevice in favor of stream-scoped sync

### Verified
- test_csr_to_coo_npu.py: 8/8
- Range int32/int64 (multi-block) matches CPU
- test_nn.py: 2969 passed

See merge request: AI4Science/dgl-ascend!44
Co-authored-by: panxiaomu<panxiaomu@noreply.gitcode.com>
[Feature] feat(ascend): add Ascend 950PR (A5) SoC build support

Created-by: panxiaomu
Commit-by: panxiaomu
Merged-by: knightgd
Description: ## Description

本 MR 为 DGL-Ascend 增加 **Ascend 950PR(A5,DAV_3510)芯片的构建支持**。

上游 `master` 目前仅支持 A2 / A3 系列(DAV_2201 架构):
- A2/A3 共享同一指令集与 buffer 尺寸(UB 192KB),SOC_VERSION 只影响编译出的 kernel 微码,可互换运行;
- A5(Ascend 950PR)是 **独立的 DAV_3510 架构**:kernel 源码兼容,但 **UB 更大(248KB vs 192KB)**、核心数为运行时查询(`aclrtGetDeviceInfo`),且 **必须使用各自的 SOC_VERSION** 编译。

本 MR 解决在 A5 设备上编译、安装与运行 DGL 的全部构建链路问题,改动集中在构建脚本与 CMake 配置,**不涉及任何 kernel 源码改动**(A5 kernel 源码与 A2/A3 兼容)。

### 背景与问题

在 Ascend950PR_9579(CANN 9.1.0)上按官方文档安装 DGL-Ascend,存在以下问题:

| # | 问题 | 现象 |
|---|---|---|
| 1 | 构建脚本无法识别 A5 | `detect_soc_version()` 只读 `npu-smi` 的 `NPU Name`(如 `9579`),无对应 case 映射;A5 被回退为 `ascend910b4`,编译出的 kernel 微码与 A5 不匹配 |
| 2 | A5 板卡 `npu-smi -c 0` 不可用 | 部分板卡(如 A310-50)不支持 `-c 0` 参数,导致 SoC 探测直接失败 |
| 3 | `SOC_VERSION` 校验拒绝 A5 | `is_valid_soc()` 仅白名单 A2/A3,`Ascend950PR_9579` 会被判为非法 SoC 而退出 |
| 4 | 探测时机过晚 | 原脚本在参数解析后才 setup Ascend 环境,但 SoC 探测若改用 `aclrtGetSocName` 需要 `libascendcl.so` 在库路径上 |
| 5 | `libpython` 查找硬编码 python3.11 | 官方文档使用 `python=3.10` 创建 conda 环境,`find_library(PYTHON_LIB python3.11 ...)` 找不到库,clean 构建 configure 阶段报 `PYTHON_LIB NOTFOUND` |

### 解决方式

**1. SoC 自动探测升级(build_dgl_ascend.sh)**

- 新增 **Strategy 1**:通过 `aclrtGetSocName` 获取驱动返回的精确 SoC 字符串(如 `Ascend950PR_9579`),该字符串可被 AscendC 编译器原样接受,覆盖全部系列(A2/A3/A5);
- 新增 **Strategy 2 回退**:`npu-smi -c 0` 不可用时自动重试不带 `-c 0` 的版本;
- 新增 `A5_SOC_LIST="ascend950pr_9579"`,按 A2/A3 的白名单风格管理,后续 A5 新型号经验证后追加;
- 新增 `is_a5_soc()` 判断,并在 `-h` 帮助文本中补充 A5 说明;
- 调整主流程顺序:**先 `detect_ascend_toolkit` + `setup_ascend_env`,再解析 SoC**(保证 `libascendcl.so` 可加载);
- `is_valid_soc` 白名单加入 A5,`is_a5_soc` 分支打印 `(Atlas A5 series, DAV_3510)`。

**2. CMake 配置(CMakeLists.txt)**

- 注释说明 A5(DAV_3510)需独立 SOC_VERSION,示例 `Ascend950PR_9579`;
- **修复 `libpython` 探测**:`find_library(PYTHON_LIB python3.11 python3.10 ...)`,兼容官方文档的 `python=3.10` 环境(该问题为仓库既有 bug,非 A5 特有,但阻塞 A5 上的 clean 构建)。

### 环境兼容说明(文档外,运行层)

> 本 MR 不含此改动,仅提示使用方:

官方文档 `AscendInstallation.md` 指定的 `torch_npu==2.8.0.post2` **不支持 A5**(运行时报 `Unsupported soc version: Ascend950PR 9579`)。验证发现需使用 `torch_npu==2.8.0.post5`(同为 torch 2.8 ABI,无需重编 DGL)。建议同步更新 `python/setup.py` 与 `AscendInstallation.md` 中的版本约束(可在后续 MR 中处理)。

---

## Changes

- [x] `script/build_dgl_ascend.sh`:新增 A5 SOC 自动探测(`aclrtGetSocName` 优先 + `npu-smi` 回退)、`A5_SOC_LIST`、`is_a5_soc`、`9579 → Ascend950PR_9579` 映射、帮助文本、探测时序调整
- [x] `CMakeLists.txt`:A5 SOC_VERSION 说明注释;`PYTHON_LIB` 探测兼容 python3.10
- [ ] 文档:`AscendInstallation.md` torch_npu 版本约束更新(建议后续处理)

## Test Plan / 验证

在 **Ascend950PR_9579(A5,CANN 9.1.0)** 上完成以下验证:

### 1. SoC 自动探测

```
$ bash script/build_dgl_ascend.sh -c -j 32
[INFO] Detected SoC via aclrtGetSocName: Ascend950PR_9579
[INFO] SoC: Ascend950PR_9579 (Atlas A5 series, DAV_3510)
[INFO] SoC version: Ascend950PR_9579
[INFO] Build completed successfully!
```

- 环境:conda `dgl-ascend`(python=3.10)、`torch==2.8.0+cpu`、`torch_npu==2.8.0.post5`
- 编译 256 并行时 OOM(cgroup 32GB 限制),以 `-j 32` 成功

### 2. NPU 算子正确性

| 算子 | 结果 | 对比 |
|---|---|---|
| `copy_u_sum` | ✅ | 与 CPU 结果 `allclose(atol=1e-5)` |
| `edge_softmax` | ✅ | 与 CPU 结果 `allclose(atol=1e-5)` |
| GCN 消息传递(update_all + copy_u/sum) | ✅ | 与 CPU 逐位一致(bit-exact) |

```python
import torch, torch_npu, dgl
import dgl.function as fn
g = dgl.graph((torch.tensor([0,1,2,3,1,0]), torch.tensor([1,2,3,0,3,2]))).to('npu')
g.ndata['h'] = torch.randn(4, 8).npu()
g.update_all(fn.copy_u('h', 'm'), fn.sum('m', 'h'))
```

### 3. 测试套件

```
tests/ascend: 152 passed, 54 failed, 4 xfailed
```

- 失败的 54 个集中在 `coo_ops_npu.py`(`COOGetRowDataAndIndices` / `COOSliceRows` / `COOSliceMatrix` 的 `edge-set mismatch`)与 `coo2csr_npu.py` 两个边界用例
- 该类失败为主仓已有算子问题(COO 排序 / eid 语义边界场景),**与 A5 适配无关**,核心图算子与消息传递全部正常

## Checklist

- [x] The PR title starts with `[Feature]`(建议)
- [x] 代码变更小(核心改动 < 200 行,仅 63 行新增)
- [x] 代码有文档注释(SoC 列表、探测策略、UB 差异说明均有注释)
- [ ] 测试覆盖:新增测试建议后续补充(当前验证为手工 + 既有测试套件)
- [x] 相关环境问题记录在 MR 描述中


See merge request: AI4Science/dgl-ascend!45
…se kernels & order DGL kernels against torch_npu submissionsFeat/ascend950pr adaptation (BUPT-GAMMA#43)

* fix(ascend): drop blacklisted GlobalTensor scalar access in binary_elewise kernels

Scalar GetValue/SetValue on GlobalTensor is a production-blacklist API on
Ascend950PR (per-core DCache write-back coherence risk, ADR-0007); the 12
binary_elewise (array-vs-scalar compare) kernels relied on it exclusively,
so on this SoC the result buffer was never written and e.g. HasVertices
(aten::LT) silently returned all-zero, breaking has_nodes/out_degrees and
the degree-normalization path of GraphConv.

Rewrite the kernels to:
- read the tiling block through a typed __gm__ pointer (same 3-word
  layout, host code unchanged);
- stream input/output through UB with DMA (DataCopyPad) instead of scalar
  GM access, comparing on UB-resident values.

Kernel symbols (binary_l_{lt,gt,le,ge,eq,ne}_{i32,i64}) are unchanged.
Verified against CPU on Ascend950PR_9579 (CANN 9.1.0): degrees and
GraphConv now match CPU (max diff ~3.6e-7, fp32).

* feat(ascend): order DGL kernels against torch_npu submissions

torch_npu submits kernels asynchronously on its own (non-default) ACL
stream, while the DGL Ascend array kernels launch on the ACL default
stream and block on it only until their own work completes.  The two
submitters are unordered, which made results nondeterministic and could
raise device-side faults whenever a DGL kernel read a tensor that
torch_npu had just written (feature tensors, generated index arrays).

Handing torch's stream to DGL via DGLSetStream is not a fix: torch_npu
submits to that stream from its internal task-queue thread while DGL
would submit from the caller thread, and concurrent submissions on one
stream corrupt the driver state (observed as host segfaults).

Add a barrier on the python FFI boundary instead:
- wrap the ctypes CDLL so every libdgl C API call first drains
  torch_npu's current stream on the host (cheap when idle);
- DGL ops already host-synchronize at the end, so the reverse direction
  was already ordered;
- the Ascend stream bridge latches lazily (also covers torch_npu being
  imported after dgl), stays silent when NPU is absent, skips
  interpreter shutdown, and can be disabled with
  DGL_ASCEND_STREAM_BRIDGE=0;
- getCurrentAscendStream() falls back to the DeviceAPI stream so the
  kernels always follow whatever stream the host side selects.

Overhead measured on Ascend950PR_9579: ~0.7 ms per GraphConv layer at
5k nodes / 20k edges / 128 hidden.

---------

Co-authored-by: jingxupan <jingxupan@users.noreply.github.com>
Route Ascend COO queries through typed AIV match and gather kernels. Add native CPU comparison and graph API regressions. Integration compilation and NPU execution remain pending; standalone validation does not establish integration test success.
* Add Ascend COOGetDataAndIndices backend and regression tests

Route Ascend COO queries through typed AIV match and gather kernels. Add native CPU comparison and graph API regressions. Integration compilation and NPU execution remain pending; standalone validation does not establish integration test success.

* Fix COO AIV registration and add isolated Python tests

---------

Co-authored-by: 李坤航 <bay@bupt.edu.cn>
* 集成SpMM,BSpMM,SegmentReduce

* 集成SpMM,BSpMM,SegmentReduce

Co-authored-by: zqm19511961081<zhuqiming1025@163.com>

* 添加分布式训练

* 添加分布式训练

Co-authored-by: zqm19511961081<zhuqiming1025@163.com>

* dgl-ascend pip 包发布至PyPI

Co-authored-by: lhp<lihepeng1@huawei.com>
Co-authored-by: lizengyong<18666662564@126.com>

* fix(npu): sync PyTorch NPU stream for graph-structure queries

* feat(sddmm): add SDDMM operator with NPU-native kernels

* feat(spmm): add unified SPMM kernel with FP32/FP16 template

* feat(edge_softmax): add edge_softmax and CSRTranspose NPU support

* fix(sddmm): route CSRSDDMM/COOSDDMM to Ascend kernels via ATEN_XPU_SWITCH_CUDA_ASCEND

PR BUPT-GAMMA#16 (GitHub) added Ascend SDDMM kernel implementations
(SDDMMCsr<kDGLAscend> / SDDMMCoo<kDGLAscend> template specializations)
and changed the macro in kernel.cc::SDDMM() from ATEN_XPU_SWITCH_CUDA
to ATEN_XPU_SWITCH_CUDA_ASCEND.

However, array.cc::CSRSDDMM() and array.cc::COOSDDMM() -- the lower-level
dispatch entry points called by dgl_sparse (matmul.cc::SDDMMNoAutoGrad
and BroadcastOpNoAutoGrad) -- were not updated. They still use
ATEN_XPU_SWITCH_CUDA, which treats kDGLAscend as unsupported and crashes
with LOG(FATAL).

This fix changes both CSRSDDMM and COOSDDMM in array.cc to use
ATEN_XPU_SWITCH_CUDA_ASCEND, consistent with kernel.cc.

Also adds TestSparseSDDMM class to test_sddmm.py verifying dgl.sparse.sddmm
does not crash on NPU.

* feat(spmm): add NPU-native gspmm binary op fallback for mul/add

Ascend SpMM kernel only supports op='copy_lhs'. NNConv's
graph.update_all(fn.u_mul_e(...), fn.sum(...)) triggers
_gspmm(op='mul', reduce='sum') which LOG(FATAL) on NPU.

Add _npu_gspmm_binary() that decomposes fused SpMM into NPU-native
ops: index_select + elementwise mul/add + segment_reduce('sum').
Add NPU interception branch in _gspmm() for op in ('mul','add')
and reduce_op=='sum'. CPU/GPU paths are unaffected.

Tested on Ascend 910B3 with MPNNModel regression/classification/reload.

* test: add NPU test suite for _npu_gspmm_binary (PR BUPT-GAMMA#29)

Covers correctness (mul/add, 2D/1D, various dims), gradient (backward
via update_all), DGL integration (fn.u_mul_e + fn.sum), and edge cases
(single edge, self-loops, large dim, non-intercepted ops).

NPU detection checks torch_npu import and torch.npu.is_available().
Tests fail (not skip) if NPU is unavailable.

16 tests, all passing on Ascend 910B3.

* feat(range): implement AscendC Range kernel for NPU

- New AscendC kernel (range_kernel.cpp): int32/int64, multi-core,
  UB + DataCopyPad batch transfer (replaces blacklisted GlobalTensor::SetValue)
- New Host launcher (range.cc): persistent tiling buffer, dynamic
  block_dim via ACL_DEV_ATTR_VECTOR_CORE_NUM, async (no stream sync)
- Modify entry dispatch (array.cc): replace CPU fallback with direct
  impl::Range<kDGLAscend, IdType> call, symmetric with CUDA path
- Add NPU test script (tests/ascend/test_range_npu.py): functional,
  precision, and performance tests (7/7 passed, 31x~279x speedup)

* feat(scatter_add): add NPU-native ScatterAdd kernel for Ascend 910B3

- Implement AscendC device kernel (SetAtomicAdd + DataCopyPad UB->GM)
- Add host launcher with int32/int64 x float32 template specializations
- Route ScatterAddDispatch to native NPU kernel (replaces CPU fallback)
- Add tests (46 cases: 40 blackbox + 6 whitebox) + golden + precision gate
- Add operator documentation

Math: out[idx[i], *] += feat[i, *] (caller pre-zeros out)
Performance: 17x-44x speedup vs CPU fallback

* feat(grad_minmax_bwd_cmp): adapt UpdateGradMinMax_hetero and BackwardSegmentCmp for Ascend NPU

- BackwardSegmentCmp: out[arg[i,k],k]=feat[i,k] (direct assign, no atomic)
- UpdateGradMinMax_hetero: conditional atomic add via SetAtomicAdd (hetero graph gradient update)
- Single-element scatter write (scratchBuf + GetValue/SetValue + DataCopyPad blockLen=4)
- Synchronization reuses scatter_add pattern (PipeBarrier + SetFlag/WaitFlag + SetAtomicNone)
- int32/int64 x float32 supported; half/bf16/double LOG(FATAL) placeholders
- Replaces CPU fallback (BackwardSegmentCmp) and LOG(FATAL) (UpdateGradMinMax_hetero)

Tests: 59 cases (50 blackbox + 9 whitebox), 58 pass + 1 xfail (binding layer defect)
QA independent probe: 43/43 pass, bit-exact for BackwardSegmentCmp

* fix(build): link libpython to resolve undefined Py* symbols

Development.Module only provides headers, leaving Python3_LIBRARIES empty.
Since libdgl.so links libtorch.so (which pulls in many Python C API
symbols), the linker fails with undefined references to Py*/PyErr_*/etc.

Switch to Development so Python3_LIBRARIES resolves to libpython and the
symbols are satisfied at link time.

* fix(spmm): support copy_rhs in NPU SpMM kernel + fix COOToCSR data array bug

Two bugs fixed in DGL Ascend NPU backend:

1. coo2csr.cc: When COO has no data array, npu_sorted_data was set to
   identity [0,1,...,nnz-1] without gathering by the sort permutation.
   Fixed: now uses launch_gather to apply perm, so npu_sorted_data[j] = perm[j]
   (the original edge index for the j-th sorted edge).

2. spmm.cc + spmm_unified_aiv_kernel.cpp: SpMMCsrAscend only supported
   copy_lhs (gather node features by indices). copy_rhs (aggregate edge
   features) fell back to CPU, but NPU->CPU->NPU data copy failed.
   Fixed: copy_rhs now uses GatherByIndex(efeat, csr.data) to reorder
   efeat into CSC row order, then calls SpMMCsrUnified with isCopyRhs=1
   flag so the kernel reads features sequentially instead of gathering.

Verified: RFdiffusion NPU pLDDT=0.9885, CPU pLDDT=0.9885, diff=0.000005
Tests: 153 passed, 9 pre-existing failures (max/min, unrelated)

* feat(segment_mm): adapt SegmentMM and SegmentMMBackwardB for Ascend NPU via Cube AIC+AIV mix

- SegmentMM: per-etype GEMM via Cube (Mmad + Nd2Nz + LoadData + Fixpipe)
- SegmentMMBackwardB: backward GEMM (A^T @ dC -> dB)
- AIC handles matrix multiplication, AIV is no-op (dense GEMM needs no vector processing)
- host iterates etypes serially, one kernel launch per etype (same as CUDA)
- B_trans handled via LoadData3D enTranspose (ifTranspose unsupported for FP32)
- int32/int64 x float32 supported; half/bf16/double LOG(FATAL) placeholders
- Replaces LOG(FATAL) (no prior CPU fallback existed)

Tests: 61 cases (45 blackbox + 16 whitebox), 100% pass
QA independent probe: 50/50 pass, float32 mixed tolerance (fixed 1e-2 max_abs_error_limit)

* delete: 删除文件 whitebox_segment_mm_branch_coverage.md


Signed-off-by: lhp_lhp <lhp_lhp@noreply.gitcode.com>

* feat(coo_ops): adapt 5 COO operators for Ascend NPU via CSR composition

- COOSort_: row-only sort via COOToCSR+CSRToCOO (column sort CPU fallback)
- COOGetRowNNZ (scalar+array): via COOToCSR + CSRGetRowNNZ
- COOGetRowDataAndIndices: via COOToCSR + CSRGetRowColumnIndices/CSRGetRowData
- COOSliceRows (start/end + rows): via COOToCSR + CSRSliceRows + CSRToCOO
- COOSliceMatrix: via COOToCSR + CSRSliceMatrix + CSRToCOO

Replaces CPU fallback (D2H+CPU+H2D) with native NPU CSR composition.
All 5 operators support int32/int64 IdType.
Tests: 126 cases, 100% pass, bit-exact vs CPU golden.

Note: COOIsSorted, COOIsNonZero (scalar+array) are excluded from this PR
(will be adapted in a follow-up with dedicated AIV kernels to avoid large D2H).

* feat(gather_mm): adapt GatherMM and GatherMMScatter for Ascend NPU via Cube

- GatherMM: per-row gather + GEMM via Cube (host groups by idx_b for efficiency)
- GatherMMScatter Kernel1 (B 3D): Cube GEMM -> AIV SetAtomicAdd scatter to C[idx_c]
- GatherMMScatter Kernel2 (B 2D): outer product scatter, grouped by idx_c (no atomic)
- Cube AIC+AIV mix: AIC does GEMM, AIV handles scatter accumulation
- int32/int64 x float32 supported; half/bf16/double LOG(FATAL) placeholders
- Replaces LOG(FATAL) (no prior CPU fallback existed)

Tests: 86 cases (62 blackbox + 24 whitebox), 84 pass + 2 xfail
  (xfail: K>64 + multi-group Cube B-data isolation, known limitation)
QA independent probe: 73/73 pass, float32 mixed tolerance

* perf(gather_mm): aggregate AIV scatter by idx_c before atomic write to GM

Reduce atomic writes from myRows to unique(idx_c) per AIV core by sorting
idx_c in UB, accumulating consecutive same-target rows, then writing once.
Collision analysis shows 80-99% atomic write reduction for real GNN workloads.

84/84 tests pass, 2 xfailed (pre-existing Cube B-data isolation).

* upload: 上传文件

Signed-off-by: zqm19511961081 <zhuqiming1025@163.com>

* feat: adapt for Ascend A3 (DAV_2201) with dynamic core count

- SOC_VERSION default changed to ascend910b4 (A2/A3 compatible, DAV_2201)
- Replace hardcoded cubeCoreCount=20/vectorCoreCount=40 with
  aclrtGetDeviceInfo runtime query, compatible with A2 (20/40) and
  A3 (24/48) core configurations
- Fix Fixpipe template parameter for CANN 9.1.0 compatibility
- FP16 SpMM sum uses AIV-only path (Cube Fixpipe broken on c220 arch)
- build_dgl_ascend.sh: add -s SOC parameter, npu-smi auto-detection,
  incremental build cache cleanup

* fix: keep 512B alignment in AllocDataSpace (+64 -> +512)

The +64 offset hack breaks 512-byte alignment on A3 (9382), causing
intermittent MTE errors. Change offset to +512 to maintain 512B
alignment while still providing cache-line avoidance.

* fix(segment_mm): address review comments on stream usage and sync memset

- use thread-local current Ascend stream (getCurrentAscendStream) instead
  of the shared default stream (nullptr) to avoid cross-thread interference
- replace blocking aclrtMemset with async aclrtMemsetAsync on the current
  stream (both fwd and bwd empty-etype zero paths)
- sync once after the etype loop instead of per-etype: all launches and
  memsets are ordered on the same stream, allowing GEMMs to pipeline

Verified: libdgl.so rebuild, pytest 61/61 passed, QA precision probe 50/50.

* fix(grad_minmax_bwd_cmp): replace device-wide sync with stream-granular sync

Address review comments (4x 'aclrtSynchronizeDevice waits on all streams
device-wide; use stream-granularity sync'):

- replace aclrtSynchronizeDevice with aclrtSynchronizeStream on the
  current stream (stream-granularity) at both op entry points and before
  the int64->int32 D2H conversion copies
- resolve the launch stream via c10_npu::getCurrentNPUStream when
  available (DGL_USE_PYTORCH_NPU_STREAM): torch_npu executes eager ops on
  its own NPU stream and context, so DGL must target the same stream for
  cross-framework ordering; fall back to getCurrentAscendStream otherwise
- CMake: fall back to linking libtorch_npu.so when standalone c10_npu is
  not found, enabling the torch stream integration
- include torch_npu stream headers before dmlc so dmlc's LOG/CHECK macro
  definitions win (c10's MessageLogger aborts on FATAL instead of
  throwing, breaking LOG(FATAL) error handling)

Verified (910B3, torch_npu 2.7.1.post4): per-test-class runs 52 passed,
1 xpassed, 6 failed (all six int64 cases; failure set identical to the
pre-change baseline in the current environment — pre-existing, unrelated
to the sync granularity change).

* fix(grad_minmax_bwd_cmp): reliable int64->int32 narrowing on current env

The int64 paths narrow idx/arg via CopyTo(CPU) + AsNumBits + CopyTo(NPU).
Under torch_npu 2.7.1.post4 both hops are broken:
  - the framework's blocking D2H memcpy (CopyDataFromTo) reads stale bytes
    from torch-written buffers across torch_npu's own ACL context, even
    after aclrtSynchronizeDevice or torch.npu.synchronize();
  - the AsNumBits AscendC kernel (as_num_bits_i64_to_i32) only converts
    the first n/GetBlockNum() elements (latent bug, block_dim=1 -> first
    16; AsNumBits<kDGLAscend> has no test coverage).

Replace the CPU round-trip with ConvertIdx64To32: stream-ordered async
D2H on the torch current stream + host narrowing + ordered H2D, then
c10_npu::stream_synchronize. Kernel launches stay on DGL's default
stream (mutually ordered). Also verified the AsNumBits kernel truncation
via an identity-mapping probe (arg[r,c]=r -> out==feat).

Verified (910B3, torch_npu 2.7.1.post4): test_grad_minmax_bwd_cmp_npu.py
58 passed + 1 xpassed out of 59 in a single full-suite process, stable
across repeated runs and on two NPU devices (previously 6 int64 failures).

* fix(coo2csr): count both staging buffers in the UB budget and drop KERNEL_TASK_TYPE_DEFAULT

Two fixes from review and regression:
- The scatter kernel allocates two staging buffers (stage_col and
  stage_eid) but the UB budget only subtracted one of them, so blocks
  with data ran 25% over budget. Subtract stage_bytes * 2 (review
  comment by knightgd on PR BUPT-GAMMA#27).
- Remove KERNEL_TASK_TYPE_DEFAULT from both kernels: the macro is not
  supported on CANN 9.0 and fails kernel registration there (107000).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(ascend): remove KERNEL_TASK_TYPE_DEFAULT from the remaining kernels

The macro is unsupported on CANN 9.0 and fails kernel registration
(RegisterAscendBinary aiv ret 107000). Covers the sampling/topk kernels
introduced by this PR and the upstream scatter_add/range/segment-cmp/
spmm_sum/update_grad_minmax kernels.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* release: prepare dgl-ascend 0.0.2 (torch 2.7.1 pin)

- bump version 0.0.1 -> 0.0.2 (update_version.py, libinfo.py,
  c_runtime_api.h, meta.yaml)
- pin torch==2.7.1 / torch_npu==2.7.1.post4 (the fully validated
  environment; the 2.8.0 pin of 0.0.1 exposes cross-context stream
  ordering and kernel issues, tracked separately)
- CMakeLists: Development.Module (wheels carry no libpython dependency)
- restore packaging docs: BUILD_GUIDE / VERSION_MATRIX /
  manylinux Dockerfile (from wheel-pypi-distribution history)
- csr_slice_rows / csr_slice_matrix: fall back to CPU for the slice
  kernels — the NPU slice kernels mishandle non-contiguous / unsorted
  row selections in release builds (memory corruption); correctness
  first, matching the COOSort_ CPU-fallback precedent

Wheel validation (910B3, torch 2.7.1): 15/17 pytest suites fully green
plus segment_reduce / spmm_sum script suites bit-exact; csr_slice suites
have a known issue (COO subgraph chain reads torch-created inputs across
torch_npu's ACL context without ordering — follow-up: central
torch-stream integration).

* fix(sampling): skip zero-length output memset in the biased launcher

CANN 9.0 rejects aclrtMemsetAsync with size 0. The all-zero-bias request
(all rows ineligible) reaches AllocZeroedOutputs with max_output == 0;
the early-exit path returns empty views regardless, so guard the three
memsets on max_output > 0. Surfaced by the first CANN 9.0 run of
test_biased_all_zero_bias (the biased suite was previously 9.1-only).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* split out csr slice CPU fallback into separate PR (review: do not mix packaging and operator changes in same PR)

* release: pin torch 2.8.0 / torch_npu 2.8.0.post2, update docs for 0.0.2

* test: add NPU test suite for _npu_gspmm_binary (PR BUPT-GAMMA#29)

Covers correctness (mul/add, 2D/1D), gradient (backward via update_all),
DGL integration (fn.u_mul_e + fn.sum), and edge cases (single edge,
self-loops, large dim, non-intercepted ops). 16 tests, all passing
on Ascend 910B3.

* fix: improve NPU detection with pytest.fail on unavailable NPU

Check torch_npu import and torch.npu.is_available() at module level.
Tests fail (not skip) if NPU is unavailable.

* feat(range): implement AscendC Range kernel for NPU

- New AscendC kernel (range_kernel.cpp): int32/int64, multi-core,
  UB + DataCopyPad batch transfer (replaces blacklisted GlobalTensor::SetValue)
- New Host launcher (range.cc): persistent tiling buffer, dynamic
  block_dim via ACL_DEV_ATTR_VECTOR_CORE_NUM, async (no stream sync)
- Modify entry dispatch (array.cc): replace CPU fallback with direct
  impl::Range<kDGLAscend, IdType> call, symmetric with CUDA path
- Add NPU test script (tests/ascend/test_range_npu.py): functional,
  precision, and performance tests (7/7 passed, 31x~279x speedup)

* fix(ascend): sync torch_npu host queue before DGL kernel launch to fix first-call zero output

Root cause of the long-standing first-call all-zero failure (e.g.
test_graph_conv0) is a dual-submission-system race:

- torch_npu operators (th.matmul in GraphConv, etc.) are NOT submitted
  to the NPU device directly; they enter the c10_npu host-side task
  queue and are flushed asynchronously by a background thread.
- DGL AscendC kernels launch via ACL directly and execute immediately.
- Neither aclrtSynchronizeDevice/Stream nor c10_npu::device_synchronize()
  flushes the host queue (verified experimentally), so a DGL kernel can
  run before its torch-side producer has written the input tensor,
  reading all-zero data. Reproduced deterministically: same ufeat
  buffer reads 0.0 on first call and the correct value on the second.

Fix: add SyncTorchNpuStream() (dlsym c10_npu::npuSynchronizeDevice,
the C++ backend of torch.npu.synchronize(), which flushes the host
queue and waits for the device) before kernel launch in:
- SpMMCsrUnified (spmm.cc): fixes GraphConv/GINConv/SAGEConv first-call
- EdgeSoftmaxAscendImpl (edge_softmax.cc): fixes GAT/GATv2 chain
- CSRGetRowNNZ (csr_get_row_nnz.cc): fixes sporadic all-zero in_degrees
  misreporting 0-in-degree DGLError

Also add SetDeviceIfChanged() (debounced aclrtSetDevice via
aclrtGetDevice) replacing raw aclrtSetDevice in spmm/edge_softmax/sddmm
to eliminate sporadic RuntimeError 507033 (SetDevice contention with
torch_npu ExchangeDevice context management).

Verification: core conv suite now stable at 1049/1050 across 6 cold
runs without any warmup hacks; the only remaining failure
test_rgcn[8-idtype0] is a known independent bdd sorted/unsorted
numerical difference.

* feat(ascend): device-side Ascend C implementation of ToBlock

Replace the previous workaround (copy graph to CPU, run ToBlockCPU,
copy back) with a full device-side ToBlock on NPU:

- New Ascend C kernel (to_block_kernel.cpp + to_block_tiling.h):
  single-entry kernel with dtype_bytes tiling dispatch (avoids the
  K_TYPE_AIV multi-function meta-section numbering toolchain bug),
  K1 dedup_hash_build (single-core order-preserving dedup with
  open-addressing hash) + K3 map_edges (multi-core edge mapping).
- Host side (graph/transform/ascend/to_block_ascend.{h,cc}):
  AscendIdsMapper following the CUDAIdsMapper pattern, workspace
  management and kernel orchestration, no host copies of graph data.
- to_block.cc: ToBlock<kDGLAscend,int32/int64> specializations now
  dispatch to ToBlockAscend instead of the CPU-copy fallback.
- array.cc: add DGL_USE_ASCEND branch in CSRRowWiseSampling dispatch
  so sample_neighbors reaches the Ascend uniform sampling kernel
  (previously raised does-not-support-ascend).

Single-entry kernel constraint: the ascendc toolchain generates meta
sections named _0 for every function in a K_TYPE_AIV kernel file,
which mismatches the second kernel symbol suffix (_1) and causes
launch error 507000; hence single entry + dtype_bytes tiling field.

Verified: dgl.to_block int32/int64 on NPU matches CPU semantics
(NID/edge mapping bitwise identical); test_hgt/test_sage_conv pass.
Known limitations: single-band hash capacity (int32>2730/int64>1365
candidates LOG(FATAL), multi-band TODO), EID passthrough affected by
pre-existing int64 graph.Edges NPU backend issue.

* fix(ascend): NPU compatibility fixes for core conv suite

Assorted fixes enabling the pytorch NN core convolution suite on NPU:

- tensor.py: F.min/F.max with dim on int32 cast to int64 and back
  (aclnnMinDim/aclnnMaxDim do not support DT_INT32).
- subgraph.py: synchronize NPU stream after edge_subgraph.
- transforms/functional.py: reorder_graph node_subgraph/edge custom
  paths rebuild graph on NPU (node_subgraph returned CPU arrays with
  npu:0 device tag; edge permute first-call order bug workaround).
- sampling_uniform kernel: merge int32/int64 entry points into a
  single csr_row_wise_sampling_uniform entry with dtype_bytes tiling
  field (K_TYPE_AIV multi-function meta-section toolchain bug causes
  507000 on the second function); kTilingHeaderWords 8->9.
- segment_reduce.cc: coreNum query fallback VECTOR_CORE_NUM ->
  AICORE_CORE_NUM -> 6 (device without vector-core attr support).
- setup.py: relax torch dependency from ==2.8.0 to >=2.1.0.
- tests/backend/__init__.py: add npu context for DGLTESTDEV=npu.
- test_nn.py: _AXWb densifies sparse adjacency on NPU (aten::addmm
  with sparse COO unsupported).

Core conv suite result: 1049/1050 (only test_rgcn[8-idtype0] fails,
known bdd sorted/unsorted numerical difference, unrelated).

* fix(ascend): sync torch_npu host queue in GatherByIndex to fix bdd RGCN first-call error

GatherByIndex is called in the copy_rhs (copy_e) path of SpMMCsr
before SpMMCsrUnified, to pre-gather edge features (efeat) into CSC
row order. When efeat is the output of a torch_npu operator (e.g.
TypedLinear bmm in RelGraphConv bdd regularizer), it sits in the
c10_npu host task queue and has not been flushed to the device yet.

GatherByIndex uses ACL memcpy (CopyTo D2H) to read src, which does
not flush the torch host queue — so it reads stale/zero data, producing
wrong gathered features that feed into the gspmm kernel, resulting in
completely wrong RGCN bdd output (diff ~6-9 vs CPU reference).

The existing SyncTorchNpuStream in SpMMCsrUnified was too late:
GatherByIndex runs before SpMMCsrUnified is called. This fix adds
SyncTorchNpuStream at the GatherByIndex entry, ensuring the torch
producer has written efeat before ACL reads it.

Verified: test_rgcn[8-idtype0] now passes (bdd diff < 1e-6 vs CPU).
Core conv suite: 1050/1050 passed (5 cold runs, no warmup needed).

* fix(ascend): merge csr_slice_matrix 6-entry kernel into single entry to fix 107000 registration

csr_slice_matrix_kernel.cpp had 6 extern C functions (3 passes x int32/int64)
without proper K_TYPE_AIV marker, causing kernel registration to fail with
107000 (ACL_ERROR_RT_PARAM_INVALID). When ToBlockAscend triggers csr_slice_matrix
on NPU, the unregistered kernel causes vector core exception 507035.

Fix: merge all 6 entry points into a single csr_slice_matrix entry with
op_type + dtype_bytes tiling dispatch, plus KERNEL_TASK_TYPE_DEFAULT(AIV_ONLY).
Single-entry avoids the K_TYPE_AIV multi-function meta-section numbering bug.

Host-side: replace the 6 extern C declarations and 3 x int32/int64 if-else
launch blocks with 3 unified launches passing the CsrSliceMatrixUnifiedTiling
struct (op_type + dtype-bytes + all op params).

* cleanup: remove torch_stream_sync.h and revert csr_slice_matrix single-entry

- torch_stream_sync.h removed (SyncTorchNpuStream/SetDeviceIfChanged)
  related references removed from spmm.cc, edge_softmax.cc, sddmm.cc, csr_get_row_nnz.cc
- Revert csr_slice_matrix single-entry back to original 6-function version.
  The cross-stream synchronization issue will be fixed by a future architecture
  change (DGL kernel on torch_npu stream instead of ACL default stream).

* review: address PR comments on torch version and tiling header comment

- setup.py: torch>=2.1.0 -> torch>=2.7.0 (narrow version range)
- csr_row_wise_sampling_uniform_tiling.h: add comment explaining
  kTilingHeaderWords=8->9 bump due to dtype_bytes field addition
- KERNEL_TASK_TYPE_DEFAULT macro (comment 7/8): already removed in prior
  revert, no action needed

* 修复ACL_DEV_ATTR_UBUF_PER_VECTOR_CORE宏在cann8.5版本不支持问题

* fix(ascend): merge range_i32/range_i64 into single range entry to fix CANN 9.0.0 registration 107000

range_kernel.cpp had two extern C functions (range_i32, range_i64), each
with KERNEL_TASK_TYPE_DEFAULT(KERNEL_TYPE_AIV_ONLY). The ascendc toolchain
generates meta sections named _0 for every function in a K_TYPE_AIV kernel
file, but the 2nd function symbol gets _1. On CANN 9.0.0 the runtime looks
up meta by full symbol name (_1) and fails (107000 registration, which
cascades into 507035). CANN 9.1.0 normalizes the match.

Fix: merge the two entry points into a single range entry that branches
on tiling->dtype_bytes (4=int32, 8=int64). Now only range_0 symbol +
range_0 meta section exist, matching correctly on 9.0.0.

Verified: single range_0 symbol, single .ascend.meta.range_0 section,
import shows 0 x 107000 registration failures.

* fix(ascend): add RAII WorkspaceGuard to to_block to prevent device memory leaks on error path

Phase A-D allocate device workspace and tiling buffers via
device->AllocWorkspace, freed in Phase E. If any CHECK/LOG(FATAL)
fires in between, Phase E is skipped and the allocations leak.
Introduces WorkspaceGuard: a scope-exit RAII guard that collects
every allocated pointer via the alloc_ws lambda and frees them
all when the AscendIdsMapper::operator() scope exits — regardless
of the exit path (normal return or fatal error).

Verified: 5 failed / 1045 passed (same baseline, no regression).

* revert(setup): restore torch==2.8.0 / torch_npu==2.8.0.post2 dependencies

The torch version constraint was accidentally relaxed during local
development (torch>=2.1.0, later >=2.7.0). Neither was correct for
the production setup — only ==2.8.0 matches the torch_npu version.

* delete: 删除文件 VERSION_MATRIX.md


Signed-off-by: lhp_lhp <lhp_lhp@noreply.gitcode.com>

* delete: 删除文件 BUILD_GUIDE.md


Signed-off-by: lhp_lhp <lhp_lhp@noreply.gitcode.com>

* 修改issue模板

Co-authored-by: knightgd<knightgd@126.com>

* update: 更新文件 Dockerfile.manylinux_cann_aarch64


Signed-off-by: lhp_lhp <lhp_lhp@noreply.gitcode.com>

* fix(ascend): order DGL kernels against torch_npu stream and rework binary_elewise for A3

Co-authored-by: jingxupan<79962048+jingxupan@users.noreply.github.com>
Co-authored-by: panxiaomu<panxiaomu@noreply.gitcode.com>

* feat(unary_elewise): add NPU-native UnaryElewise (Neg) operator for Ascend NPU

Co-authored-by: knightgd<knightgd@126.com>

* feat(ascend): support  BFS Nodes/Edges Frontiers capabilities in dgl

Co-authored-by: Bowen Ma<iambowen.m@qq.com>

* fix(array): add AscendC Full operator with vectorized fill path

Co-authored-by: gxlgyr<240729782@qq.com>

* [feature] 实现单次启动的Ascend concat算子

Co-authored-by: shaozengwei<zengwei19861029@163.com>

* fix(ascend): native kernels for Range int32 and CSRToCOO (drop CPU fallback) + review fixes

Co-authored-by: xuejikan11<xuejikan11@noreply.gitcode.com>

* [Feature] feat(ascend): add Ascend 950PR (A5) SoC build support

Co-authored-by: panxiaomu<panxiaomu@noreply.gitcode.com>

* Fixing the issue of NaN values in the spmm sum part

* update test_csr_to_coo_npu.py

* Support Ascend950PR: fix blacklisted GM scalar access in binary_elewise kernels & order DGL kernels against torch_npu submissionsFeat/ascend950pr adaptation (BUPT-GAMMA#43)

* fix(ascend): drop blacklisted GlobalTensor scalar access in binary_elewise kernels

Scalar GetValue/SetValue on GlobalTensor is a production-blacklist API on
Ascend950PR (per-core DCache write-back coherence risk, ADR-0007); the 12
binary_elewise (array-vs-scalar compare) kernels relied on it exclusively,
so on this SoC the result buffer was never written and e.g. HasVertices
(aten::LT) silently returned all-zero, breaking has_nodes/out_degrees and
the degree-normalization path of GraphConv.

Rewrite the kernels to:
- read the tiling block through a typed __gm__ pointer (same 3-word
  layout, host code unchanged);
- stream input/output through UB with DMA (DataCopyPad) instead of scalar
  GM access, comparing on UB-resident values.

Kernel symbols (binary_l_{lt,gt,le,ge,eq,ne}_{i32,i64}) are unchanged.
Verified against CPU on Ascend950PR_9579 (CANN 9.1.0): degrees and
GraphConv now match CPU (max diff ~3.6e-7, fp32).

* feat(ascend): order DGL kernels against torch_npu submissions

torch_npu submits kernels asynchronously on its own (non-default) ACL
stream, while the DGL Ascend array kernels launch on the ACL default
stream and block on it only until their own work completes.  The two
submitters are unordered, which made results nondeterministic and could
raise device-side faults whenever a DGL kernel read a tensor that
torch_npu had just written (feature tensors, generated index arrays).

Handing torch's stream to DGL via DGLSetStream is not a fix: torch_npu
submits to that stream from its internal task-queue thread while DGL
would submit from the caller thread, and concurrent submissions on one
stream corrupt the driver state (observed as host segfaults).

Add a barrier on the python FFI boundary instead:
- wrap the ctypes CDLL so every libdgl C API call first drains
  torch_npu's current stream on the host (cheap when idle);
- DGL ops already host-synchronize at the end, so the reverse direction
  was already ordered;
- the Ascend stream bridge latches lazily (also covers torch_npu being
  imported after dgl), stays silent when NPU is absent, skips
  interpreter shutdown, and can be disabled with
  DGL_ASCEND_STREAM_BRIDGE=0;
- getCurrentAscendStream() falls back to the DeviceAPI stream so the
  kernels always follow whatever stream the host side selects.

Overhead measured on Ascend950PR_9579: ~0.7 ms per GraphConv layer at
5k nodes / 20k edges / 128 hidden.

---------

Co-authored-by: jingxupan <jingxupan@users.noreply.github.com>

* merge github and gitcode

* Add Ascend COOGetDataAndIndices backend and regression tests

Route Ascend COO queries through typed AIV match and gather kernels. Add native CPU comparison and graph API regressions. Integration compilation and NPU execution remain pending; standalone validation does not establish integration test success.

* Fix COO AIV registration and add isolated Python tests

* optimize COOGetDataAndIndices

---------

Signed-off-by: lhp_lhp <lhp_lhp@noreply.gitcode.com>
Signed-off-by: zqm19511961081 <zhuqiming1025@163.com>
Co-authored-by: xiaoyixin7171 <xiaoyixin7171@noreply.gitcode.com>
Co-authored-by: knightgd <knightgd@126.com>
Co-authored-by: xuejikan <xuejikan@163.com>
Co-authored-by: xuejikan11 <xuejikan11@noreply.gitcode.com>
Co-authored-by: gxlgyr <240729782@qq.com>
Co-authored-by: gxlgyr <gxlgyr@github.com>
Co-authored-by: lhp_lhp <lhp_lhp@users.noreply.gitcode.com>
Co-authored-by: lhp_lhp <lhp_lhp@noreply.gitcode.com>
Co-authored-by: xuejikan11 <xuejikan11@gitcode.com>
Co-authored-by: chenzhongsong <songjay1993@foxmail.com>
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
Co-authored-by: panxiaomu <panxiaomu@noreply.gitcode.com>
Co-authored-by: TokenDance <iambowen.m@qq.com>
Co-authored-by: shaozengwei <zengwei19861029@163.com>
Co-authored-by: jingxupan <79962048+jingxupan@users.noreply.github.com>
Co-authored-by: jingxupan <jingxupan@users.noreply.github.com>
Co-authored-by: 李坤航 <bay@bupt.edu.cn>
Co-authored-by: yqlee <yqlee@bupt.edu.cn>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

10 participants