[test] Add _get_module_fsdp_state_if_fully_sharded_module API test case

Co-authored-by: lihaokun-2026<851563813@qq.com>



# message auto-generated for no-merge-commit merge:
!45546 merge _get_module_fsdp_state_if_fully_sharded_module-master into master

[test] Add _get_module_fsdp_state_if_fully_sharded_module API test case

Created-by: lihaokun-2026
Commit-by: lihaokun-2026
Merged-by: ascend-robot
Description: <!--
PR描述模板更新日期:20260203
-->

# 【合入来源】

> <span style="color:red"><strong>如有社区 Issue,请关联 Issue 链接</strong></span>
> <span style="color:red"><strong>请勿携带内部流程信息(需求链接、问题单、内部issue等)</strong></span>


- [ ] 需求
- [ ] 问题单
- [x] issue/工单 https://gitcode.com/Ascend/pytorch-ecosystem/issues/269
- [ ] 重构优化
- [ ] 资料更新

# 1、API功能分析

- `torch.distributed.fsdp._common_utils._get_module_fsdp_state_if_fully_sharded_module`

`torch.distributed.fsdp._common_utils._get_module_fsdp_state_if_fully_sharded_module `是 `FSDP` 内部私有辅助函数,用于判断传入的 `module` 本身是否是真正由 `FSDP` 管理的 `fully-sharded module`;如果是传统 `FullyShardedDataParallel module`,或者是 `composable fully_shard` 管理的 module,就返回对应 `_FSDPState`,否则返回 None。这个函数自身只是做 Python 层的 FSDP state 查询和 module 身份判断,不直接执行 NPU 算子或 HCCL 通信,所以不是直接的 NPU API;但它位于 FSDP 运行链路中,而 NPU 上的 FSDP 会涉及设备管理、HCCL、参数 shard/unshard 等,因此和 torch-npu 间接相关。

# 2、上游用例检查情况

| API                                              | PyTorch 上游测试情况                                      |        单卡能否完成核心测试 | torch-npu 推荐环境      |
| ------------------------------------------------ | --------------------------------------------------- | ----------------: | ------------------- |
| `_get_module_fsdp_state_if_fully_sharded_module` | **未找到直接针对该私有函数的独立测试,但被 FSDP state_dict 测试链路间接覆盖**   | **直接 API 测试可以单卡** | 单卡可测;完整 FSDP 推荐多卡   |


`torch.distributed.fsdp._common_utils._get_module_fsdp_state_if_fully_sharded_module._get_module_fsdp_state_if_fully_sharded_module` 需要进行测试用例的补充。


# 3. 资料检查


- `torch.distributed.fsdp._common_utils._get_module_fsdp_state_if_fully_sharded_module` 这个API是内部方法无需进行资料补充。


# 4. API功能测试

- `torch.distributed.fsdp._common_utils._get_module_fsdp_state_if_fully_sharded_module._get_module_fsdp_state_if_fully_sharded_module` 

测试方法:

```
source /usr/local/Ascend/ascend-toolkit/set_env.sh
TORCH_DEVICE_BACKEND_AUTOLOAD=1 python test/distributed/fsdp/test_get_module_fsdp_state_if_fully_sharded_module.py -v
```


测试覆盖范围:

| 测试项 | 覆盖内容 | 预期结果 |
| --- | --- | --- |
| 普通 NPU Module | 创建未经过 FSDP 管理的 `nn.Linear` NPU Module,调用 `_get_module_fsdp_state_if_fully_sharded_module` | 返回 `None` |
| 单 rank HCCL 初始化 | 使用 `backend="hccl"`、`rank=0`、`world_size=1` 初始化默认 ProcessGroup | HCCL ProcessGroup 初始化成功 |
| FSDP NPU Module | 将 NPU `nn.Linear` 使用 `FullyShardedDataParallel` 包装后调用目标 API | 返回非 `None` 的 FSDP state |
| 返回值类型 | 检查 FSDP Module 对应的返回结果 | 返回结果为 `_FSDPState` |

测试结果:

v2.7.1

![image.png](https://raw.gitcode.com/user-images/assets/7404318/ca8f2094-e2a6-48a2-a026-fd17fdac92d5/image.png 'image.png')

v2.11.0

![image.png](https://raw.gitcode.com/user-images/assets/7404318/db5188c0-54d8-43c1-a05a-62c3f1bf3fc1/image.png 'image.png')

v2.12.0

![image.png](https://raw.gitcode.com/user-images/assets/7404318/fb8acf29-6c13-46b4-93b1-04d6429ee9f1/image.png 'image.png')

# 【CheckList】
> PR提交人对以下CheckList自检项进行全量自检,自检通过或不涉及,均修改 [ ] 为 [x]

- [x] 代码注释完备,正确记录错误日志
- [x] 代码实现进行了返回值、空指针等校验
- [x] PR标题正确使用类型标签,如:feat、fix、refactor、docs、test等
- [x] PR持续集成流水线(CI)执行通过,代码检查无异常


See merge request: Ascend/pytorch!45546
This commit is contained in:
lihaokun-2026
2026-10-01 19:25:45 +08:00
committed by ascend-robot
parent 6d7431c640
commit 9cd8d1f148
@@ -0,0 +1,83 @@
# Copyright (c) 2026 Huawei Technologies Co., Ltd
# All rights reserved.
#
# Licensed under the BSD 3-Clause License (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://opensource.org/licenses/BSD-3-Clause
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
Add validation cases for
torch.distributed.fsdp._common_utils._get_module_fsdp_state_if_fully_sharded_module
on NPU.
This file validates that a normal NPU module returns None and an FSDP-wrapped
NPU module returns the corresponding FSDP state.
"""
import socket
import torch
import torch.distributed as dist
import torch.nn as nn
from torch.distributed.fsdp import FullyShardedDataParallel as FSDP
from torch.distributed.fsdp._common_utils import (
_FSDPState,
_get_module_fsdp_state_if_fully_sharded_module,
)
from torch_npu.testing.testcase import TestCase, run_tests
def find_free_port():
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
sock.bind(("127.0.0.1", 0))
return sock.getsockname()[1]
class TestGetModuleFSDPStateIfFullyShardedModule(TestCase):
def tearDown(self):
if dist.is_initialized():
dist.destroy_process_group()
super().tearDown()
def test_normal_npu_module(self):
torch.npu.set_device(0)
device = torch.device("npu:0")
module = nn.Linear(4, 4).to(device)
result = _get_module_fsdp_state_if_fully_sharded_module(module)
self.assertIsNone(result)
def test_fsdp_npu_module(self):
torch.npu.set_device(0)
device = torch.device("npu:0")
dist.init_process_group(
backend="hccl",
init_method=f"tcp://127.0.0.1:{find_free_port()}",
rank=0,
world_size=1,
)
module = nn.Linear(4, 4).to(device)
fsdp_module = FSDP(module, device_id=device)
result = _get_module_fsdp_state_if_fully_sharded_module(
fsdp_module
)
self.assertIsNotNone(result)
self.assertIsInstance(result, _FSDPState)
if __name__ == "__main__":
run_tests()