Files
litianyu_2026 f662280f51 【API一致性任务】test: add Partial placement test for compute_local_shape_and_global_offset
Co-authored-by: litianyu2026<1483211810@qq.com>



# message auto-generated for no-merge-commit merge:
!45656 merge test-compute-local-shape-master into master

【API一致性任务】test: add Partial placement test for compute_local_shape_and_global_offset

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

# 【合入来源】
> <font color="red">https://gitcode.com/Ascend/pytorch-ecosystem/issues/326</font>\
> <font color="red">**请勿携带内部流程信息(需求链接、问题单、内部issue等)**</font>

- [ ] 需求
- [ ] 问题单
- [x] issue/工单
- [ ] 重构优化
- [ ] 资料更新

# 【修改方案】
> 请描述修改内容的具体实现,涉及哪些组件之间进行交互,可以用1、2、3、...进行罗列\
> 如果是需求或者重构类的PR,需要补充详细设计文档(说明上下游组件关系、时序图、类图、DFX能力等内容)

1. **API 功能说明**:`torch.distributed.tensor._utils.compute_local_shape_and_global_offset` 是 DTensor 模块下一个纯 Python 实现的内部元数据工具函数。其功能为:给定全局张量的形状、设备网格(DeviceMesh)以及放置策略(placements),计算并推导出当前 rank 对应的局部张量形状(`local_shape`)以及该数据块在全局张量中的绝对偏移量(`global_offset`)。
2. **新增测试用例的原因**:经排查 PyTorch 原生测试代码,官方原有的 1D 和 2D 测试用例中仅覆盖了 `Shard`(切分)和 `Replicate`(复制)策略,**客观上遗漏了对另一合法核心策略 `Partial`(部分状态)的入参验证**。为了保证该 API 在 NPU 环境下的参数完备性与逻辑全覆盖,必须进行用例补齐。
3. **实现细节**:新增 `test_compute_local_shape_and_global_offset_partial` 测试用例,显式导入 `Partial` 策略类,并断言验证其推导结果:在 `Partial` 策略下,局部张量尺寸未发生物理切分(保持等于全局尺寸),且全局偏移坐标全为 0。

# 【资料变更】
> 请确认是否涉及资料变更。如涉及,需要在PR中体现,并简要说明修改内容。如不涉及,需填写“不涉及”

不涉及。

**原因说明**:本次测试的目标接口 `torch.distributed.tensor._utils.compute_local_shape_and_global_offset` 属于带有 `_utils` 前缀的内部私有 API。上游 PyTorch 官方未对其开放公开的原生独立文档(仅在 `Shard` API 的 Note 中作为对照参考提及)。且该 API 逻辑为纯 Python 的坐标数学推导,不涉及 NPU 底层内存操作或算子调用,无特殊硬件约束,故不涉及对外公开资料的编写与变更。

# 【接口变更】
> 请确认是否涉及跨代码仓或者客户面可见的接口变更。如涉及,需要详细说明接口以及对应的变更内容,同时需要在资料中体现。如不涉及,需填写“不涉及”

不涉及。本次提交仅为纯测试层面的用例补充。

# 【功能验证】
> 说明测试场景,测试方法。如果本次测试方式与常规单元测试不同,请详细说明您的测试步骤\
> 新增/变更内容是否已新增/适配UT测试用例看护,并补充测试自验证截图

**测试场景与方法**:在分布式环境下(世界大小为 8),测试传入 `Partial` 策略时的尺寸和偏移量推导是否正确。
**执行步骤**:
```bash
python test_utils.py -v -k test_compute_local_shape_and_global_offset_partial
```

测试结果:8 个通信进程均正常计算完毕并匹配正确断言,结果为 OK。

910B3的4卡测试自验证截图,无A5多卡环境,无法验证A5支持情况,不再进行A5多卡验证测试:
![d226a08c6d1c153e0afe79da4528a656.png](https://raw.gitcode.com/user-images/assets/7404318/a1f5b369-4285-495c-8b29-02900f0e94da/d226a08c6d1c153e0afe79da4528a656.png 'd226a08c6d1c153e0afe79da4528a656.png')

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

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


See merge request: Ascend/pytorch!45656
2026-09-15 20:13:37 +08:00

223 lines
8.6 KiB
Python

import itertools
from contextlib import nullcontext
import torch
import torch.distributed as dist
from torch.distributed._local_tensor import (
local_tensor_mode,
LocalTensor,
LocalTensorMode,
)
from torch.distributed._tensor import distribute_tensor
from torch.distributed.tensor._utils import (
compute_local_shape_and_global_offset,
)
from torch.distributed.device_mesh import init_device_mesh
from torch.distributed.tensor import DeviceMesh
from torch.distributed.tensor._utils import ExplicitRedistributionContext
from torch.distributed.tensor.debug import CommDebugMode
from torch.distributed.tensor.placement_types import Replicate, Shard, Partial
from torch.testing._internal.common_utils import run_tests, TestCase
from torch.testing._internal.distributed._tensor.common_dtensor import DTensorTestBase
from torch_npu.testing.common_distributed import with_comms, skipIfUnsupportMultiNPU
class UtilTest(DTensorTestBase):
@property
def world_size(self):
return 8
@skipIfUnsupportMultiNPU(4)
@with_comms
def test_compute_local_shape_and_global_offset_1D(self):
one_d_placements = [[Shard(0)], [Replicate()]]
for placements in one_d_placements:
mesh_tensor = torch.arange(self.world_size)
device_mesh = DeviceMesh(self.device_type, mesh_tensor)
global_tensor = torch.arange(64).view(8, 8)
global_shape = global_tensor.size()
dtensor = distribute_tensor(global_tensor, device_mesh, placements)
local_size, global_offset = compute_local_shape_and_global_offset(
global_shape, device_mesh, placements
)
dim0_start = global_offset[0]
dim0_end = global_offset[0] + local_size[0]
# Check the local tensor of dtensor is exactly the same
# if we slice the global_tensor with local_size and global_offset
self.assertEqual(
dtensor.to_local(),
global_tensor[dim0_start:dim0_end],
)
@skipIfUnsupportMultiNPU(4)
@with_comms
def test_compute_local_shape_and_global_offset_2D(self):
two_d_placements_options = [Shard(0), Shard(1), Replicate()]
# Generating 6 two-d placements combinations
two_d_placements = list(
itertools.combinations_with_replacement(two_d_placements_options, 2)
)
for placements in two_d_placements:
# mesh: 2 * 4
mesh_tensor = torch.arange(self.world_size).reshape(2, 4)
device_mesh = DeviceMesh(self.device_type, mesh_tensor)
global_tensor = torch.arange(64).view(8, 8)
global_shape = global_tensor.size()
dtensor = distribute_tensor(global_tensor, device_mesh, placements)
local_size, global_offset = compute_local_shape_and_global_offset(
global_shape, device_mesh, placements
)
dim0_start = global_offset[0]
dim0_end = global_offset[0] + local_size[0]
dim1_start = global_offset[1]
dim1_end = global_offset[1] + local_size[1]
# Check the local tensor of dtensor is exactly the same
# if we slice the global_tensor with local_size and global_offset
self.assertEqual(
dtensor.to_local(),
global_tensor[dim0_start:dim0_end, dim1_start:dim1_end],
)
@skipIfUnsupportMultiNPU(4)
@with_comms
def test_compute_local_shape_and_global_offset_partial(self):
# Verify local size and global offset for Partial placement.
placements = [Partial()]
mesh_tensor = torch.arange(self.world_size)
device_mesh = DeviceMesh(self.device_type, mesh_tensor)
global_tensor = torch.arange(64).view(8, 8)
global_shape = global_tensor.size()
local_size, global_offset = compute_local_shape_and_global_offset(global_shape, device_mesh, placements)
self.assertEqual(local_size, tuple(global_shape))
self.assertEqual(global_offset, tuple([0] * len(global_shape)))
class LocalTensorTestBase(TestCase):
def assertEqual(self, lhs, rhs, **kwargs):
mode = local_tensor_mode()
with nullcontext() if mode is None else mode.disable():
if isinstance(lhs, LocalTensor) and isinstance(rhs, LocalTensor):
assert isinstance(lhs, LocalTensor) and isinstance(rhs, LocalTensor)
super().assertEqual(lhs._ranks, rhs._ranks)
for r in lhs._ranks:
super().assertEqual(
lhs._local_tensors[r],
rhs._local_tensors[r],
lambda m: f"rank {r}: {m}",
)
elif isinstance(lhs, LocalTensor) or isinstance(rhs, LocalTensor):
lhs, rhs = (lhs, rhs) if isinstance(lhs, LocalTensor) else (rhs, lhs)
for r in lhs._ranks:
super().assertEqual(
lhs._local_tensors[r], rhs, lambda m: f"rank {r}: {m}"
)
else:
return super().assertEqual(lhs, rhs, **kwargs)
@property
def world_size(self):
raise NotImplementedError("override world-size in your subclass")
def build_device_mesh(self) -> DeviceMesh:
return init_device_mesh("cpu", (self.world_size,))
def setUp(self):
super().setUp()
torch.distributed.init_process_group(
# TODO: test other ranks too
"fake",
rank=0,
world_size=self.world_size,
)
def tearDown(self):
super().tearDown()
try:
dist.destroy_process_group()
except AssertionError:
pass
class TestExplicitRedistribute(LocalTensorTestBase):
@property
def world_size(self):
return 4
def test_explicit_matmul(self):
with LocalTensorMode(self.world_size):
device_mesh = self.build_device_mesh()
dim = 128
x = torch.randn(8, dim, requires_grad=True)
A = torch.randn(dim, dim, requires_grad=True)
# Prepare DTensors
dx = distribute_tensor(x, device_mesh, [Shard(0)])
dA = distribute_tensor(A, device_mesh, [Shard(0)])
# implicit redistribute works as usual by default
with CommDebugMode() as comm_mode:
torch.matmul(dx, dA)
self.assertEqual(comm_mode.get_total_counts(), 1)
# explicit redistribute works too
with ExplicitRedistributionContext():
with self.assertRaisesRegex(RuntimeError, "Implicit redistribution"):
torch.matmul(dx, dA)
with ExplicitRedistributionContext(mode="warn"):
with self.assertLogs(
torch.distributed.tensor._utils.logger, level="WARN"
) as captured:
torch.matmul(dx, dA)
self.assertEqual(len(captured.output), 1)
self.assertRegex(
captured.output[0],
r"WARNING:.*Implicit redistribution occurred",
)
# TODO enable this once fixing the issue that op_info.schema is None in some calls to
# redistribute_local_tensor
# self.assertRegex(
# captured.output[0],
# r".*aten\.mm\.default.*",
# )
# explicit redistribute allows manual redistribute
with ExplicitRedistributionContext():
dA_repl = dA.redistribute(device_mesh, [Replicate()])
torch.matmul(dx, dA_repl)
dx = distribute_tensor(x, device_mesh, [Shard(0)])
dA = distribute_tensor(A, device_mesh, [Replicate()])
with ExplicitRedistributionContext(strict=True):
dY = torch.matmul(dx, dA_repl)
loss = dY.sum()
# we now see the error during backwards
with self.assertRaisesRegex(RuntimeError, "Implicit redistribution"):
loss.backward(retain_graph=True)
with ExplicitRedistributionContext(strict=False):
# but since it's a 'free' redistribute, we can still do it under non-strict mode
loss.backward(retain_graph=True)
with ExplicitRedistributionContext(enable=False):
# and we can disable
loss.backward(retain_graph=True)
# and re-enable
with self.assertRaisesRegex(RuntimeError, "Implicit redistribution"):
loss.backward(retain_graph=True)
if __name__ == "__main__":
run_tests()