Coverage for  / home / jenkins / .local / lib / python3.10 / site-packages / hyper_parallel / core / dtensor / layout.py: 96%

504 statements  

« prev     ^ index     » next       coverage.py v7.13.1, created at 2026-12-05 05:12 +0800

1# Copyright 2026 Huawei Technologies Co., Ltd 

2# 

3# Licensed under the Apache License, Version 2.0 (the "License"); 

4# you may not use this file except in compliance with the License. 

5# You may obtain a copy of the License at 

6# 

7# http://www.apache.org/licenses/LICENSE-2.0 

8# 

9# Unless required by applicable law or agreed to in writing, software 

10# distributed under the License is distributed on an "AS IS" BASIS, 

11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 

12# See the License for the specific language governing permissions and 

13# limitations under the License. 

14# ============================================================================ 

15"""layout""" 

16# pylint: disable=C9006,C9007,C9008 

17 

18import copy 

19import functools 

20from typing import Any, NamedTuple, Optional, Sequence, Union 

21 

22import numpy as np 

23import torch.distributed as dist 

24 

25from hyper_parallel.core.dtensor.placement_types import ( 

26 Partial, 

27 Placement, 

28 RaggedShard, 

29 Replicate, 

30 Shard, 

31 StridedShard, 

32) 

33from hyper_parallel.core.dtensor.device_mesh import DeviceMesh, _create_device_mesh 

34 

35 

36class RaggedShardInfo(NamedTuple): 

37 """RaggedShard placement and its corresponding mesh dimension.""" 

38 

39 mesh_dim: int 

40 placement: RaggedShard 

41 

42 

43def _extract_ragged_shard(placements: Sequence[Placement]) -> Optional[RaggedShardInfo]: 

44 """Extract the single RaggedShard placement from a placement sequence.""" 

45 ragged_shard = None 

46 for mesh_dim, placement in enumerate(placements): 

47 if not placement.is_ragged_shard(): 

48 continue 

49 if ragged_shard is not None: 

50 raise ValueError( 

51 "Layout supports at most one RaggedShard placement, " 

52 f"but got placements={tuple(placements)!r}" 

53 ) 

54 ragged_shard = RaggedShardInfo(mesh_dim, placement) 

55 return ragged_shard 

56 

57 

58def _replace_ragged_with_replicate(placements: Sequence[Placement]) -> tuple[Placement, ...]: 

59 """Return placements with RaggedShard represented as Replicate.""" 

60 return tuple( 

61 Replicate() if placement.is_ragged_shard() else placement 

62 for placement in placements 

63 ) 

64 

65 

66def infer_balanced_chunk_range( 

67 tensor_size: int, 

68 shard_count: int, 

69 shard_rank: int, 

70) -> tuple[int, int]: 

71 """Return one balanced half-open shard range.""" 

72 shard_size, remainder = divmod(tensor_size, shard_count) 

73 chunk_start = shard_rank * shard_size + min(shard_rank, remainder) 

74 chunk_end = chunk_start + shard_size + int(shard_rank < remainder) 

75 return chunk_start, chunk_end 

76 

77 

78def infer_ceil_chunk_range( 

79 tensor_size: int, 

80 shard_count: int, 

81 shard_rank: int, 

82) -> tuple[int, int]: 

83 """Return one ceil-chunk range, including empty trailing ranks.""" 

84 chunk_size = (tensor_size + shard_count - 1) // shard_count 

85 chunk_start = min(shard_rank * chunk_size, tensor_size) 

86 chunk_end = min(chunk_start + chunk_size, tensor_size) 

87 return chunk_start, chunk_end 

88 

89 

90def _calculate_mesh_coordinate_for_rank( 

91 mesh_shape: Sequence[int], rank_id: int 

92) -> list[int]: 

93 """Calculate the device-mesh coordinate for a linear rank.""" 

94 coordinate = [0] * len(mesh_shape) 

95 remaining_rank = rank_id 

96 for mesh_dim in range(len(mesh_shape) - 1, -1, -1): 

97 coordinate[mesh_dim] = remaining_rank % mesh_shape[mesh_dim] 

98 remaining_rank //= mesh_shape[mesh_dim] 

99 return coordinate 

100 

101 

102def _infer_tensor_dimension_slice( 

103 global_size: int, 

104 tensor_mapping: Union[int, Sequence[int]], 

105 mesh_shape: Sequence[int], 

106 mesh_coordinate: Sequence[int], 

107 uneven_shard_mesh_dims: set[int], 

108) -> tuple[int, int]: 

109 """Infer the half-open slice for one tensor dimension.""" 

110 mapped_dims = (tensor_mapping,) if isinstance(tensor_mapping, int) else tensor_mapping 

111 slice_start, slice_end = 0, global_size 

112 for mapped_mesh_dim in mapped_dims: 

113 if mapped_mesh_dim == -1: 

114 continue 

115 mesh_dim = len(mesh_shape) - mapped_mesh_dim - 1 

116 infer_chunk_range = ( 

117 infer_ceil_chunk_range 

118 if mesh_dim in uneven_shard_mesh_dims 

119 else infer_balanced_chunk_range 

120 ) 

121 chunk_start, chunk_end = infer_chunk_range( 

122 slice_end - slice_start, 

123 mesh_shape[mesh_dim], 

124 mesh_coordinate[mesh_dim], 

125 ) 

126 slice_start += chunk_start 

127 slice_end = slice_start + chunk_end - chunk_start 

128 return slice_start, slice_end 

129 

130 

131def _infer_slice_area_by_rank( 

132 mesh_shape: tuple[int, ...], 

133 tensor_map: Sequence, 

134 rank_id: int, 

135 full_shape: Sequence[int], 

136 uneven_shard_mesh_dims: set[int], 

137) -> tuple[tuple[int, int], ...]: 

138 """Return one rank's slice using placement-specific shard geometry.""" 

139 mesh_coordinate = _calculate_mesh_coordinate_for_rank(mesh_shape, rank_id) 

140 return tuple( 

141 _infer_tensor_dimension_slice( 

142 global_size, 

143 tensor_map[tensor_dim], 

144 mesh_shape, 

145 mesh_coordinate, 

146 uneven_shard_mesh_dims, 

147 ) 

148 for tensor_dim, global_size in enumerate(full_shape) 

149 ) 

150 

151 

152def infer_slice_area_by_rank( 

153 mesh_shape: tuple[int, ...], 

154 tensor_map: Sequence, 

155 rank_id: int, 

156 full_shape: Sequence[int], 

157 uneven_shard_mesh_dims: Optional[Sequence[int]] = None, 

158) -> tuple[tuple[int, int], ...]: 

159 """Return one rank's global slice using placement-specific shard semantics.""" 

160 return _infer_slice_area_by_rank( 

161 mesh_shape, 

162 tensor_map, 

163 rank_id, 

164 full_shape, 

165 set(uneven_shard_mesh_dims or ()), 

166 ) 

167 

168 

169def infer_slice_area_by_layout( 

170 layout: "Layout", 

171 rank_id: int, 

172 full_shape: Sequence[int], 

173) -> tuple[tuple[int, int], ...]: 

174 """Return one rank's slice using ``uneven_shard`` placement markers.""" 

175 return infer_slice_area_by_rank( 

176 layout.mesh_shape, 

177 layout.tensor_map, 

178 rank_id, 

179 full_shape, 

180 layout.uneven_shard_mesh_dims, 

181 ) 

182 

183 

184def _get_slice_tensor_by_layout(global_tensor, layout): 

185 """Transfer global tensor to local tensor by layout""" 

186 inner_rank_id = layout.rank_list.index(layout.mesh.rank) 

187 slice_area = infer_slice_area_by_layout(layout, inner_rank_id, global_tensor.shape) 

188 

189 def get_slice_data(full_data, offset): 

190 area = () 

191 for begin, end in offset: 

192 area += (slice(begin, end),) 

193 return full_data[area].clone() 

194 

195 local_tensor = get_slice_data(global_tensor, slice_area) 

196 return local_tensor 

197 

198 

199def _infer_slice_shape_by_layout(global_shape, layout): 

200 """Infer slice shape from global_shape and layout""" 

201 inner_rank_id = layout.rank_list.index(layout.mesh.rank) 

202 slice_area = infer_slice_area_by_layout(layout, inner_rank_id, global_shape) 

203 return [end - start for start, end in slice_area] 

204 

205 

206class Layout: 

207 """ 

208 Topological abstraction describing cluster devices for tensor slice placement on the cluster. 

209 

210 Note: 

211 - It is valid only in semi auto parallel or auto parallel mode. 

212 - The multiplication result of the `mesh_shape` must be equal to the device count in a pipeline stage. 

213 - When the layout function is invoked to constructs a sharding strategy, each alias name is only allowed to be 

214 used once to shard a tensor. 

215 

216 Args: 

217 mesh_shape (tuple): Describe the shape of devices arrangement, its element type is int. 

218 alias_name (tuple): The alias name for each axis of mesh_shape, its length shoits element type is string. 

219 When using "interleaved_parallel" as an alias name, the tensor would be split into multiple 

220 copies on the corresponding partition dimension on a single card. 

221 rank_list (tuple, optional): Data is allocated to the device according to rank_list. Default: ``None``. 

222 

223 Raises: 

224 TypeError: `mesh_shape` is not a tuple type. 

225 TypeError: `alias_name` is not a tuple type. 

226 TypeError: 'rank_list' is not a list type. 

227 ValueError: `mesh_shape` length is not equal to `alias_name` length. 

228 TypeError: The element of `mesh_shape` is not int type. 

229 TypeError: The element of `alias_name` is not a str type. 

230 TypeError: The element of `rank_list` is not int type. 

231 ValueError: The element of `alias_name` is an empty str. 

232 ValueError: The element of `alias_name` is "None". 

233 ValueError: `alias_name` contains repeated element. 

234 

235 Supported Platforms: 

236 ``Ascend`` 

237 

238 Examples: 

239 >>> layout = Layout((2, 2, 2), ("dp", "sp", "mp")) 

240 >>> layout0 = layout("dp", "mp") 

241 >>> print(layout0.to_dict()) 

242 {"mesh_shape": (2, 2, 2), "tensor_map": (2, 0), "interleaved_parallel": False, 

243 'alias_name': {'dp', 'sp', 'mp'}, "rank_list": [0, 1, 2, 3, 4, 5, 6, 7]} 

244 >>> layout = Layout((2, 2, 2), ("dp", "sp", "interleaved_parallel")) 

245 >>> layout1 = layout(("dp", "interleaved_parallel"), "sp") 

246 """ 

247 

248 def __init__(self, mesh_shape, alias_name, rank_list=None, init_backend=True): 

249 self._alias_name = alias_name 

250 self._tensor_map = None 

251 if not rank_list: 

252 self._rank_list = tuple(range(np.prod(np.array(mesh_shape)))) 

253 else: 

254 self._rank_list = tuple(rank_list) 

255 self._partial = [None] * len(mesh_shape) # partial status for each dev dim 

256 self._support_partial_op = ['sum', 'max', 'min', 'avg', 'prod', 'all', None] 

257 self._alias_tensor_map = None 

258 self._tensor_shape = None 

259 self._tensor_stride = None 

260 self._tensor_dtype = None 

261 self._mesh = _create_device_mesh("npu", mesh_shape, mesh_dim_names=alias_name, rank_list=self._rank_list, 

262 init_backend=init_backend) 

263 self._placements = None 

264 self.partial_ops = {} # Initialized in _build_dim_map_from_placements() 

265 self._ragged_shard = None 

266 self._compact_str = self._to_compact_string() 

267 

268 @classmethod 

269 def from_device_mesh(cls, device_mesh: DeviceMesh) -> 'Layout': 

270 """ 

271 Create a Layout from an existing DeviceMesh. 

272 

273 Args: 

274 device_mesh (DeviceMesh): The device mesh to create layout from. 

275 

276 Returns: 

277 Layout: A new Layout instance initialized with the properties of the provided device mesh. 

278 

279 Examples: 

280 >>> from hyper_parallel.core.dtensor.layout import Layout, DeviceMesh 

281 >>> device_mesh = DeviceMesh("npu", (2, 2), mesh_dim_names=("dp", "mp")) 

282 >>> layout = Layout.from_device_mesh(device_mesh) 

283 """ 

284 obj = cls.__new__(cls) 

285 obj._mesh = device_mesh 

286 obj._alias_name = device_mesh.mesh_dim_names 

287 obj._rank_list = device_mesh.rank_list 

288 obj._tensor_map = None 

289 obj._partial = [None] * len(device_mesh.mesh_shape) 

290 obj._support_partial_op = ['sum', 'max', 'min', 'avg', 'prod', 'all', None] 

291 obj._alias_tensor_map = None 

292 obj._tensor_shape = None 

293 obj._tensor_stride = None 

294 obj._tensor_dtype = None 

295 obj._placements = None 

296 obj._ragged_shard = None 

297 obj._compact_str = obj._to_compact_string() 

298 return obj 

299 

300 def __call__(self, *alias_tensor_map): 

301 obj = copy.deepcopy(self) 

302 

303 # Clear the inherited partial status. 

304 # When creating a new layout mapping configuration via __call__, 

305 # it should not inherit the dynamic execution state (Partial) of the original layout. 

306 # If the user intends to create a Partial placement, it will be parsed from alias_tensor_map. 

307 obj._partial = [None] * len(obj.mesh_shape) 

308 

309 if len(alias_tensor_map) == 1 and isinstance(alias_tensor_map[0], (list, tuple)): 

310 if len(alias_tensor_map[0]) > 0 and isinstance(alias_tensor_map[0][0], Placement): 

311 return self._process_placement_layout(obj, alias_tensor_map[0]) 

312 

313 if len(alias_tensor_map) > 0 and isinstance(alias_tensor_map[0], Placement): 

314 return self._process_placement_layout(obj, alias_tensor_map) 

315 

316 return self._process_alias_layout(obj, alias_tensor_map) 

317 

318 def __deepcopy__(self, memo): 

319 """Deep copy layout without rebuilding the underlying device mesh. 

320 

321 ``_mesh`` is shared by identity: a DeviceMesh is process-wide topology 

322 (created once, never mutated in place) and deep-copying it would clone 

323 its mesh tensor and process-group bookkeeping on every layout copy. 

324 """ 

325 cls = self.__class__ 

326 result = cls.__new__(cls) 

327 memo[id(self)] = result 

328 for k, v in self.__dict__.items(): 

329 setattr(result, k, v if k == "_mesh" else copy.deepcopy(v, memo)) 

330 return result 

331 

332 @staticmethod 

333 def _process_placement_layout(obj, placements): 

334 """Process layout defined by Placement types.""" 

335 obj.set_placements(placements) 

336 return copy.deepcopy(obj) 

337 

338 @staticmethod 

339 def _process_alias_layout(obj, alias_tensor_map): 

340 """Process layout defined by alias strings.""" 

341 obj.set_alias_tensor_map(alias_tensor_map) 

342 tensor_map = () 

343 writed_map = () 

344 for ele in alias_tensor_map: 

345 if isinstance(ele, tuple): 

346 ele_map = () 

347 for item in ele: 

348 if item == "None": 

349 ele_map += (-1,) 

350 continue 

351 if item not in obj.alias_name: 

352 raise ValueError(f'The axis {item} is not found in {obj.alias_name}') 

353 if item in writed_map: 

354 raise ValueError(f'The axis {item} has been set more than one in {obj.alias_name}') 

355 ele_map += (len(obj.alias_name) - 1 - obj.alias_name.index(item),) 

356 writed_map += (item,) 

357 tensor_map += (ele_map,) 

358 continue 

359 if ele == "None": 

360 tensor_map += (-1,) 

361 continue 

362 if ele not in obj.alias_name: 

363 raise ValueError(f'The axis {ele} is not found in {obj.alias_name}') 

364 if ele in writed_map: 

365 raise ValueError(f'The axis {ele} has been set more than one in {obj.alias_name}') 

366 tensor_map += (len(obj.alias_name) - 1 - obj.alias_name.index(ele),) 

367 writed_map += (ele,) 

368 obj.set_tensor_map(tensor_map) 

369 obj.tensor_map_to_placement() 

370 obj.update_compact_str() 

371 return copy.deepcopy(obj) 

372 

373 def to_dict(self): 

374 """ 

375 Transform layout to a dictionary. 

376 """ 

377 if self._mesh.mesh_shape is None: 

378 raise ValueError("The device_shape of layout is None") 

379 if self._tensor_map is None: 

380 raise ValueError("The tensor_map of layout is None") 

381 interleaved_parallel = "interleaved_parallel" in self._mesh.mesh_dim_names 

382 return {"mesh_shape": self._mesh.mesh_shape, "tensor_map": self._tensor_map, 

383 "interleaved_parallel": interleaved_parallel, "alias_name": self._mesh.mesh_dim_names, 

384 "rank_list": self._rank_list} 

385 

386 def placement_to_tensor_map(self, dim): 

387 """ 

388 Transform placement to tensor map. 

389 

390 This method converts the `placements` configuration (consisting of Shard, StridedShard, 

391 Replicate, Partial) 

392 into a `tensor_map` representation used for distributed tensor operations. 

393 

394 Args: 

395 dim (int): The dimension of the tensor. Must be a positive integer. 

396 

397 Returns: 

398 tuple: A tuple representing the tensor map, where each element corresponds to a tensor dimension. 

399 A value of -1 indicates the dimension is not sharded, an integer indicates the mesh 

400 dimension index along which the tensor dimension is sharded, and a tuple indicates 

401 that the same tensor dimension is sharded multiple times in order. 

402 

403 Raises: 

404 ValueError: If `dim` is negative. 

405 ValueError: If a shard dimension in `placements` is out of bounds for the given tensor dimension. 

406 """ 

407 if dim < 0: 

408 raise ValueError(f"Tensor dimension must be positive, but got {dim}") 

409 if dim == 0: 

410 return self._handle_zero_dim_placement() 

411 

412 dim_map = self._build_dim_map_from_placements(dim) 

413 tensor_map = self._convert_dim_map_to_tensor_map(dim_map) 

414 self.set_tensor_map(tuple(tensor_map)) 

415 self._alias_tensor_map = self._build_readable_tensor_map() 

416 self.update_compact_str() 

417 return tensor_map 

418 

419 def _handle_zero_dim_placement(self): 

420 """Handle the special case of zero-dimensional tensor.""" 

421 self.set_tensor_map(()) 

422 self._alias_tensor_map = () 

423 for mesh_idx, placement in enumerate(self.normal_placements): 

424 if isinstance(placement, Partial): 

425 self._partial[mesh_idx] = self._extract_reduce_op(placement) 

426 return [] 

427 

428 def _build_dim_map_from_placements(self, dim): 

429 """Build dimension map from placements.""" 

430 dim_map = [-1] * dim 

431 self.partial_ops = {} 

432 for mesh_idx, placement in enumerate(self.normal_placements): 

433 if isinstance(placement, Shard): 

434 shard_dim = placement.dim 

435 if shard_dim < -dim or shard_dim >= dim: 

436 raise ValueError(f"Shard dimension {shard_dim} is out of bounds for tensor of dimension {dim}") 

437 if shard_dim < 0: 

438 shard_dim += dim 

439 if dim_map[shard_dim] == -1: 

440 dim_map[shard_dim] = [mesh_idx] 

441 else: 

442 dim_map[shard_dim].append(mesh_idx) 

443 elif isinstance(placement, Partial): 

444 self._partial[mesh_idx] = self._extract_reduce_op(placement) 

445 self._validate_strided_shard_split_factor(dim_map) 

446 self._reorder_dim_map_for_strided_shard(dim_map) 

447 return dim_map 

448 

449 @staticmethod 

450 def _placement_split_factor(placement): 

451 """Return the effective split factor carried by a placement.""" 

452 return placement.split_factor if isinstance(placement, StridedShard) else 1 

453 

454 @staticmethod 

455 def _build_order_positions(shard_order): 

456 """Build a mesh axis to order position mapping.""" 

457 return {mesh_idx: order_idx for order_idx, mesh_idx in enumerate(shard_order)} 

458 

459 def _compute_expected_split_factors(self, shard_axes, shard_order): 

460 """Infer the split_factor each mesh axis should carry for the given sharding order.""" 

461 order_positions = self._build_order_positions(shard_order) 

462 expected_split_factors = {} 

463 for mesh_idx in shard_axes: 

464 split_factor = 1 

465 for right_mesh_idx in shard_axes: 

466 if right_mesh_idx <= mesh_idx: 

467 continue 

468 if order_positions[right_mesh_idx] < order_positions[mesh_idx]: 

469 split_factor *= self.mesh_shape[right_mesh_idx] 

470 expected_split_factors[mesh_idx] = split_factor 

471 return expected_split_factors 

472 

473 def _get_effective_shard_axes(self, shard_axes): 

474 """Return shard axes ordered by their effective sharding order.""" 

475 return sorted( 

476 shard_axes, 

477 key=lambda mesh_idx: self._placement_split_factor(self.placements[mesh_idx]), 

478 ) 

479 

480 def _reorder_dim_map_for_strided_shard(self, dim_map): 

481 """Reorder dim_map entries to reflect the effective sharding order.""" 

482 for i, shard_axes in enumerate(dim_map): 

483 if shard_axes == -1 or len(shard_axes) <= 1: 

484 continue 

485 dim_map[i] = self._get_effective_shard_axes(shard_axes) 

486 

487 def _validate_strided_shard_split_factor(self, dim_map): 

488 """Validate that split factors match the effective sharding order.""" 

489 for shard_axes in dim_map: 

490 if shard_axes == -1: 

491 continue 

492 shard_order = self._get_effective_shard_axes(shard_axes) 

493 expected_split_factors = self._compute_expected_split_factors( 

494 shard_axes, shard_order 

495 ) 

496 for mesh_idx in shard_axes: 

497 placement = self.placements[mesh_idx] 

498 actual_split_factor = self._placement_split_factor(placement) 

499 expected_split_factor = expected_split_factors[mesh_idx] 

500 if actual_split_factor != expected_split_factor: 

501 raise ValueError( 

502 f"StridedShard split_factor mismatch on mesh axis {mesh_idx}: " 

503 f"expected {expected_split_factor}, got {actual_split_factor}." 

504 ) 

505 

506 @staticmethod 

507 def _extract_reduce_op(placement): 

508 """Extract reduce operation name from Partial placement.""" 

509 op_name = getattr(placement, "reduce_op", "sum") 

510 if isinstance(op_name, str): 

511 op_name = op_name.lower() 

512 return op_name 

513 

514 def _convert_dim_map_to_tensor_map(self, dim_map): 

515 """Convert dimension map to tensor map format.""" 

516 device_dim_count = len(self.mesh_shape) 

517 tensor_map = [] 

518 for mesh_idx in dim_map: 

519 if mesh_idx == -1: 

520 tensor_map.append(-1) 

521 continue 

522 mapped_axes = tuple(device_dim_count - 1 - axis for axis in mesh_idx) 

523 tensor_map.append(mapped_axes[0] if len(mapped_axes) == 1 else mapped_axes) 

524 return tensor_map 

525 

526 def _build_readable_tensor_map(self): 

527 """Build human-readable alias tensor map from tensor_map.""" 

528 mesh_dim_names = self._mesh.mesh_dim_names 

529 has_names = mesh_dim_names is not None 

530 

531 def _map_dim(dim): 

532 """convert dimension index to dimension name.""" 

533 if dim == -1: 

534 return "None" 

535 if not has_names: 

536 return f"dim_{dim}" 

537 return mesh_dim_names[len(mesh_dim_names) - 1 - dim] 

538 

539 readable_map = [] 

540 for item in self._tensor_map: 

541 if isinstance(item, tuple): 

542 mapped_tuple = tuple(_map_dim(dim) for dim in item) 

543 readable_map.append(mapped_tuple) 

544 else: 

545 readable_map.append(_map_dim(item)) 

546 return tuple(readable_map) 

547 

548 def tensor_map_to_placement(self): 

549 """ 

550 Transform tensor map to placement. 

551 

552 This method converts the existing `tensor_map` and `partial` status into a list of `Placement` objects 

553 (Shard, StridedShard, Replicate, Partial). This is the inverse operation of 

554 `placement_to_tensor_map`. 

555 

556 Returns: 

557 list[Placement]: A list of Placement objects describing the distribution strategy for each 

558 dimension of the device mesh. 

559 

560 Raises: 

561 ValueError: If `tensor_map` is not configured (None). 

562 """ 

563 if self._tensor_map is None: 

564 raise ValueError("The tensor_map is None, cannot transform to placements.") 

565 uneven_shard_dims = { 

566 mesh_idx: placement.dim 

567 for mesh_idx, placement in enumerate(self.placements or ()) 

568 if isinstance(placement, Shard) and placement.uneven_shard 

569 } 

570 mesh_ndim = len(self.mesh_shape) 

571 placements = [Replicate()] * mesh_ndim 

572 for tensor_dim, mapping in enumerate(self._tensor_map): 

573 mapping_list = mapping if isinstance(mapping, tuple) else (mapping,) 

574 valid_mapping = [map_val for map_val in mapping_list if map_val != -1] 

575 mesh_indices = [mesh_ndim - 1 - map_val for map_val in valid_mapping] 

576 shard_axes = sorted(mesh_indices) 

577 expected_split_factors = self._compute_expected_split_factors( 

578 shard_axes, mesh_indices 

579 ) 

580 for mesh_idx in shard_axes: 

581 split_factor = expected_split_factors[mesh_idx] 

582 uneven_shard = uneven_shard_dims.get(mesh_idx) == tensor_dim 

583 placement = ( 

584 StridedShard( 

585 dim=tensor_dim, 

586 split_factor=split_factor, 

587 uneven_shard=uneven_shard, 

588 ) 

589 if split_factor > 1 

590 else Shard(dim=tensor_dim, uneven_shard=uneven_shard) 

591 ) 

592 placements[mesh_idx] = placement 

593 for mesh_idx, op in enumerate(self.partial): 

594 if op is not None: 

595 placements[mesh_idx] = Partial(reduce_op=op) 

596 if self._ragged_shard is not None: 

597 placements[self._ragged_shard.mesh_dim] = self._ragged_shard.placement 

598 self.set_placements(placements) 

599 self._alias_tensor_map = self._build_readable_tensor_map() 

600 self.update_compact_str() 

601 return placements 

602 

603 def __setstate__(self, state): 

604 self.__dict__.update(state) 

605 self.update_mesh(init_backend=False) 

606 

607 @property 

608 def mesh(self): 

609 """ 

610 Get the device mesh associated with this layout. 

611 

612 Returns: 

613 DeviceMesh: The device mesh describing the device topology. 

614 """ 

615 return self._mesh 

616 

617 def update_mesh(self, init_backend: bool = True): 

618 """Recreate the internal DeviceMesh from current layout properties. 

619 

620 Args: 

621 init_backend (bool): Whether to initialize communication backend 

622 (process groups). Set to ``False`` during deserialization to 

623 avoid creating process groups with a stale rank_list from the 

624 sender side. Default ``True``. 

625 """ 

626 self._mesh = _create_device_mesh("npu", self.mesh_shape, mesh_dim_names=self.alias_name, 

627 rank_list=self.rank_list, init_backend=init_backend) 

628 

629 @property 

630 def rank_list(self): 

631 """ 

632 Get the list of ranks participating in this layout. 

633 

634 Returns: 

635 tuple[int]: The rank list. 

636 """ 

637 return self._rank_list 

638 

639 @rank_list.setter 

640 def rank_list(self, val): 

641 self._rank_list = val 

642 

643 @property 

644 def mesh_shape(self): 

645 """mesh shape""" 

646 return self._mesh.mesh_shape 

647 

648 @property 

649 def alias_name(self): 

650 """alias name""" 

651 return self._mesh.mesh_dim_names 

652 

653 @property 

654 def alias_tensor_map(self): 

655 """Return the human-readable alias tensor map for this layout.""" 

656 return self._alias_tensor_map 

657 

658 @property 

659 def alias_placements(self): 

660 """Return alias_tensor_map when it contains multi-axis tuples, otherwise placements. 

661 

662 alias_tensor_map preserves multi-axis ordering information 

663 (e.g., (("dp", "tp"), "None") vs (("tp", "dp"), "None")) 

664 that Placement objects cannot represent, since both map to 

665 [Shard(0), Shard(0)]. 

666 

667 For single-axis layouts, Placement objects are preferred because they 

668 also carry Partial status which alias_tensor_map cannot encode. 

669 

670 Use this property when constructing DTensors from an existing Layout 

671 to avoid the lossy Placement round-trip for multi-axis cases. 

672 """ 

673 if self._ragged_shard is not None: 

674 return self._placements 

675 if self._alias_tensor_map is not None and any( 

676 isinstance(item, tuple) for item in self._alias_tensor_map 

677 ): 

678 return self._alias_tensor_map 

679 return self._placements 

680 

681 def set_alias_tensor_map(self, alias_tensor_map): 

682 """Set alias_tensor_map""" 

683 self._alias_tensor_map = alias_tensor_map 

684 

685 @property 

686 def placements(self): 

687 """placements""" 

688 return self._placements 

689 

690 def set_placements(self, placements: Optional[Sequence[Placement]]) -> None: 

691 """Set placements and retain the RaggedShard omitted from tensor_map.""" 

692 self._placements = placements 

693 self._ragged_shard = ( 

694 None if placements is None else _extract_ragged_shard(placements) 

695 ) 

696 

697 @property 

698 def tensor_shape(self) -> Optional[tuple[int, ...]]: 

699 """Return the explicit logical global shape, if present.""" 

700 return self._tensor_shape 

701 

702 @property 

703 def tensor_stride(self) -> Optional[tuple[int, ...]]: 

704 """Return the explicit logical global stride, if present.""" 

705 return self._tensor_stride 

706 

707 @property 

708 def tensor_dtype(self) -> Optional[Any]: 

709 """Return the explicit logical dtype, if present.""" 

710 return self._tensor_dtype 

711 

712 @property 

713 def uneven_shard_mesh_dims(self) -> tuple[int, ...]: 

714 """Return mesh dimensions carrying FSDP ceil-chunk placements.""" 

715 return tuple( 

716 mesh_dim 

717 for mesh_dim, placement in enumerate(self._placements or ()) 

718 if isinstance(placement, Shard) and placement.uneven_shard 

719 ) 

720 

721 @property 

722 def has_uneven_shard(self) -> bool: 

723 """Return whether any placement uses FSDP ceil-chunk geometry.""" 

724 return bool(self.uneven_shard_mesh_dims) 

725 

726 def set_tensor_meta( 

727 self, 

728 shape: Sequence[int], 

729 stride: Sequence[int], 

730 dtype: Any, 

731 ) -> None: 

732 """Set logical tensor metadata independently from local shard storage. 

733 

734 Args: 

735 shape: Logical global tensor shape. 

736 stride: Logical global tensor stride. 

737 dtype: Logical tensor dtype. 

738 """ 

739 self._tensor_shape = tuple(shape) 

740 self._tensor_stride = tuple(stride) 

741 self._tensor_dtype = dtype 

742 self.update_compact_str() 

743 

744 @property 

745 def normal_placements(self) -> Optional[tuple[Placement, ...]]: 

746 """Return placements with RaggedShard represented as Replicate.""" 

747 if self._placements is None: 

748 return None 

749 return _replace_ragged_with_replicate(self._placements) 

750 

751 @property 

752 def ragged_shard(self) -> Optional[RaggedShardInfo]: 

753 """Return the RaggedShard placement and its mesh dimension, if present.""" 

754 return self._ragged_shard 

755 

756 @property 

757 def tensor_map(self): 

758 """tensor map""" 

759 return self._tensor_map 

760 

761 def set_tensor_map(self, tensor_map): 

762 """Set tensor_map.""" 

763 self._tensor_map = tensor_map 

764 

765 @property 

766 def partial(self): 

767 """partial status""" 

768 return self._partial 

769 

770 def set_partial_by_dev_axis(self, axis, op): 

771 """Set the partial status for the specified dev ID, means pending to do reduce by op.""" 

772 if op not in self._support_partial_op: 

773 raise ValueError(f"Partial op must be one of {self._support_partial_op}, but got {op}") 

774 if self.is_dev_axis_apply_shard(axis): 

775 raise ValueError("Partial dim must be replicate.") 

776 self._partial[self._mesh.axis_index(axis)] = op 

777 self.tensor_map_to_placement() 

778 self.update_compact_str() 

779 

780 def get_partial_by_dev_id(self, axis): 

781 """Get the partial status for the specified dev id""" 

782 return self.partial[self._mesh.axis_index(axis)] 

783 

784 def is_dev_axis_apply_shard(self, axis): 

785 """Return true if device axis is applying shard""" 

786 axis_id = self._mesh.axis_id(axis) 

787 

788 def flatten(input_x): 

789 flatten_res = [] 

790 for item in input_x: 

791 if isinstance(item, tuple): 

792 flatten_res.extend(flatten(item)) 

793 else: 

794 flatten_res.append(item) 

795 return flatten_res 

796 

797 flatten_tensor_map = flatten(self.tensor_map) 

798 return axis_id in flatten_tensor_map 

799 

800 def get_dev_axis_apply_shard_axis(self, axis): 

801 """Return the axis which be split by axis. If axis not be apply to shard, return None.""" 

802 for dim, dim_map in enumerate(self.alias_tensor_map): 

803 if (isinstance(dim_map, tuple) and axis in dim_map) or axis == dim_map: 

804 return dim 

805 return None 

806 

807 def reset_partial(self): 

808 """Clear all partial statuses and regenerate placements from the tensor map.""" 

809 self._partial = [None] * len(self.mesh_shape) 

810 self.tensor_map_to_placement() 

811 self.update_compact_str() 

812 

813 def is_partial(self): 

814 """Return true if any dim in mesh_shape is partial""" 

815 return any(self.partial) 

816 

817 def get_dim_split_num(self, tensor_dim: int) -> int: 

818 """Return the total shard count for ``tensor_dim`` via alias_tensor_map. 

819 

820 Args: 

821 tensor_dim: Tensor dimension index to check. 

822 

823 Returns: 

824 Number of shards (1 if not sharded or no alias_tensor_map set). 

825 """ 

826 alias_tm = self.alias_tensor_map 

827 if alias_tm is None or tensor_dim >= len(alias_tm): 

828 return 1 

829 dim_entry = alias_tm[tensor_dim] 

830 if dim_entry == 'None': 

831 return 1 

832 if isinstance(dim_entry, str): 

833 return self.mesh.get_device_num_along_axis(dim_entry) 

834 if isinstance(dim_entry, tuple): 

835 total = 1 

836 for axis in dim_entry: 

837 if axis != 'None': 

838 total *= self.mesh.get_device_num_along_axis(axis) 

839 return total 

840 return 1 

841 

842 def get_split_id(self, tensor_dim: int) -> int: 

843 """Return this rank's global position among all shards of ``tensor_dim``. 

844 

845 For a single sharding axis, returns the rank's position within that axis group. 

846 For multiple sharding axes (e.g. dp+cp both sharding T1), computes the combined 

847 global position as a mixed-radix number ordered by the axis tuple: 

848 global_id = ax0_pos * ax1_size * ... + ax1_pos * ax2_size * ... + axN_pos 

849 This matches MindFormers' ``offset_id = dp_rank * (cp*tp) + cp_rank * tp + tp_rank`` 

850 for combined sequence-parallel sharding across dp, cp, and tp dimensions. 

851 

852 Args: 

853 tensor_dim: Tensor dimension index to query. 

854 

855 Returns: 

856 Split index for this rank (0 if not sharded or rank not in rank list). 

857 """ 

858 alias_tm = self.alias_tensor_map 

859 if alias_tm is None or tensor_dim >= len(alias_tm): 

860 return 0 

861 dim_entry = alias_tm[tensor_dim] 

862 if dim_entry == 'None': 

863 return 0 

864 rank = dist.get_rank() 

865 if isinstance(dim_entry, tuple): 

866 non_none = [ax for ax in dim_entry if ax != 'None'] 

867 if not non_none: 

868 return 0 

869 global_id = 0 

870 for ax in non_none: 

871 rank_list = self.mesh.get_rank_list_along_axis(ax) 

872 local_id = rank_list.index(rank) if rank in rank_list else 0 

873 ax_size = self.mesh.get_device_num_along_axis(ax) 

874 global_id = global_id * ax_size + local_id 

875 return global_id 

876 if isinstance(dim_entry, str): 

877 rank_list = self.mesh.get_rank_list_along_axis(dim_entry) 

878 return rank_list.index(rank) if rank in rank_list else 0 

879 return 0 

880 

881 def get_global_shape(self, slice_shape): 

882 """get global shape""" 

883 if self._tensor_shape is not None: 

884 return self._tensor_shape 

885 return self._mesh.get_global_shape(slice_shape, self._tensor_map) 

886 

887 def get_devices_for_axis(self, axis, rank): 

888 """ 

889 Get the repeat rank list when the axis is not shard. 

890 

891 Args: 

892 layout (Layout): Layout 

893 axis (str): Axis name. 

894 rank (int): Global rank 

895 

896 Returns: 

897 list: reduce rank list 

898 """ 

899 return self._mesh.get_devices_for_axis(axis, rank) 

900 

901 def get_comm_group_by_axis(self, axis): 

902 """Return the communication group for the specified mesh axis via the underlying DeviceMesh.""" 

903 return self._mesh.get_comm_group_by_axis(axis) 

904 

905 def repeat_num(self): 

906 """ 

907 Number of repeated placements. 

908 For example: 

909 layout = Layout((2, 4), ("dp", "mp")) 

910 x_layout = layout("dp", "None") 

911 The repeat_num is equal to all device num 8 divided by device num corresponding to used axis 2, that is 4. 

912 """ 

913 if self._tensor_map is None: 

914 raise ValueError(f"The tensor_map is None, the mesh_shape is {self._mesh.mesh_shape}," 

915 f" alias_name is {self._mesh.mesh_dim_names}") 

916 

917 all_device_num = functools.reduce(lambda x, y: x * y, self._mesh.mesh_shape) 

918 used_dev_num = 1 

919 for ele in self._tensor_map: 

920 if isinstance(ele, tuple): 

921 for item in ele: 

922 if item >= 0: 

923 used_dev_num *= self._mesh.mesh_shape[len(self._mesh.mesh_shape) - item - 1] 

924 continue 

925 if ele >= 0: 

926 used_dev_num *= self._mesh.mesh_shape[len(self._mesh.mesh_shape) - ele - 1] 

927 

928 return all_device_num // used_dev_num 

929 

930 def _to_compact_string(self): 

931 """ 

932 generate dict key 

933 

934 Returns: 

935 str: string for compact 

936 """ 

937 mesh_key = self._mesh.to_hash() 

938 hash_key = ( 

939 self._tensor_map, 

940 self.partial, 

941 self.uneven_shard_mesh_dims, 

942 self._tensor_shape, 

943 self._tensor_stride, 

944 str(self._tensor_dtype), 

945 ) 

946 hash_key += mesh_key 

947 return str(hash_key) 

948 

949 @property 

950 def compact_str(self): 

951 """Return the cached compact string representation of this layout.""" 

952 return self._compact_str 

953 

954 def update_compact_str(self): 

955 """Recompute and store the compact string representation of this layout.""" 

956 self._compact_str = self._to_compact_string() 

957 

958 def to_string(self): 

959 """ 

960 layout dump 

961 

962 Returns: 

963 str: layout string 

964 """ 

965 device_info = f"Mesh shape: {self._mesh.mesh_shape}" 

966 alias_info = f"Alias Names: {self._mesh.mesh_dim_names}" 

967 rank_info = f"Rank List: {self._rank_list}" 

968 partial_info = f"Partial: {self.partial}" 

969 

970 if self._tensor_map is None: 

971 tensor_info = "Tensor Map: Not configured" 

972 else: 

973 readable_map = [] 

974 for item in self._tensor_map: 

975 if isinstance(item, tuple): 

976 # handle nested tuple 

977 mapped_tuple = tuple( 

978 self._mesh.mesh_dim_names[len(self._mesh.mesh_dim_names) - 1 - dim] if dim != -1 else "None" 

979 for dim in item 

980 ) 

981 readable_map.append(mapped_tuple) 

982 else: 

983 readable_map.append( 

984 self._mesh.mesh_dim_names[len(self._mesh.mesh_dim_names) - 1 - item] if item != -1 else "None" 

985 ) 

986 

987 tensor_info = f"Tensor Map: {tuple(readable_map)}" 

988 

989 interleaved = "Yes" if "interleaved_parallel" in self._mesh.mesh_dim_names else "No" 

990 interleaved_info = f"Interleaved Parallel: {interleaved}" 

991 

992 return ( 

993 f"Layout Configuration:\n" 

994 f" {device_info}\n" 

995 f" {alias_info}\n" 

996 f" {partial_info}\n" 

997 f" {tensor_info}\n" 

998 f" {interleaved_info}\n" 

999 f" {rank_info}" 

1000 ) 

1001 

1002 def __str__(self): 

1003 """__str__""" 

1004 return self.to_string() 

1005 

1006 def __repr__(self): 

1007 """__repr__""" 

1008 return f"<Layout at {hex(id(self))}>" 

1009 

1010 def __eq__(self, other): 

1011 """ 

1012 __eq__ 

1013 """ 

1014 if not isinstance(other, Layout): 

1015 return False 

1016 

1017 same_layout_attrs = ( 

1018 self.mesh_shape, 

1019 self.alias_name, 

1020 self.partial, 

1021 self.rank_list, 

1022 self.uneven_shard_mesh_dims, 

1023 self.tensor_shape, 

1024 self.tensor_stride, 

1025 self.tensor_dtype, 

1026 ) == ( 

1027 other.mesh_shape, 

1028 other.alias_name, 

1029 other.partial, 

1030 other.rank_list, 

1031 other.uneven_shard_mesh_dims, 

1032 other.tensor_shape, 

1033 other.tensor_stride, 

1034 other.tensor_dtype, 

1035 ) 

1036 if not same_layout_attrs: 

1037 return False 

1038 

1039 if self._tensor_map is None or other.tensor_map is None: 

1040 return self._tensor_map is other.tensor_map 

1041 return self._tensor_map == other.tensor_map