Files
kuhn7 3144ddbbe4 test: verify community 2.11.0 features and fixes
Co-authored-by: chenkun<chenkun82@huawei.com>



# message auto-generated for no-merge-commit merge:
!36312 merge master_verify_distributed into master

test: verify community 2.11.0 features and fixes

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

# 【合入来源】
> <font color="red">**如有社区issue,请关联issue链接**</font>\
> <font color="red">**请勿携带内部流程信息(需求链接、问题单、内部issue等)**</font>

- [x] 需求 [【分布式】社区2.11.0版本特性和修复验证](https://gitcode.com/Ascend/pytorch/issues/2025) 
- [ ] 问题单
- [ ] issue/工单
- [ ] 重构优化
- [ ] 资料更新

# 【修改方案】
PyTorch 社区新增特性和bugfix,需要基于torch_npu进行验证,运行torch_npu或社区用例,保障功能正常运行。

# 【资料变更】
不涉及

# 【接口变更】
不涉及

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

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


See merge request: Ascend/pytorch!36312
2026-05-21 14:23:28 +08:00

329 lines
11 KiB
Python

# Copyright (c) Meta Platforms, Inc. and affiliates
# Owner(s): ["oncall: distributed"]
from typing import Any, Callable, Dict, Optional, Sequence
from unittest import skip
import torch
import torch.utils._pytree as pytree
from torch import Tensor
from torch.distributed._tensor import DeviceMesh, distribute_tensor, DTensor
from torch.distributed._tensor.placement_types import (
Partial,
Placement,
Replicate,
Shard,
)
from torch.distributed.tensor.debug import CommDebugMode
from torch.testing._internal.common_utils import (
instantiate_parametrized_tests,
parametrize,
run_tests,
)
from torch.distributed.distributed_c10d import ReduceOp
from torch.testing._internal.common_utils import run_tests
from torch.testing._internal.distributed._tensor.common_dtensor import DTensorTestBase
import torch_npu
from torch_npu.testing.common_distributed import with_comms, skipIfUnsupportMultiNPU
npu = torch.ops.npu
def no_op():
return None
def deepcopy_convert_to_dtensor(
val: Any,
device_mesh: DeviceMesh,
placements: Sequence[Placement],
) -> Any:
"""
Recursively convert (over Sequence and Dict types) Tensors into DTensors.
:param device_mesh: the DeviceMesh to use.
:param placements: the Placement list to use.
:return: the transformed structure.
"""
def f(x):
if isinstance(x, Tensor) and not isinstance(x, DTensor):
return distribute_tensor(
x,
device_mesh=device_mesh,
placements=placements,
)
return x
return pytree.tree_map(f, [val])[0]
def deepcopy_convert_from_dtensor(val: Any) -> Any:
"""
Recursive convert any DTensor to local Tensor.
:param val: the structure to coerce.
:return: the coerced structure.
"""
def f(x):
if isinstance(x, DTensor):
return x.redistribute(
device_mesh=x.device_mesh,
placements=[Replicate()] * x.device_mesh.ndim,
).to_local()
return x
return pytree.tree_map(f, [val])[0]
class DistElementwiseOpsTest(DTensorTestBase):
def _compare_pairwise_ops(
self,
*,
device_mesh: DeviceMesh,
placements: Sequence[Placement],
op: Callable,
pre_op_fn: Optional[Callable] = None,
args: Sequence[Any] = tuple(),
kwargs: Optional[Dict[str, Any]] = None,
):
if pre_op_fn is None:
pre_op_fn = no_op
if not kwargs:
kwargs = {}
dargs = deepcopy_convert_to_dtensor(
args,
device_mesh=device_mesh,
placements=placements,
)
dkwargs = deepcopy_convert_to_dtensor(
kwargs,
device_mesh=device_mesh,
placements=placements,
)
pre_op_fn()
# run the reference first, in case the call is broken;
# it's better to debug an incorrect call at this point.
reference_result = op(*args, **kwargs)
pre_op_fn()
dist_result = op(*dargs, **dkwargs)
collected_result = deepcopy_convert_from_dtensor(dist_result)
self.assertEqual(reference_result, collected_result)
def _run_sharded_elementwise_ops(
self,
*,
device_mesh: DeviceMesh,
placements: Sequence[Placement],
pre_op_fn: Optional[Callable] = None,
input_size: Sequence[int],
op: Callable,
**kwargs,
):
if pre_op_fn is None:
pre_op_fn = no_op
input_tensor = torch.randn(
*input_size,
device=self.device_type,
requires_grad=True,
)
self._compare_pairwise_ops(
device_mesh=device_mesh,
placements=placements,
pre_op_fn=pre_op_fn,
op=op,
args=(input_tensor,),
kwargs=kwargs,
)
@skipIfUnsupportMultiNPU(4)
@with_comms
def test_partial_add(self):
device_mesh = DeviceMesh(self.device_type, list(range(self.world_size)))
d_1 = DTensor.from_local(torch.rand(2, 2), device_mesh, [Partial()])
d_2 = DTensor.from_local(torch.rand(2, 2), device_mesh, [Partial()])
d_3 = d_1 + d_2
self.assertEqual(d_3._spec.placements[0].is_partial(), True)
@skipIfUnsupportMultiNPU(4)
@with_comms
def test_activations(self):
device_mesh = DeviceMesh(self.device_type, list(range(self.world_size)))
self._run_sharded_elementwise_ops(
device_mesh=device_mesh,
placements=[Shard(0)],
input_size=(8, 5),
op=torch.nn.functional.gelu,
)
self._run_sharded_elementwise_ops(
device_mesh=device_mesh,
placements=[Replicate()],
input_size=(8, 5),
op=torch.nn.functional.gelu,
)
self._run_sharded_elementwise_ops(
device_mesh=device_mesh,
placements=[Shard(0)],
input_size=(8, 5),
op=npu.fast_gelu,
)
self._run_sharded_elementwise_ops(
device_mesh=device_mesh,
placements=[Replicate()],
input_size=(8, 5),
op=npu.fast_gelu,
)
self._run_sharded_elementwise_ops(
device_mesh=device_mesh,
placements=[Shard(0)],
input_size=(8, 5),
op=npu.npu_fast_gelu,
)
self._run_sharded_elementwise_ops(
device_mesh=device_mesh,
placements=[Replicate()],
input_size=(8, 5),
op=npu.npu_fast_gelu,
)
self._run_sharded_elementwise_ops(
device_mesh=device_mesh,
placements=[Shard(1)],
input_size=(3, 12),
op=torch.nn.functional.relu,
)
self._run_sharded_elementwise_ops(
device_mesh=device_mesh,
placements=[Replicate()],
input_size=(8, 5),
op=torch.nn.functional.relu,
)
self._run_sharded_elementwise_ops(
device_mesh=device_mesh,
placements=[Shard(0)],
input_size=(8, 5),
op=torch.sigmoid,
)
self._run_sharded_elementwise_ops(
device_mesh=device_mesh,
placements=[Replicate()],
input_size=(8, 5),
op=torch.sigmoid,
)
@skipIfUnsupportMultiNPU(4)
@skip("testing RNG based ops is broken")
@with_comms
def test_dropout(self):
device_mesh = DeviceMesh(self.device_type, list(range(self.world_size)))
def _reset_random_seed():
torch.manual_seed(self.rank + 4)
self._run_sharded_elementwise_ops(
device_mesh=device_mesh,
placements=[Shard(0)],
input_size=(8, 5),
op=torch.nn.functional.dropout,
pre_op_fn=_reset_random_seed,
p=0.4,
training=False,
)
self._run_sharded_elementwise_ops(
device_mesh=device_mesh,
placements=[Shard(1)],
input_size=(3, 14),
op=torch.nn.functional.dropout,
pre_op_fn=_reset_random_seed,
p=0.5,
training=True,
)
@skipIfUnsupportMultiNPU(4)
@with_comms
def test_dropout_errors(self):
device_mesh = DeviceMesh(self.device_type, list(range(self.world_size)))
with self.assertRaisesRegex(RuntimeError, "supported"):
self._run_sharded_elementwise_ops(
device_mesh=device_mesh,
placements=[Partial(ReduceOp.SUM)],
input_size=(8, 5),
op=torch.nn.functional.dropout,
)
@skipIfUnsupportMultiNPU(4)
@with_comms
def test_mul_out(self):
device_mesh = DeviceMesh(self.device_type, list(range(self.world_size)))
torch.manual_seed(self.rank)
shard_spec = [Shard(0)]
input_size = (8, 4)
input_tensor = torch.randn(*input_size, device=self.device_type)
dtensor = DTensor.from_local(input_tensor, device_mesh, shard_spec)
other_tensor = torch.randn(*input_size, device=self.device_type)
other_dtensor = DTensor.from_local(other_tensor, device_mesh, shard_spec)
output_tensor = torch.randn(*input_size, device=self.device_type)
output_dtensor = DTensor.from_local(output_tensor, device_mesh, shard_spec)
dt = torch.mul(dtensor, other_dtensor, out=output_dtensor)
expected = torch.mul(input_tensor, other_tensor, out=output_tensor)
self.assertEqual(input_tensor, dtensor.to_local())
self.assertEqual(expected, dt.to_local())
@skipIfUnsupportMultiNPU(4)
@with_comms
def test_cast_strided_shard(self):
from torch.distributed.device_mesh import init_device_mesh
from torch.distributed.tensor.placement_types import _StridedShard
npu_input = torch.randn((8, 8), dtype=torch.float32).npu()
dst_dtype = torch.float16
local_result = torch_npu.npu_dtype_cast(npu_input, dst_dtype)
# distributed tensor
device_mesh = init_device_mesh(self.device_type, [1, 4], mesh_dim_names=["dp", "tp"])
shard0_spec = Shard(0)
strided_shard0_spec = _StridedShard(0, split_factor=4)
replica_spec = Replicate()
dt_input = distribute_tensor(npu_input, device_mesh, [strided_shard0_spec, shard0_spec])
dist_res: DTensor = torch_npu.npu_dtype_cast(dt_input, dst_dtype).redistribute(
device_mesh, [replica_spec, replica_spec]
)
self.assertEqual(dist_res.to_local().dtype, dst_dtype)
self.assertEqual(dist_res.to_local(), local_result)
@with_comms
@parametrize("op,reduce_op", [(torch.maximum, "max"), (torch.minimum, "min")])
def test_partial_propagation(self, op, reduce_op):
# Test that torch.maximum/minimum preserves Partial("max"/"min") placements
# since max(max(a), max(b)) == max(a, b) and min(min(a), min(b)) == min(a, b)
device_mesh = self.build_device_mesh()
comm_mode = CommDebugMode()
input1 = torch.rand(8, 8) * self.rank
input2 = torch.rand(8, 8) * (self.world_size - self.rank)
d_input1 = DTensor.from_local(input1, device_mesh, [Partial(reduce_op)])
d_input2 = DTensor.from_local(input2, device_mesh, [Partial(reduce_op)])
with comm_mode:
result = op(d_input1, d_input2)
# Should not require any communication
self.assertEqual(comm_mode.get_total_counts(), 0)
# Result should still be Partial with the same reduce_op
self.assertEqual(result.placements, (Partial(reduce_op),))
instantiate_parametrized_tests(DistElementwiseOpsTest)
if __name__ == "__main__":
run_tests()