| 文件 | 最后提交记录 | 最后更新时间 |
|---|---|---|
[test] add CheckpointFunction.backward cpp_extension.BuildExtension.with_options hipify_python.hipify _contextlib._DecoratorContextManager API test case Co-authored-by: lyd123333<3906916351@qq.com> # message auto-generated for no-merge-commit merge: !45275 merge CheckpointFunction-BuildExtension-hipify_python-_contextlib-master into master [test] add CheckpointFunction.backward cpp_extension.BuildExtension.with_options hipify_python.hipify _contextlib._DecoratorContextManager API test case Created-by: lyd123333 Commit-by: lyd123333 Merged-by: ascend-robot Description: <!-- PR描述模板更新日期:20260203 --> # 【合入来源】 [#147](https://gitcode.com/Ascend/pytorch-ecosystem/issues/147) [#122](https://gitcode.com/Ascend/pytorch-ecosystem/issues/122) [#74](https://gitcode.com/Ascend/pytorch-ecosystem/issues/74) [#134](https://gitcode.com/Ascend/pytorch-ecosystem/issues/134) - [ ] 需求 - [ ] 问题单 - [x] issue/工单 - [ ] 重构优化 - [ ] 资料更新 公开issue: - torch.utils.checkpoint.CheckpointFunction.backward:[8月社区任务第二期-Ascend for PyTorch API 一致性开发(26)](https://gitcode.com/Ascend/pytorch-ecosystem/issues/147) - torch.utils.cpp_extension.BuildExtension.with_options:[8月社区任务第二期-Ascend for PyTorch API 一致性开发(33)](https://gitcode.com/Ascend/pytorch-ecosystem/issues/122) - torch.utils.hipify.hipify_python.hipify:[8月社区任务第二期-Ascend for PyTorch API 一致性开发(51)](https://gitcode.com/Ascend/pytorch-ecosystem/issues/74) - torch.utils._contextlib._DecoratorContextManager: [8月社区任务第二期-Ascend for PyTorch API 一致性开发(13) ](https://gitcode.com/Ascend/pytorch-ecosystem/issues/134) # torch.utils 相关四个 API 分析 ## 1. API 功能说明 | API | 功能说明 | 是否硬件相关 | |---|---|---| | torch.utils.checkpoint.CheckpointFunction.backward | CheckpointFunction 是 activation checkpoint 的底层 autograd Function。其 backward 方法在反向传播阶段重新执行前向计算,从而避免在 forward 阶段保存全部中间激活,达到以计算换显存的目的。 | 不是专门硬件接口,但会依赖具体设备上的 autograd、算子执行和 RNG 状态管理。 | | torch.utils.cpp_extension.BuildExtension.with_options | BuildExtension 是 PyTorch 提供的自定义 C++/CUDA/SYCL 扩展构建类;with_options(**options) 用于生成一个带默认构建参数的 BuildExtension 子类/构造器,常用于 setup.py 的 cmdclass={"build_ext": BuildExtension.with_options(...)}。 | 属于构建工具接口,涉及 CUDA/SYCL 编译参数,但本身不是运行时硬件 API。 | | torch.utils.hipify.hipify_python.hipify | PyTorch 内置 HIPIFY 工具入口,用于扫描指定项目目录,将 CUDA/C++ 源文件中的 CUDA API、头文件、kernel launch 等模式转换为 HIP/ROCm 对应形式。 | 是 GPU 迁移工具,面向 AMD ROCm/HIP;不是 Ascend NPU 运行时接口。 | | torch.utils._contextlib._DecoratorContextManager | PyTorch 内部上下文管理器基类,用于让 context manager 同时具备 decorator 用法,例如 torch.no_grad()、torch.inference_mode() 这类接口。 | 纯 Python 上下文控制工具,不涉及硬件。 | ## 3. torch-npu 平台测试必要性 | API | 是否建议补充 NPU 测试 | 原因 | |---|---|---| | torch.utils.checkpoint.CheckpointFunction.backward | 建议 | checkpoint backward 会触发反向传播阶段的重计算,涉及 NPU Tensor 的 autograd、算子执行、梯度回传以及 RNG 状态保存/恢复,适合作为 torch-npu 兼容性测试。 | | torch.utils.cpp_extension.BuildExtension.with_options | 不建议作为 NPU 专项测试 | 该接口只负责构建参数注入,不直接执行 NPU 算子。可做纯 Python import/行为测试,但不需要 NPU 设备测试。 | | torch.utils.hipify.hipify_python.hipify | 不建议作为 NPU 专项测试 | 该接口面向 CUDA 到 HIP/ROCm 的源码迁移,与 Ascend NPU 后端无直接关系。 | | torch.utils._contextlib._DecoratorContextManager | 不建议作为 NPU 专项测试 | 该接口是内部 Python 上下文管理工具,设备无关。若需要覆盖,可通过公开 API torch.no_grad() 在 NPU Tensor 上做轻量验证。 | # 二. 上游用例检查情况: 1. torch.utils.checkpoint.CheckpointFunction.backward: 上游有测试,但不是直接调用内部 backward,而是通过 checkpoint(..., use_reentrant=True) + backward() 间接覆盖真实路径,因此需要补充torch-npu平台的测试用例, 2. torch.utils.cpp_extension.BuildExtension.with_options: 上游有测试/使用覆盖,在 test/cpp_extensions/setup.py 中通过 BuildExtension.with_options(use_ninja=USE_NINJA)间接参与真实扩展构建流程,因此需要补充torch-npu平台的测试用例。 3. torch.utils.hipify.hipify_python.hipify: 上游有 hipify 模块 import 测试和 Trie 辅助结构测试;没有看到完整直接调用 hipify() 并校验 CUDA→HIP 转换结果的单测,但 cpp_extension 的 ROCm 构建链路会间接调用它。该API和torch-npu平台无关,因此无需进行测试用例补充。 4. torch.utils._contextlib._DecoratorContextManager: 上游没有直接测试该内部类,但通过 set_device、torch.no_grad 等上下文管理器的装饰器用法间接覆盖其核心能力。因此需要进行测试用例补充。 # 三. 资料情况检查: | API | PyTorch 2.7 | PyTorch 2.11 | PyTorch 2.12 | PyTorch 2.13 | 结论 | |---|---|---|---|---|---| | torch.utils.checkpoint.CheckpointFunction.backward | 未查到独立条目 | 未查到独立条目 | 未查到独立条目 | 未查到独立条目 | 官方公开文档主要记录 torch.utils.checkpoint.checkpoint,CheckpointFunction.backward 更偏内部实现。 | | torch.utils.cpp_extension.BuildExtension.with_options | 未查到独立条目 | 未查到独立条目 | 未查到独立条目 | 未查到独立条目 | 官方文档有 BuildExtension 类条目,但 with_options 方法本身未单独成页。 | | torch.utils.hipify.hipify_python.hipify | 有独立条目 | 有独立条目 | 有独立条目 | 有独立条目 | 2.7.1/2.11/2.12/2.13 官方 generated 文档均有独立条目 | | torch.utils._contextlib._DecoratorContextManager | 未查到独立条目 | 未查到独立条目 | 未查到独立条目 | 未查到独立条目 | 内部类,不属于稳定公开 API 文档条目。 | 如表所示,虽然torch.utils.hipify.hipify_python.hipify在各个分支都有独立条目,因此 torch.utils.hipify.hipify_python.hipify 需要进行资料补充。 # 四. API功能性验证 ## 1. 测试场景 | API | 测试场景 | 预期结果 | |---|---|---| | torch.utils.checkpoint.CheckpointFunction.backward | 检查 CheckpointFunction.backward 是否存在且可调用 | API 存在,并且是可调用对象 | | torch.utils.checkpoint.CheckpointFunction.backward | 在 NPU 上通过 checkpoint(..., use_reentrant=True) 触发 backward,并与普通 backward 对比 | checkpoint 路径输出和梯度与普通路径一致,梯度位于 NPU | | torch.utils.checkpoint.CheckpointFunction.backward | checkpoint 函数包含非 Tensor 参数 | backward 正常执行,输出和梯度与普通路径一致 | | torch.utils.checkpoint.CheckpointFunction.backward | checkpoint 函数返回多个 Tensor 输出 | 多输出均正确,合并 loss 后梯度与普通路径一致 | | torch.utils.checkpoint.CheckpointFunction.backward | checkpoint 中包含 Dropout,并验证 RNG 状态保存恢复 | checkpoint 路径和普通路径的梯度一致 | | torch.utils.cpp_extension.BuildExtension.with_options | 调用 with_options(use_ninja=False) 生成构建类 | 返回结果是 BuildExtension 的子类,且不是原始 BuildExtension 类 | | torch.utils.cpp_extension.BuildExtension.with_options | 注入 use_ninja=False、no_python_abi_suffix=True 参数 | 实例化后的构建命令参数正确生效 | | torch.utils.cpp_extension.BuildExtension.with_options | 构造时传入与预设参数冲突的参数 | with_options 中预设的参数优先生效 | | torch.utils.cpp_extension.BuildExtension.with_options | 多次调用 with_options 生成不同构建类 | 不同构建类可独立实例化,配置互不影响 | | torch.utils.hipify.hipify_python.hipify | 检查 hipify_python.hipify 是否存在且可调用 | API 存在,并且是可调用对象 | | torch.utils.hipify.hipify_python.hipify | 创建 .cu 文件并调用 hipify() 处理 | 返回结果为 dict,且包含目标 CUDA 文件处理记录 | | torch.utils.hipify.hipify_python.hipify | 使用 extra_files 和 hipify_extra_files_only=True 只处理额外文件 | 返回结果包含指定 extra CUDA 文件 | | torch.utils.hipify.hipify_python.hipify | 使用 ignores 忽略指定 CUDA 文件 | 被忽略文件不出现在处理结果中 | | torch.utils._contextlib._DecoratorContextManager | 自定义上下文管理器作为普通函数装饰器 | 执行顺序为 enter -> body -> exit,函数结果正确 | | torch.utils._contextlib._DecoratorContextManager | 被装饰函数抛出异常 | 即使函数抛异常,__exit__ 仍正常执行 | | torch.utils._contextlib._DecoratorContextManager | 自定义上下文管理器作为 generator 函数装饰器 | generator 执行期间上下文保持生效,产出结果正确 | | torch.utils._contextlib._DecoratorContextManager | 通过公开接口 @torch.no_grad() 在 NPU Tensor 上间接验证装饰器行为 | 输出 Tensor 位于 NPU,且 requires_grad=False | ## 2. 测试核心代码 ```python class TestTorchUtilsCheckpointFunctionBackward(TestCase): def test_checkpoint_function_backward_exists(self): self.assertTrue(hasattr(CheckpointFunction, "backward")) self.assertTrue(callable(CheckpointFunction.backward)) def test_checkpoint_backward_matches_normal_backward_on_npu(self): if not npu_available(): self.skipTest("NPU is not available") def run_fn(x): return torch.sin(x) * torch.cos(x) + x * x x = torch.randn(4, 4, device="npu", dtype=torch.float32, requires_grad=True) x_ref = x.detach().clone().requires_grad_(True) checkpoint_out = checkpoint(run_fn, x, use_reentrant=True) normal_out = run_fn(x_ref) checkpoint_out.sum().backward() normal_out.sum().backward() self.assertEqual(checkpoint_out.device.type, "npu") self.assertIsNotNone(x.grad) self.assertEqual(x.grad.device.type, "npu") self.assertRtolEqual(checkpoint_out.detach().cpu(), normal_out.detach().cpu()) self.assertRtolEqual(x.grad.cpu(), x_ref.grad.cpu()) def test_checkpoint_backward_with_non_tensor_argument_on_npu(self): if not npu_available(): self.skipTest("NPU is not available") def run_fn(x, scale): return x * scale + x.relu() x = torch.randn(3, 3, device="npu", dtype=torch.float32, requires_grad=True) x_ref = x.detach().clone().requires_grad_(True) scale = 2.5 checkpoint_out = checkpoint(run_fn, x, scale, use_reentrant=True) normal_out = run_fn(x_ref, scale) checkpoint_out.sum().backward() normal_out.sum().backward() self.assertRtolEqual(checkpoint_out.detach().cpu(), normal_out.detach().cpu()) self.assertRtolEqual(x.grad.cpu(), x_ref.grad.cpu()) def test_checkpoint_backward_with_multiple_outputs_on_npu(self): if not npu_available(): self.skipTest("NPU is not available") def run_fn(x): return x * 2.0, x * x x = torch.randn(2, 3, device="npu", dtype=torch.float32, requires_grad=True) x_ref = x.detach().clone().requires_grad_(True) out1, out2 = checkpoint(run_fn, x, use_reentrant=True) ref1, ref2 = run_fn(x_ref) loss = out1.sum() + out2.sum() ref_loss = ref1.sum() + ref2.sum() loss.backward() ref_loss.backward() self.assertRtolEqual(out1.detach().cpu(), ref1.detach().cpu()) self.assertRtolEqual(out2.detach().cpu(), ref2.detach().cpu()) self.assertRtolEqual(x.grad.cpu(), x_ref.grad.cpu()) def test_checkpoint_backward_rng_state_with_dropout_on_npu(self): if not npu_available(): self.skipTest("NPU is not available") if not hasattr(torch.npu, "get_rng_state") or not hasattr(torch.npu, "set_rng_state"): self.skipTest("NPU RNG state APIs are not available") torch.manual_seed(1234) torch.npu.manual_seed(1234) dropout = torch.nn.Dropout(p=0.5) def run_fn(x): return dropout(x) x = torch.randn(128, device="npu", dtype=torch.float32, requires_grad=True) cpu_state = torch.get_rng_state() npu_state = torch.npu.get_rng_state() checkpoint_out = checkpoint(run_fn, x, use_reentrant=True) checkpoint_out.sum().backward() checkpoint_grad = x.grad.detach().clone() torch.set_rng_state(cpu_state) torch.npu.set_rng_state(npu_state) x_ref = x.detach().clone().requires_grad_(True) normal_out = run_fn(x_ref) normal_out.sum().backward() self.assertRtolEqual(checkpoi See merge request: Ascend/pytorch!45275 | 9 天前 | |
【feat】NPUAffinityController support multiple rangs of affinity cpu core Co-authored-by: zhaoyu<nanzhaogang@qq.com> # message auto-generated for no-merge-commit merge: !34407 merge Affinity into master 【feat】NPUAffinityController support multiple rangs of affinity cpu core Created-by: zhaoyu65 Commit-by: zhaoyu Merged-by: ascend-robot Description: <!-- PR描述模板更新日期:20260203 --> # 【合入来源】 > <font color="red">**如有社区issue,请关联issue链接**</font>\ > <font color="red">**请勿携带内部流程信息(需求链接、问题单、内部issue等)**</font> - [x] 需求 [#1816](https://gitcode.com/Ascend/pytorch/issues/1816) - [ ] 问题单 - [ ] issue/工单 - [ ] 重构优化 - [ ] 资料更新 # 【修改方案】 ## 1、修改内容总体 本次 commit 的核心目的是让 **NPUAffinityController 支持绑定多个不连续的 CPU 核范围**。同时修改了lintrunner工具扫描出来的代码规范问题。 主要技术变更: - 将数据结构从 CoreIdRange {start, end} 改为 CoreIdList = std::set<CoreId>,支持离散/多段 CPU 核集合,set容器符合语义,不存在重复值 - 支持解析查出来的多段CPU亲和段 - 对GetAffinityCPUInfo.cpp和NPUAffinityController.cpp重构,优化函数圏复杂度,将cpp内部调用函数使用namespace或static关键词封装, --- ## 2、各文件修改的内容和目的 | 文件 | 修改内容 | 目的 | |------|----------|------| | **NPUAffinityController.h** | 将 CoreIdRange 结构体替换为 CoreIdList = std::set<CoreId>,新增 SetThreadAffinity(const CoreIdList) 接口 | 数据结构重构,支持多核集合 | | **NPUAffinityController.cpp** | 重构核心绑定逻辑:解析配置支持 npu0:0-1,npu0:4-9 多段格式;新增 formatCoreRange() 输出函数;重构 parseDeviceCoreRange() 解析多段范围 | 核心实现支持多段 CPU 核绑定 | | **GetAffinityCPUInfo.cpp** | 将 parseAffinityCPU() 改为 parseAffinityCores(),支持逗号分隔的多段范围;重构 GetExclusiveAffinityCPU() 的核分配逻辑 | DCMI 接口层适配新数据结构,避免重复初始化 | | **GetAffinityCPUInfo.h** | 简化接口,对其他cpp文件只保留 GetAffinityCores(int card_id)接口 | 接口统一 | | **Module.cpp** | Python 绑定增加对 PyList 参数的解析,支持python内部接口侧传入 [0, 1, 4, 5] 格式的核列表 | Python API 支持新参数类型 | | **affinity.py** | _set_thread_affinity() 支持 List[int] 或 List[List[int]] 参数,如 [[0,5], [8,10]] | Python 层 API 扩展 | | **torch_npu_schema.json** | 更新签名 Union[List[int], List[List[int]], NoneType] | 类型提示更新 | | **test_affinity.py** | 新增加多段CPU核相关测试用例 | 新增用例 | --- ## 3、修改后的影响 ### 功能增强 - **用户可配置多段 CPU 核范围**:如 CPU_AFFINITY_CONF='1,npu0:0-3,npu0:8-15',同一设备可绑定不连续的核,取并集 - **API 更灵活**:set_thread_affinity() 新增接受 [[0,5], [8,10]] 格式参数的功能 ### 行为变化 - 环境变量 CPU_AFFINITY_CONF 同一设备多次指定核范围会合并(如 npu0:0-1,npu0:4-9 绑定核 0,1,4,5,6,7,8,9) ### 代码改进 - 新增 formatCoreRange() 函数统一输出格式(如 0-3,8-15) - 代码结构更清晰:解析函数拆分为 parseNpuAffineMode()、parseLazyBindMode()、parseForceMode()、parseDeviceCoreRange() --- # 【资料变更】 在后续2.7.1分支的PR中修改 # 【接口变更】 CPU_AFFINITY_CONF环境变量和set_thread_affinity()接口变更方案已通过SEG例会评审,兼容旧版本; # 【功能验证】 自测OK  验证环境变量CPU_AFFINITY_CONF bash #!/bin/bash # 设置环境变量 export ASCEND_PROCESS_LOG_PATH=$(pwd) export ASCEND_GLOBAL_LOG_LEVEL=0 echo -e 'import torch\na=torch.tensor([1],device="npu")\nb=a+1\n' > add.py # 定义配置和期望值数组 configs=( "1,npu_affine:1,npu0:0-5" "1,npu_affine:1,npu0:0-5,npu1:6-7,npu2:8-8,npu2:10-11,npu0:12-19" "1,npu_affine:1,npu0:0-5,npu1:10-13,npu0:4-7" ) values=( "0-5" "0-5,12-19" "0-7" ) run_test() { local index=$1 local conf=$2 local expected_val=$3 export CPU_AFFINITY_CONF="$conf" # 清理旧日志,确保获取的是本次运行的日志 rm -rf debug/ # 执行测试脚本 python add.py # 检查 python 执行是否成功,可选 if [ $? -ne 0 ]; then echo "[ERROR] Index $index: python add.py failed." >> result.log return 1 fi # 提取 affinity 值 # 使用 find 避免 glob 匹配不到文件时的报错,或者保留原来的 glob 但确保目录存在 local log_file log_file=$(find debug/plog -name "*.log" 2>/dev/null | head -1) if [ -z "$log_file" ]; then echo "[ERROR] Index $index: No log file found in debug/plog/" >> result.log return 1 fi local affinity_line affinity_line=$(grep "Device 0 set acl_thread affinity to" "$log_file" 2>/dev/null | head -1) if [ -z "$affinity_line" ]; then echo "[ERROR] Index $index: Affinity line not found in log." >> result.log return 1 fi # 提取 "affinity to" 后面的具体值 local affinity_value # sed 提取最后一个非空字段,或者根据具体日志格式调整 affinity_value=$(echo "$affinity_line" | sed -n 's/.*affinity to \([^ ]*\).*/\1/p') # 去除可能的首尾空白字符 (trim) affinity_value=$(echo "$affinity_value" | xargs) # 比较实际值与期望值 if [ "$affinity_value" == "$expected_val" ]; then echo "测试环境变量 CPU_AFFINITY_CONF $conf: 的结果为:SUCCESS (Actual: ${affinity_value} == Expected: ${expected_val})" else echo "测试环境变量 CPU_AFFINITY_CONF $conf: 的结果为:FAIL (Actual: ${affinity_value} != Expected: ${expected_val})" fi } # 循环遍历配置 # 使用 C 风格的 for 循环以便同时获取索引 for ((i=0; i<${#configs[@]}; i++)); do run_test "$i" "${configs[$i]}" "${values[$i]}" done echo "All tests completed." 测试结果为:所有用例都通过  # 【CheckList】 > PR提交人对以下CheckList自检项进行全量自检,自检通过或不涉及,均修改 [ ] 为 [x] - [x] 代码注释完备,正确记录错误日志 - [x] 代码实现进行了返回值、空指针等校验 - [x] PR标题正确使用类型标签,如:feat、fix、refactor、docs、test等 - [x] PR持续集成流水线(CI)执行通过,代码检查无异常 See merge request: Ascend/pytorch!34407 | 5 个月前 | |
AI assist developer for python dt master Co-authored-by: aksksks<mengzichao@h-partners.com> # message auto-generated for no-merge-commit merge: !26538 merge master into master AI assist developer for python dt master Created-by: aksksks Commit-by: aksksks Merged-by: ascend-robot Description: <!-- Thanks for sending a pull request! --> **What type of PR is this?** > Uncomment only one /kind <> line, hit enter to put that in a new line, and remove leading whitespaces from that line: > > /kind bug > /kind task > /kind feature **What does this PR do / why do we need it**: **Which issue(s) this PR fixes**: <!-- *Automatically closes linked issue when PR is merged. Usage: Fixes #<issue number>, or Fixes (paste link of issue). --> Fixes # **Special notes for your reviewers**: See merge request: Ascend/pytorch!26538 | 10 个月前 | |
AI assist developer for python dt master Co-authored-by: aksksks<mengzichao@h-partners.com> # message auto-generated for no-merge-commit merge: !26538 merge master into master AI assist developer for python dt master Created-by: aksksks Commit-by: aksksks Merged-by: ascend-robot Description: <!-- Thanks for sending a pull request! --> **What type of PR is this?** > Uncomment only one /kind <> line, hit enter to put that in a new line, and remove leading whitespaces from that line: > > /kind bug > /kind task > /kind feature **What does this PR do / why do we need it**: **Which issue(s) this PR fixes**: <!-- *Automatically closes linked issue when PR is merged. Usage: Fixes #<issue number>, or Fixes (paste link of issue). --> Fixes # **Special notes for your reviewers**: See merge request: Ascend/pytorch!26538 | 10 个月前 | |
AI assist developer for python dt for master Co-authored-by: aksksks<mengzichao@h-partners.com> # message auto-generated for no-merge-commit merge: !27014 merge master into master AI assist developer for python dt for master Created-by: aksksks Commit-by: aksksks Merged-by: ascend-robot Description: <!-- Thanks for sending a pull request! --> **What type of PR is this?** > Uncomment only one /kind <> line, hit enter to put that in a new line, and remove leading whitespaces from that line: > > /kind bug > /kind task > /kind feature **What does this PR do / why do we need it**: **Which issue(s) this PR fixes**: <!-- *Automatically closes linked issue when PR is merged. Usage: Fixes #<issue number>, or Fixes (paste link of issue). --> Fixes # **Special notes for your reviewers**: See merge request: Ascend/pytorch!27014 | 10 个月前 | |
refactor(inductor): remove upstreamed NPU compatibility patches Co-authored-by: srhust<hwxhewenxuan321@163.com> # message auto-generated for no-merge-commit merge: !43791 merge cleanup/remove-gpu-monkey-patches into master refactor(inductor): remove upstreamed NPU compatibility patches Created-by: srhust Commit-by: srhust Merged-by: ascend-robot Description: # 【合入来源】 关联 issue: https://gitcode.com/Ascend/pytorch/issues/3634 - [ ] 需求 - [ ] 问题单 - [x] issue/工单 - [x] 重构优化 - [ ] 资料更新 # 〖修改方案〗 基于 PyTorch upstream 提供的 PrivateUse1 / out-of-tree backend 扩展机制, 将 NPU Inductor 中原有的设备相关 monkey patch 迁移到 DeviceOpOverrides、DeviceInterface 等统一 backend extension points。 同时将 PyTorch 版本差异收敛到 torch_npu/_compat 层: 业务代码不直接进行版本判断,统一通过 compat 接口访问对应能力。 兼容策略: - torch < 2.15:保留原有 legacy patch / mapping 行为。 - torch >= 2.15:使用 PyTorch upstream 提供的统一 backend extension points。 - 当最低支持 PyTorch 版本提升至 2.15 及以上后,可删除对应 legacy compat 实现。 具体修改如下。 1. 接入 C++ wrapper routing 扩展能力 - 在 NewNPUDeviceOpOverrides 中实现: python def uses_gpu_cpp_wrapper(self) -> bool: return True - 通过 PyTorch DeviceOpOverrides.uses_gpu_cpp_wrapper() 向 GraphLowering 提供 NPU C++ wrapper routing capability。 - torch < 2.15 通过 _compat 保留原 patch_codegen_with_cpp_wrapper 行为。 - 对应 upstream:pytorch/pytorch#190615。 2. 接入 device compute-unit 查询能力 - 在 NpuInterface 中实现: python @classmethod def get_multi_processor_count(cls, device=None) -> int: return cls.get_device_properties(device).vector_core_num - 通过 PyTorch DeviceInterface.get_multi_processor_count() 向 DeviceProperties.create() 提供 NPU compute-unit 数量。 - torch < 2.15 通过 _compat 保留原 patch_create_device_properties 行为。 - 对应 upstream:pytorch/pytorch#190615。 3. 接入 AOTI / C++ wrapper ATen DeviceType 扩展能力 - 在 NewNPUDeviceOpOverrides 中实现: python def aten_device_type(self) -> str: return "at::kPrivateUse1" - 通过 PyTorch DeviceOpOverrides.aten_device_type() 提供 NPU ATen DeviceType 映射。 - 新增 _compat.inductor.device_to_aten() 统一接口: - torch >= 2.15 调用 PyTorch upstream device_to_aten(); - torch < 2.15 继续使用 legacy DEVICE_TO_ATEN mapping。 - cpp_wrapper_npu.py 统一通过 _compat 接口获取 ATen DeviceType, 不直接依赖不同 PyTorch 版本下的内部实现。 - 对应 upstream:pytorch/pytorch#193904。 4. 接入 CodeCache system metadata 扩展能力 - 在 NpuInterface 中实现: python @classmethod def get_cache_system_info(cls): try: device_properties = get_device_properties_npu(current_device()) except (AssertionError, RuntimeError): return None return { "name": device_properties.name, "cann": torch.version.cann, } - 通过 PyTorch DeviceInterface.get_cache_system_info() 向 CacheBase.get_system() 提供 NPU device name 和 CANN version。 - 保证 NPU backend metadata 参与统一的 CodeCache system key 及 cache hash 生成。 - torch < 2.15 通过 _compat 保留原 patch_cache_base_get_system 行为。 - 对应 upstream:pytorch/pytorch#193908。 5. 收敛版本兼容逻辑 - 新增 torch_npu/_compat/inductor.py,统一管理上述 Inductor 版本兼容逻辑。 - 业务实现优先调用 _compat 层提供的统一接口,不在业务模块中 分散进行 PyTorch 版本判断。 - CURRENT_VERSION >= (2, 15) 使用 upstream contract; 旧版本继续保持原有 PTA 行为。 - 删除/收敛已由 upstream extension point 替代的版本相关 monkey patch 实现。 6. 同步测试及模块注册信息 - 增加 NPU C++ wrapper routing capability 测试。 - 增加 NPU ATen DeviceType / device_to_aten 测试。 - 增加 NPU compute-unit 查询测试。 - 更新 CodeCache 测试,覆盖 NPU device metadata、CANN version 及 cache hash。 - 覆盖 <2.15 legacy compat 与 >=2.15 upstream contract 的版本分支。 - 同步更新 test_public_bindings.py,使 public bindings 检查与 当前 Inductor 模块结构保持一致。 # 〖资料变更〗 不涉及。 # 〖接口变更〗 不涉及客户可见接口变更。 内部实现使用 PyTorch upstream 提供的以下 backend extension points: - DeviceOpOverrides.uses_gpu_cpp_wrapper() - DeviceInterface.get_multi_processor_count() - DeviceOpOverrides.aten_device_type() - DeviceInterface.get_cache_system_info() PTA 内部新增 _compat 统一适配层,用于隔离不同 PyTorch 版本下 Inductor backend contract 的差异,不新增客户可见 API。 # 〖功能验证〗 新增/更新以下 UT: 1. test/_inductor/test_npu_device.py - 验证 NewNPUDeviceOpOverrides.uses_gpu_cpp_wrapper() 返回 True。 - 验证 NewNPUDeviceOpOverrides.aten_device_type() 返回 at::kPrivateUse1。 - 验证 NPU ATen DeviceType 可通过统一 device_to_aten() 接口获取。 2. test/utils/test_dynamo_device.py - 验证 NpuInterface.get_multi_processor_count() 从 vector_core_num 获取 NPU compute-unit 数量。 3. test/_inductor/test_codecache.py - 验证 CacheBase.get_system()["device_interfaces"]["npu"] 包含 NPU device name 和 CANN version。 - 验证 NPU backend metadata 参与 CodeCache system hash 生成。 4. test/npu/test_public_bindings.py - 验证 public bindings 配置与当前 Inductor 模块结构保持一致。 兼容性验证: - torch < 2.15 使用 legacy compat 实现。 - torch >= 2.15 使用 PyTorch upstream backend extension points。 - compat 版本判断通过 PTA version compatibility checker 约束。 静态检查: - git diff --check 通过。 - python -m compileall 通过。 # 〖CheckList〗 - [x] 代码注释完备,正确记录错误日志 - [x] 代码实现进行了返回值、空指针等校验 - [x] PR标题正确使用类型标签,如:feat、fix、refactor、docs、test等 - [x] PR持续集成流水线(CI)执行通过,代码检查无异常 See merge request: Ascend/pytorch!43791 | 1 个月前 | |
AI assist developer for python dt for master Co-authored-by: aksksks<mengzichao@h-partners.com> # message auto-generated for no-merge-commit merge: !27014 merge master into master AI assist developer for python dt for master Created-by: aksksks Commit-by: aksksks Merged-by: ascend-robot Description: <!-- Thanks for sending a pull request! --> **What type of PR is this?** > Uncomment only one /kind <> line, hit enter to put that in a new line, and remove leading whitespaces from that line: > > /kind bug > /kind task > /kind feature **What does this PR do / why do we need it**: **Which issue(s) this PR fixes**: <!-- *Automatically closes linked issue when PR is merged. Usage: Fixes #<issue number>, or Fixes (paste link of issue). --> Fixes # **Special notes for your reviewers**: See merge request: Ascend/pytorch!27014 | 10 个月前 | |
fix: cut patch_getenv overhead from 3x to ~1x and gate it by TORCH_NPU_LOGS Co-authored-by: wuyouqi1<wuyouqi1@h-partners.com> # message auto-generated for no-merge-commit merge: !47484 merge personal/fix-patch-getenv-3x-overhead-master into master fix: cut patch_getenv overhead from 3x to ~1x and gate it by TORCH_NPU_LOGS Created-by: wuyouqi1 Commit-by: wuyouqi1 Merged-by: ascend-robot Description: # 【合入来源】> **如有社区issue,请关联issue链接**\ > **请勿携带内部流程信息(需求链接、问题单、内部issue等)** - [ ] 需求 - [ ] 问题单 - [x] issue/工单 - [ ] 重构优化 - [ ] 资料更新 关联issue:https://gitcode.com/Ascend/pytorch/issues/5090(Fixes #5090) # 【修改方案】 torch_npu/utils/patch_getenv.py 使全进程 os.getenv/os.environ.get 开销达 ~3.3x。根因:保存的原生 os.getenv 调用时重新解析 environ.get,再次进入被 patch 的实例属性(嵌套);且 key in os.environ 预检查本身即一次完整查找—— 一次调用共 3 次真实查找。 修复: 1. 两个 patch 点共用一个 _patched_getenv,直读 os.environ[key] (KeyError 即未命中):恰好 1 次真实查找,构造上无嵌套 2. 仅当日志可观测时安装:TORCH_NPU_LOGS/TORCH_LOGS 已设置,或 import 时 torch_npu.env logger 已可见 INFO。patch_getenv 早于 _add_logging_module() 配置 logger,import 时 isEnabledFor 不可信,故按 原始环境变量门控(与 ACL log 门禁做法一致);钩子为私有 _install(),不进入公开 API 兼容性检查 3. UT:test/utils/test_patch_getenv.py 6 用例(门控/包装语义/单次查找计数); test_torch_npu_init.py 快照断言按门控分支 # 【资料变更】 不涉及 # 【接口变更】 不涉及。os.getenv/os.environ.get 返回值行为完全不变(含 bytes key 抛 TypeError 对齐),仅日志按需安装;默认配置不安装(原生直通)。 # 【功能验证】 | 场景 | 真实查找/次 | 耗时(py3.14) | |---|---|---| | native | 1 | 597 ns (1.00x) | | 修复前 | 3 | 1974 ns (3.31x) | | 修复后(已安装) | 1 | 626 ns (1.05x) | | 修复后(默认不装) | 1 | 1.00x | (py3.11 修复前 3.39x;纯 CPython 复现,与硬件/CANN 无关) 语义回归(命中/未命中/default/空串/kwargs/bytes key)、门控矩阵(默认不装, TORCH_NPU_LOGS/TORCH_LOGS/预先配置 INFO 均安装)、端到端日志去重:全部 PASS。test_api_compatibility 复检通过(公开 callable 为空)。 本地 whl 实测(conda wyq_py10,torch_npu 2.7.1 whl):test_patch_getenv.py 6 用例全过;test_torch_npu_init.py 16 用例全过(test_14 按 #5230 skip)。 **test_14 临时 skip**:test_torch_npu_init.py::test_14_dtensor_strategies_are_ registered_without_dynamo 在 v2.7.1 HEAD 上确定性失败,与本 MR 无关—— !44496 的 flex_attention 补丁在 import 时经 from torch.nn.attention import flex_attention 拉入 torch._dynamo (torch 2.7.x),破坏 #2788 的延迟导入契约。详见 https://gitcode.com/Ascend/pytorch/issues/5230,待修复后恢复用例。 # 【CheckList】 > PR提交人对以下CheckList自检项进行全量自检,自检通过或不涉及,均修改 [ ] 为 [x] - [x] 代码注释完备,正确记录错误日志 - [x] 代码实现进行了返回值、空指针等校验 - [x] PR标题正确使用类型标签,如:feat、fix、refactor、docs、test等(fix) - [x] PR持续集成流水线(CI)执行通过,代码检查无异常(个人分支暂未触发 CI,合入前补充) See merge request: Ascend/pytorch!47484 | 8 天前 | |
AI assist developer for python dt for master Co-authored-by: aksksks<mengzichao@h-partners.com> # message auto-generated for no-merge-commit merge: !27014 merge master into master AI assist developer for python dt for master Created-by: aksksks Commit-by: aksksks Merged-by: ascend-robot Description: <!-- Thanks for sending a pull request! --> **What type of PR is this?** > Uncomment only one /kind <> line, hit enter to put that in a new line, and remove leading whitespaces from that line: > > /kind bug > /kind task > /kind feature **What does this PR do / why do we need it**: **Which issue(s) this PR fixes**: <!-- *Automatically closes linked issue when PR is merged. Usage: Fixes #<issue number>, or Fixes (paste link of issue). --> Fixes # **Special notes for your reviewers**: See merge request: Ascend/pytorch!27014 | 10 个月前 | |
[Fix] Fix static check errors detected by SPACES Co-authored-by: huangjingwei<huangjingwei4@huawei.com> # message auto-generated for no-merge-commit merge: !35981 merge master_lintrunner into master [Fix] Fix static check errors detected by SPACES Created-by: huangjingwei Commit-by: huangjingwei Merged-by: ascend-robot Description: <!-- PR描述模板更新日期:20260203 --> # 【合入来源】 > <font color="red">**如有社区issue,请关联issue链接**</font>\ > <font color="red">**请勿携带内部流程信息(需求链接、问题单、内部issue等)**</font> - [ ] 需求 - [ ] 问题单 - [x] issue/工单 - [ ] 重构优化 - [ ] 资料更新 # 【修改方案】 检测和删除代码中的行尾空白字符 # 【资料变更】 不涉及 # 【接口变更】 不涉及 # 【功能验证】 不涉及 # 【CheckList】 > PR提交人对以下CheckList自检项进行全量自检,自检通过或不涉及,均修改 [ ] 为 [x] - [x] 代码注释完备,正确记录错误日志 - [x] 代码实现进行了返回值、空指针等校验 - [x] PR标题正确使用类型标签,如:feat、fix、refactor、docs、test等 - [x] PR持续集成流水线(CI)执行通过,代码检查无异常 See merge request: Ascend/pytorch!35981 | 4 个月前 |
| 文件 | 最后提交记录 | 最后更新时间 |
|---|---|---|
| 9 天前 | ||
| 5 个月前 | ||
| 10 个月前 | ||
| 10 个月前 | ||
| 10 个月前 | ||
| 1 个月前 | ||
| 10 个月前 | ||
| 8 天前 | ||
| 10 个月前 | ||
| 4 个月前 |