| 文件 | 最后提交记录 | 最后更新时间 |
|---|---|---|
test(distributed): adapt DynamicMetaLoadPlanner test for NPU Co-authored-by: qq_65095566<1922937030@qq.com> # message auto-generated for no-merge-commit merge: !35165 merge test-dynamic-meta-load-planner-v2.9.0 into v2.9.0 test(distributed): adapt DynamicMetaLoadPlanner test for NPU Created-by: qq_65095566 Commit-by: qq_65095566 Merged-by: ascend-robot Description: <!-- PR描述模板更新日期:20260203 --> # 【合入来源】 > <font color="red">**[[Usage]: test/distributed/checkpoint 中 DynamicMetaLoadPlanner 相关用例 NPU 适配不完整,需要修正或补充 patch](https://gitcode.com/Ascend/pytorch/issues/1914)**</font>\ > <font color="red">**请勿携带内部流程信息(需求链接、问题单、内部issue等)**</font> - [x] 问题单 # 【修改方案】 > 请描述修改内容的具体实现,涉及哪些组件之间进行交互,可以用1、2、3、...进行罗列\ > 如果是需求或者重构类的PR,需要补充详细设计文档(说明上下游组件关系、时序图、类图、DFX能力等内容) 经检查,v2.9.0 分支 test_upstream/test/distributed/checkpoint/ 目录下未发现 test_format_utils.py.patch,因此本 PR 基于 PyTorch 社区原生测试文件 test/distributed/checkpoint/test_format_utils.py 新增 NPU 适配 patch,使该测试用例可以在 NPU/HCCL 场景下运行。 ## 一、API 功能说明 torch.distributed.checkpoint.format_utils.DynamicMetaLoadPlanner 是分布式 checkpoint 格式转换与加载流程中的加载规划器。该类用于在没有 DCP metadata 文件的情况下,根据传入的 state_dict 动态构造加载所需的 metadata,从而支持通过 dcp.load 将 torch.save 格式保存的 checkpoint 加载到目标模型或分片模型中。 在 PyTorch 社区原生测试中,DynamicMetaLoadPlanner 与 BroadcastingTorchSaveReader 配合使用,用于验证将 torch.save 保存的模型参数直接加载到 FSDP 分片模型中的场景。 ## 二、测试用例完备性说明 PyTorch 社区原生测试文件 test/distributed/checkpoint/test_format_utils.py 已覆盖 torch.distributed.checkpoint.format_utils.DynamicMetaLoadPlanner 的核心使用场景,因此本 PR 不新增独立测试文件,而是在社区原生用例基础上修正 NPU 适配 patch。 该测试文件主要覆盖以下内容: 1. test_dcp_to_torch_save:验证 DCP checkpoint 到 torch.save 格式的转换; 2. test_torch_save_to_dcp:验证 torch.save 格式 checkpoint 到 DCP checkpoint 的转换; 3. test_online_torch_save_to_dcp:验证通过 dcp.load、DynamicMetaLoadPlanner 和 BroadcastingTorchSaveReader,将 torch.save checkpoint 在线加载到 FSDP 分片模型中。 其中,test_online_torch_save_to_dcp 直接覆盖 torch.distributed.checkpoint.format_utils.DynamicMetaLoadPlanner 的核心使用场景。 ## 三、NPU 适配方案 本 PR 主要修改如下: 1. 新增 import torch_npu,确保测试环境识别 NPU 设备; 2. 将 skip_if_lt_x_gpu(2) 替换为 skipIfUnsupportMultiNPU(2),适配 NPU 多设备检查; 3. 将需要运行在设备侧的模型显式迁移到 NPU,例如 SimpleModelUneven().to("npu"); 4. 将分布式 FSDP 在线加载测试中的模型迁移到当前测试设备:SimpleModelUneven().to(self.device_type); 5. 为 TestFormatUtils 设置 backend = "hccl" 和 device_type = "npu"; 6. 在 init_pg 中调用 torch_npu.npu.set_device(self.rank),确保多进程分布式测试中每个 rank 绑定对应 NPU; 7. init_pg 使用 *args, **kwargs 透传参数:该写法用于兼容不同 PyTorch 版本中 with_comms 对 init_pg 的调用方式,避免出现 init_pg 参数数量不匹配问题,同时保留每个 rank 绑定对应 NPU 的多卡测试逻辑。 python def init_pg(self, *args, **kwargs) -> None: self.device_type = type(self).device_type torch_npu.npu.set_device(self.rank) super().init_pg(*args, **kwargs) 8. 保留 PyTorch 社区原生 DTensorTestBase 和 with_comms 测试结构。 ## 四、版本差异说明 本 PR 当前对应版本为:v2.9.0。 各版本的 PyTorch 社区原生 test_format_utils.py 存在差异,因此各版本 patch 均基于对应版本的 PyTorch 原生文件分别修改,并通过 git diff 单独生成,未直接复用其他版本 patch。 具体差异如下: 1. v2.7.1 与 v2.9.0 原始文件整体基本一致,主要差异为 init_device_mesh 的导入路径不同: v2.7.1 使用:from torch.distributed._tensor.device_mesh import init_device_mesh v2.9.0 使用:from torch.distributed.device_mesh import init_device_mesh 2. v2.7.1 和 v2.9.0 原始用例中仍存在较明显的 CUDA/GPU 相关写法,例如 device="cuda"、.cuda()、skip_if_lt_x_gpu(2),因此对应 patch 显式替换为 NPU/HCCL 相关逻辑。 3. v2.10.0 和 v2.11.0 原始用例已经引入: device_type = acc.type if (acc := torch.accelerator.current_accelerator()) else cpu 并且部分位置已使用 device=device_type 或 .to(self.device_type)。因此对应 patch 保留该版本已有的通用设备变量,同时补充 import torch_npu、skipIfUnsupportMultiNPU(2)、backend = "hccl"、device_type = "npu"、init_pg 绑定 NPU 等分布式 NPU 适配逻辑。 4. v2.10.0 与 v2.11.0 的原始文件结构基本一致,因此两者修改思路一致,分别基于各自版本原始文件通过 git diff 生成 patch。 # 【资料变更】 > 请确认是否涉及资料变更。如涉及,需要在PR中体现,并简要说明修改内容。如不涉及,需填写“不涉及” 本 PR 不混合提交资料修改。 已检查 docs/zh/native_apis 中 torch.distributed.checkpoint.format_utils.DynamicMetaLoadPlanner 的资料支持情况,当前未检索到该 API 的支持项。本 PR 仅提交 test_upstream 测试适配 patch,不修改资料文件。 资料补齐将按照资料补齐规范,单独在 v2.7.1 分支提交 docs PR,并刷新对应版本的 native API 支持情况。 # 【接口变更】 > 请确认是否涉及跨代码仓或者客户面可见的接口变更。如涉及,需要详细说明接口以及对应的变更内容,同时需要在资料中体现。如不涉及,需填写“不涉及” 不涉及 # 【功能验证】 > 说明测试场景,测试方法。如果本次测试方式与常规单元测试不同,请详细说明您的测试步骤\ > 新增/变更内容是否已新增/适配UT测试用例看护,并补充测试自验证截图 ## 测试场景: 测试执行通过,日志如下: [W516 10:26:02.516726110 NPUCachingAllocator.cpp:199] Warning: The current CANN and Soc versions require processing for 32 padding size, with memory allocation. (function operator()) /usr/local/python/lib/python3.11/site-packages/torch/distributed/checkpoint/utils.py:483: UserWarning: torch.distributed is disabled, unavailable or uninitialized, assuming the intent is to load in a single process. return func(*args, **kwargs) [W516 10:26:02.559271925 NPUCachingAllocator.cpp:199] Warning: The current CANN and Soc versions require processing for 32 padding size, with memory allocation. (function operator()) [W516 10:26:02.564576756 NPUCachingAllocator.cpp:199] Warning: The current CANN and Soc versions require processing for 32 padding size, with memory allocation. (function operator()) /usr/local/python/lib/python3.11/site-packages/torch/distributed/checkpoint/utils.py:483: UserWarning: torch.distributed is disabled, unavailable or uninitialized, assuming the intent is to load in a single process. return func(*args, **kwargs) /usr/local/python/lib/python3.11/site-packages/torch/distributed/checkpoint/utils.py:483: UserWarning: torch.distributed is disabled, unavailable or uninitialized, assuming the intent is to load in a single process. return func(*args, **kwargs) [W516 10:26:03.849173689 NPUCachingAllocator.cpp:199] Warning: The current CANN and Soc versions require processing for 32 padding size, with memory allocation. (function operator()) /usr/local/python/lib/python3.11/site-packages/torch/distributed/checkpoint/utils.py:483: UserWarning: torch.distributed is disabled, unavailable or uninitialized, assuming the intent is to load in a single process. return func(*args, **kwargs) . ---------------------------------------------------------------------- Ran 3 tests in 56.095s OK root@hostname-fqv42:/home# ## 结果说明: 上述 CANN/NPU 内存分配提示和 torch.distributed is disabled, unavailable or uninitialized 为单进程 checkpoint 转换场景下的 warning,不影响测试结果。最终 3 个测试用例均执行通过。 本次共执行 3 个测试: 1. test_dcp_to_torch_save:验证 DCP 格式 checkpoint 转换为 torch.save 格式; 2. test_torch_save_to_dcp:验证 torch.save 格式 checkpoint 转换为 DCP 格式; 3. test_online_torch_save_to_dcp:验证通过 DynamicMetaLoadPlanner 和 BroadcastingTorchSaveReader 将 torch.save checkpoint 在线加载到 FSDP 分片模型中。 # 【CheckList】 > PR提交人对以下CheckList自检项进行全量自检,自检通过或不涉及,均修改 [ ] 为 [x] - [x] 代码注释完备,正确记录错误日志 - [x] 代码实现进行了返回值、空指针等校验 - [x] PR标题正确使用类型标签,如:feat、fix、refactor、docs、test等 - [x] PR持续集成流水线(CI)执行通过,代码检查无异常 See merge request: Ascend/pytorch!35165 | 5 个月前 | |
test: add NPU coverage for symbolic_shapes APIs (issue #1614) Co-authored-by: zhangjiahao-2026<2332445379@qq.com> # message auto-generated for no-merge-commit merge: !36328 merge intern-1614-symbolic-shapes into v2.9.0 test: add NPU coverage for symbolic_shapes APIs (issue #1614) Created-by: zhangjiahao-2026 Commit-by: zhangjiahao-2026 Merged-by: ascend-robot Description: # 【合入来源】 > **关联社区 issue:** https://gitcode.com/Ascend/pytorch/issues/1614 - [ ] 需求 - [ ] 问题单 - [x] issue/工单 - [ ] 重构优化 - [ ] 资料更新 # 【修改方案】 本次为 Torch-NPU API 一致性对齐任务,针对 torch.fx.experimental.symbolic_shapes 下 5 个 API 补充/适配测试,**不涉及算子或 API 实现代码修改**(NPU 上与 PyTorch 2.9 行为一致)。 ## API 功能说明 torch.fx.experimental.symbolic_shapes 是 PyTorch FX 动态 shape 推导体系中的符号形状模块,负责在编译/导出过程中管理 SymInt/SymBool 约束、guard 生成及 shape 相等关系。本次验证的 5 个 API 均为纯 Python 层面的符号 shape 工具,与底层计算硬件无关。 - torch.fx.experimental.symbolic_shapes.DivideByKey:整除键类,用于在符号 shape 表达中表示对某个常量做 floor division(整除)的运算模式,可通过构造参数指定除数。 - torch.fx.experimental.symbolic_shapes.DivideByKey.get:DivideByKey 实例方法,对给定数值执行 floor division,即 value // divisor,返回整除结果。 - torch.fx.experimental.symbolic_shapes.EqualityConstraint:符号 shape 约束类,用于在 FX 图导出/动态 shape 推导中表达多个 shape 源之间的相等关系,包含 source_pairs、derived_equalities、phantom_symbols、relaxed_sources、warn_only 等字段。 - torch.fx.experimental.symbolic_shapes.has_free_symbols:判断给定对象(通常为 sympy 表达式)是否包含未被绑定的自由符号,用于区分常量表达式与含符号变量的动态 shape 表达式。 - torch.fx.experimental.symbolic_shapes.guard_size_oblivious:符号 shape guard 生成过程中的辅助函数,对布尔条件做 size-oblivious 处理,使其与具体 tensor size 解耦。 ## API 全名与测试覆盖场景 | 全名 API | 测试用例 | 覆盖场景 | |----------|----------|----------| | torch.fx.experimental.symbolic_shapes.DivideByKey | 自写 TestDivideByKeyAndEqualityConstraint::test_divide_by_key + 官方 test/export/test_export.py(patch) | 自写:构造 DivideByKey(4),验证 str(key) 为 ".__floordiv__(4)";官方:patch 注入 torch_npu 后复用 export 场景用例 | | torch.fx.experimental.symbolic_shapes.DivideByKey.get | 自写 TestDivideByKeyAndEqualityConstraint::test_divide_by_key_get | 构造 DivideByKey(4),调用 .get(17),验证返回 4 | | torch.fx.experimental.symbolic_shapes.EqualityConstraint | 自写 TestDivideByKeyAndEqualityConstraint::test_equality_constraint_init | 以空约束参数初始化(source_pairs=[],derived_equalities=[],phantom_symbols=[],relaxed_sources=set(),warn_only=False),验证 source_pairs、phantom_symbols 为空且 warn_only=False | | torch.fx.experimental.symbolic_shapes.has_free_symbols | 官方 test/test_dynamic_shapes.py::TestUnbacked::test_has_free_symbols(patch) | patch 注入 import torch_npu 后复用官方用例 | | torch.fx.experimental.symbolic_shapes.guard_size_oblivious | 官方 test/dynamo/test_misc.py(patch) | patch 注入 import torch_npu 后复用官方用例 | ## 具体改动 1. 在 test/fx/test_symbolic_shapes.py 新增 TestDivideByKeyAndEqualityConstraint 类,补充 3 个自写用例 - 使用 unittest + torch.testing._internal.common_utils.run_tests - 覆盖 API:DivideByKey、DivideByKey.get、EqualityConstraint - 用例均带 @unittest.skipUnless(torch.npu.is_available()) 2. 新增 test_upstream/test/test_dynamic_shapes.py.patch - 在 import torch 后增加 import torch_npu - 适配官方 has_free_symbols 用例 3. 新增 test_upstream/test/dynamo/test_misc.py.patch - 在 import torch 后增加 import torch_npu - 适配官方 guard_size_oblivious 用例 4. 新增 test_upstream/test/export/test_export.py.patch - 在 import torch 后增加 import torch_npu - 适配官方 DivideByKey export 场景用例 5. 上述 3 个 patch 已对 **v2.9.0** 上游文件执行 git apply --check,验证可应用。 # 【资料变更】 不涉及 # 【接口变更】 不涉及 # 【功能验证】 **环境:** torch 2.9.0 + torch_npu 2.9.0,torch.npu.is_available()==True **(1)自写用例** bash cd /tmp && python3 /data/pytorch/test/fx/test_symbolic_shapes.py \ TestDivideByKeyAndEqualityConstraint.test_divide_by_key \ TestDivideByKeyAndEqualityConstraint.test_divide_by_key_get \ TestDivideByKeyAndEqualityConstraint.test_equality_constraint_init \ 2>&1 | grep -vE "recording\.py|set_unbacked_var_to_val|E0626" | tail -10 结果:  **(2)5 API 快速验证** bash cd /workspace python -c "import torch; import torch_npu; from torch.fx.experimental.symbolic_shapes import DivideByKey, EqualityConstraint, guard_size_oblivious, has_free_symbols; print('DivideByKey.get(17)=', DivideByKey(4).get(17)); print('guard_size_oblivious(True)=', guard_size_oblivious(True)); print('has_free_symbols(3)=', has_free_symbols(3)); print('EqualityConstraint OK'); print('npu:', torch.npu.is_available())" 结果:  **(3)官方 torch.fx.experimental.symbolic_shapes.has_free_symbols** bash cd /workspace python -m pytest pytorch-upstream/test/test_dynamic_shapes.py -k test_has_free_symbols -xvs 结果:  **(4)patch 可应用性** bash cd /workspace/pytorch-upstream && git checkout -- test git apply --check /workspace/pytorch/test_upstream/test/test_dynamic_shapes.py.patch && echo OK git apply --check /workspace/pytorch/test_upstream/test/dynamo/test_misc.py.patch && echo OK git apply --check /workspace/pytorch/test_upstream/test/export/test_export.py.patch && echo OK 结果:  # 【CheckList】 - [x] 代码注释完备,正确记录错误日志 - [x] 代码实现进行了返回值、空指针等校验(不涉及) - [x] PR标题正确使用类型标签(test: 前缀) - [x] PR持续集成流水线(CI)执行通过 --- See merge request: Ascend/pytorch!36328 | 3 个月前 | |
test: add NPU coverage for symbolic_shapes APIs (issue #1614) Co-authored-by: zhangjiahao-2026<2332445379@qq.com> # message auto-generated for no-merge-commit merge: !36328 merge intern-1614-symbolic-shapes into v2.9.0 test: add NPU coverage for symbolic_shapes APIs (issue #1614) Created-by: zhangjiahao-2026 Commit-by: zhangjiahao-2026 Merged-by: ascend-robot Description: # 【合入来源】 > **关联社区 issue:** https://gitcode.com/Ascend/pytorch/issues/1614 - [ ] 需求 - [ ] 问题单 - [x] issue/工单 - [ ] 重构优化 - [ ] 资料更新 # 【修改方案】 本次为 Torch-NPU API 一致性对齐任务,针对 torch.fx.experimental.symbolic_shapes 下 5 个 API 补充/适配测试,**不涉及算子或 API 实现代码修改**(NPU 上与 PyTorch 2.9 行为一致)。 ## API 功能说明 torch.fx.experimental.symbolic_shapes 是 PyTorch FX 动态 shape 推导体系中的符号形状模块,负责在编译/导出过程中管理 SymInt/SymBool 约束、guard 生成及 shape 相等关系。本次验证的 5 个 API 均为纯 Python 层面的符号 shape 工具,与底层计算硬件无关。 - torch.fx.experimental.symbolic_shapes.DivideByKey:整除键类,用于在符号 shape 表达中表示对某个常量做 floor division(整除)的运算模式,可通过构造参数指定除数。 - torch.fx.experimental.symbolic_shapes.DivideByKey.get:DivideByKey 实例方法,对给定数值执行 floor division,即 value // divisor,返回整除结果。 - torch.fx.experimental.symbolic_shapes.EqualityConstraint:符号 shape 约束类,用于在 FX 图导出/动态 shape 推导中表达多个 shape 源之间的相等关系,包含 source_pairs、derived_equalities、phantom_symbols、relaxed_sources、warn_only 等字段。 - torch.fx.experimental.symbolic_shapes.has_free_symbols:判断给定对象(通常为 sympy 表达式)是否包含未被绑定的自由符号,用于区分常量表达式与含符号变量的动态 shape 表达式。 - torch.fx.experimental.symbolic_shapes.guard_size_oblivious:符号 shape guard 生成过程中的辅助函数,对布尔条件做 size-oblivious 处理,使其与具体 tensor size 解耦。 ## API 全名与测试覆盖场景 | 全名 API | 测试用例 | 覆盖场景 | |----------|----------|----------| | torch.fx.experimental.symbolic_shapes.DivideByKey | 自写 TestDivideByKeyAndEqualityConstraint::test_divide_by_key + 官方 test/export/test_export.py(patch) | 自写:构造 DivideByKey(4),验证 str(key) 为 ".__floordiv__(4)";官方:patch 注入 torch_npu 后复用 export 场景用例 | | torch.fx.experimental.symbolic_shapes.DivideByKey.get | 自写 TestDivideByKeyAndEqualityConstraint::test_divide_by_key_get | 构造 DivideByKey(4),调用 .get(17),验证返回 4 | | torch.fx.experimental.symbolic_shapes.EqualityConstraint | 自写 TestDivideByKeyAndEqualityConstraint::test_equality_constraint_init | 以空约束参数初始化(source_pairs=[],derived_equalities=[],phantom_symbols=[],relaxed_sources=set(),warn_only=False),验证 source_pairs、phantom_symbols 为空且 warn_only=False | | torch.fx.experimental.symbolic_shapes.has_free_symbols | 官方 test/test_dynamic_shapes.py::TestUnbacked::test_has_free_symbols(patch) | patch 注入 import torch_npu 后复用官方用例 | | torch.fx.experimental.symbolic_shapes.guard_size_oblivious | 官方 test/dynamo/test_misc.py(patch) | patch 注入 import torch_npu 后复用官方用例 | ## 具体改动 1. 在 test/fx/test_symbolic_shapes.py 新增 TestDivideByKeyAndEqualityConstraint 类,补充 3 个自写用例 - 使用 unittest + torch.testing._internal.common_utils.run_tests - 覆盖 API:DivideByKey、DivideByKey.get、EqualityConstraint - 用例均带 @unittest.skipUnless(torch.npu.is_available()) 2. 新增 test_upstream/test/test_dynamic_shapes.py.patch - 在 import torch 后增加 import torch_npu - 适配官方 has_free_symbols 用例 3. 新增 test_upstream/test/dynamo/test_misc.py.patch - 在 import torch 后增加 import torch_npu - 适配官方 guard_size_oblivious 用例 4. 新增 test_upstream/test/export/test_export.py.patch - 在 import torch 后增加 import torch_npu - 适配官方 DivideByKey export 场景用例 5. 上述 3 个 patch 已对 **v2.9.0** 上游文件执行 git apply --check,验证可应用。 # 【资料变更】 不涉及 # 【接口变更】 不涉及 # 【功能验证】 **环境:** torch 2.9.0 + torch_npu 2.9.0,torch.npu.is_available()==True **(1)自写用例** bash cd /tmp && python3 /data/pytorch/test/fx/test_symbolic_shapes.py \ TestDivideByKeyAndEqualityConstraint.test_divide_by_key \ TestDivideByKeyAndEqualityConstraint.test_divide_by_key_get \ TestDivideByKeyAndEqualityConstraint.test_equality_constraint_init \ 2>&1 | grep -vE "recording\.py|set_unbacked_var_to_val|E0626" | tail -10 结果:  **(2)5 API 快速验证** bash cd /workspace python -c "import torch; import torch_npu; from torch.fx.experimental.symbolic_shapes import DivideByKey, EqualityConstraint, guard_size_oblivious, has_free_symbols; print('DivideByKey.get(17)=', DivideByKey(4).get(17)); print('guard_size_oblivious(True)=', guard_size_oblivious(True)); print('has_free_symbols(3)=', has_free_symbols(3)); print('EqualityConstraint OK'); print('npu:', torch.npu.is_available())" 结果:  **(3)官方 torch.fx.experimental.symbolic_shapes.has_free_symbols** bash cd /workspace python -m pytest pytorch-upstream/test/test_dynamic_shapes.py -k test_has_free_symbols -xvs 结果:  **(4)patch 可应用性** bash cd /workspace/pytorch-upstream && git checkout -- test git apply --check /workspace/pytorch/test_upstream/test/test_dynamic_shapes.py.patch && echo OK git apply --check /workspace/pytorch/test_upstream/test/dynamo/test_misc.py.patch && echo OK git apply --check /workspace/pytorch/test_upstream/test/export/test_export.py.patch && echo OK 结果:  # 【CheckList】 - [x] 代码注释完备,正确记录错误日志 - [x] 代码实现进行了返回值、空指针等校验(不涉及) - [x] PR标题正确使用类型标签(test: 前缀) - [x] PR持续集成流水线(CI)执行通过 --- See merge request: Ascend/pytorch!36328 | 3 个月前 | |
test(fx): add/update test_subgraph_rewriter.py.patch for NPU Co-authored-by: gcw_N9D3Qs4C<1763674271@qq.com> # message auto-generated for no-merge-commit merge: !37326 merge test_subgraph_rewriter_npu_v2.9.0 into v2.9.0 test(fx): add/update test_subgraph_rewriter.py.patch for NPU Created-by: gcw_N9D3Qs4C Commit-by: gcw_N9D3Qs4C Merged-by: ascend-robot Description: <!-- PR描述模板更新日期:20260203 --> # 【合入来源】 > **https://gitcode.com/Ascend/pytorch/issues/2095** [x] issue/工单 # 【修改方案】 torch.fx.replace_pattern 是 torch.fx.subgraph_rewriter 模块中的核心函数,用于在 FX Graph 中匹配指定的子图模式(pattern)并将其替换为新的子图(replacement)。 本 PR 为本分支新增 test_upstream/test/fx/test_subgraph_rewriter.py.patch,补齐 NPU 适配。原官方用例缺少张量在 NPU 上的验证,本 PR 添加 import torch_npu 并将张量创建改为 .npu(),确保张量在 NPU 设备上创建和计算。 # 【API 适配】 ## API 适配 torch.fx.replace_pattern 为纯框架层实现(FX Graph 子图匹配和节点替换),无需对 API 做任何代码修改。 ## 测试用例适配 适配方式(最小改动原则): 1. 文件头部添加 import torch_npu 2. 将 torch.rand(...) 改为 torch.rand(...).npu(),torch.randn(...) 改为 torch.randn(...).npu() 验证确认张量在 NPU 设备上执行计算(input device: npu:0, output device: npu:0)。 # 【资料变更】 torch.fx.replace_pattern 在 docs/zh/native_apis 各版本中均已标注为"是"(支持),文档状态与实际一致,无需修改文档。 # 【接口变更】 不涉及 # 【用例完备性说明】 PyTorch 官方社区 test/fx/test_subgraph_rewriter.py 中有 29 个直接测试 torch.fx.replace_pattern 功能的用例(TestSubgraphRewriter 类),完整覆盖:逻辑保持验证、单行/多行 pattern 匹配、单模式/多模式匹配、图参数顺序保持、正确的输出替换、traced callable 作为 pattern、pattern 覆盖整个图、placeholder 匹配、子模块引用替换、类型注解保持、连续子模块替换、重叠匹配处理、多输出/重复输出、未使用参数/结果、call_method 节点、kwargs 参数、局部回滚、replace_pattern_with_filters、replace_pattern_with_callback 等全部功能场景,无需新增用例。 # 【功能验证】 在 NPU 环境下,应用 patch 后执行全部 29 个用例,全部通过。 测试命令: bash cd /data/pkgs/pytorch_<version>/test && python -m unittest test_fx.TestSubgraphRewriter -v 运行日志:  **结论**:torch.fx.replace_pattern 在 NPU 环境下功能完全正确,29 个用例全部通过,张量计算在 NPU 设备上执行。 # 【CheckList】 - [x] 代码注释完备,正确记录错误日志 - [x] 代码实现进行了返回值、空指针等校验 - [x] PR标题正确使用类型标签 - [x] CI执行通过 See merge request: Ascend/pytorch!37326 | 4 个月前 | |
test(jit): add NPU adaptation for torch.jit.optimize_for_inference - v2.9.0 Co-authored-by: mushroom9679<mushroomcode@126.com> # message auto-generated for no-merge-commit merge: !37714 merge test-optimize-for-inference-v2.9.0-20260605-v4 into v2.9.0 test(jit): add NPU adaptation for torch.jit.optimize_for_inference - v2.9.0 Created-by: mushroom9679 Commit-by: mushroom9679 Merged-by: ascend-robot Description: test(jit): add NPU adaptation for torch.jit.optimize_for_inference-v2.9.0 # 【合入来源】 > <font color="red">**如有社区issue,请关联issue链接**</font>\ > <font color="red">**请勿携带内部流程信息(需求链接、问题单、内部issue等)**</font> - [x] issue/工单 Issue: https://gitcode.com/Ascend/pytorch/issues/1859 # 【修改方案】 ## 1. 问题背景 torch.jit.optimize_for_inference 对冻结的 ScriptModule 执行推理优化。python入口 torch/jit/_freeze.py:185-234,C++ 核心 torch/csrc/jit/api/module.cpp:494-497 包含三个优化 pass: cpp void optimize_for_inference(std::shared_ptr<Graph> graph) { FuseFrozenConvAddRelu(graph); // ① Conv+Add+ReLU 融合 ConvertFrozenOpsToMKLDNN(graph); // ② MKL-DNN 转换 FrozenLinearTranspose(graph); // ③ Linear 权重转置 } 其中 Pass ① FuseFrozenConvAddRelu(frozen_conv_add_relu_fusion_cuda.cpp:17-131)将 Conv+Add+ReLU 图模式替换为 CUDA 专用算子 cudnn_convolution_add_relu 或 ROCm 专用算子 miopen_convolution_add_relu。该 pass 有双重保护: - 编译时:#if AT_CUDNN_ENABLED() || AT_ROCM_ENABLED() — NPU 编译环境不满足 - 运行时:weight.device().is_cuda() filter — NPU 张量返回 false Pass ② ConvertFrozenOpsToMKLDNN 为 CPU MKL-DNN 专用。Pass ③ FrozenLinearTranspose 为通用图优化。 因此 optimize_for_inference 在 NPU 上安全可用,三个 pass 中两个自动跳过、一个通用兼容。 ## 2. 社区用例分析 PyTorch 社区 test/jit/test_freezing.py(v2.9.0)中 TestFrozenOptimizations 类涉及 optimize_for_inference 的测试: | 测试方法 | 行号 | 设备 guard | NPU | |---------|------|-----------|-----| | test_freeze_conv_relu_fusion | 2969-3029 | @skipIf(not (TEST_CUDNN or TEST_WITH_ROCM)) | ⏭ 跳过 | | test_freeze_conv_relu_fusion_not_forward | 3031-3077 | @skipIf(not (TEST_CUDNN or TEST_WITH_ROCM)) | ⏭ 跳过 | | test_numel_less_than_size_with_padding | 3079 | MKL-DNN guard | ⏭ 跳过 | | test_scalar_mul | 3302 | 无 | ✅ | | test_remove_detach | 3322 | 无 | ✅ | CUDA guard 测试(前 2 个)在 NPU 上被跳过,不覆盖 Conv 融合验证等 NPU 关键场景。 ## 3. 修改内容 对 test/jit/test_freezing.py 中两个 CUDA guard 测试做 NPU 适配,通过 upstream patch 方式提交: | 改动点 | 上游原代码 | 修改后 | |--------|-----------|--------| | import torch_npu | 无 | 新增 | | 设备放置 | .eval().cuda() / torch.rand(...).cuda() | .eval().npu() / torch.rand(...).npu() | | skipIf | not (TEST_CUDNN or TEST_WITH_ROCM) | not (TEST_CUDNN or TEST_WITH_ROCM or torch.npu.is_available()) | | 图检查 | if TEST_WITH_ROCM: ... else: ... | if TEST_WITH_ROCM: ... elif torch.npu.is_available(): pass else: ... | patch 规模:+67 / -5 行。 # 【资料变更】 不涉及 — docs/zh/native_apis/pytorch_2-9-0/torch-jit.md 已标注 |[torch.jit.optimize_for_inference](...)|是|-|,无需修改 # 【接口变更】 不涉及 — 仅修改社区测试用例,不修改任何 API 代码 # 【功能验证】 **环境:** 910B 物理机,Docker (vllm-ascend:v0.18.0rc1),torch 2.9.0 + torch_npu 2.9.0.post1,单卡 NPU bash npu-smi info # +------------------------------------------------------------------------------------------------+ # | NPU Name | Health | Power(W) Temp(C) Hugepages-Usage(page)| # | 0 910B1 | OK | 96.6 40 0 / 0 | # +------------------------------------------------------------------------------------------------+ python3 -c "import torch; print(torch.__version__)" # 2.9.0+cpu python3 -c "import torch_npu; print(torch_npu.__version__)" # 2.9.0.post1+gitee7ba04 python3 -c "import torch; print(torch.npu.is_available(), torch.npu.device_count())" # True 1 ### 一、改动前:社区用例在 NPU 上的运行结果 拉取 PyTorch 社区代码 git clone -b v2.9.0 https://gitee.com/mirrors/pytorch.git --depth 1,安装 pytest pip3 install pytest。 bash python3 -m pytest pytorch/test/jit/test_freezing.py::TestFrozenOptimizations::test_scalar_mul -v # ============================= test session starts ============================== # platform linux -- Python 3.11.14, pytest-9.0.3, pluggy-1.6.0 # pytorch/test/jit/test_freezing.py::TestFrozenOptimizations::test_scalar_mul PASSED [0.1379s] # ============================== 1 passed in 9.14s =============================== python3 -m pytest pytorch/test/jit/test_freezing.py::TestFrozenOptimizations::test_remove_detach -v # pytorch/test/jit/test_freezing.py::TestFrozenOptimizations::test_remove_detach PASSED [0.0453s] # ============================== 1 passed in 8.65s =============================== python3 -m pytest pytorch/test/jit/test_freezing.py::TestFrozenOptimizations::test_remove_detach_not_applied -v # pytorch/test/jit/test_freezing.py::TestFrozenOptimizations::test_remove_detach_not_applied PASSED [0.1181s] # ============================== 1 passed in 8.99s =============================== python3 -m pytest pytorch/test/jit/test_freezing.py::TestFrozenOptimizations::test_freeze_conv_relu_fusion -v # pytorch/test/jit/test_freezing.py::TestFrozenOptimizations::test_freeze_conv_relu_fusion SKIPPED [0.0064s] # ============================== 1 skipped in 8.75s ============================== 结果:test_scalar_mul、test_remove_detach、test_remove_detach_not_applied 3 个无设备 guard 的社区测试 PASS。CUDA guard 测试 test_freeze_conv_relu_fusion SKIPPED(预期行为)。 ### 二、改动后:新增 NPU 用例的运行结果 bash python3 -m pytest pytorch/test/jit/test_optimize_for_inference_npu.py -v 终端输出: ============================= test session starts ============================== platform linux -- Python 3.11.14, pytest-9.0.3, pluggy-1.6.0 collected 4 items pytorch/test/jit/test_optimize_for_inference_npu.py::TestOptimizeForInferenceNPU::test_optimize_conv_add_relu_residual_npu PASSED [ 25%] pytorch/test/jit/test_optimize_for_inference_npu.py::TestOptimizeForInferenceNPU::test_optimize_conv_bn_relu_npu PASSED [ 50%] pytorch/test/jit/test_optimize_for_inference_npu.py::TestOptimizeForInferenceNPU::test_optimize_conv_relu_npu PASSED [ 75%] pytorch/test/jit/test_optimize_for_inference_npu.py::TestOptimizeForInferenceNPU::test_optimize_scalar_mul_npu PASSED [100%] ============================== 4 passed in 17.04s ============================== ### 三、补充验证:Conv+ReLU 融合在 NPU 上不产生非法算子 bash python3 -c " import torch; import torch_npu; import torch.nn as nn class ConvReLU(nn.Module): def __init__(self): super().__init__() self.conv = nn.Conv2d(3, 16, 3, padding=1) self.relu = nn.ReLU(inplace=True) def forward(self, x): return self.relu(self.conv(x)) m = ConvReLU().eval().npu() x = torch.randn(2, 3, 32, 32).npu() with torch.no_grad(): eager_out = m(x) scripted = torch.jit.script(m) optimized = torch.jit.optimize_for_inference(scripted) with torch.no_grad(): opt_out = optimized(x) print(f'Eager: {eager_out.sum().item():.6f}') print(f'Optimized: {opt_out.sum().item():.6f}') print(f'Allclose: {torch.allclose(eager_out, opt_out, atol=1e-4, rtol=1e-4)}') print(f'cudnn in graph: {chr(34) + \"cudnn\" + chr(34) in str(optimized.graph)}') print(f'miopen in graph: {chr(34) + \"miopen\" + chr(34) in str(optimized.graph)}') print(optimized.graph) " 终端输出: Eager: 6795.992188 Optimized: 6795.992188 Allclose: True cudnn in graph: False miopen in graph: False graph(%self : __torch__.___torch_mangle_0.ConvReLU, %x.1 : Tensor): %18 : int[] = prim::Constant[value=[1, 1]]() %6 : int = prim::Constant[value=1]() %self.conv.bias : Float(16, strides=[1], requires_grad=0, device=npu:0) = prim::Constant[value=<Tensor>]() %self.conv.weight : Float(16, 3, 3, 3, strides=[27, 9, 3, 1], requires_grad=0, device=npu:0) = prim::Constant[value=<Tensor>]() %12 : Tensor = aten::conv2d(%x.1, %self.conv.weight, %self.conv.bias, %18, %18, %18, %6) %result.1 : Tensor = aten::relu_(%12) return (%result.1) 图中保留 aten::conv2d + aten::relu_,无 cudnn_convolution_relu / miopen_convolution_relu 等非法算子。 # 【CheckList】 > PR提交人对以下CheckList自检项进行全量自检,自检通过或不涉及,均修改 [ ] 为 [x] - [x] 代码注释完备,正确记录错误日志 - [x] 代码实现进行了返回值、空指针等校验 - [x] PR标题正确使用类型标签,如:feat、fix、refactor、docs、test等 - [x] PR持续集成流水线(CI)执行通过,代码检查无异常 See merge request: Ascend/pytorch!37714 | 4 个月前 | |
test: add nn module load_state_dict npu test patch Co-authored-by: zj<2943168611@qq.com> # message auto-generated for no-merge-commit merge: !38382 merge test/2.9.0-nn-module-api-npu into v2.9.0 test: add nn module load_state_dict npu test patch Created-by: zjucn Commit-by: zj Merged-by: ascend-robot Description: <!-- PR描述模板更新日期:20260203 --> # 【合入来源】 - [x] issue/工单: https://gitcode.com/Ascend/pytorch/issues/2266 本 PR 覆盖以下 API: - torch.nn.Module.load_state_dict # 【修改方案】 ## 一、总体方案 本 PR 复用 PyTorch 官方 test/nn/test_load_state_dict.py,对 torch.nn.Module.load_state_dict 的设备相关加载路径进行 NPU 适配,不修改 torch-npu 生产代码。 PyTorch 官方测试已覆盖 load_state_dict 的核心语义,包括正常加载、strict 行为、missing key、unexpected key、shape mismatch、BatchNorm metadata 兼容、递归子模块加载、load pre-hook、自定义 _save_to_state_dict / _load_from_state_dict、assign=True、meta tensor、optimizer 交互和 Tensor subclass 加载。本 PR 在保留官方测试结构的基础上,将需要验证设备行为的路径迁移到 NPU。 修改文件: text test_upstream/test/nn/test_load_state_dict.py.patch patch 目标文件: text test/nn/test_load_state_dict.py ## 二、适配内容 本 PR 的适配点如下: - 引入 torch_npu,使测试文件可直接构造 NPU module 和 NPU tensor。 - 在关键加载断言中增加 device 校验,确认加载后的 parameter 和 buffer 保持在 NPU。 - 在 test_load_state_dict 中将 module 迁移到 NPU,并在 NPU module 的 state_dict 基础上覆盖部分 CPU tensor,验证 CPU tensor 可加载到 NPU parameter 和 buffer,且加载后 device 与数值正确。 - 在 DDP 前缀消费场景中保留官方 consume_prefix_in_state_dict_if_present 路径,验证消费 module. 前缀后的 state_dict 可加载到 NPU module。 - 在 BatchNorm metadata 兼容测试中使用 NPU BatchNorm module,验证缺失 num_batches_tracked 时自动补齐的 buffer 位于 NPU,dtype 和数值符合官方语义。 - 在递归子模块和 load pre-hook 测试中使用 NPU module 树,验证递归加载路径和 hook 调用范围在 NPU module 上保持一致。 - 在自定义 _save_to_state_dict / _load_from_state_dict 测试中使用 NPU module,验证自定义状态加载可写入 NPU parameter,并保持子模块参数加载行为。 - 在 assign=True shape/stride 测试中使用 NPU module 和 NPU state_dict tensor,验证同 shape 不同 stride tensor 可赋值加载,shape mismatch 仍按官方语义报错。 - 在 unexpected key 后缀边界测试中使用 NPU module 和 NPU state_dict tensor,验证 strict=True 报错和 strict=False 返回 unexpected key 的行为。 ## 三、用例覆盖 已适配用例覆盖如下: | 用例 | 覆盖内容 | | --- | --- | | test_load_state_dict | NPU module 加载 state_dict、CPU tensor 写入 NPU parameter/buffer、DDP 前缀消费、strict=True / strict=False、missing key、unexpected key、shape mismatch、部分加载后旧值保持 | | test_load_state_dict_BC | BatchNorm 旧 metadata 下补齐 num_batches_tracked,并验证补齐 buffer 位于 NPU | | test_load_state_dict_child | 多层嵌套 module、递归加载、load pre-hook 在 NPU module 树上的执行行为 | | test_load_state_dict_custom | 自定义 _save_to_state_dict / _load_from_state_dict、自定义 serialized key、子模块参数加载 | | test_load_state_dict_assign_shape_stride | assign=True、NPU state_dict tensor、同 shape 不同 stride、shape mismatch | | test_load_state_dict_with_unexpected_key | unexpected key、合法 key 前缀加后缀、strict=True / strict=False | 以下官方用例保持原样: | 用例 | 保持原样原因 | | --- | --- | | test_load_state_dict_invalid | 验证非 Tensor 输入类型校验,与设备无关 | | test_load_state_dict_type | 验证 state_dict 非 Mapping 类型校验,与设备无关 | | test_load_state_dict_ref_cycle | 验证 Python 引用关系和 GC 行为,与 NPU 设备迁移无关 | | test_load_state_dict_assign_meta | 验证 meta tensor 下 assign=True 的对象关系和输出一致性,测试目标为 meta 语义 | | test_load_state_dict_assign_with_optimizer | 验证 assign=True 与 optimizer 构造时机和 optimizer state_dict 加载关系,测试目标为 optimizer 交互 | | test_load_state_dict_warn_assign | 验证 non-meta checkpoint 到 meta parameter 的 warning 文案,测试目标为 meta warning 语义 | | Tensor subclass 参数化测试 | 验证 Tensor subclass / wrapper subclass 协议,测试目标为 subclass 加载语义 | # 【资料变更】 已检查 docs/zh/native_apis 下 torch-nn.md 中 torch.nn.Module.load_state_dict 的登记状态。该 API 已登记为支持,当前验证结论与文档现有支持状态一致,因此本 PR 不涉及资料变更。 # 【接口变更】 > 不涉及 # 【功能验证】 在 torch-npu 环境下,运行 patch 后的 PyTorch 官方 test/nn/test_load_state_dict.py。 测试命令如下: bash python test/nn/test_load_state_dict.py 验证结果摘要如下: text Ran 27 tests OK 执行结果表明,patch 后的 PyTorch 官方 load_state_dict 专项测试可在 torch-npu 环境下通过。测试集合覆盖 load_state_dict 的正常加载、DDP 前缀 state_dict、missing key、unexpected key、strict=False、shape mismatch、BatchNorm metadata BC、递归子模块加载、load pre-hook、自定义 state_dict 逻辑、assign=True shape/stride 行为、meta tensor、optimizer 交互、warning 文案和 Tensor subclass 协议。 本次 patch 将关键设备相关路径迁移到 NPU,验证 NPU module 或 NPU state_dict tensor 场景下,加载后的 parameter/buffer device、数值、错误行为和返回结构与 PyTorch 官方语义一致。 # 【CheckList】 > PR提交人对以下CheckList自检项进行全量自检,自检通过或不涉及,均修改 [ ] 为 [x] - [x] 代码注释完备,正确记录错误日志 - [x] 代码实现进行了返回值、空指针等校验 - [x] PR标题正确使用类型标签,如:feat、fix、refactor、docs、test等 - [x] PR持续集成流水线(CI)执行通过,代码检查无异常 See merge request: Ascend/pytorch!38382 | 4 个月前 | |
test(onnx): skip test_quantized_arithmetic in ONNX runtime patch Co-authored-by: Margaret_wangrui<wangrui178@huawei.com> # message auto-generated for no-merge-commit merge: !36860 merge v2.9.0__test_quantized_arithmetic into v2.9.0 test(onnx): skip test_quantized_arithmetic in ONNX runtime patch Created-by: Margaret_wangrui Commit-by: Margaret_wangrui Merged-by: ascend-robot Description: <!-- PR描述模板更新日期:20260203 --> # 【合入来源】 > <font color="red">**如有社区issue,请关联issue链接**</font>\ > <font color="red">**请勿携带内部流程信息(需求链接、问题单、内部issue等)**</font> https://gitcode.com/Ascend/pytorch/issues/2120 - [ ] 需求 - [x] 问题单 - [ ] issue/工单 - [ ] 重构优化 - [ ] 资料更新 # 【修改方案】 PTA / 门禁执行 ONNX 用例 test_quantized_arithmetic 时,在 torch.onnx.verification.verify 阶段失败:12 个 quint8 元素中常有 1 个与 ONNX Runtime(ORT)QDQ 结果相差 1(例如 PT=103、ORT=104),并非导出失败。 **根因(方案 A):** PyTorch QuantizedCPU 上 quantized::add / quantized::mul(requant scale=0.4, zero_point=100)与 ORT 的 QuantizeLinear 舍入存在 ±1 个量化阶差异;verification.verify 对整型输出默认 atol=1e-7,无法容忍该差异。用例输入在 CPU,与 NPU 执行路径无关。同文件 test_quantized_arithmetic_qfunctional(QFunctional、默认 scale=1.0/zp=0)可正常通过,故仅跳过本用例。 **具体实现:** 1. 在 test_upstream/test/onnx/test_pytorch_onnx_onnxruntime.py.patch 中,为 TestONNXRuntime.test_quantized_arithmetic 增加 @unittest.skip,并在 skip 原因中说明 PT vs ORT 的 ±1 quint8 差异及 atol 限制。 2. 补丁适配 上游 test/onnx/test_pytorch_onnx_onnxruntime.py 行号(@@ -13166)。 **应用方式:** 将 test_upstream 置于源码根目录后执行 test_upstream/apply_patch.sh,再运行 ONNX 门禁用例。 # 【资料变更】 不涉及 # 【接口变更】 不涉及 # 【功能验证】 **测试场景:** ONNX 门禁中 test_quantized_arithmetic(opset 10、非 script、默认 initializer 配置)。 **测试命令:** bash cd test_upstream && ./apply_patch.sh cd ../test/onnx python test_pytorch_onnx_onnxruntime.py -v -k \ TestONNXRuntime_opset_version_10_is_script_False_keep_initializers_as_inputs_False.test_quantized_arithmetic **预期结果:** 用例状态为 **skipped**(不再出现 AssertionError: Tensor-likes are not close!)。 **UT 看护:** 通过 test_upstream 补丁对上游用例做 skip 看护。 # 【CheckList】 - [x] 代码注释完备,正确记录错误日志(skip 文案说明根因;无新增运行时代码) - [x] 代码实现进行了返回值、空指针等校验(不涉及) - [x] PR标题正确使用类型标签,如:feat、fix、refactor、docs、test等(建议:test(onnx): skip test_quantized_arithmetic in ONNX runtime patch) - [ ] PR持续集成流水线(CI)执行通过,代码检查无异常 See merge request: Ascend/pytorch!36860 | 5 个月前 | |
test(utils): adapt torch.utils.checkpoint.checkpoint, torch.utils.checkpoint.checkpoint_sequential and torch.overrides.is_tensor_like on NPU Co-authored-by: yulin520<yutianaoxiang@163.com> # message auto-generated for no-merge-commit merge: !39483 merge test-checkpoint-overrides-npu-v290 into v2.9.0 test(utils): adapt torch.utils.checkpoint.checkpoint, torch.utils.checkpoint.checkpoint_sequential and torch.overrides.is_tensor_like on NPU Created-by: weixin_65332823 Commit-by: yulin520 Merged-by: ascend-robot Description: # 【合入来源】 > <font color="red">**如有社区issue,请关联issue链接**</font> <font color="red">**请勿携带内部流程信息(需求链接、问题单、内部issue等)**</font> * [ ] 需求 * [ ] 问题单 * [x] issue/工单 * [ ] 重构优化 * [ ] 资料更新 关联 Issue:https://gitcode.com/Ascend/pytorch/issues/2529 关联 Issue:#2529 关联任务: torch.overrides.is_tensor_like、torch.utils.checkpoint.checkpoint、torch.utils.checkpoint.checkpoint_sequential API 一致性验证。 本 PR 对 v2.9.0 分支补充上述 API 在 NPU 场景下的上游测试适配。 # 【修改方案】 本 PR 仅涉及 test_upstream 上游测试 patch 适配,不修改 torch_npu 功能实现代码,不改变已有 API 行为。 修改文件: * test_upstream/test/test_autograd.py.patch * test_upstream/test/dynamo/test_misc.py.patch 具体修改如下: 1. 在 test_upstream/test/test_autograd.py.patch 中补充 torch.utils.checkpoint.checkpoint_sequential 相关用例的 NPU 适配: * 将 torch.utils.checkpoint.checkpoint_sequential 相关测试输入 Tensor 从 CPU 放置到 NPU; * 将 torch.utils.checkpoint.checkpoint_sequential 测试中使用的 torch.nn.Linear 模块迁移到 NPU; * 验证 torch.utils.checkpoint.checkpoint_sequential 在 NPU Tensor 输入下能够正常前向、反向传播。 2. 在 test_upstream/test/dynamo/test_misc.py.patch 中补充 torch.overrides.is_tensor_like 相关用例的 NPU 适配: * 将 torch.overrides.is_tensor_like 测试输入 Tensor 放置到 NPU; * 验证 NPU Tensor 场景下 torch.overrides.is_tensor_like 返回结果正确。 3. 保留现有 torch.utils.checkpoint.checkpoint 相关 NPU 适配内容: * 本次修改未改变 torch.utils.checkpoint.checkpoint API 的功能实现; * 仅在本地验证中同时覆盖 torch.utils.checkpoint.checkpoint、torch.utils.checkpoint.checkpoint_sequential 和 torch.overrides.is_tensor_like,确保三类目标 API 在 NPU 场景下均可正常运行。 # 【资料变更】 不涉及。 本 PR 仅补充上游测试用例在 NPU 场景下的适配,不新增或修改用户可见资料。相关 API 在目标版本资料中已有说明,因此本任务不需要新增 doc PR。 # 【接口变更】 不涉及。 本 PR 不新增、删除或修改客户可见接口,不涉及跨代码仓接口变更,不改变 torch.utils.checkpoint.checkpoint、torch.utils.checkpoint.checkpoint_sequential 或 torch.overrides.is_tensor_like 的调用方式和返回语义。 # 【功能验证】 已在 Ascend 910B4 NPU 环境完成 v2.9.0 对应分支的本地运行验证。 验证环境: * 操作系统:Ubuntu 22.04.5 LTS / aarch64 * CANN:cann-9.1.0-beta.1 * NPU 设备:Ascend910B4 * 目标分支:v2.9.0 * 测试分支:test-checkpoint-overrides-npu-v290 * torch 版本:2.9.0 * torch_npu 版本:2.9.0.post2 * NPU 可用性:torch.npu.is_available() == True 验证内容: 1. torch.utils.checkpoint.checkpoint_sequential * NPU Tensor 输入; * NPU Linear 模块; * 前向计算和反向传播均通过。 2. torch.overrides.is_tensor_like * NPU Tensor 输入; * torch.overrides.is_tensor_like 返回结果为 True。 3. torch.utils.checkpoint.checkpoint * NPU Tensor 输入; * 前向计算和反向传播均通过。 本地验证结果: * torch.utils.checkpoint.checkpoint_sequential NPU validation PASSED * torch.overrides.is_tensor_like NPU validation PASSED * torch.utils.checkpoint.checkpoint NPU validation PASSED * RUNTIME VALIDATION PASSED 测试自验证截图: [](url) Patch 生成与检查说明: 本 PR 中的 patch 基于对应版本的 PyTorch 社区源码生成。已有 patch 时,先在对应版本 PyTorch 社区源码中应用原 patch,再根据代码审查意见修改社区源码文件,将 torch.ones(10) 调整为 torch.ones(10).npu(),避免默认生成 CPU Tensor 后与 NPU Tensor x 相加导致设备不一致。修改完成后,通过 git diff 重新生成 patch 文件,未在生成后直接编辑 patch 文件。 已完成以下检查: * 已执行 patch 应用检查; * 已检查 patch 不包含整文件删除; * 已检查 patch 不包含冲突标记; * 已检查本 PR 仅包含目标 patch 文件修改; * 已确认 torch.ones(10) 已在社区源码中迁移至 NPU,并通过 git diff 重新生成对应 patch; * 已在匹配版本的 torch / torch_npu 运行时环境中完成本地 NPU 复验。 # 【CheckList】 > PR提交人对以下CheckList自检项进行全量自检,自检通过或不涉及,均修改 [ ] 为 [x] * [x] 代码注释完备,正确记录错误日志 * [x] 代码实现进行了返回值、空指针等校验 * [x] PR标题正确使用类型标签,如:feat、fix、refactor、docs、test等 * [x] PR持续集成流水线(CI)执行通过,代码检查无异常 See merge request: Ascend/pytorch!39483 | 3 个月前 | |
[v2.9.0] Adapt NPU tests for torch.utils.data APIs Co-authored-by: coconut77<2416273142@qq.com> # message auto-generated for no-merge-commit merge: !38120 merge api-completion-utils-data-v2.9.0 into v2.9.0 [v2.9.0] Adapt NPU tests for torch.utils.data APIs Created-by: coconut77 Commit-by: coconut77 Merged-by: ascend-robot Description: <!-- PR描述模板更新日期:20260203 --> # 【合入来源】 > <font color="red">**如有社区issue,请关联issue链接**</font>\ > <font color="red">**请勿携带内部流程信息(需求链接、问题单、内部issue等)**</font> - [ ] 需求 - [ ] 问题单 - [x] issue/工单 - [ ] 重构优化 - [ ] 资料更新 关联issue:https://gitcode.com/Ascend/pytorch/issues/2315 # 【修改方案】 ## 一、9 个 API 功能如下 1. torch.utils.data.random_split - 将一个数据集按长度或比例拆分成多个子集。 2. torch.utils.data.RandomSampler - 按随机顺序从数据集中采样,可配置是否放回。 3. torch.utils.data.Sampler - 定义采样器接口,用于自定义样本索引迭代逻辑。 4. torch.utils.data.SequentialSampler - 按顺序遍历数据集索引。 5. torch.utils.data.StackDataset - 将多个数据集按索引对齐后打包返回。 6. torch.utils.data.Subset - 使用给定索引集合从原始数据集中构造子集。 7. torch.utils.data.SubsetRandomSampler - 对给定索引集合进行随机采样。 8. torch.utils.data.TensorDataset - 基于多个 tensor 构造数据集,并按相同下标返回样本。 9. torch.utils.data.WeightedRandomSampler - 根据权重分布进行随机采样。 ## 二、社区用例对这 9 个 API 的验证完整性分析 1. 官方文件 test/test_dataloader.py 已覆盖以下 9 个 API: - torch.utils.data.random_split - torch.utils.data.RandomSampler - torch.utils.data.Sampler - torch.utils.data.SequentialSampler - torch.utils.data.StackDataset - torch.utils.data.Subset - torch.utils.data.SubsetRandomSampler - torch.utils.data.TensorDataset - torch.utils.data.WeightedRandomSampler 2. 相关官方用例位置可定位为: - random_split 相关用例约位于 test/test_dataloader.py 第 165~250 行附近; - TensorDataset 相关用例约位于 test/test_dataloader.py 第 391 行开始; - StackDataset 相关用例约位于 test/test_dataloader.py 第 438 行开始; - SequentialSampler、RandomSampler、SubsetRandomSampler、WeightedRandomSampler、Sampler 相关用例约位于 test/test_dataloader.py 第 1335~1841 行附近。 3. 社区用例对这 9 个 API 的功能验证是完整的,本次无需新增测试文件,主要工作是保持官方测试语义不变并完成 NPU 适配。 ## 三、NPU 适配 1. 在最新 fork coconut77/pytorch_3940 的现有 test_upstream/test/test_dataloader.py.patch 基础上做增量修改,不整份替换 patch,也不回退别人已经存在的 NPU 适配内容。 - 本次操作遵循“先应用现有 patch 到真实 test/test_dataloader.py,再在真实源码上增量修改,最后重新生成 patch”的流程,避免手工编辑 hunk 导致 patch 格式错误。 - 本次只补齐当前 patch 尚未覆盖完整的 random_split / Subset 相关 NPU 测试场景。 - 已有的 TensorDataset、StackDataset、ConcatDataset、DataLoader 顺序加载、sampler 相关 patch 内容全部保留原样。 - 这样处理的原因是:当前 fork 中这份 patch 已经包含其他人先前完成的一批 NPU 迁移,如果直接套用旧 patch 或整份覆盖,会把别人已有实现风格、上下文位置和已有适配一起冲掉,容易引入无关差异甚至合并冲突。 2. 具体新增修改集中在 random_split / Subset 关联用例,补的是“原 patch 还没覆盖到、但这 9 个 API 补齐任务需要覆盖”的缺口。 - 在 TestDatasetRandomSplit.test_splits_generator 中,v2.9.0、v2.10.0、v2.11.0 补齐 NPU 场景,使 random_split 相关测试块在当前 patch 体系下形成完整覆盖。 - 对于 v2.12.0,保留 test_splits_generator 的 CPU RNG 校验语义,只补 Subset 相关 NPU 场景;原因是该断言在 v2.12.0 上改成 NPU 随机数后实测不稳定,会破坏原测试“验证默认 RNG 是否被影响”的语义,所以这里不能机械迁移到 NPU。 - 在 TestDatasetRandomSplit.test_slicing_of_subset_of_dataset 中,把底层 TensorDataset(torch.tensor([1, 2, 3, 4, 5])) 改成 NPU tensor 场景,用来覆盖Subset 在 NPU tensor dataset 上的切片访问行为。 - 在 TestDatasetRandomSplit.test_slicing_of_subset_of_subset 中,同样把底层 TensorDataset 改成 NPU tensor 场景,用来覆盖“子集的子集”这一条 Subset 链式路径。 3. 明确保留不修改的部分包括 TensorDataset、StackDataset、各类 sampler、以及 DataLoader 顺序/批处理相关已有 patch,因为这些内容在当前 fork 中已经具备 NPU 适配 能力,继续改反而风险更高。 - TensorDataset 相关用例原 patch 已经把构造输入改成了 .npu() tensor,能够直接覆盖 TensorDataset 在 NPU 上的长度、索引、单 tensor、多 tensor 等场景,所以无需重复修改。 - StackDataset 相关用例原 patch 已经把其底层 TensorDataset 输入迁移到了 NPU,已经能够覆盖 StackDataset 组合、长度校验、索引访问等行为,因此不需要再动。 - SequentialSampler、RandomSampler、SubsetRandomSampler、WeightedRandomSampler、Sampler 这些 sampler 相关测试,本身主要验证“索引生成顺序、随机性、长度、复现性、采样协议”是否正确,核心断言落在索引逻辑而不是张量算子上;当前 patch 中配套的 dataset / dataloader 场景已能在 NPU 跑通,所以这些测试无需额外修改sampler 本身的逻辑。 - test_sequential_nonbatch、test_sequential_batch 等 DataLoader 顺序加载测试,现有 patch 已经通过 _move_dataset_to_npu() 把底层数据集迁移到 NPU,因此能够间接覆盖 SequentialSampler 路径;继续修改只会增加无关差异。 - test_random_sampler*、test_sampler_reproducibility、test_sampler 等随机采样测试,现有 patch 依赖的 dataset/dataloader 组合已经可在 NPU 环境执行,且断言关注的是 sampler 结果而非 device 特性,所以保持原逻辑最稳妥。 # 【资料变更】 不涉及 # 【接口变更】 不涉及 # 【功能验证】 ## 1. 测试环境 text - 操作系统:Ubuntu - 昇腾硬件信息:NPU - CANN软件版本:8.5.0 - 安装的对应软件版本:torch 2.9.0+cpu、torch_npu 2.9.0.post2 ## 2. 测试命令 bash python -u /workspace/torch_npu_v2.9.0/test/test_dataloader.py TestDatasetRandomSplit TestTensorDataset TestStackDataset TestDataLoader.test_sequential_nonbatch TestDataLoader.test_sequential_batch TestDataLoader.test_bulk_loading_nobatch TestDataLoader.test_sequential_workers TestDataLoader.test_seqential_batch_workers TestDataLoader.test_seqential_batch_workers_prefetch TestDataLoader.test_random_sampler TestDataLoader.test_random_sampler_len_with_replacement TestDataLoader.test_random_sampler_len_without_replacement TestDataLoader.test_sampler_reproducibility TestDataLoader.test_sampler > /workspace/version_logs/utils_data_v2.9.0.log 2>&1 ## 3. patch 格式检查真实输出 text EXIT_CODE:0 ## 4. 测试真实输出 text /workspace/patch_rebuild_3940_step2_20260610_164030/v2.9.0/test/test_dataloader.py:80: UserWarning: psutil not found. Some critical data loader tests relying on it (e.g., TestDataLoader.test_proper_exit) will not run. warnings.warn(err_msg) /workspace/patch_rebuild_3940_step2_20260610_164030/v2.9.0/test/test_dataloader.py:80: UserWarning: psutil not found. Some critical data loader tests relying on it (e.g., TestDataLoader.test_proper_exit) will not run. warnings.warn(err_msg) ................................./workspace/patch_rebuild_3940_step2_20260610_164030/v2.9.0/test/test_dataloader.py:80: UserWarning: psutil not found. Some critical data loader tests relying on it (e.g., TestDataLoader.test_proper_exit) will not run. warnings.warn(err_msg) /workspace/patch_rebuild_3940_step2_20260610_164030/v2.9.0/test/test_dataloader.py:80: UserWarning: psutil not found. Some critical data loader tests relying on it (e.g., TestDataLoader.test_proper_exit) will not run. warnings.warn(err_msg) /workspace/patch_rebuild_3940_step2_20260610_164030/v2.9.0/test/test_dataloader.py:80: UserWarning: psutil not found. Some critical data loader tests relying on it (e.g., TestDataLoader.test_proper_exit) will not run. warnings.warn(err_msg) /workspace/patch_rebuild_3940_step2_20260610_164030/v2.9.0/test/test_dataloader.py:80: UserWarning: psutil not found. Some critical data loader tests relying on it (e.g., TestDataLoader.test_proper_exit) will not run. warnings.warn(err_msg) /workspace/patch_rebuild_3940_step2_20260610_164030/v2.9.0/test/test_dataloader.py:80: UserWarning: psutil not found. Some critical data loader tests relying on it (e.g., TestDataLoader.test_proper_exit) will not run. warnings.warn(err_msg) /workspace/patch_rebuild_3940_step2_20260610_164030/v2.9.0/test/test_dataloader.py:80: UserWarning: psutil not found. Some critical data loader tests relying on it (e.g., TestDataLoader.test_proper_exit) will not run. warnings.warn(err_msg) /workspace/patch_rebuild_3940_step2_20260610_164030/v2.9.0/test/test_dataloader.py:80: UserWarning: psutil not found. Some critical data loader tests relying on it (e.g., TestDataLoader.test_proper_exit) will not run. warnings.warn(err_msg) /workspace/patch_rebuild_3940_step2_20260610_164030/v2.9.0/test/test_dataloader.py:80: UserWarning: psutil not found. Some critical data loader tests relying on it (e.g., TestDataLoader.test_proper_exit) will not run. warnings.warn(err_msg) . ---------------------------------------------------------------------- Ran 34 tests in 11.621s OK # 【CheckList】 > PR提交人对以下CheckList自检项进行全量自检,自检通过或不涉及,均修改 [ ] 为 [x] - [x] 代码注释完备,正确记录错误日志 - [x] 代码实现进行了返回值、空指针等校验 - [x] PR标题正确使用类型标签,如:feat、fix、refactor、docs、test等 - [x] PR持续集成流水线(CI)执行通过,代码检查无异常 See merge request: Ascend/pytorch!38120 | 4 个月前 | |
test(data): adapt torch.utils.data tests on NPU Co-authored-by: yulin520<yutianaoxiang@163.com> # message auto-generated for no-merge-commit merge: !37377 merge test-data-npu-adaptation-v290 into v2.9.0 test(data): adapt torch.utils.data tests on NPU Created-by: weixin_65332823 Commit-by: yulin520 Merged-by: ascend-robot Description: ## 关联 Issue * https://gitcode.com/Ascend/pytorch/issues/2202 ## 修改内容 本 PR 对 torch.utils.data 相关社区用例进行 NPU 适配。 修改文件: * test_upstream/test/test_dataloader.py.patch * test_upstream/test/test_datapipe.py.patch 主要修改: 1. 对相关测试用例中的 Tensor 显式迁移至 NPU; 2. 在测试文件中引入: python import torch_npu from torch_npu.contrib import transfer_to_npu 3. 对 TestDataLoader.test_multiprocessing_contexts 增加 NPU IPC 条件判断。当未启用 expandable_segments:True 时跳过该用例,避免 DataLoader worker 间 NPU Tensor 共享场景异常。 ## 验证环境 * 操作系统:Linux * 昇腾硬件:Ascend 910B3 * CANN:8.5.0 * 目标分支:v2.9.0 * PyTorch:2.9.0+cpu * torch_npu:2.9.0 ## 验证命令 bash python test_dataloader.py -v \ TestTensorDataset \ TestStackDataset \ TestConcatDataset \ TestDataLoader.test_distributed_sampler_invalid_rank \ TestDataLoader.test_duplicating_data_with_drop_last \ TestDataLoader.test_multiprocessing_contexts python test_datapipe.py -v \ TestFunctionalIterDataPipe.test_map_iterdatapipe \ TestFunctionalIterDataPipe.test_collate_iterdatapipe \ TestFunctionalMapDataPipe.test_map_mapdatapipe \ TestSharding.test_simple_sharding \ TestSharding.test_sharding_groups \ TestSharding.test_sharding_length \ TestSharding.test_multi_sharding \ TestGraph.test_simple_traverse \ TestGraph.test_traverse_forked \ TestGraph.test_traverse_mapdatapipe \ TestGraph.test_traverse_circular_datapipe ## 验证结果 * DataLoader 相关用例:23个测试,OK;其中 test_multiprocessing_contexts 在未启用 expandable_segments:True 时按预期跳过; * DataPipe 相关用例:11 个测试,OK; * 保留原始语义测试:13 个测试,OK。 ### 保留原始语义用例 bash python test_dataloader.py -v \ TestDataLoader.test_default_collate_dtype \ TestDataLoader.test_default_collate_mapping_keep_type \ TestDataLoader.test_default_collate_sequence_keep_type \ TestDataLoader.test_default_collate_sequence_dont_keep_type \ TestDataLoader.test_default_collate_bad_numpy_types \ TestDataLoader.test_default_collate_numpy_memmap \ TestDataLoader.test_default_collate_bad_sequence_type \ TestDataLoader.test_default_collate_shared_tensor \ TestDataLoader.test_get_worker_info \ TestDataLoader.test_invalid_ctor_args_combinations \ TestDataLoader.test_iterable_style_dataset \ TestDataLoader.test_chain_iterable_style_dataset \ TestDataLoader.test_iterabledataset_len ### Patch 生成与检查说明 本 PR 中的 patch 基于对应版本的 PyTorch 社区源码生成。已有 patch 时,先应用原 patch,再修改社区源码,最后通过 git diff 重新生成 patch 文件。未手动编辑 patch 文件。 已执行: bash git apply --check git diff --check 检查结果通过。 ### 补充对应版本的用例执行结果和耗时截图 目标分支:v2.9.0 已在匹配版本的PyTorch和torch_npu运行时环境中完成以下验证: DataLoader相关用例 DataPipe相关用例 原始语义回归用例 以上用例均已执行通过。 其中,test_multiprocessing_contexts在未启用expandable_segments:True时按预期跳过。 详细测试数量和执行耗时见附件截图。  See merge request: Ascend/pytorch!37377 | 4 个月前 | |
test: add NPU coverage for symbolic_shapes APIs (issue #1614) Co-authored-by: zhangjiahao-2026<2332445379@qq.com> # message auto-generated for no-merge-commit merge: !36328 merge intern-1614-symbolic-shapes into v2.9.0 test: add NPU coverage for symbolic_shapes APIs (issue #1614) Created-by: zhangjiahao-2026 Commit-by: zhangjiahao-2026 Merged-by: ascend-robot Description: # 【合入来源】 > **关联社区 issue:** https://gitcode.com/Ascend/pytorch/issues/1614 - [ ] 需求 - [ ] 问题单 - [x] issue/工单 - [ ] 重构优化 - [ ] 资料更新 # 【修改方案】 本次为 Torch-NPU API 一致性对齐任务,针对 torch.fx.experimental.symbolic_shapes 下 5 个 API 补充/适配测试,**不涉及算子或 API 实现代码修改**(NPU 上与 PyTorch 2.9 行为一致)。 ## API 功能说明 torch.fx.experimental.symbolic_shapes 是 PyTorch FX 动态 shape 推导体系中的符号形状模块,负责在编译/导出过程中管理 SymInt/SymBool 约束、guard 生成及 shape 相等关系。本次验证的 5 个 API 均为纯 Python 层面的符号 shape 工具,与底层计算硬件无关。 - torch.fx.experimental.symbolic_shapes.DivideByKey:整除键类,用于在符号 shape 表达中表示对某个常量做 floor division(整除)的运算模式,可通过构造参数指定除数。 - torch.fx.experimental.symbolic_shapes.DivideByKey.get:DivideByKey 实例方法,对给定数值执行 floor division,即 value // divisor,返回整除结果。 - torch.fx.experimental.symbolic_shapes.EqualityConstraint:符号 shape 约束类,用于在 FX 图导出/动态 shape 推导中表达多个 shape 源之间的相等关系,包含 source_pairs、derived_equalities、phantom_symbols、relaxed_sources、warn_only 等字段。 - torch.fx.experimental.symbolic_shapes.has_free_symbols:判断给定对象(通常为 sympy 表达式)是否包含未被绑定的自由符号,用于区分常量表达式与含符号变量的动态 shape 表达式。 - torch.fx.experimental.symbolic_shapes.guard_size_oblivious:符号 shape guard 生成过程中的辅助函数,对布尔条件做 size-oblivious 处理,使其与具体 tensor size 解耦。 ## API 全名与测试覆盖场景 | 全名 API | 测试用例 | 覆盖场景 | |----------|----------|----------| | torch.fx.experimental.symbolic_shapes.DivideByKey | 自写 TestDivideByKeyAndEqualityConstraint::test_divide_by_key + 官方 test/export/test_export.py(patch) | 自写:构造 DivideByKey(4),验证 str(key) 为 ".__floordiv__(4)";官方:patch 注入 torch_npu 后复用 export 场景用例 | | torch.fx.experimental.symbolic_shapes.DivideByKey.get | 自写 TestDivideByKeyAndEqualityConstraint::test_divide_by_key_get | 构造 DivideByKey(4),调用 .get(17),验证返回 4 | | torch.fx.experimental.symbolic_shapes.EqualityConstraint | 自写 TestDivideByKeyAndEqualityConstraint::test_equality_constraint_init | 以空约束参数初始化(source_pairs=[],derived_equalities=[],phantom_symbols=[],relaxed_sources=set(),warn_only=False),验证 source_pairs、phantom_symbols 为空且 warn_only=False | | torch.fx.experimental.symbolic_shapes.has_free_symbols | 官方 test/test_dynamic_shapes.py::TestUnbacked::test_has_free_symbols(patch) | patch 注入 import torch_npu 后复用官方用例 | | torch.fx.experimental.symbolic_shapes.guard_size_oblivious | 官方 test/dynamo/test_misc.py(patch) | patch 注入 import torch_npu 后复用官方用例 | ## 具体改动 1. 在 test/fx/test_symbolic_shapes.py 新增 TestDivideByKeyAndEqualityConstraint 类,补充 3 个自写用例 - 使用 unittest + torch.testing._internal.common_utils.run_tests - 覆盖 API:DivideByKey、DivideByKey.get、EqualityConstraint - 用例均带 @unittest.skipUnless(torch.npu.is_available()) 2. 新增 test_upstream/test/test_dynamic_shapes.py.patch - 在 import torch 后增加 import torch_npu - 适配官方 has_free_symbols 用例 3. 新增 test_upstream/test/dynamo/test_misc.py.patch - 在 import torch 后增加 import torch_npu - 适配官方 guard_size_oblivious 用例 4. 新增 test_upstream/test/export/test_export.py.patch - 在 import torch 后增加 import torch_npu - 适配官方 DivideByKey export 场景用例 5. 上述 3 个 patch 已对 **v2.9.0** 上游文件执行 git apply --check,验证可应用。 # 【资料变更】 不涉及 # 【接口变更】 不涉及 # 【功能验证】 **环境:** torch 2.9.0 + torch_npu 2.9.0,torch.npu.is_available()==True **(1)自写用例** bash cd /tmp && python3 /data/pytorch/test/fx/test_symbolic_shapes.py \ TestDivideByKeyAndEqualityConstraint.test_divide_by_key \ TestDivideByKeyAndEqualityConstraint.test_divide_by_key_get \ TestDivideByKeyAndEqualityConstraint.test_equality_constraint_init \ 2>&1 | grep -vE "recording\.py|set_unbacked_var_to_val|E0626" | tail -10 结果:  **(2)5 API 快速验证** bash cd /workspace python -c "import torch; import torch_npu; from torch.fx.experimental.symbolic_shapes import DivideByKey, EqualityConstraint, guard_size_oblivious, has_free_symbols; print('DivideByKey.get(17)=', DivideByKey(4).get(17)); print('guard_size_oblivious(True)=', guard_size_oblivious(True)); print('has_free_symbols(3)=', has_free_symbols(3)); print('EqualityConstraint OK'); print('npu:', torch.npu.is_available())" 结果:  **(3)官方 torch.fx.experimental.symbolic_shapes.has_free_symbols** bash cd /workspace python -m pytest pytorch-upstream/test/test_dynamic_shapes.py -k test_has_free_symbols -xvs 结果:  **(4)patch 可应用性** bash cd /workspace/pytorch-upstream && git checkout -- test git apply --check /workspace/pytorch/test_upstream/test/test_dynamic_shapes.py.patch && echo OK git apply --check /workspace/pytorch/test_upstream/test/dynamo/test_misc.py.patch && echo OK git apply --check /workspace/pytorch/test_upstream/test/export/test_export.py.patch && echo OK 结果:  # 【CheckList】 - [x] 代码注释完备,正确记录错误日志 - [x] 代码实现进行了返回值、空指针等校验(不涉及) - [x] PR标题正确使用类型标签(test: 前缀) - [x] PR持续集成流水线(CI)执行通过 --- See merge request: Ascend/pytorch!36328 | 3 个月前 | |
test(functionalization): migrate CPU tensor to NPU for preserve_node_meta Co-authored-by: m0_45651774<2759927519@qq.com> # message auto-generated for no-merge-commit merge: !36942 merge test-fx-traceback-presercve_node_meta-v2.9.0 into v2.9.0 test(functionalization): migrate CPU tensor to NPU for preserve_node_meta Created-by: m0_45651774 Commit-by: m0_45651774 Merged-by: ascend-robot Description: <!-- PR描述模板更新日期:20260203 --> # 【合入来源】 **[[Usage]: torch.fx.traceback.preserve_node_meta()在 torch-npu 的 docs/zh/native_apis未明确标注支持状态,但实际在 NPU 环境下可正常使用](https://gitcode.com/Ascend/pytorch/issues/2036)**</font>\ **请勿携带内部流程信息(需求链接、问题单、内部issue等)**</font> - [ ] 需求 - [ ] 问题单 - [ ] issue/工单 - [ ] 重构优化 - [X] 资料更新 # 【API功能】 torch.fx.traceback.preserve_node_meta 是 PyTorch FX 追溯(traceback)子系统中的一个上下文管理器(Context Manager)。在它的 with 作用域生命周期内,它会动态修改 FX 编译器前端的全局/线程局部状态标志。显式通知后续的图追踪(Graph Tracing)、子图重写(Subgraph Rewriting)或图变换(Transformation)流程,在创建或衍生新节点时,强制激活元数据传递链(Metadata Propagation)。这确保了诸如 stack_trace(调用栈调试信息)、val(包含 Shape/Dtype 的 FakeTensor 模拟值)和 nn_module_stack 等关键信息不会因为图结构的重建而丢失。 # 【修改方案】 本 PR 补充内容: 2.9.0分支无test_upstream/test/test_functionalization.py.patch文件,且之前的pytorch官网test_functionalization.py文件涉及torch.fx.traceback.preserve_node_meta()的测试用例有cpu张量计算,需将该api相关测试用例进行CPU张量迁移至npu,因此新增test_upstream/test/test_functionalization.py.patch文件。 # 【NPU适配】 ## 1. API 适配 该 API 实现中不包含任何张量运算、设备初始化或硬件相关调用,仅操作 Python 上下文和 FX 节点的元数据字典。不涉及张量运算、设备内存访问或硬件驱动调用,与底层 CPU/GPU/NPU 计算硬件完全解耦,因此无需修改任何代码,可直接在 NPU 环境中使用。 ## 2. 测试用例适配 测试用例中存在张量计算,需把张量计算全部搬到 NPU。 - 张量设备调整:将原测试用例中默认的 CPU 张量计算 logs = self.get_logs(g, torch.ones(16, 64, 128, 128, requires_grad=True))修改为 NPU 张量计算logs = self.get_logs(g, torch.ones(16, 64, 128, 128, requires_grad=True, device='npu')),确保异步计算的结果载体(张量)运行在 NPU 上,贴合 NPU 场景使用需求。 # 【资料变更】 不涉及。该API无官网资料链接,不展示。 # 【接口变更】 不涉及。 # 【测试用例完备性】 ## 2.1 用例来源 PyTorch 上游社区已有完整的测试覆盖,核心用例查询结果如图:  ## 2.2 用例覆盖分析 在test/test_functionalization.py中出现了 torch.fx.traceback.preserve_node_meta() 功能的调用,验证在反向传播(loss.backward())过程中,保留并传递 FX 节点的元数据(如 source_fn_stack、seq_nr、stack_trace),确保 AOT 导出或 make_fx 生成的图中,每个操作(包括视图、克隆、原地操作)的原始溯源信息不丢失。  ## 完备性结论 存在torch.fx.traceback.preserve_node_meta测试用例, API 在 NPU 环境下 功能完整、行为正确,与 CPU 环境完全一致。 # 【功能验证】 在 NPU 环境下,使用各版本对应的虚拟环境直接执行 PyTorch 官方社区原版 test/test_functionalization.py中的用例,未做任何代码修改,全部通过。 测试命令: python -m unittest test_functionalization.TestFunctionalization.test_view_clone_view_inplace 运行日志: **v2.7.1**  **v2.8.0**  **v2.9.0**  **v2.10.0**  **v2.11.0**  **V2.12.0**  **结论**:torch.fx.traceback.preserve_node_meta 在 NPU 环境下已实际支持,原生测试用例全部通过,但文档未更新支持状态,因此需要对文档进行修正。 # 【CheckList】 > PR提交人对以下CheckList自检项进行全量自检,自检通过或不涉及,均修改 [ ] 为 [x] - [X] 代码注释完备,正确记录错误日志 - [X] 代码实现进行了返回值、空指针等校验 - [X] PR标题正确使用类型标签,如:feat、fix、refactor、docs、test等 - [X] PR持续集成流水线(CI)执行通过,代码检查无异常 See merge request: Ascend/pytorch!36942 | 4 个月前 | |
test(futures): add test case patch for futures Co-authored-by: dinglaiping<1016581171@qq.com> # message auto-generated for no-merge-commit merge: !33278 merge add-testcasepatch-for-futures-2.9.0 into v2.9.0 test(futures): add test case patch for futures Created-by: dinglaiping Commit-by: dinglaiping Merged-by: ascend-robot Description: <!-- PR描述模板更新日期:20260203 --> # 【合入来源】 > <font color="red">**https://gitcode.com/Ascend/pytorch/issues/1670**</font>\ > <font color="red">**请勿携带内部流程信息(需求链接、问题单、内部issue等)**</font> [ ] 问题单 # 【修改方案】 > 请描述修改内容的具体实现,涉及哪些组件之间进行交互,可以用1、2、3、...进行罗列\ > 如果是需求或者重构类的PR,需要补充详细设计文档(说明上下游组件关系、时序图、类图、DFX能力等内容) 一、API功能 Future.value():该方法用于获取 Future 对象的结果值。当 Future 已经完成时,它会直接返回设置的结果;但如果 Future 是通过 set_exception 标记为完成的,调用 value() 会抛出对应的异常。这个 API 和 wait() 的区别在于它不会阻塞等待,只适用于已经完成的 Future。 Future.set_result(value):用于将 Future 标记为完成状态并设置结果值。一旦调用,Future 立即进入完成状态,所有等待该 Future 的线程都会被唤醒并收到这个结果。每个 Future 只能被标记完成一次,重复调用会触发 RuntimeError。 Future.set_exception(err):将 Future 标记为完成状态但携带一个异常。调用后 Future 被视为已完成,但任何尝试通过 wait() 或 value() 获取结果的调用都会抛出这个设置的异常。这在异步错误传播中非常有用。 Future.wait():阻塞当前线程直到 Future 完成,然后返回结果值。如果 Future 是通过 set_exception 完成的,wait() 会抛出设置的异常。这是最基础的获取 Future 结果的方式。 Future.done():返回一个布尔值指示 Future 是否已经完成。如果 Future 已经被 set_result 或 set_exception 标记过,返回 True;否则返回 False。可以用于非阻塞地检查状态。 Future.then(cb):注册一个回调函数,当 Future 完成时自动执行。回调函数接收完成的 Future 作为参数,可以调用 wait() 获取结果进行处理。then 返回一个新的 Future 对象,代表回调执行的结果,支持链式调用形成 Future 链条。如果回调本身抛出异常,新 Future 会携带这个异常。 Future.add_done_callback(cb):添加一个完成时的回调函数,与 then 不同,它不返回新的 Future,回调的错误会被静默忽略(仅记录日志)。多个回调按添加顺序执行,适合用于副作用操作(如状态标记、清理工作)。 torch.futures.collect_all(futs):接受一个 Future 列表,返回一个新的 Future,该 Future 在所有输入 Future 完成时完成,其结果是一个包含所有原始 Future 的列表,每个都可以通过 wait() 获取各自的结果。 torch.futures.wait_all(futs):接受一个 Future 列表,阻塞等待所有 Future 完成,直接返回一个包含所有结果的列表。如果任何一个 Future 携带异常,wait_all 会抛出 RuntimeError 包裹的异常信息。 二、测试用例完备性说明 PyTorch 社区原生测试用例(test_futures.py)对上述 9 个 API 实现全维度场景覆盖,核心验证内容如下: Future.set_exception 的验证:test_set_exception 测试用例创建了 Future 并调用 set_exception 设置 ValueError,然后验证 wait() 会抛出带有"Intentional"消息的 ValueError,同时也验证 value() 同样会抛出该异常。test_set_exception_multithreading 进一步在一个线程等待的同时,另一个线程设置异常,验证跨线程的错误传播。 多线程场景验证:test_set_exception_multithreading 使用 threading.Thread 在一个线程中调用 wait(),主线程中设置异常,验证异常能正确传播到等待线程。test_wait_multi_thread 则测试了在后台线程延迟设置结果,主线程调用 wait() 能正确阻塞并获取结果。 Future.done() 的验证:test_done 测试创建一个 Future,初始状态验证 done() 返回 False,调用 set_result 后验证 done() 返回 True。test_done_exception 则验证通过 then 链接触发异常的 Future,其 done() 状态也为 True,但 wait() 会抛出异常。 单次完成限制验证:test_mark_future_twice 专门测试多次调用 set_result 会触发 RuntimeError,提示"Future can only be marked completed once"。 序列化限制验证:test_pickle_future 验证 Future 对象不能被 pickle 序列化,尝试保存时会抛出 RuntimeError。 then 方法的验证:test_then 测试基本回调,验证回调能正确获取结果并返回新 Future。test_chained_then 创建了 20 个 then 链,每个回调给结果加 1,验证链式调用的计算顺序正确。test_then_error 系列包括三个子测试:test_then_wrong_arg 验证回调参数类型错误,test_then_no_arg 验证回调不接受参数的错误,test_then_raise 验证回调内部抛出异常的情况,都验证错误正确传播到新 Future。 add_done_callback 的验证:test_add_done_callback_simple 验证回调在 set_result 后被调用,并能正确获取结果。test_add_done_callback_maintains_callback_order 添加两个回调修改同一变量,验证执行顺序与添加顺序一致。test_add_done_callback_error_is_ignored 验证回调中的 ValueError 不会传播,只是被记录。test_add_done_callback_no_arg_error_is_ignored 验证参数不匹配的错误同样被忽略。 then 与 add_done_callback 交互验证:test_interleaving_then_and_add_done_callback_maintains_callback_order 交替添加 then 和 add_done_callback,验证回调执行顺序保持插入顺序。test_interleaving_then_and_add_done_callback_propagates_error 验证 then 的错误会传播到结果 Future,而 add_done_callback 的错误被忽略。 collect_all 的验证:test_collect_all 创建两个 Future,在一个后台线程中延迟设置第一个 Future 的结果,主线程立即设置第二个,然后验证 collect_all 返回的 Future 能正确收集两个结果,且等待时间由最慢的决定。 wait_all 的验证:test_wait_all(Windows 除外)先测试两个已完成的 Future,验证返回列表包含正确结果。然后测试包含异常的链条,验证 wait_all 会抛出 RuntimeError 包含"Expected error"消息。 空值处理验证:test_wait_none 验证向 torch.jit.wait、torch.futures.wait_all 和 torch.futures.collect_all 传递 None 时,都会抛出 RuntimeError 提示"Future can't be None"。 三、npu适配 3.1 api适配 torch.futures 模块 API 底层无硬件相关逻辑,所有异步结果管理、回调触发、异常传播等核心功能均为框架层通用实现,torch_npu 已完成 NPU 设备的底层适配,无需修改 API 源码,仅通过测试用例的设备相关调整即可实现 NPU 兼容。 3.2 测试用例适配 • 基础环境适配:新增 import torch_npu,让 PyTorch 框架识别 NPU 设备,支持 NPU 张量的创建与操作; • 张量设备调整:将原测试用例中默认的 CPU 张量(torch.ones(2,2))修改为 NPU 张量(torch.ones(2,2).npu()),确保异步计算的结果载体(张量)运行在 NPU 上,贴合 NPU 场景使用需求。 # 【资料变更】 > 不涉及 # 【接口变更】 > 不涉及 # 【功能验证】 > 说明测试场景,测试方法。如果本次测试方式与常规单元测试不同,请详细说明您的测试步骤\ > 新增/变更内容是否已新增/适配UT测试用例看护,并补充测试自验证截图 2.6版本 [root@hostname-fqv42 ~]# docker exec -it test26 bash root@hostname-fqv42:/home# python /root/torchnpuapi/test_futures_gai.py Fail to import hypothesis in common_utils, tests are not derandomized [E226 11:44:33.636064398 pybind_utils.h:209] Got the following error when running the callback: ValueError: Expected error At: /root/torchnpuapi/test_futures_gai.py(243): raise_value_error /usr/local/python/lib/python3.11/site-packages/torch/futures/__init__.py(245): set_result /root/torchnpuapi/test_futures_gai.py(236): _test_add_done_callback_error_ignored /root/torchnpuapi/test_futures_gai.py(245): test_add_done_callback_error_is_ignored /usr/local/python/lib/python3.11/site-packages/torch/testing/_internal/common_utils.py(3108): wrapper /usr/local/python/lib/python3.11/unittest/case.py(579): _callTestMethod /usr/local/python/lib/python3.11/unittest/case.py(623): run /usr/local/python/lib/python3.11/site-packages/torch/testing/_internal/common_utils.py(3215): _run_custom /usr/local/python/lib/python3.11/site-packages/torch/testing/_internal/common_utils.py(3243): run /usr/local/python/lib/python3.11/unittest/case.py(678): __call__ /usr/local/python/lib/python3.11/unittest/suite.py(122): run /usr/local/python/lib/python3.11/unittest/suite.py(84): __call__ /usr/local/python/lib/python3.11/unittest/suite.py(122): run /usr/local/python/lib/python3.11/unittest/suite.py(84): __call__ /usr/local/python/lib/python3.11/unittest/runner.py(217): run /usr/local/python/lib/python3.11/unittest/main.py(274): runTests /usr/local/python/lib/python3.11/unittest/main.py(102): __init__ /usr/local/python/lib/python3.11/site-packages/torch/testing/_internal/common_utils.py(1353): run_tests /root/torchnpuapi/test_futures_gai.py(347): <module> ..[E226 11:44:38.999984481 pybind_utils.h:209] Got the following error when running the callback: TypeError: TestFuture.test_add_done_callback_no_arg_error_is_ignored.<locals>.no_arg() takes 0 positional arguments but 1 was given .......[E226 11:44:38.132336345 pybind_utils.h:209] Got the following error when running the callback: ValueError: Expected error At: /root/torchnpuapi/test_futures_gai.py(287): raise_value_error /usr/local/python/lib/python3.11/site-packages/torch/futures/__init__.py(245): set_result /root/torchnpuapi/test_futures_gai.py(292): test_interleaving_then_and_add_done_callback_propagates_error /usr/local/python/lib/python3.11/site-packages/torch/testing/_internal/common_utils.py(3108): wrapper /usr/local/python/lib/python3.11/unittest/case.py(579): _callTestMethod /usr/local/python/lib/python3.11/unittest/case.py(623): run /usr/local/python/lib/python3.11/site-packages/torch/testing/_internal/common_utils.py(3215): _run_custom /usr/local/python/lib/python3.11/site-packages/torch/testing/_internal/common_utils.py(3243): run /usr/local/python/lib/python3.11/unittest/case.py(678): __call__ /usr/local/python/lib/python3.11/unittest/suite.py(122): run /usr/local/python/lib/python3.11/unittest/suite.py(84): __call__ /usr/local/python/lib/python3.11/unittest/suite.py(122): run /usr/local/python/lib/python3.11/unittest/suite.py(84): __call__ /usr/local/python/lib/python3.11/unittest/runner.py(217): run /usr/local/python/lib/python3.11/unittest/main.py(274): runTests /usr/local/python/lib/python3.11/unittest/main.py(102): __init__ /usr/local/python/lib/python3.11/site-packages/torch/testing/_internal/common_utils.py(1353): run_tests /root/torchnpuapi/test_futures_gai.py(347): <module> ..........[1, 2] ... ---------------------------------------------------------------------- Ran 22 tests in 6.038s OK root@hostname-fqv42:/home# ## 结果说明 执行test_futures.py测试用例后,终端输出包含若干[E226]级别的错误日志,但最终显示Ran 22 tests in 6.038s且OK,表明所有测试用例执行通过,日志中出现的报错属于测试用例设计的预期行为,非代码 Bug 或 NPU 适配问题。 # 【CheckList】 > PR提交人对以下CheckList自检项进行全量自检,自检通过或不涉及,均修改 [ ] 为 [x] - [x] 代码注释完备,正确记录错误日志 - [x] 代码实现进行了返回值、空指针等校验 - [x] PR标题正确使用类型标签,如:feat、fix、refactor、docs、test等 - [x] PR持续集成流水线(CI)执行通过,代码检查无异常 See merge request: Ascend/pytorch!33278 | 6 个月前 | |
test: supplement NPU patch for torch.fx.Tracer.create_node in v2.9.0 Co-authored-by: Deng_RH<1848477588@qq.com> # message auto-generated for no-merge-commit merge: !36772 merge test/fx-tracer-create-node-npu-v2.9.0 into v2.9.0 test: supplement NPU patch for torch.fx.Tracer.create_node in v2.9.0 Created-by: Deng_RH Commit-by: Deng_RH Merged-by: ascend-robot Description: <!-- PR描述模板更新日期:20260203 --> # 【合入来源】 > **https://gitcode.com/Ascend/pytorch/issues/2089** - [x] issue/工单 # 【修改方案】 一、API功能说明 torch.fx.Tracer.create_node(kind, target, args, kwargs, name, type_expr):在FX图的符号追踪(symbolic trace)过程中创建一个新的 torch.fx.Node,是 Tracer 的核心方法。该接口属于纯图构建逻辑,不触发实际的 Tensor 运算,与底层硬件后端(CPU/CUDA/NPU)完全解耦。但上游测试用例中通过子类化 Tracer 重写 create_node 时,forward 内部可能存在张量创建,需确保张量运行在NPU上。 二、修改内容 补充 test_upstream/test/test_fx.py.patch 中 test_disallow_override 用例的 NPU 张量迁移。 该用例验证子类化 Tracer 重写 create_node 拦截 in-place 操作的功能。MyInplaceMod3.forward 中 torch.ones(3, 4) 在 FX tracing 时会被实际执行(因为不依赖 Proxy 输入),需迁移到 NPU。 diff - y = torch.ones(3, 4) + y = torch.ones(3, 4).npu() 三、NPU适配说明 - test_disallow_override:有张量 torch.ones(3, 4),位于 MyInplaceMod3.forward 中,FX tracing 时实际执行该行代码创建张量。已合入的 PR !36297/!36298/!36299/!36300 未覆盖此处,本次补充。 - test_node_tagging:forward 为 return a + b,tracing 时 a、b 均为 Proxy 对象,无任何实际张量创建或运算,无需设备迁移修改。已通过 import torch_npu 覆盖NPU环境。 # 【资料变更】 已检查文档,https://gitcode.com/Ascend/pytorch/tree/v2.7.1/docs/zh/native_apis 目录下的 pytorch_2-6-0 至 pytorch_2-12-0 文件夹中的 torch-fx.md 均已对 torch.fx.Tracer.create_node 标注“是”,无需更改。 # 【接口变更】 "不涉及" # 【功能验证】 > 在已安装 torch + torch_npu 的 Ascend 910B1 环境下执行 **测试环境:** - 硬件:Atlas 800T A2 (Ascend 910B1) - CANN: 8.5.0 - torch: 2.1.0 + torch_npu 2.1.0 **测试命令:** bash python3 test_tracer_create_node.py **测试日志:** test_disallow_override (__main__.TestFX.test_disallow_override) ... ok test_node_tagging (__main__.TestFX.test_node_tagging) ... ok ---------------------------------------------------------------------- Ran 2 tests in 1.770s OK # 【CheckList】 - [x] 代码注释完备,正确记录错误日志 - [x] 代码实现进行了返回值、空指针等校验 - [x] PR标题正确使用类型标签,如:feat、fix、refactor、docs、test等 - [x] PR持续集成流水线(CI)执行通过,代码检查无异常 See merge request: Ascend/pytorch!36772 | 4 个月前 | |
fix: split_module api功能v2.9.0昇腾验证 Co-authored-by: 豳州牧之<1277070050@qq.com> # message auto-generated for no-merge-commit merge: !37017 merge test-split-module-ascend-v290 into v2.9.0 fix: split_module api功能v2.9.0昇腾验证 Created-by: weixin_42886776 Commit-by: 豳州牧之 Merged-by: ascend-robot Description: <!-- PR描述模板更新日期:20260203 --> # 【合入来源】 > <font color="red">**如有社区issue,请关联issue链接**</font>\ > <font color="red">**请勿携带内部流程信息(需求链接、问题单、内部issue等)**</font> - [ ] 需求 - [ ] 问题单 - [ ] issue/工单 - [ ] 重构优化 - [ ] 资料更新 # 【修改方案】 一、API功能说明 API: torch.fx.passes.split_module.split_module 功能:split_module 是 PyTorch FX 的图拆分工具,用于把大的FX GraphModule 计算图,按指定的规则(split_callback)拆成多个子图(子 GraphModule),顶层保留一个主 GraphModule,其 forward 会按依赖顺序调用各个子图,自动处理跨子图的数据传递,常用于模型并行、算子异构分发、编译优化、子图导出(如 NPU/CPU 拆分、vLLM 推理拆分)。 二、版本API及测试用例完备性说明 1、经 PyTorch 社区代码检索,v2.7.1/v2.9.0/v2.10.0/v2.11.0/v2.12.0均存在该API 2、经 PyTorch 社区代码检索,v2.7.1/v2.9.0/v2.10.0/v2.11.0/v2.12.0均有test/fx/test_fx_experimental.py用例覆盖torch.fx.passes.split_module功能,v2.9.0包括 test_split_module_dead_code test_split_module_default_arg test_split_module_input_names test_split_module_keep_original_order_and_noop_graph test_split_module_kwargs_expansion test_split_module_return_node test_split_module_symint_dependency_handling test_split_qualname_mapping test_subgraph_creation test_subgraph_trivial_resnet test_subgraph_uniquename 用例,因此不需要新增测试用例。 原用例执行,均通过,但相关张量均运行在CPU。 三、npu适配 1、 api适配 torch.fx.passes.split_module.split_module底层无硬件相关逻辑,torch_npu 已完成 NPU 设备的底层适配,无需修改 API 源码,仅通过测试用例的设备相关调整即可实现 NPU 兼容。 2、 测试用例适配 • 基础环境适配:新增 import torch_npu,让 PyTorch 框架识别 NPU 设备,支持 NPU 张量的创建与操作; • 张量设备调整:将原测试用例中默认的 CPU 张量修改为 NPU 张量,确保张量运行在 NPU 上,贴合 NPU 场景使用需求。 四、测试环境版本 操作系统 :openEuler 24.03 (LTS) 昇腾硬件信息:Atlas 800I A2(32GB) CANN软件版本:8.5.0 安装的对应软件版本 :torch 和 torch-npu,覆盖2.7.1到2.12.0各个版本 五、修改说明 新增内容: test_upstream/test/fx/test_fx_experimental.py.patch 备注:新提交patch的PR:一是import torch_npu,二是把相关torch张量后面加上.npu(),使得tensor运行到npu上。 # 【资料变更】 不涉及 # 【接口变更】 不涉及 # 【功能验证】 运行结果 1.v2.9.0原样运行结果 python test_fx_experimental.py -k test_split_module -k test_subgraph_creation -k test_subgraph_uniquename -k test_split_qualname_mapping -k test_subgraph_trivial_resnet -v test_split_module_dead_code (__main__.TestFXExperimental.test_split_module_dead_code) ... ok test_split_module_default_arg (__main__.TestFXExperimental.test_split_module_default_arg) ... ok test_split_module_input_names (__main__.TestFXExperimental.test_split_module_input_names) ... ok test_split_module_keep_original_order_and_noop_graph (__main__.TestFXExperimental.test_split_module_keep_original_order_and_noop_graph) ... ok test_split_module_kwargs_expansion (__main__.TestFXExperimental.test_split_module_kwargs_expansion) ... ok test_split_module_return_node (__main__.TestFXExperimental.test_split_module_return_node) ... ok test_split_module_symint_dependency_handling (__main__.TestFXExperimental.test_split_module_symint_dependency_handling) ... ok test_split_qualname_mapping (__main__.TestFXExperimental.test_split_qualname_mapping) ... ok test_subgraph_creation (__main__.TestFXExperimental.test_subgraph_creation) ... ok test_subgraph_trivial_resnet (__main__.TestFXExperimental.test_subgraph_trivial_resnet) ... skipped 'no torchvision' test_subgraph_uniquename (__main__.TestFXExperimental.test_subgraph_uniquename) ... ok ---------------------------------------------------------------------- Ran 11 tests in 0.687s OK (skipped=1)  2.npu适配验证 python test_fx_experimental.py -k test_split_module -k test_subgraph_creation -k test_subgraph_uniquename -k test_split_qualname_mapping -k test_subgraph_trivial_resnet -v test_split_module_dead_code (__main__.TestFXExperimental.test_split_module_dead_code) ... ok test_split_module_default_arg (__main__.TestFXExperimental.test_split_module_default_arg) ... ok test_split_module_input_names (__main__.TestFXExperimental.test_split_module_input_names) ... ok test_split_module_keep_original_order_and_noop_graph (__main__.TestFXExperimental.test_split_module_keep_original_order_and_noop_graph) ... ok test_split_module_kwargs_expansion (__main__.TestFXExperimental.test_split_module_kwargs_expansion) ... ok test_split_module_return_node (__main__.TestFXExperimental.test_split_module_return_node) ... ok test_split_module_symint_dependency_handling (__main__.TestFXExperimental.test_split_module_symint_dependency_handling) ... ok test_split_qualname_mapping (__main__.TestFXExperimental.test_split_qualname_mapping) ... ok test_subgraph_creation (__main__.TestFXExperimental.test_subgraph_creation) ... ok test_subgraph_trivial_resnet (__main__.TestFXExperimental.test_subgraph_trivial_resnet) ... skipped 'no torchvision' test_subgraph_uniquename (__main__.TestFXExperimental.test_subgraph_uniquename) ... ok ---------------------------------------------------------------------- Ran 11 tests in 1.014s OK (skipped=1)  # 【CheckList】 > PR提交人对以下CheckList自检项进行全量自检,自检通过或不涉及,均修改 [ ] 为 [x] - [ ] 代码注释完备,正确记录错误日志 - [ ] 代码实现进行了返回值、空指针等校验 - [ ] PR标题正确使用类型标签,如:feat、fix、refactor、docs、test等 - [ ] PR持续集成流水线(CI)执行通过,代码检查无异常 See merge request: Ascend/pytorch!37017 | 5 个月前 | |
test(jit): adapt ScriptModule iterator tests on NPU Co-authored-by: Jinfan Liu<1300083451@qq.com> # message auto-generated for no-merge-commit merge: !38171 merge test-jit-scriptmodule-named-iterators-npu-v2.9.0 into v2.9.0 test(jit): adapt ScriptModule iterator tests on NPU Created-by: JfanLiu Commit-by: Jinfan Liu Merged-by: ascend-robot Description: <!-- PR描述模板更新日期:20260203 --> # 【合入来源】 > <font color="red">**https://gitcode.com/Ascend/pytorch/issues/2350**</font> > <font color="red">**请勿携带内部流程信息(需求链接、问题单、内部issue等)**</font> [x] issue/工单 # 【修改方案】 一、API功能说明 本 PR 验证以下 ScriptModule 命名遍历/参数遍历 API 在 NPU Parameter、NPU Buffer 和 NPU 输入路径上的一致性: - torch.jit.ScriptModule.named_buffers - torch.jit.ScriptModule.named_children - torch.jit.ScriptModule.named_modules - torch.jit.ScriptModule.named_parameters - torch.jit.ScriptModule.parameters 上述接口用于遍历 ScriptModule 中注册的 buffer、子模块、递归模块和参数状态;其实现语义继承自 torch.nn.Module,本 PR 不修改 API 源码,只补充官方 JIT 用例在 NPU 上的运行覆盖。 二、测试用例完备性说明 本 PR 适配 PyTorch 官方社区 test/test_jit.py 中与本组 API 相关的 5 个用例: 1. TestScript.test_cpp_module_iterator:通过 torch._C._jit_debug_module_iterators 直接断言 named_buffers、named_children、named_modules、named_parameters、parameters 在 ScriptModule 上的迭代结果;本次将 Parameter 和 Buffer 迁移到 NPU。 2. TestScript.test_parameter_order:注册 52 个 Parameter,断言原始 Module 与 ScriptModule 的 parameters() 顺序一致;本次所有 Parameter 均为 NPU Tensor。 3. TestScript.test_module_apis:在 @torch.jit.export 方法内部直接调用 named_modules() 与 named_children(),并与 Python Module 结果对齐;本次输入 Tensor 迁移到 NPU。 4. TestScript.test_module_parameters_and_buffers:构造包含 NPU Parameter、NPU Buffer 和子模块复用的 ScriptModule,验证 forward 结果及导出导入一致性。 5. TestScript.test_named_buffers_are_iterable:在脚本化方法中直接遍历 named_buffers(),验证注册 Buffer 可迭代、普通 Tensor 不被误识别,并覆盖导出导入后一致性;本次 Buffer 和普通 Tensor 均迁移到 NPU。 上述用例覆盖 C++ 调试迭代器直接枚举、ScriptModule 方法内直接调用、参数顺序、buffer 边界和导出导入一致性,可作为本组 API 的一致性验证依据。 三、NPU适配方案 1. API 源码无需修改:本组 API 属于模块状态遍历接口,不涉及新增 NPU kernel 或设备通信逻辑。 2. 测试用例适配:当前分支已有 test_upstream/test/test_jit.py.patch,本 PR 保留既有 patch,仅在对应官方用例中追加 NPU Tensor/Parameter/Buffer 迁移 hunk。 3. 变更文件:test_upstream/test/test_jit.py.patch。 # 【资料变更】 > 已检查 v2.7.1 分支 docs/zh/native_apis 下各版本 torch-jit.md,本组公开 API 已在 2.7.1、2.9.0、2.10.0、2.11.0、2.12.0 文档条目中记录,无需新增资料 PR。已记录 API:torch.jit.ScriptModule.named_buffers、torch.jit.ScriptModule.named_children、torch.jit.ScriptModule.named_modules、torch.jit.ScriptModule.named_parameters、torch.jit.ScriptModule.parameters。 # 【接口变更】 > 不涉及。API 源码无修改,不新增、删除或变更对外接口。 # 【功能验证】 > 已在 2.9.0 对应 torch-npu 环境执行本组官方用例,结果如下。 ## 验证环境 - 操作系统:Ubuntu / Linux aarch64 - 昇腾硬件:910B2 - CANN 软件版本:8.3.RC1 - 验证环境:torch 2.9.0+cpu / torch-npu 2.9.0.post1 ## 运行命令与结果 bash python test/test_jit.py TestScript.test_cpp_module_iterator TestScript.test_parameter_order TestScript.test_module_apis TestScript.test_module_parameters_and_buffers TestScript.test_named_buffers_are_iterable Ran 5 tests in 1.081s OK # 【CheckList】 - [x] 代码注释完备,正确记录错误日志 - [x] 代码实现进行了返回值、空指针等校验 - [x] PR标题正确使用类型标签,如:feat、fix、refactor、docs、test等 - [ ] PR持续集成流水线(CI)执行通过,代码检查无异常 See merge request: Ascend/pytorch!38171 | 4 个月前 | |
test(multiprocessing&type_info):add test case patch for multiprocessing and type_info Co-authored-by: HeYang<heyang88@h-partners.com> # message auto-generated for no-merge-commit merge: !34039 merge v2.9.0 into v2.9.0 test(multiprocessing&type_info):add test case patch for multiprocessing and type_info Created-by: VnOcean Commit-by: HeYang Merged-by: ascend-robot Description: <!-- PR描述模板更新日期:20260203 --> # 【合入来源】 > <font color="red">https://gitcode.com/Ascend/pytorch/issues/1683</font>\ > <font color="red">**请勿携带内部流程信息(需求链接、问题单、内部issue等)**</font> 一、API功能:本次适配的 12 个核心 API,均为硬件无关的框架层实现,核心功能为多进程调度和获取不同类型数据的信息,各api 功能介绍及适配情况如下: >1.torch.multiprocessing.\_set_thread_name : >用于设置当前线程的名称,复用测试用例。测试用例中,调用_set_thread_name 为线程指定名称。 >2.torch.multiprocessing.Pool : >用于创建进程池的类,可以自动管理一组工作进程,并将任务分发到这些进程中进行并行处理。它适合“数据并行”的任务模式,例如并行地对列表中的每个元素应用同一个函数。使用官网测试用例,执行python test_multiprocessing.py TestMultiprocessing.test_fd_pool -v,test_fd_pool方法,调用自有函数self.\_test_pool(repeat=TEST_REPEATS),传入重复次数 >3.torch.multiprocessing.spawn: >PyTorch 推荐用于启动多个进程的入口点,适合数据并行和分布式训练,官网存在测试用例,位于test_multiprocessing_spawn.py 文件中的SpawnTest 类 >4.torch.multiprocessing.reductions.rebuild_cuda_tensor: >作用是在多进程编程中,重建通过 IPC(进程间通信)接收到的 CUDA 张量,一个 CUDA 张量被从一个进程发送到另一个进程时,它首先会被 reduce_tensor 函数“拆解”或“序列化”成一个包含必要信息的元组。在接收端,rebuild_cuda_tensor 就会被调用来执行相反的操作,根据这些信息在接收进程中重新构建出这个 CUDA 张量. torch_npu 下 distributed/rpc/multiprocessing/test_reduction_new.py 文件中已适配 rebuild_npu_tensor 方法 >5.torch.multiprocessing.get_context: >获取一个多进程上下文对象,该对象具有与标准 multiprocessing 模块相同的API。在 test_leaf_variable_sharing 方法中被调用,因此可以验证 test_leaf_variable_sharing 的效果,达到对get_context API的测试验证。 >6.torch.multiprocessing.Process: >用于创建单个进程的类,与 Python 原生 multiprocessing.Process 完全兼容。它用于在一个新的子进程中运行指定的函数。在 test_leaf_variable_sharing 方法中被调用,因此可以验证 test_leaf_variable_sharing 的效果,达到对ProcessAPI的测试验证。 >7.torch.multiprocessing.Queue: >一个用于进程间通信的队列,与 Python 原生的 Queue 使用方式完全一致。当通过这个队列传递 PyTorch 的 Tensor 时,其数据会被自动移到共享内存,只传递一个句柄,从而实现零拷贝传输。它用于在一个新的子进程中运行指定的函数。在 test_leaf_variable_sharing 方法中被调用,因此可以验证 test_leaf_variable_sharing 的效果,达到对QueueAPI的测试验证。 >8.torch.multiprocessing.set_sharing_strategy: >set_sharing_strategy用于设置 CPU Tensor 在不同进程间共享时所使用的策略。在test_multiprocessing.py 文件中TestMultiprocessing类中的test_fs_sharing方法中被调用,可通过测试该函数的方式测试 API set_sharing_strategy。test_fs_sharing方法在fs_sharing()的限制条件下调用了自有函数 self.\_test_sharing,而 fs_sharing() 方法调用了API set_sharing_strategy fs_sharing作为上下文管理器调用 api set_sharing_strategy,临时将多进程共享策略设置为 "file_system",执行测试代码后恢复原来的共享策略 >9.torch.multiprocessing.SimpleQueue: >一个简化版的 Queue,它提供了基本的 put 和 get 方法,但内部不使用任何额外的线程。在某些复杂的多线程环境中,这有助于避免因线程竞争导致的死锁问题。其被 test_non_leaf_variable_sharing 方法调用,可测试此方法来验证 SimpleQueue API 的功能。test_non_leaf_variable_sharing 方法验证在多进程场景下,PyTorch中带有梯度信息的张量(requires_grad=True)不能被序列化并通过SimpleQueue在进程间传递的行为。 >10.torch.multiprocessing.start_processes >用于弹性的分布式训练。不仅能启动函数,还能启动二进制文件作为子进程,并提供更完善的日志重定向和管理功能。在test_multiprocessing_spawn.py 文件_TestMultiProcessing类中被多次调用,可以通过验证该方法,达到验证 start_processes API的作用。 >11.torch.finfo: >用于获取浮点数类型数值属性的 API。官网已有测试用例,用例验证了 PyTorch NPU后端的浮点信息类在数值精度、范围和属性方面与CPU NumPy实现的一致性,同时覆盖了特殊浮点格式的正确实现。它确保了跨设备(NPU vs CPU)和跨框架(PyTorch vs NumPy)的浮点属性一致性。 >12.torch.iinfo: >用于获取整型数类型数值属性的 API。官网已有测试用例,用例验证了PyTorch NPU后端的整数信息类在位数、取值范围和类型标识方面与CPU NumPy实现的一致性。与finfo测试一起,完整覆盖了PyTorch数值类型系统的基本信息查询功能。 二、测试用例完备性说明 PyTorch 社区原生测试用例(test_multiprocessing.py)对上述 前10个 API 实现全维度场景覆盖,核心验证内容如下: 1. torch.multiprocessing.Queue / SimpleQueue:进程间 tensor 传递、阻塞获取超时、空/满队列状态校验;混合数据类型(float/byte)顺序读写及事件同步机制验证。 2. torch.multiprocessing.Process:子进程 tensor 原地修改(add_)、daemon 模式、join 超时及异常退出码校验;多进程生命周期管理与资源回收验证。 3. torch.multiprocessing.Pool:多 worker 并行执行 tensor 填充映射(map),跨进程结果汇总及 worker 进程 PID 追踪;池关闭与等待逻辑验证。 4. torch.multiprocessing.get_context:spawn/fork 上下文切换下的 IPC、autograd 错误隔离、参数序列化兼容性验证;多 NPU 设备上下文隔离测试。 5. torch.multiprocessing.set_sharing_strategy:文件描述符(fd)与文件系统(fs)两种策略下的 tensor 共享、shm 残留检测、存储持久化行为对比验证。 6. torch.multiprocessing.reductions.rebuild_cuda_tensor:untyped storage 跨进程重建、storage 句柄/偏移/大小等元数据完整还原;多 device 下 tensor chunk 拆分与合并验证。 7. torch.multiprocessing._set_thread_name / _get_thread_name:Linux 平台下线程名称读写功能验证(依赖 prctl)。 PyTorch 社区原生测试用例(test_type_info.py)对上述 后 2 个 API 实现全维度场景覆盖,核心验证内容如下: 1. 获取全量浮点数类型数值属性的 API 2. 获取全量整型数类型数值属性的 API 三、API适配 主要分为以下3个级别的适配: 1. 不涉及张量操作、及硬件强绑定操作时:不修改,完全复用原生实现 。 2. 张量操作由 .cuda() 操作改写为 .npu() 操作,npu 已适配的 api 进行替换。 3. 当前场景不适合或有条件限制的的用例,增加条件判断,不适合则跳过。 功能验证: root@k8s-node1:/home/torch_2.9.0/pytorch/test# python test_multiprocessing.py TestMultiprocessing.test_set_thread_name -v test_set_thread_name (__main__.TestMultiprocessing.test_set_thread_name) ... ok ---------------------------------------------------------------------- Ran 1 test in 0.865s OK root@k8s-node1:/home/torch_2.9.0/pytorch/test# python test_multiprocessing.py TestMultiprocessing.test_fd_pool -v test_fd_pool (__main__.TestMultiprocessing.test_fd_pool) ... ok ---------------------------------------------------------------------- Ran 1 test in 39.361s OK root@k8s-node1:/home/torch_2.9.0/pytorch/test# python test_multiprocessing_spawn.py ..... ---------------------------------------------------------------------- Ran 31 tests in 226.550s OK root@k8s-node1:/home/torch_2.9.0/pytorch/test# python test_multiprocessing.py TestMultiprocessing.test_leaf_variable_sharing -v test_leaf_variable_sharing (__main__.TestMultiprocessing.test_leaf_variable_sharing) ... ok ---------------------------------------------------------------------- Ran 1 test in 29.204s OK root@k8s-node1:/home/torch_2.9.0/pytorch/test# python test_multiprocessing.py TestMultiprocessing.test_fs_sharing -v test_fs_sharing (__main__.TestMultiprocessing.test_fs_sharing) ... ok ---------------------------------------------------------------------- Ran 1 test in 52.557s OK root@k8s-node1:/home/torch_2.9.0/pytorch/test# python test_multiprocessing.py TestMultiprocessing.test_non_leaf_variable_sharing -v test_non_leaf_variable_sharing (__main__.TestMultiprocessing.test_non_leaf_variable_sharing) ... ok ---------------------------------------------------------------------- Ran 1 test in 1.270s OK root@k8s-node1:/home/torch_2.9.0/pytorch/test# python test_type_info.py TestDTypeInfo.test_finfo . ---------------------------------------------------------------------- Ran 1 test in 1.309s OK root@k8s-node1:/home/torch_2.9.0/pytorch/test# python test_type_info.py TestDTypeInfo.test_iinfo . ---------------------------------------------------------------------- Ran 1 test in 1.267s OK ` See merge request: Ascend/pytorch!34039 | 5 个月前 | |
test(multiprocessing&type_info):add test case patch for multiprocessing and type_info Co-authored-by: HeYang<heyang88@h-partners.com> # message auto-generated for no-merge-commit merge: !34039 merge v2.9.0 into v2.9.0 test(multiprocessing&type_info):add test case patch for multiprocessing and type_info Created-by: VnOcean Commit-by: HeYang Merged-by: ascend-robot Description: <!-- PR描述模板更新日期:20260203 --> # 【合入来源】 > <font color="red">https://gitcode.com/Ascend/pytorch/issues/1683</font>\ > <font color="red">**请勿携带内部流程信息(需求链接、问题单、内部issue等)**</font> 一、API功能:本次适配的 12 个核心 API,均为硬件无关的框架层实现,核心功能为多进程调度和获取不同类型数据的信息,各api 功能介绍及适配情况如下: >1.torch.multiprocessing.\_set_thread_name : >用于设置当前线程的名称,复用测试用例。测试用例中,调用_set_thread_name 为线程指定名称。 >2.torch.multiprocessing.Pool : >用于创建进程池的类,可以自动管理一组工作进程,并将任务分发到这些进程中进行并行处理。它适合“数据并行”的任务模式,例如并行地对列表中的每个元素应用同一个函数。使用官网测试用例,执行python test_multiprocessing.py TestMultiprocessing.test_fd_pool -v,test_fd_pool方法,调用自有函数self.\_test_pool(repeat=TEST_REPEATS),传入重复次数 >3.torch.multiprocessing.spawn: >PyTorch 推荐用于启动多个进程的入口点,适合数据并行和分布式训练,官网存在测试用例,位于test_multiprocessing_spawn.py 文件中的SpawnTest 类 >4.torch.multiprocessing.reductions.rebuild_cuda_tensor: >作用是在多进程编程中,重建通过 IPC(进程间通信)接收到的 CUDA 张量,一个 CUDA 张量被从一个进程发送到另一个进程时,它首先会被 reduce_tensor 函数“拆解”或“序列化”成一个包含必要信息的元组。在接收端,rebuild_cuda_tensor 就会被调用来执行相反的操作,根据这些信息在接收进程中重新构建出这个 CUDA 张量. torch_npu 下 distributed/rpc/multiprocessing/test_reduction_new.py 文件中已适配 rebuild_npu_tensor 方法 >5.torch.multiprocessing.get_context: >获取一个多进程上下文对象,该对象具有与标准 multiprocessing 模块相同的API。在 test_leaf_variable_sharing 方法中被调用,因此可以验证 test_leaf_variable_sharing 的效果,达到对get_context API的测试验证。 >6.torch.multiprocessing.Process: >用于创建单个进程的类,与 Python 原生 multiprocessing.Process 完全兼容。它用于在一个新的子进程中运行指定的函数。在 test_leaf_variable_sharing 方法中被调用,因此可以验证 test_leaf_variable_sharing 的效果,达到对ProcessAPI的测试验证。 >7.torch.multiprocessing.Queue: >一个用于进程间通信的队列,与 Python 原生的 Queue 使用方式完全一致。当通过这个队列传递 PyTorch 的 Tensor 时,其数据会被自动移到共享内存,只传递一个句柄,从而实现零拷贝传输。它用于在一个新的子进程中运行指定的函数。在 test_leaf_variable_sharing 方法中被调用,因此可以验证 test_leaf_variable_sharing 的效果,达到对QueueAPI的测试验证。 >8.torch.multiprocessing.set_sharing_strategy: >set_sharing_strategy用于设置 CPU Tensor 在不同进程间共享时所使用的策略。在test_multiprocessing.py 文件中TestMultiprocessing类中的test_fs_sharing方法中被调用,可通过测试该函数的方式测试 API set_sharing_strategy。test_fs_sharing方法在fs_sharing()的限制条件下调用了自有函数 self.\_test_sharing,而 fs_sharing() 方法调用了API set_sharing_strategy fs_sharing作为上下文管理器调用 api set_sharing_strategy,临时将多进程共享策略设置为 "file_system",执行测试代码后恢复原来的共享策略 >9.torch.multiprocessing.SimpleQueue: >一个简化版的 Queue,它提供了基本的 put 和 get 方法,但内部不使用任何额外的线程。在某些复杂的多线程环境中,这有助于避免因线程竞争导致的死锁问题。其被 test_non_leaf_variable_sharing 方法调用,可测试此方法来验证 SimpleQueue API 的功能。test_non_leaf_variable_sharing 方法验证在多进程场景下,PyTorch中带有梯度信息的张量(requires_grad=True)不能被序列化并通过SimpleQueue在进程间传递的行为。 >10.torch.multiprocessing.start_processes >用于弹性的分布式训练。不仅能启动函数,还能启动二进制文件作为子进程,并提供更完善的日志重定向和管理功能。在test_multiprocessing_spawn.py 文件_TestMultiProcessing类中被多次调用,可以通过验证该方法,达到验证 start_processes API的作用。 >11.torch.finfo: >用于获取浮点数类型数值属性的 API。官网已有测试用例,用例验证了 PyTorch NPU后端的浮点信息类在数值精度、范围和属性方面与CPU NumPy实现的一致性,同时覆盖了特殊浮点格式的正确实现。它确保了跨设备(NPU vs CPU)和跨框架(PyTorch vs NumPy)的浮点属性一致性。 >12.torch.iinfo: >用于获取整型数类型数值属性的 API。官网已有测试用例,用例验证了PyTorch NPU后端的整数信息类在位数、取值范围和类型标识方面与CPU NumPy实现的一致性。与finfo测试一起,完整覆盖了PyTorch数值类型系统的基本信息查询功能。 二、测试用例完备性说明 PyTorch 社区原生测试用例(test_multiprocessing.py)对上述 前10个 API 实现全维度场景覆盖,核心验证内容如下: 1. torch.multiprocessing.Queue / SimpleQueue:进程间 tensor 传递、阻塞获取超时、空/满队列状态校验;混合数据类型(float/byte)顺序读写及事件同步机制验证。 2. torch.multiprocessing.Process:子进程 tensor 原地修改(add_)、daemon 模式、join 超时及异常退出码校验;多进程生命周期管理与资源回收验证。 3. torch.multiprocessing.Pool:多 worker 并行执行 tensor 填充映射(map),跨进程结果汇总及 worker 进程 PID 追踪;池关闭与等待逻辑验证。 4. torch.multiprocessing.get_context:spawn/fork 上下文切换下的 IPC、autograd 错误隔离、参数序列化兼容性验证;多 NPU 设备上下文隔离测试。 5. torch.multiprocessing.set_sharing_strategy:文件描述符(fd)与文件系统(fs)两种策略下的 tensor 共享、shm 残留检测、存储持久化行为对比验证。 6. torch.multiprocessing.reductions.rebuild_cuda_tensor:untyped storage 跨进程重建、storage 句柄/偏移/大小等元数据完整还原;多 device 下 tensor chunk 拆分与合并验证。 7. torch.multiprocessing._set_thread_name / _get_thread_name:Linux 平台下线程名称读写功能验证(依赖 prctl)。 PyTorch 社区原生测试用例(test_type_info.py)对上述 后 2 个 API 实现全维度场景覆盖,核心验证内容如下: 1. 获取全量浮点数类型数值属性的 API 2. 获取全量整型数类型数值属性的 API 三、API适配 主要分为以下3个级别的适配: 1. 不涉及张量操作、及硬件强绑定操作时:不修改,完全复用原生实现 。 2. 张量操作由 .cuda() 操作改写为 .npu() 操作,npu 已适配的 api 进行替换。 3. 当前场景不适合或有条件限制的的用例,增加条件判断,不适合则跳过。 功能验证: root@k8s-node1:/home/torch_2.9.0/pytorch/test# python test_multiprocessing.py TestMultiprocessing.test_set_thread_name -v test_set_thread_name (__main__.TestMultiprocessing.test_set_thread_name) ... ok ---------------------------------------------------------------------- Ran 1 test in 0.865s OK root@k8s-node1:/home/torch_2.9.0/pytorch/test# python test_multiprocessing.py TestMultiprocessing.test_fd_pool -v test_fd_pool (__main__.TestMultiprocessing.test_fd_pool) ... ok ---------------------------------------------------------------------- Ran 1 test in 39.361s OK root@k8s-node1:/home/torch_2.9.0/pytorch/test# python test_multiprocessing_spawn.py ..... ---------------------------------------------------------------------- Ran 31 tests in 226.550s OK root@k8s-node1:/home/torch_2.9.0/pytorch/test# python test_multiprocessing.py TestMultiprocessing.test_leaf_variable_sharing -v test_leaf_variable_sharing (__main__.TestMultiprocessing.test_leaf_variable_sharing) ... ok ---------------------------------------------------------------------- Ran 1 test in 29.204s OK root@k8s-node1:/home/torch_2.9.0/pytorch/test# python test_multiprocessing.py TestMultiprocessing.test_fs_sharing -v test_fs_sharing (__main__.TestMultiprocessing.test_fs_sharing) ... ok ---------------------------------------------------------------------- Ran 1 test in 52.557s OK root@k8s-node1:/home/torch_2.9.0/pytorch/test# python test_multiprocessing.py TestMultiprocessing.test_non_leaf_variable_sharing -v test_non_leaf_variable_sharing (__main__.TestMultiprocessing.test_non_leaf_variable_sharing) ... ok ---------------------------------------------------------------------- Ran 1 test in 1.270s OK root@k8s-node1:/home/torch_2.9.0/pytorch/test# python test_type_info.py TestDTypeInfo.test_finfo . ---------------------------------------------------------------------- Ran 1 test in 1.309s OK root@k8s-node1:/home/torch_2.9.0/pytorch/test# python test_type_info.py TestDTypeInfo.test_iinfo . ---------------------------------------------------------------------- Ran 1 test in 1.267s OK ` See merge request: Ascend/pytorch!34039 | 5 个月前 | |
test:update test_nn.test_unflatten npu patch Co-authored-by: m0_73361278<1241425935@qq.com> # message auto-generated for no-merge-commit merge: !36934 merge test-unflatten-2.9.0 into v2.9.0 test:update test_nn.test_unflatten npu patch Created-by: m0_73361278 Commit-by: m0_73361278 Merged-by: ascend-robot Description: <!-- PR描述模板更新日期:20260203 --> # 【合入来源】 > <font color="red">**如有社区issue,请关联issue链接**</font>\ > <font color="red">**请勿携带内部流程信息(需求链接、问题单、内部issue等)**</font> [[Usage]: torch.nn.Sequential.append和torch.nn.Unflatten.NamedShape API适配说明](https://gitcode.com/Ascend/pytorch/issues/2134) - [ ] 需求 - [ ] 问题单 - [ ] issue/工单 - [ ] 重构优化 - [ ] 资料更新 # 【修改方案】 > 请描述修改内容的具体实现,涉及哪些组件之间进行交互,可以用1、2、3、...进行罗列\ > 如果是需求或者重构类的PR,需要补充详细设计文档(说明上下游组件关系、时序图、类图、DFX能力等内容) ## 一、API功能 **1. torch.nn.Sequential.append** torch.nn.Sequential.append 是 nn.Sequential 中用于向顺序容器末尾追加子模块的接口。用户传入一个 nn.Module 对象后,append 会将该模块注册到当前 Sequential 容器的最后位置,使其成为该容器的一部分,并在后续 forward 中按照顺序参与执行。该接口调用本身只进行模块注册和容器结构更新,不执行 Tensor 计算,也不会修改已有子模块的参数或 buffer 内容。 **2. torch.nn.Unflatten.NamedShape** torch.nn.Unflatten.NamedShape 是 nn.Unflatten 中用于描述命名维度展开形状的参数格式。用户在使用命名维度 dim 时,可以通过 (('C', 2), ('H', 5), ('W', 5)) 这类形式同时指定展开后的维度名称和维度大小,Unflatten 会根据该 NamedShape 将原命名维度展开为多个新的命名维度。该机制主要用于命名维度的 shape 描述和元信息解析,不对 Tensor 元素进行数值运算,也不会改变 Tensor 元素本身的取值。 ## 二、测试用例完备性说明 PyTorch 官方社区已有覆盖的测试用例,位于 test/目录: | API | 测试文件 | 原测试文件所在行 | 覆盖情况 | |--|--|--|--| | torch.nn.Sequential.append | test_nn.py | 846-855 | 直接覆盖:在 test_Sequential_append 中验证了 torch.nn.Sequential.append 的基本功能,即向已有 Sequential(l1, l2, l3) 末尾追加 l4 后,容器结构变为 Sequential(l1, l2, l3, l4)。同时通过 n2 = n.append(l4) 验证了 append 返回追加后的 Sequential 对象本身。<br>间接覆盖:通过 nn.Sequential(l1).append(l2).append(l4) 验证了 append 支持链式调用,说明该接口返回值可以继续调用 append,并且多次追加后模块顺序保持正确。 | | torch.nn.Unflatten.NamedShape | test_nn.py | 7117-7161 | 直接覆盖:在 test_unflatten 中通过 dim='features' 和 unflattened_size=(('C', 2), ('H', 5), ('W', 5)) 验证了 Unflatten.NamedShape 的基本正向场景,即支持将命名维度 features 展开为目标形状 [2, 2, 5, 5]。在 test_unflatten_invalid_arg 中验证了 NamedShape 的部分非法参数校验,包括外层不能是 list,内部元素不能是 list 或 dict。<br>间接覆盖:在 test_unflatten 中通过 NamedTensor 输入和 dim='features' 的配合,验证了 NamedShape 与命名维度展开流程可以正常使用。在 test_unflatten_invalid_arg 中通过 dim='features' 触发 NamedShape 参数校验路径,验证其 tuple of tuples 的结构要求。 | ## 三、npu适配 **API适配:** torch.nn.Sequential.append 接口调用本身仅完成子模块注册和容器结构更新,不涉及 Tensor 计算或 NPU device dispatch。 torch.nn.Unflatten.NamedShape 主要属于命名维度和 shape 元信息处理逻辑,不涉及 Tensor 元素数值计算,也不改变 Tensor 元素取值。 因此,API适配无需修改 **测试用例适配:** 两个API均存在 NPU 场景下的功能使用,因此对测试用例进行NPU适配,社区已有patch PR合并如下: **test_nn.py:** v2.7.1[add test_nn upstream npu patch](https://gitcode.com/Ascend/pytorch/pull/35668) v2.9.0[add test_nn upstream npu patch](https://gitcode.com/Ascend/pytorch/pull/35669) v2.10.0[add test_nn upstream npu patch](https://gitcode.com/Ascend/pytorch/pull/35670) v2.11.0[add test_nn upstream npu patch](https://gitcode.com/Ascend/pytorch/pull/35671) v2.12.0[test: add upstream npu patch files for 2.12](https://gitcode.com/Ascend/pytorch/pull/36541) 在社区patch基础上,对test_unflatten(self)进行如下npu适配 def test_unflatten(self): - tensor_input = torch.randn(2, 50) + tensor_input = torch.randn(2, 50, device="npu") # 【资料变更】 > 请确认是否涉及资料变更。如涉及,需要在PR中体现,并简要说明修改内容。如不涉及,需填写“不涉及” 在docs/zh/native_apis/pytorch_2-7-1,docs/zh/native_apis/pytorch_2-9-0,docs/zh/native_apis/pytorch_2-10-0文档中添加了如下内容: |torch.nn.Unflatten.NamedShape|是|-| # 【接口变更】 > 请确认是否涉及跨代码仓或者客户面可见的接口变更。如涉及,需要详细说明接口以及对应的变更内容,同时需要在资料中体现。如不涉及,需填写“不涉及” 不涉及 # 【功能验证】 > 说明测试场景,测试方法。如果本次测试方式与常规单元测试不同,请详细说明您的测试步骤\ > 新增/变更内容是否已新增/适配UT测试用例看护,并补充测试自验证截图 git apply patch后torch-npu NPU 环境验证结果 | API | 运行命令 | v2.7.1 | v2.9.0 | v2.10.0 | v2.11.0 | v2.12.0 | |--|--|--|--|--|--|--| | torch.nn.Sequential.append | python -m unittest test_nn.TestNN.test_Sequential_append | Ran 1 test in 0.006s<br><br>OK | Ran 1 test in 0.006s<br><br>OK | Ran 1 test in 0.006s<br><br>OK | Ran 1 test in 0.006s<br><br>OK | Ran 1 test in 0.006s<br><br>OK | | torch.nn.Unflatten.NamedShape | python -m unittest test_nn.TestNN.test_unflatten test_nn.TestNN.test_unflatten_invalid_arg | Ran 1 test in 0.010s<br><br>OK | Ran 1 test in 0.011s<br><br>OK | Ran 1 test in 0.009s<br><br>OK | Ran 1 test in 0.010s<br><br>OK | Ran 1 test in 0.010s<br><br>OK | # 【CheckList】 > PR提交人对以下CheckList自检项进行全量自检,自检通过或不涉及,均修改 [ ] 为 [x] - [ ] 代码注释完备,正确记录错误日志 - [ ] 代码实现进行了返回值、空指针等校验 - [ ] PR标题正确使用类型标签,如:feat、fix、refactor、docs、test等 - [ ] PR持续集成流水线(CI)执行通过,代码检查无异常 See merge request: Ascend/pytorch!36934 | 5 个月前 | |
test(overrides): adapt override tests on NPU Co-authored-by: Jinfan Liu<1300083451@qq.com> # message auto-generated for no-merge-commit merge: !36096 merge test-overrides-npu-v2.9.0 into v2.9.0 test(overrides): adapt override tests on NPU Created-by: JfanLiu Commit-by: Jinfan Liu Merged-by: ascend-robot Description: <!-- PR描述模板更新日期:20260203 --> # 【合入来源】 > <font color="red">**https://gitcode.com/Ascend/pytorch/issues/2006**</font>\ > <font color="red">**请勿携带内部流程信息(需求链接、问题单、内部issue等)**</font> [ ] 问题单 # 【修改方案】 一、API功能说明 本 PR 覆盖以下 API: - torch.overrides.get_ignored_functions - torch.overrides.get_overridable_functions - torch.overrides.get_testing_overrides - torch.overrides.handle_torch_function - torch.overrides.has_torch_function - torch.overrides.is_tensor_method_or_property - torch.overrides.resolve_name - torch.overrides.wrap_torch_function 上述 API 属于 PyTorch __torch_function__ override 机制:has_torch_function / handle_torch_function 负责 Tensor-like 对象检测与分发;get_overridable_functions / get_testing_overrides / get_ignored_functions 负责 override 覆盖面管理;is_tensor_method_or_property / resolve_name 用于测试生成和名称解析;wrap_torch_function 用于为 Python 函数包装 override 分发逻辑。 二、测试用例完备性说明 PyTorch 官方 test/test_overrides.py 是 override 机制集中测试文件,本 PR 复用社区用例: 1. foo、bar、baz、quux 等 helper 直接调用 has_torch_function 和 handle_torch_function,覆盖 Tensor-like 分发、类型优先级、NotImplemented 和异常路径。 2. generate_tensor_like_torch_implementations 和自动生成用例基于 get_overridable_functions 与 get_testing_overrides 枚举可覆盖 API,验证 override registry 的完整性。 3. get_ignored_functions、get_overridable_functions、get_testing_overrides 的完整性/告警检查会遍历 registry 和测试 override 表,确认 PyTorch upstream 可覆盖函数均有对应测试 override 或明确忽略。 4. test_resolve_name 直接验证 resolve_name;test_wrap_torch_function 直接验证 wrap_torch_function;warning 测试直接覆盖 is_tensor_method_or_property 等辅助接口。 5. 本 PR 在不改变 override 测试目标的前提下,将部分普通 Tensor 构造迁移到 NPU,覆盖 test_mm_semantics、TestDisabledTorchFunction、TorchFunctionMode stack/reentrant 等路径中的 NPU Tensor 行为。 三、NPU适配方案 1. API 源码无需修改:上述 API 是 Python 层 override 协议和函数注册表逻辑,不涉及 NPU kernel、设备内存、通信后端或 stream/event 语义。 2. registry 过滤:torch-npu 环境会在 import torch 时注入 NPU 扩展函数,原生 test/test_overrides.py 的 PyTorch override completeness 检查面向 upstream PyTorch API,不应把 torch-npu 私有/扩展函数作为 upstream override 测试目标。本 PR 只窄范围排除 patched_to_dlpack、patched_from_dlpack、dropout_with_byte_mask、type,并跳过 torch_npu.distributed.distributed_c10d._gather 的 TensorLike 自动生成用例。 3. NPU Tensor 迁移:将 test_mm_semantics 中的 torch.eye、TestDisabledTorchFunction 中的 Parameter/module 输入、TorchFunctionMode stack/reentrant 场景中的 torch.randn 迁移到 NPU,验证 NPU Tensor 参与 override 相关路径时检测、分发和模式栈行为稳定。 4. 分支处理:2.9.0 分支原无 test_upstream/test/test_overrides.py.patch,本 PR 新增该 patch,使社区 test/test_overrides.py 在 NPU 环境下整文件通过。 # 【资料变更】 > 已检查 v2.7.1 docs/zh/native_apis 中各版本 torch-overrides.md,以及 v2.12.0 docs/api/torch_npu_apis.md。torch.overrides.get_ignored_functions、torch.overrides.get_overridable_functions、torch.overrides.get_testing_overrides、torch.overrides.handle_torch_function、torch.overrides.has_torch_function、torch.overrides.is_tensor_method_or_property、torch.overrides.resolve_name、torch.overrides.wrap_torch_function 均已列入 API 支持列表。本次只适配测试用例,不涉及资料补充。 # 【接口变更】 > 不涉及。API 源码无修改,不新增、删除或变更对外接口。 # 【功能验证】 > 已在 2.9.0 torch-npu 环境应用本 PR 改动后执行 PyTorch 社区整文件用例,结果如下: bash # 在 PyTorch 源码根目录先放置本 PR 中的 test_upstream 目录,并应用对应 patch patch -p1 < test_upstream/test/test_overrides.py.patch python test/test_overrides.py Ran 1480 tests in 3.324s OK See merge request: Ascend/pytorch!36096 | 4 个月前 | |
Add ShapeEnv symbolic shapes API tests Co-authored-by: nannan-2026<1794949109@qq.com> # message auto-generated for no-merge-commit merge: !36571 merge test-shape-env-symbolic-shapes-v2.9.0 into v2.9.0 Add ShapeEnv symbolic shapes API tests Created-by: nannan-2026 Commit-by: nannan-2026 Merged-by: ascend-robot Description: # 【合入来源】 > <font color="red">**如有社区issue,请关联issue链接**</font>\ > <font color="red">**请勿携带内部流程信息(需求链接、问题单、内部issue等)**</font> - [ ] 需求 - [ ] 问题单 - [x] issue/工单 - [ ] 重构优化 - [ ] 资料更新 关联 issue:https://gitcode.com/Ascend/pytorch/issues/1622 # 【修改方案】 > 请描述修改内容的具体实现,涉及哪些组件之间进行交互,可以用1、2、3、...进行罗列\ > 如果是需求或者重构类的PR,需要补充详细设计文档(说明上下游组件关系、时序图、类图、DFX能力等内容) 本 PR 针对 torch.fx.experimental.symbolic_shapes.ShapeEnv 相关 PyTorch 原生 API 补充 Torch-NPU 侧测试验证,覆盖如下 API: - torch.fx.experimental.symbolic_shapes.ShapeEnv.create_symbolic_sizes_strides_storage_offset - torch.fx.experimental.symbolic_shapes.ShapeEnv.create_symboolnode - torch.fx.experimental.symbolic_shapes.ShapeEnv.create_symfloatnode - torch.fx.experimental.symbolic_shapes.ShapeEnv.create_symintnode - torch.fx.experimental.symbolic_shapes.ShapeEnv.create_unbacked_symbool 本 PR 仅涉及测试用例补齐与上游用例 NPU 适配,不修改 torch_npu/ 功能代码,不新增 NPU 算子实现,不改变现有 API 行为。 ## 一、API 功能说明 1. torch.fx.experimental.symbolic_shapes.ShapeEnv.create_symbolic_sizes_strides_storage_offset 该 API 用于根据输入 Tensor 创建符号化的 size、stride 和 storage offset 信息,是 PyTorch dynamic shape / symbolic shape 相关逻辑中的基础能力之一。 2. torch.fx.experimental.symbolic_shapes.ShapeEnv.create_symboolnode 该 API 用于根据 symbolic boolean expression 创建 torch.SymBool,用于表达符号化布尔条件。 3. torch.fx.experimental.symbolic_shapes.ShapeEnv.create_symfloatnode 该 API 用于根据 symbolic float expression 创建 torch.SymFloat,用于表达符号化浮点值。 4. torch.fx.experimental.symbolic_shapes.ShapeEnv.create_symintnode 该 API 用于根据 symbolic integer expression 创建 torch.SymInt,用于表达符号化整数值。 5. torch.fx.experimental.symbolic_shapes.ShapeEnv.create_unbacked_symbool 该 API 用于创建 unbacked symbolic bool,不依赖具体 Tensor shape 的已绑定实际值,属于 symbolic shape 相关能力。 ## 二、上游社区用例分析与用例补齐说明 经检索 PyTorch 上游社区测试用例,本次涉及 API 的上游覆盖情况如下: 1. torch.fx.experimental.symbolic_shapes.ShapeEnv.create_symbolic_sizes_strides_storage_offset PyTorch 上游社区已有相关测试,位于 test/dynamo/test_misc.py。因此本 PR 按照 Torch-NPU test_upstream 机制,对该上游用例进行 NPU 适配,并提交 patch: - test_upstream/test/dynamo/test_misc.py.patch 2. torch.fx.experimental.symbolic_shapes.ShapeEnv.create_unbacked_symbool PyTorch 上游社区已有相关测试,位于 test/dynamo/test_misc.py。因此本 PR 同样通过如下 patch 对上游用例进行 NPU 适配: - test_upstream/test/dynamo/test_misc.py.patch 3. torch.fx.experimental.symbolic_shapes.ShapeEnv.create_symintnode PyTorch 上游社区已有相关测试,位于 test/test_python_dispatch.py。因此本 PR 按照 Torch-NPU test_upstream 机制,对该上游用例进行 NPU 适配,并提交 patch: - test_upstream/test/test_python_dispatch.py.patch 4. torch.fx.experimental.symbolic_shapes.ShapeEnv.create_symboolnode 经检索,PyTorch 上游社区中未发现该 API 充分、直接的专项验证用例。 5. torch.fx.experimental.symbolic_shapes.ShapeEnv.create_symfloatnode 经检索,PyTorch 上游社区中未发现该 API 充分、直接的专项验证用例。 因此,本 PR 对上游已有用例的 API 提交 test_upstream patch,对上游缺少充分直接验证的 API 新增本地专项测试文件: - test/fx/experimental/test_symbolic_shapes.py ## 三、test_upstream patch 新增说明 在 v2.9.0 分支中,经检查当前 test_upstream 目录下未发现以下相关 patch: - test_upstream/test/dynamo/test_misc.py.patch - test_upstream/test/test_python_dispatch.py.patch 因此,本 PR 基于 PyTorch 官方 v2.9.0 上游测试文件生成新的 NPU 适配 patch。 本次新增 patch 文件如下: - test_upstream/test/dynamo/test_misc.py.patch - test_upstream/test/test_python_dispatch.py.patch patch 文件均通过 git diff -U0 生成,未手动编辑 patch 文件。 ## 四、新增测试文件说明 本 PR 新增测试文件: - test/fx/experimental/test_symbolic_shapes.py 该文件用于集中验证 torch.fx.experimental.symbolic_shapes.ShapeEnv 相关 API 的基础兼容性。文件开头已补充英文说明,说明该文件用于补充 ShapeEnv symbolic shape API 的 NPU 侧验证用例,并可继续扩展同类 API 测试。 文件开头说明如下: """ Add validation cases for torch.fx.experimental.symbolic_shapes.ShapeEnv APIs on NPU: 1. PyTorch community lacks sufficient and direct API validations for these APIs, so this file is added. 2. This file validates ShapeEnv.create_symboolnode and ShapeEnv.create_symfloatnode. 3. This file is extendable for other torch.fx.experimental.symbolic_shapes.ShapeEnv APIs. """ 新增测试覆盖以下场景: 1. torch.fx.experimental.symbolic_shapes.ShapeEnv.create_symboolnode 基础行为验证 通过 NPU Tensor 的 shape metadata 构造 symbolic expression,调用 ShapeEnv.create_symboolnode 创建 torch.SymBool,并验证返回类型和布尔结果。 2. torch.fx.experimental.symbolic_shapes.ShapeEnv.create_symfloatnode 基础行为验证 通过 NPU Tensor 的 shape metadata 构造 symbolic expression,调用 ShapeEnv.create_symfloatnode 创建 torch.SymFloat,并验证返回类型和具体数值结果。 ## 五、NPU 适配说明 本次涉及的 API 均属于 torch.fx.experimental.symbolic_shapes.ShapeEnv Python 层 symbolic shape 相关接口,不涉及新增 NPU 算子实现,也不涉及 C++、Kernel 或底层算子逻辑修改。 但测试用例中涉及 Tensor,因此需要确保测试 Tensor 运行在 NPU / 当前 accelerator 侧。 ### 1. 上游用例 NPU 适配 针对 test/dynamo/test_misc.py 中 torch.fx.experimental.symbolic_shapes.ShapeEnv.create_symbolic_sizes_strides_storage_offset 相关用例,将原 CPU Tensor: torch.randn(3, 2) 适配为 NPU Tensor: torch.randn(3, 2).npu() 针对 test/test_python_dispatch.py 中 torch.fx.experimental.symbolic_shapes.ShapeEnv.create_symintnode 相关用例,新增 NPU Tensor 作为 shape metadata 来源: tensor = torch.ones(123).npu() 并将原固定整数输入: 123 hint=123 调整为来源于 NPU Tensor shape: tensor.size(0) hint=tensor.size(0) ### 2. 新增本地测试 NPU 适配 新增本地测试文件中使用如下方式获取当前 accelerator: device_type = acc.type if (acc := torch.accelerator.current_accelerator()) else "cpu" 并通过如下方式将测试 Tensor 迁移到当前设备: tensor = torch.ones(2, 3).to(device_type) 在 Torch-NPU 测试环境中,当前 accelerator 为 NPU,因此测试 Tensor 会通过 .to(device_type) 迁移到 NPU 侧运行,满足新增用例涉及 Tensor 必须运行在 NPU 侧的要求。 ## 六、涉及版本说明 本次用例补齐分别提交到以下目标分支: - v2.7.1 - v2.9.0 - v2.10.0 - v2.11.0 - v2.12.0 - master 各版本均单独提交 PR,目标分支与源码分支一一对应。 本 PR 为 v2.9.0 分支对应的测试 PR。 说明: 1. release 分支提交 test_upstream patch 和本地测试; 2. master 分支不提交 test_upstream patch,仅提交本地测试; 3. 文档资料补齐通过单独文档 PR 提交到 v2.7.1 分支; 4. 本次根据当前任务要求提交上述分支,不涉及 v2.8.0 分支。 # 【资料变更】 > 请确认是否涉及资料变更。如涉及,需要在PR中体现,并简要说明修改内容。如不涉及,需填写“不涉及” 不涉及。 本 PR 仅补齐测试用例,不直接修改 docs/zh/native_apis 资料文档。 资料支持情况已同步检查: 1. 本次涉及的 API 均属于 torch.fx.experimental.symbolic_shapes.ShapeEnv 下的 Python 层 symbolic shape 相关接口; 2. 经检查,相关 API 在 docs/zh/native_apis 中需要补充支持状态记录; 3. 本测试 PR 仅负责补齐 test_upstream patch 与 test/fx/experimental/test_symbolic_shapes.py 测试用例,不直接修改资料文档; 4. 相关 API 的 docs/zh/native_apis 支持状态通过单独资料 PR 补充; 5. 文档 PR 仅提交到 v2.7.1 分支,并刷新 docs/zh/native_apis 下要求版本的 API 支持状态。 配套文档 PR: - 待补充:Add ShapeEnv symbolic shapes API documentation # 【接口变更】 > 请确认是否涉及跨代码仓或者客户面可见的接口变更。如涉及,需要详细说明接口以及对应的变更内容,同时需要在资料中体现。如不涉及,需填写“不涉及” 不涉及。 本 PR 不修改客户可见接口,不修改 API 行为,仅新增 / 适配测试用例验证现有 API 兼容性。 # 【功能验证】 > 说明测试场景,测试方法。如果本次测试方式与常规单元测试不同,请详细说明您的测试步骤\ > 新增/变更内容是否已新增/适配UT测试用例看护,并补充测试自验证截图 新增 / 适配测试内容: - test_upstream/test/dynamo/test_misc.py.patch - test_upstream/test/test_python_dispatch.py.patch - test/fx/experimental/test_symbolic_shapes.py 测试场景: 1. 验证 torch.fx.experimental.symbolic_shapes.ShapeEnv.create_symbolic_sizes_strides_storage_offset 上游用例中的 Tensor 输入已适配为 NPU Tensor; 2. 验证 torch.fx.experimental.symbolic_shapes.ShapeEnv.create_unbacked_symbool 所在上游用例路径可与 NPU Tensor 适配后的 ShapeEnv 测试共同覆盖; 3. 验证 torch.fx.experimental.symbolic_shapes.ShapeEnv.create_symintnode 上游用例中的 symbolic value 和 hint 来源于 NPU Tensor shape metadata; 4. 验证 torch.fx.experimental.symbolic_shapes.ShapeEnv.create_symboolnode 可基于 NPU Tensor shape metadata 创建 torch.SymBool; 5. 验证 torch.fx.experimental.symbolic_shapes.ShapeEnv.create_symfloatnode 可基于 NPU Tensor shape metadata 创建 torch.SymFloat; 6. 验证新增测试中涉及的 Tensor 已通过 .to(device_type) 迁移到当前 accelerator / NPU 侧运行。 本地验证命令: cd /tmp python /root/torch_npu_api_task/pytorch-v2.9.0/test/fx/experimental/test_symbolic_shapes.py 本地验证结果: .. ---------------------------------------------------------------------- Ran 2 tests in 1.212s OK 说明: 该组 API 为 torch.fx.experimental.symbolic_shapes.ShapeEnv Python 层 symbolic shape 相关接口,不涉及 NPU 算子计算。本次测试主要验证 API 功能行为与 PyTorch 原生保持一致,同时确保测试中涉及的 Tensor 运行在当前 accelerator / NPU 侧。 # 【CheckList】 > PR提交人对以下CheckList自检项进行全量自检,自检通过或不涉及,均修改 [ ] 为 [x] - [x] 代码注释完备,正确记录错误日志 - [x] 代码实现进行了返回值、空指针等校验 - [x] PR标题正确使用类型标签,如:feat、fix、refactor、docs、test等 - [ ] PR持续集成流水线(CI)执行通过,代码检查无异常 See merge request: Ascend/pytorch!36571 | 5 个月前 | |
fix(npu): add minimal pytree test patch Co-authored-by: whirlpool_dark<kk2425597323@126.com> # message auto-generated for no-merge-commit merge: !36552 merge patch-pytree-api-v2.9.0 into v2.9.0 fix(npu): add minimal pytree test patch Created-by: whirlpool_dark Commit-by: whirlpool_dark Merged-by: ascend-robot Description: # test(npu): add minimal pytree test patch 【合入来源】 [[Usage]: 官方社区用例对 torch.utils._pytree 相关 API 适配不完整,部分版本缺少 patch,且不应依赖 transfer_to_npu](https://gitcode.com/Ascend/pytorch/issues/2080) 【修改方案】 一、API 功能 本次检查的 API 均来自 PyTorch 原生 torch.utils._pytree,属于框架层 Python pytree 结构处理能力,不需要 torch-npu 增加 NPU 专属源码实现。 本次涉及的 API 如下: 1. torch.utils._pytree._dict_flatten 用于将 dict 节点展开为 value 列表和 key 上下文。该方法保留字典遍历顺序,供 tree_flatten 生成 TreeSpec 时记录重建所需的 key 信息。 2. torch.utils._pytree._dict_flatten_with_keys 用于在展开 dict 节点时同时生成 key path 信息。返回值中的 key 使用 MappingKey 表示,可供 tree_flatten_with_path、tree_map_with_path 等路径感知 API 使用。 3. torch.utils._pytree._dict_unflatten 用于根据 flat values 和 key context 重建 dict 节点,是 _dict_flatten 的反向操作,保证 pytree 展开和还原行为一致。 4. torch.utils._pytree._get_node_type 用于识别 pytree 节点类型,例如 dict、list、tuple、namedtuple 等,辅助判断当前对象应按容器节点处理还是按叶子节点处理。 5. torch.utils._pytree._is_leaf 用于判断对象是否为 pytree 叶子节点。该方法支持用户传入 is_leaf 自定义逻辑,保证特殊对象可按调用方需求终止递归展开。 6. torch.utils._pytree.MappingKey 用于表示 mapping 类型节点中的 key path 元素,支撑 tree_flatten_with_path、tree_leaves_with_path、key_get、keystr 等路径相关能力。 7. torch.utils._pytree.tree_iter 用于按 pytree 结构递归遍历叶子节点,并支持 is_leaf 参数控制遍历边界。 二、测试用例完备性说明 PyTorch 官方社区 test/test_pytree.py 已覆盖 torch.utils._pytree 的主要功能场景,包括: 1. 基础容器类型的 flatten / unflatten 行为验证,例如 tuple、list、dict、OrderedDict、defaultdict、deque、namedtuple; 2. 嵌套 pytree 结构的 tree_flatten、tree_unflatten、tree_map、tree_all、tree_any 等行为验证; 3. TreeSpec 的序列化、反序列化、相等性、repr 等行为验证; 4. key path 相关 API 验证,包括 tree_map_with_path、tree_flatten_with_path、tree_leaves_with_path、MappingKey、key_get、keystr; 5. is_leaf 自定义叶子判断逻辑验证; 6. Python pytree 与 C++ pytree public API 对齐验证。 具体到本次关注的 API,官方用例调用关系如下: 1. torch.utils._pytree._dict_flatten 在 TestGenericPytree.test_flatten_unflatten_dict 中,通过 pytree.tree_flatten(dct) 间接调用。用例断言展开后的 flat values 等于 list(dct.values()),并检查生成的 TreeSpec 与预期一致,从而验证 dict 节点按 value 顺序展开且 key 上下文被正确记录。 2. torch.utils._pytree._dict_unflatten 在 TestGenericPytree.test_flatten_unflatten_dict 中,通过 pytree.tree_unflatten(values, treespec) 间接调用。用例断言还原结果与原始 dict 一致,且类型仍为 dict,从而验证 _dict_flatten 记录的 key 上下文可以正确用于重建 dict。 3. torch.utils._pytree._dict_flatten_with_keys 在 TestPythonPytree.test_tree_map_with_path、TestPythonPytree.test_tree_flatten_with_path_roundtrip、TestPythonPytree.test_tree_leaves_with_path、TestPythonPytree.test_flatten_flatten_with_key_consistency 中,通过 tree_map_with_path(...)、tree_flatten_with_path(...)、tree_leaves_with_path(...) 间接调用。用例验证带 key path 的展开结果与普通 flatten 的 leaves / spec 一致,并验证带路径展开后的 leaves 可以通过 tree_unflatten 还原原始 pytree。 4. torch.utils._pytree._get_node_type 在 TestGenericPytree.test_flatten_unflatten_dict、TestGenericPytree.test_flatten_unflatten_nested 等用例中,通过 tree_flatten(...) 识别 dict、list、tuple 等节点类型间接调用。用例通过不同容器和嵌套结构的 flatten / unflatten 结果验证节点类型识别正确。 5. torch.utils._pytree._is_leaf 在 TestGenericPytree.test_flatten_unflatten_leaf、TestGenericPytree.test_flatten_with_is_leaf 以及 TestPythonPytree.test_tree_flatten_with_path_is_leaf 中,通过 tree_flatten(..., is_leaf=...) 和 tree_flatten_with_path(..., is_leaf=...) 间接调用。用例验证自定义 is_leaf 能按预期终止递归展开,并使指定对象整体作为叶子节点处理。 6. torch.utils._pytree.MappingKey 在 TestPythonPytree.test_tree_map_with_path、TestPythonPytree.test_tree_leaves_with_path、TestPythonPytree.test_key_str、TestPythonPytree.test_key_access 中,通过 tree_flatten_with_path(...) 生成 dict key path,再通过 keystr(kp) 和 key_get(tree, kp) 验证 key path 的字符串表示和按路径取值能力,从而覆盖 mapping key path 的构造与访问语义。 7. torch.utils._pytree.tree_iter 在 TestGenericPytree.test_tree_map、TestGenericPytree.test_tree_all_any 中,通过 tree_leaves(...)、tree_all(...)、tree_any(...) 间接调用。tree_leaves 会调用 list(tree_iter(...)) 获取叶子节点,tree_all 和 tree_any 也会基于 tree_iter 遍历叶子节点后执行谓词判断,因此可以覆盖 tree_iter 的递归遍历和 is_leaf 边界控制能力。 上述测试内容可直接用于验证本次关注的 pytree API。官方用例中部分 Tensor 作为 pytree 叶子节点参与结构验证,本次将可直接迁移的 torch.tensor、torch.randn、torch.rand、torch.ones、torch.zeros 调用改为 .npu()。该迁移不改变 pytree API 的验证目标,只保证用例中的 Tensor 运行在 NPU 上。 三、API 适配 3.1 API 适配:无源码修改,复用 PyTorch 原生实现 本次涉及的 torch.utils._pytree API 均为 PyTorch 原生框架层实现。torch-npu 不需要为这些 API 增加 NPU 专属源码适配。 这些 API 的执行逻辑主要围绕 Python 对象递归、容器展开、TreeSpec 构造、key path 记录和叶子节点判断,不依赖 CUDA 或 NPU 后端。 3.2 测试用例适配:迁移 Tensor 到 NPU,并保留必要 skip v2.9.0 分支此前没有 test_upstream/test/test_pytree.py.patch。本次新增该 patch,用于复用 PyTorch 官方社区 test/test_pytree.py 对 pytree API 的既有验证。 因此本次 v2.9.0 修改为: 1. 新增 test_upstream/test/test_pytree.py.patch; 2. 将官方用例中可直接迁移的 Tensor factory 调用改为 .npu(); 3. 跳过 test_import_pytree_doesnt_import_optree。 跳过test_import_pytree_doesnt_import_optree的原因是该用例验证的是 PyTorch upstream 对 torch.utils._pytree、torch.utils._cxx_pytree、optree 的导入边界,在 torch-npu 适配测试环境中,运行时存在额外的初始化逻辑,提前导入该用例检查的模块。跳过该用例不影响功能检验。 【资料变更】 不涉及。 本次检查的api属于私有接口,资料不需要补充。 【接口变更】 不涉及。 本次不修改 torch.utils._pytree API 源码,不新增、不删除、不变更 Python 对外接口。 【功能验证】 一、patch 静态校验 v2.9.0 patch 可正常应用到 PyTorch 官方 v2.9.0 的 test/test_pytree.py,应用后可通过 Python 语法检查: bash git apply --check test_upstream/test/test_pytree.py.patch python3 -m py_compile test/test_pytree.py 二、用例执行验证 在昇腾云算力环境执行 v2.9.0 test_pytree.py: bash python3 ./api_consistency_workspace/pytorch_official_v2.9.0/test/test_pytree.py text [root@10ea5b5e6c38 workspace]# python3 ./api_consistency_workspace/pytorch_official_v2.9.0/test/test_pytree.py ...................................................................s.............................. ---------------------------------------------------------------------- Ran 98 tests in 0.315s OK (skipped=1) 其中 skipped=1 为预期跳过的 test_import_pytree_doesnt_import_optree,其余 pytree upstream 用例均执行通过。 【CheckList】 PR 提交人对以下 CheckList 自检项进行全量自检,自检通过或不涉及,均修改 [ ] 为 [x] - [x] 代码注释完备,正确记录错误日志 - [x] 代码实现进行了返回值、空指针等校验 - [x] PR 标题正确使用类型标签,如:feat、fix、refactor、docs、test 等 - [x] PR 持续集成流水线(CI)执行通过,代码检查无异常 See merge request: Ascend/pytorch!36552 | 4 个月前 | |
fix(npu):update SummaryWriter test patch; Co-authored-by: Nicet<1849404617@qq.com> # message auto-generated for no-merge-commit merge: !36740 merge v2.9.0 into v2.9.0 fix(npu):update SummaryWriter test patch; Created-by: Nice_try Commit-by: Nicet Merged-by: ascend-robot Description: <!-- PR描述模板更新日期:20260203 --> # 【合入来源】 >**https://gitcode.com/Ascend/pytorch/issues/2103** > <font color="red">**请勿携带内部流程信息(需求链接、问题单、内部issue等)**</font> * [ ] 需求 * [x] 问题单 * [ ] issue/工单 * [ ] 重构优化 * [ ] 资料更新 # 【修改方案】 一、API功能: 1.1 核心 API 功能说明 本次覆盖的 API 属于 torch.utils.tensorboard 模块中的数据记录与可视化 API,核心类为 SummaryWriter。它是 PyTorch 与 TensorBoard 交互的基础设施,其核心功能如下: 1. **数据记录与序列化**:提供丰富的 add_* 接口,能够接收标量(scalar)、图像(image)、音频(audio)、文本(text)、直方图(histogram)、嵌入向量(embedding)等类型的数据,将其序列化为 TensorBoard 可读取的事件文件(Event Files)。 2. **模型计算图追踪**:通过 add_graph 接口,利用 PyTorch 的 JIT 追踪机制(Tracing),解析神经网络的算子节点和数据流向,生成可视化的模型计算图。 3. **资源与生命周期管理**:支持上下文管理器(Context Manager),通过 flush 和 close 方法管理文件句柄和异步写入线程,确保数据完整落盘。 1.2 本次明确覆盖的 API 列表 python torch.utils.tensorboard.SummaryWriter torch.utils.tensorboard.writer.SummaryWriter torch.utils.tensorboard.writer.SummaryWriter.__init__ torch.utils.tensorboard.writer.SummaryWriter.add_audio torch.utils.tensorboard.writer.SummaryWriter.add_embedding torch.utils.tensorboard.writer.SummaryWriter.add_figure torch.utils.tensorboard.writer.SummaryWriter.add_graph torch.utils.tensorboard.writer.SummaryWriter.add_histogram torch.utils.tensorboard.writer.SummaryWriter.add_hparams torch.utils.tensorboard.writer.SummaryWriter.add_images torch.utils.tensorboard.writer.SummaryWriter.add_mesh torch.utils.tensorboard.writer.SummaryWriter.add_pr_curve torch.utils.tensorboard.writer.SummaryWriter.add_scalar torch.utils.tensorboard.writer.SummaryWriter.add_scalars torch.utils.tensorboard.writer.SummaryWriter.add_text torch.utils.tensorboard.writer.SummaryWriter.add_video torch.utils.tensorboard.writer.SummaryWriter.close 二、测试用例完备性说明 PyTorch 原生测试用例(test/test_tensorboard.py 中的 TestTensorBoardWriter、TestTensorBoardPytorchGraph、TestTensorBoardEmbedding 等测试类)对上述 API 进行了全维度的覆盖: 1. **基础记录接口覆盖**:全面测试了标量、直方图、音视频、PR曲线、Mesh、图像、文本以及嵌入向量的序列化写入操作。 2. **模型结构可视化追踪**:通过 test_pytorch_graph 等函数深度测试了不同网络结构(Sequential、字典输入等)的图追踪能力,并验证了在错误输入维度下正确抛出异常且不保存损坏计算图的健壮性。 3. **生命周期与初始化**:测试了通过 pathlib.Path 对象初始化的支持,以及 close 方法和上下文管理器结束时的句柄清理释放机制。 三、API与测试用例适配 3.1 API 适配:无修改,完全复用原生实现 SummaryWriter 及其衍生接口主要负责在前端对 Python 原生数据或 PyTorch Tensor 进行处理,利用底层 tensorboardX 或 protobuf 进行数据序列化落盘。该过程不涉及底层计算硬件的特定强绑定,因此直接复用 PyTorch 原生 API 实现,无任何修改。 3.2 测试用例适配:引入 NPU Patch 以确保设备级数据读取与追踪的一致性 TensorBoard 在提取 PyTorch Tensor(尤其是标量、直方图、嵌入向量和计算图的追踪)时,会读取张量底层内存。为了验证 NPU 环境下(存放于 NPU 设备上的 Tensor)能够被 TensorBoard 模块正确接管、拷贝并完成落盘序列化,而不触发 Device 报错,必须对测试用例进行 NPU 适配: 1. **张量设备重定向**:将测试脚本中用于模拟输入、权重或度量指标的所有张量显式指派到 NPU,例如在初始化时增加 .to("npu") 或 device='npu'。 2. **模块设备重定向**:针对 add_graph 测试,将追踪的神经网络模型显式调用 .npu(),确保网络组件与伪造的输入张量位于同一 NPU 设备上,以验证 NPU JIT 追踪机制的一致性。 3. **覆盖范围**:对上述涉及的 6 大测试类的输入数据进行全量设备重定位,实现测试用例的 NPU 端到端闭环验证。 # 【资料变更】 > 请确认是否涉及资料变更。如涉及,需要在PR中体现,并简要说明修改内容。如不涉及,需填写“不涉及” 经分析,文档中缺少对torch.utils.tensorboard.SummaryWriter接口的支持说明,docs更改pr为: https://gitcode.com/Ascend/pytorch/pull/37108 # 【接口变更】 > 请确认是否涉及跨代码仓或者客户面可见的接口变更。如涉及,需要详细说明接口以及对应的变更内容,同时需要在资料中体现。如不涉及,需填写“不涉及” 不涉及 # 【功能验证】 > 说明测试场景,测试方法。如果本次测试方式与常规单元测试不同,请详细说明您的测试步骤 > 新增/变更内容是否已新增/适配UT测试用例看护,并补充测试自验证截图 **测试场景**:验证 PyTorch SummaryWriter API 系列在处理完全位于 NPU 设备上的张量及模型时,能否正确完成数据读取、JIT 计算图追踪及序列化落盘。 **测试方法**:在昇腾机器上(如 910B3 环境),执行上述打了 NPU Patch 后的单元测试。 验证命令(各分支均已执行): bash python -m unittest test_tensorboard.TestTensorBoardWriter test_tensorboard.TestTensorBoardEmbedding test_tensorboard.TestTensorBoardFigure test_tensorboard.TestTensorBoardPytorchGraph test_tensorboard.TestTensorBoardPyTorchNumpy test_tensorboard.TestTensorBoardSummaryWriter -v v2.7.1 text Ran 19 tests in 50.887s OK v2.9.0 text Ran 19 tests in 51.896s OK v2.10.0 text Ran 19 tests in 51.473s OK v2.11.0 text Ran 19 tests in 41.624s OK v2.12.0 text Ran 19 tests in 41.029s OK *(注:为保持报告整洁,日志中过滤了框架运行中对异常测试进行拦截拦截时打印的标准 Warning/Error 信息,所有测试函数均成功断言并返回 ok)* **测试结果**:各分支测试均 100% Passed。无 Error 与 Failure,张量与网络模块在 NPU 环境下序列化和图追踪行为与原生 CPU/CUDA 表现严格一致。 # 【CheckList】 > PR提交人对以下CheckList自检项进行全量自检,自检通过或不涉及,均修改 [ ] 为 [x] * [x] 代码注释完备,正确记录错误日志 * [x] 代码实现进行了返回值、空指针等校验 * [x] PR标题正确使用类型标签,如:feat、fix、refactor、docs、test等 * [x] PR持续集成流水线(CI)执行通过,代码检查无异常 See merge request: Ascend/pytorch!36740 | 5 个月前 | |
test(multiprocessing&type_info):add test case patch for multiprocessing and type_info Co-authored-by: HeYang<heyang88@h-partners.com> # message auto-generated for no-merge-commit merge: !34039 merge v2.9.0 into v2.9.0 test(multiprocessing&type_info):add test case patch for multiprocessing and type_info Created-by: VnOcean Commit-by: HeYang Merged-by: ascend-robot Description: <!-- PR描述模板更新日期:20260203 --> # 【合入来源】 > <font color="red">https://gitcode.com/Ascend/pytorch/issues/1683</font>\ > <font color="red">**请勿携带内部流程信息(需求链接、问题单、内部issue等)**</font> 一、API功能:本次适配的 12 个核心 API,均为硬件无关的框架层实现,核心功能为多进程调度和获取不同类型数据的信息,各api 功能介绍及适配情况如下: >1.torch.multiprocessing.\_set_thread_name : >用于设置当前线程的名称,复用测试用例。测试用例中,调用_set_thread_name 为线程指定名称。 >2.torch.multiprocessing.Pool : >用于创建进程池的类,可以自动管理一组工作进程,并将任务分发到这些进程中进行并行处理。它适合“数据并行”的任务模式,例如并行地对列表中的每个元素应用同一个函数。使用官网测试用例,执行python test_multiprocessing.py TestMultiprocessing.test_fd_pool -v,test_fd_pool方法,调用自有函数self.\_test_pool(repeat=TEST_REPEATS),传入重复次数 >3.torch.multiprocessing.spawn: >PyTorch 推荐用于启动多个进程的入口点,适合数据并行和分布式训练,官网存在测试用例,位于test_multiprocessing_spawn.py 文件中的SpawnTest 类 >4.torch.multiprocessing.reductions.rebuild_cuda_tensor: >作用是在多进程编程中,重建通过 IPC(进程间通信)接收到的 CUDA 张量,一个 CUDA 张量被从一个进程发送到另一个进程时,它首先会被 reduce_tensor 函数“拆解”或“序列化”成一个包含必要信息的元组。在接收端,rebuild_cuda_tensor 就会被调用来执行相反的操作,根据这些信息在接收进程中重新构建出这个 CUDA 张量. torch_npu 下 distributed/rpc/multiprocessing/test_reduction_new.py 文件中已适配 rebuild_npu_tensor 方法 >5.torch.multiprocessing.get_context: >获取一个多进程上下文对象,该对象具有与标准 multiprocessing 模块相同的API。在 test_leaf_variable_sharing 方法中被调用,因此可以验证 test_leaf_variable_sharing 的效果,达到对get_context API的测试验证。 >6.torch.multiprocessing.Process: >用于创建单个进程的类,与 Python 原生 multiprocessing.Process 完全兼容。它用于在一个新的子进程中运行指定的函数。在 test_leaf_variable_sharing 方法中被调用,因此可以验证 test_leaf_variable_sharing 的效果,达到对ProcessAPI的测试验证。 >7.torch.multiprocessing.Queue: >一个用于进程间通信的队列,与 Python 原生的 Queue 使用方式完全一致。当通过这个队列传递 PyTorch 的 Tensor 时,其数据会被自动移到共享内存,只传递一个句柄,从而实现零拷贝传输。它用于在一个新的子进程中运行指定的函数。在 test_leaf_variable_sharing 方法中被调用,因此可以验证 test_leaf_variable_sharing 的效果,达到对QueueAPI的测试验证。 >8.torch.multiprocessing.set_sharing_strategy: >set_sharing_strategy用于设置 CPU Tensor 在不同进程间共享时所使用的策略。在test_multiprocessing.py 文件中TestMultiprocessing类中的test_fs_sharing方法中被调用,可通过测试该函数的方式测试 API set_sharing_strategy。test_fs_sharing方法在fs_sharing()的限制条件下调用了自有函数 self.\_test_sharing,而 fs_sharing() 方法调用了API set_sharing_strategy fs_sharing作为上下文管理器调用 api set_sharing_strategy,临时将多进程共享策略设置为 "file_system",执行测试代码后恢复原来的共享策略 >9.torch.multiprocessing.SimpleQueue: >一个简化版的 Queue,它提供了基本的 put 和 get 方法,但内部不使用任何额外的线程。在某些复杂的多线程环境中,这有助于避免因线程竞争导致的死锁问题。其被 test_non_leaf_variable_sharing 方法调用,可测试此方法来验证 SimpleQueue API 的功能。test_non_leaf_variable_sharing 方法验证在多进程场景下,PyTorch中带有梯度信息的张量(requires_grad=True)不能被序列化并通过SimpleQueue在进程间传递的行为。 >10.torch.multiprocessing.start_processes >用于弹性的分布式训练。不仅能启动函数,还能启动二进制文件作为子进程,并提供更完善的日志重定向和管理功能。在test_multiprocessing_spawn.py 文件_TestMultiProcessing类中被多次调用,可以通过验证该方法,达到验证 start_processes API的作用。 >11.torch.finfo: >用于获取浮点数类型数值属性的 API。官网已有测试用例,用例验证了 PyTorch NPU后端的浮点信息类在数值精度、范围和属性方面与CPU NumPy实现的一致性,同时覆盖了特殊浮点格式的正确实现。它确保了跨设备(NPU vs CPU)和跨框架(PyTorch vs NumPy)的浮点属性一致性。 >12.torch.iinfo: >用于获取整型数类型数值属性的 API。官网已有测试用例,用例验证了PyTorch NPU后端的整数信息类在位数、取值范围和类型标识方面与CPU NumPy实现的一致性。与finfo测试一起,完整覆盖了PyTorch数值类型系统的基本信息查询功能。 二、测试用例完备性说明 PyTorch 社区原生测试用例(test_multiprocessing.py)对上述 前10个 API 实现全维度场景覆盖,核心验证内容如下: 1. torch.multiprocessing.Queue / SimpleQueue:进程间 tensor 传递、阻塞获取超时、空/满队列状态校验;混合数据类型(float/byte)顺序读写及事件同步机制验证。 2. torch.multiprocessing.Process:子进程 tensor 原地修改(add_)、daemon 模式、join 超时及异常退出码校验;多进程生命周期管理与资源回收验证。 3. torch.multiprocessing.Pool:多 worker 并行执行 tensor 填充映射(map),跨进程结果汇总及 worker 进程 PID 追踪;池关闭与等待逻辑验证。 4. torch.multiprocessing.get_context:spawn/fork 上下文切换下的 IPC、autograd 错误隔离、参数序列化兼容性验证;多 NPU 设备上下文隔离测试。 5. torch.multiprocessing.set_sharing_strategy:文件描述符(fd)与文件系统(fs)两种策略下的 tensor 共享、shm 残留检测、存储持久化行为对比验证。 6. torch.multiprocessing.reductions.rebuild_cuda_tensor:untyped storage 跨进程重建、storage 句柄/偏移/大小等元数据完整还原;多 device 下 tensor chunk 拆分与合并验证。 7. torch.multiprocessing._set_thread_name / _get_thread_name:Linux 平台下线程名称读写功能验证(依赖 prctl)。 PyTorch 社区原生测试用例(test_type_info.py)对上述 后 2 个 API 实现全维度场景覆盖,核心验证内容如下: 1. 获取全量浮点数类型数值属性的 API 2. 获取全量整型数类型数值属性的 API 三、API适配 主要分为以下3个级别的适配: 1. 不涉及张量操作、及硬件强绑定操作时:不修改,完全复用原生实现 。 2. 张量操作由 .cuda() 操作改写为 .npu() 操作,npu 已适配的 api 进行替换。 3. 当前场景不适合或有条件限制的的用例,增加条件判断,不适合则跳过。 功能验证: root@k8s-node1:/home/torch_2.9.0/pytorch/test# python test_multiprocessing.py TestMultiprocessing.test_set_thread_name -v test_set_thread_name (__main__.TestMultiprocessing.test_set_thread_name) ... ok ---------------------------------------------------------------------- Ran 1 test in 0.865s OK root@k8s-node1:/home/torch_2.9.0/pytorch/test# python test_multiprocessing.py TestMultiprocessing.test_fd_pool -v test_fd_pool (__main__.TestMultiprocessing.test_fd_pool) ... ok ---------------------------------------------------------------------- Ran 1 test in 39.361s OK root@k8s-node1:/home/torch_2.9.0/pytorch/test# python test_multiprocessing_spawn.py ..... ---------------------------------------------------------------------- Ran 31 tests in 226.550s OK root@k8s-node1:/home/torch_2.9.0/pytorch/test# python test_multiprocessing.py TestMultiprocessing.test_leaf_variable_sharing -v test_leaf_variable_sharing (__main__.TestMultiprocessing.test_leaf_variable_sharing) ... ok ---------------------------------------------------------------------- Ran 1 test in 29.204s OK root@k8s-node1:/home/torch_2.9.0/pytorch/test# python test_multiprocessing.py TestMultiprocessing.test_fs_sharing -v test_fs_sharing (__main__.TestMultiprocessing.test_fs_sharing) ... ok ---------------------------------------------------------------------- Ran 1 test in 52.557s OK root@k8s-node1:/home/torch_2.9.0/pytorch/test# python test_multiprocessing.py TestMultiprocessing.test_non_leaf_variable_sharing -v test_non_leaf_variable_sharing (__main__.TestMultiprocessing.test_non_leaf_variable_sharing) ... ok ---------------------------------------------------------------------- Ran 1 test in 1.270s OK root@k8s-node1:/home/torch_2.9.0/pytorch/test# python test_type_info.py TestDTypeInfo.test_finfo . ---------------------------------------------------------------------- Ran 1 test in 1.309s OK root@k8s-node1:/home/torch_2.9.0/pytorch/test# python test_type_info.py TestDTypeInfo.test_iinfo . ---------------------------------------------------------------------- Ran 1 test in 1.267s OK ` See merge request: Ascend/pytorch!34039 | 5 个月前 |
| 文件 | 最后提交记录 | 最后更新时间 |
|---|---|---|
| 5 个月前 | ||
| 3 个月前 | ||
| 3 个月前 | ||
| 4 个月前 | ||
| 4 个月前 | ||
| 4 个月前 | ||
| 5 个月前 | ||
| 3 个月前 | ||
| 4 个月前 | ||
| 4 个月前 | ||
| 3 个月前 | ||
| 4 个月前 | ||
| 6 个月前 | ||
| 4 个月前 | ||
| 5 个月前 | ||
| 4 个月前 | ||
| 5 个月前 | ||
| 5 个月前 | ||
| 5 个月前 | ||
| 4 个月前 | ||
| 5 个月前 | ||
| 4 个月前 | ||
| 5 个月前 | ||
| 5 个月前 |