Diff Coverage

Diff: origin/master...HEAD, staged and unstaged changes

Source File Diff Coverage (%) Missing Lines
hyper_parallel/core/dtensor/_collective_utils.py 25.0% 54-56,58,94-95,107,121,142
hyper_parallel/core/dtensor/_from_local_utils.py 60.0% 54,80
hyper_parallel/core/dtensor/_ragged_utils.py 66.7% 201
hyper_parallel/core/dtensor/_utils.py 20.0% 46-52,57,62-66,71-78,83-85,90-103,108,114-116,137,146-150,155,160-163,168-171,176,181-185,190-194,199-202,211-213,215-218,220,222-223,236-238,240-247,249,254-255,264-268,273-274,279,291-298,329-332,334-335,337-338,340-341,344-347,351,353,355,357,359-360,367-369,372-373,379-382,385,387-388,394,413-416,418-419,422-431,434,436-437,440-441,443,445-446,449-450,453-454,456-457,459,472-473,478-479,494-501,506,508-513,518-521,530-536,541-544,548-555,578-580,582-583,591-592,595,643-644,647-648,659-660,662-663,665,674-677,679-683,694-695,697-698,700,707,709-713,722-726,730-732,737-739,743-745,754-760,762-766,772-776,778-780,782-787,792-795,800-803,805-808,816-820,825-826,830-835,840,845-847,852,854-855,860-862,865,867,870-872,877-878,882,897,903,913-915,921,929,936,941-943,952,957,973-974,977-980,983-986,989-992,994-998,1000-1002
hyper_parallel/core/dtensor/debug/_collective_tracer.py 25.0% 50,53-54,70,75-76
hyper_parallel/core/dtensor/debug/_comm_debug_mode.py 100%  
hyper_parallel/core/dtensor/debug/_dispatch_logger.py 100%  
hyper_parallel/core/dtensor/device_mesh.py 22.2% 40,191,194,204,222,246,319,348,420,443,446,455-456,503,755,757,780,782,1315,1480,1482
hyper_parallel/core/dtensor/dtensor.py 14.8% 82,434,614-618,621-627,1004,1078,1083-1084,1317,1368,1397,1429,1458
hyper_parallel/core/dtensor/init_weights.py 50.0% 49,70
hyper_parallel/core/dtensor/layout.py 50.0% 843
hyper_parallel/core/dtensor/parameter_init.py 0.0% 29-32
hyper_parallel/core/dtensor/random.py 18.2% 70,100,105,113,118,137,178,193,443-444,447,492,556,568,577-578,583,585
hyper_parallel/core/dtensor/tensor_redistribution.py 11.1% 75,82,89,97,103,111,117,158,300,345,418,457,460-461,464,479
hyper_parallel/core/dtensor/_collective_utils.py
50
51
52
53
54
55
56
57
58
59
60
61
62
    contiguous_list = [
        chunk.contiguous() if hasattr(chunk, "is_contiguous") and not chunk.is_contiguous() else chunk
        for chunk in scatter_list
    ]
    src = dist.get_global_rank(group, group_src)
    if dist.get_group_rank(group, dist.get_rank()) == group_src:
        dist.scatter(output, list(contiguous_list), src=src, group=group)
    else:
        dist.scatter(output, None, src=src, group=group)
    return output


def mesh_scatter_ragged(
90
91
92
93
94
95
96
97
98
99
        raise ValueError(
            f"group_src must be in [0, {group_size}), but got {group_src}"
        )

    group_rank = dist.get_group_rank(group, dist.get_rank())
    source_global_rank = dist.get_global_rank(group, group_src)
    if group_rank == group_src:
        if scatter_list is None or len(scatter_list) != group_size:
            raise ValueError(
                "source scatter_list length must equal the mesh dimension size, "
103
104
105
106
107
108
109
110
111
        works = []
        for destination_group_rank, chunk in enumerate(scatter_list):
            if destination_group_rank == group_src:
                continue
            destination_global_rank = dist.get_global_rank(
                group, destination_group_rank
            )
            works.append(
                dist.isend(
117
118
119
120
121
122
123
124
125
        for work in works:
            work.wait()
        return output

    work = dist.irecv(
        output,
        src=source_global_rank,
        group=group,
    )
138
139
140
141
142
143
    _ensure_mesh_process_groups(mesh)
    group = mesh.get_group(mesh_dim)
    if hasattr(tensor, "is_contiguous") and not tensor.is_contiguous():
        tensor = tensor.contiguous()
    dist.broadcast(tensor, src=dist.get_global_rank(group, group_src), group=group)
    return tensor
hyper_parallel/core/dtensor/_from_local_utils.py
50
51
52
53
54
55
56
57
58
    if hasattr(tensor, "is_contiguous") and not tensor.is_contiguous():
        tensor = tensor.contiguous()
    rank_list = mesh.get_rank_list_along_axis(mesh_dim)
    src = rank_list[group_src]
    dist.broadcast(tensor, src, group=group)
    return tensor


def _tensor_meta(local_tensor: Tensor, *, check_shape_stride: bool) -> dict:
76
77
78
79
80
81
82
83
84
) -> None:
    """Gather tensor metadata across *group* and verify consistency."""
    local_meta = _tensor_meta(local_tensor, check_shape_stride=check_shape_stride)
    gathered = [None] * group_size
    dist.all_gather_object(gathered, local_meta, group=group)
    if not all(meta == local_meta for meta in gathered if meta is not None):
        raise ValueError(
            "Inconsistent tensor metadata across ranks in from_local(run_check=True): "
            f"local={local_meta}, gathered={gathered}"
hyper_parallel/core/dtensor/_ragged_utils.py
197
198
199
200
201
202
203
204
205
        raise ValueError("distribute_tensor with RaggedShard requires a contiguous tensor")
    info = layout.ragged_shard
    ragged_slice = _compute_ragged_slice(tuple(tensor.shape), layout)
    flat_tensor = tensor.reshape((-1,))
    output = torch.empty(
        (ragged_slice.local_numel,),
        dtype=tensor.dtype,
        device=getattr(tensor, "device", None),
    )
hyper_parallel/core/dtensor/_utils.py
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112

    ``out_perm`` has shape ``[ws, *rest_dims]``, chunk at ``concat_dim + 1``.
    Returns tensor with merged chunk dimension.
    """
    new_ndim = out_perm.dim()
    chunk_in_perm = concat_dim + 1
    recon_perm = list(range(1, chunk_in_perm)) + [0] + list(range(chunk_in_perm, new_ndim))
    x_recon = out_perm.permute(recon_perm).contiguous()
    shape = list(x_recon.shape)
    merged = shape[concat_dim] * shape[concat_dim + 1]
    return x_recon.reshape(shape[:concat_dim] + [merged] + shape[concat_dim + 2:])


def _normalize_dim(dim: int, ndim: int) -> int:
    """Normalize a possibly negative dimension index."""
    return dim + ndim if dim < 0 else dim


def _move_dim_to_front(tensor: torch.Tensor, dim: int) -> torch.Tensor:
    """Move ``dim`` to the front while keeping the other dimensions ordered."""
    dim = _normalize_dim(dim, tensor.dim())
    if dim == 0:
        return tensor.contiguous()
    perm = [dim] + [i for i in range(tensor.dim()) if i != dim]
    return tensor.permute(perm).contiguous()


def _move_dim_from_front(tensor: torch.Tensor, dim: int) -> torch.Tensor:
    """Inverse of :func:`_move_dim_to_front`."""
    dim = _normalize_dim(dim, tensor.dim())
    if dim == 0:
        return tensor.contiguous()
    perm = [dim] + [i for i in range(tensor.dim()) if i != dim]
    inverse = [0] * len(perm)
    for idx, value in enumerate(perm):
        inverse[value] = idx
    return tensor.permute(inverse).contiguous()


def _ensure_contiguous(x):
    """Return a contiguous copy of *x* if not already contiguous."""
    if torch.compiler.is_compiling():
        return x.contiguous()
    return x if x.is_contiguous() else x.contiguous()


def get_op_name(func):
    """Extract the canonical operation name from a callable or torch op overload."""
    if hasattr(func, "__name__"):
        return func.__name__
    if isinstance(func, OpOverload):
        full_name = func.name
        core_name = full_name.split("::")[-1].split(".")[0]
        return core_name
    if isinstance(func, OpOverloadPacket):
        return func.name.split("::")[-1]
    func_str = str(func)
    if "built-in function" in func_str:
        return func_str.split()[-1].strip(">")
    if "function" in func_str:
        return func_str.split()[1]
    return "unknown_op"


def tensor_type_cast(input_data, cast_type):
    """Cast tensor to specified data type."""
    type_mapping = {
        'float32': torch.float32,
        'float16': torch.float16,
        'int64': torch.int64,
        'int32': torch.int32
110
111
112
113
114
115
116
117
118
119
120
        'float16': torch.float16,
        'int64': torch.int64,
        'int32': torch.int32
    }
    if cast_type not in type_mapping:
        raise ValueError(f"Unknown cast type: {cast_type}. Supported types: {list(type_mapping.keys())}")
    return input_data.to(type_mapping[cast_type])


# Mapping from string op names to torch.distributed.ReduceOp
_OP_MAP = {
133
134
135
136
137
138
139
140
141
    _OP_MAP['mean'] = dist.ReduceOp.AVG
else:
    # Fallback for older torch versions if necessary, though this might require manual division upstream
    # Assuming standard behavior where 'mean' implies native AVG support or upstream handling
    _OP_MAP['mean'] = dist.ReduceOp.SUM


# ---------------------------------------------------------------------------
# Device / process group helpers
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
# ---------------------------------------------------------------------------

def get_device_handle(device_type: str = "npu"):  # pylint: disable=W0621
    """Return the torch device module (e.g. ``torch.npu`` or ``torch.cuda``) for the given device type."""
    try:
        handle = getattr(torch, device_type)
    except AttributeError as e:
        raise RuntimeError(f"expect got device handle: 'torch.{device_type}' failed.") from e
    return handle


def device_count(device_handle):
    """Return the number of available devices for *device_handle*."""
    return device_handle.device_count()


def device_type():
    """Return the current device type string ("npu" for NPU, "cuda" for GPU)."""
    device_handle = get_device_handle()
    if device_handle == getattr(torch, "npu", None):
        return "npu"
    return "cuda"


def device(device_idx=None):
    """Return a :class:`torch.device` for the current device type."""
    current_device_type = device_type()
    if device_idx is None:
        return torch.device(current_device_type)
    return torch.device(f"{current_device_type}:{device_idx:d}")


def manual_seed(seed):
    """Set the random seed for reproducibility."""
    return torch.manual_seed(seed)


def get_rng_state(device=None, device_handle=None):  # pylint: disable=W0621
    """Get the random number generator state."""
    if device_handle is None:
        return torch.get_rng_state()
    if device is None:
        return device_handle.get_rng_state()
    return device_handle.get_rng_state(device)


def set_rng_state(state, device=None, device_handle=None):  # pylint: disable=W0621
    """Set the random number generator state."""
    if device_handle is None:
        return torch.set_rng_state(state)
    if device is None:
        return device_handle.set_rng_state(state)
    return device_handle.set_rng_state(state, device)


def get_created_group(rank_list: Union[list[int], tuple[int]]):
    """Return an existing process group by rank list, or ``None``."""
    group_key = str(tuple(sorted(rank_list)))
    if group_key in EXISTING_COMM_GROUPS:
        return EXISTING_COMM_GROUPS[group_key]
    return None


def create_group(rank_list):
    """Create or retrieve a communication group with the specified ranks.
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227

    If a group with the same rank list already exists, returns the existing
    group instead of creating a new one.
    """
    group_key = str(tuple(sorted(rank_list)))
    if group_key in EXISTING_COMM_GROUPS:
        return EXISTING_COMM_GROUPS[group_key]

    normalized_rank_list = tuple(sorted(rank_list))
    world_rank_list = tuple(range(dist.get_world_size()))
    if normalized_rank_list == world_rank_list:
        group = _get_default_group()
    else:
        group = create_sub_groups(rank_list)[normalized_rank_list]

    EXISTING_COMM_GROUPS[group_key] = group
    return group


def split_group(parent_pg: Optional[ProcessGroup] = None,
                split_ranks: Optional[list] = None,
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
    """Create split groups for every rank list in *split_ranks*.

    Returns the split process group relative to the current rank id.
    """
    del parent_pg, timeout, group_desc
    if split_ranks is None or len(split_ranks) == 0:
        raise ValueError("split_ranks cannot be None or empty")

    split_group_pg = None
    for split_rank in split_ranks:
        dist_group = get_created_group(split_rank)
        if dist_group is None:
            dist_group = dist.new_group(ranks=split_rank, pg_options=pg_options)
            EXISTING_COMM_GROUPS[str(tuple(sorted(split_rank)))] = dist_group
        if dist.get_rank() in split_rank:
            split_group_pg = dist_group

    return split_group_pg


def init_process_group(*args, **kwargs):
    """Initialize the default torch distributed process group."""
    if not dist.is_initialized():
        dist.init_process_group(*args, **kwargs)


# ---------------------------------------------------------------------------
# Sub-group construction
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
# ---------------------------------------------------------------------------

def _validate_intra_step(normalized_template: list[int], template_len: int) -> int:
    """Verify consistent intra-group step and return intra_step."""
    intra_step = normalized_template[1] - normalized_template[0]
    for i in range(1, template_len - 1):
        diff = normalized_template[i + 1] - normalized_template[i]
        if diff != intra_step:
            msg = (
                f"Template must have consistent intra-group step. "
                f"Found {normalized_template[i+1]} - {normalized_template[i]} = {diff}, "
                f"expected {intra_step}"
            )
            raise ValueError(msg)
    return intra_step


def _compute_group_starts(world_size: int, block_size: int, inter_step: int) -> list[int]:
    """Compute all valid block start positions."""
    return [s for s in range(0, world_size, inter_step) if s + block_size <= world_size]


def _build_groups_for_blocks(
    group_starts: list[int],
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
    template_len: int,
    world_size: int,
) -> list[list[int]]:
    """Build all groups from block starts."""
    all_groups = []
    for start_block in group_starts:
        max_offset = block_size - template_span_int
        for offset in range(0, max_offset):
            group = [start_block + offset + normalized_template[i] for i in range(template_len)]
            if all(0 <= r < world_size for r in group):
                all_groups.append(group)
    return all_groups


def generate_groups_from_template(
    template: Union[list[int], tuple[int, ...]],
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
        3. Iterate by blocks, generate valid sub-groups per block
        4. Ensure each rank appears in exactly one group
    """
    # convert template to int list and sort (rank_list may come from numpy/tensor as float)
    template = sorted([int(x) for x in list(template)])
    world_size = int(world_size)
    my_rank = int(my_rank)
    template_len = len(template)

    if verbose:
        print(f"Rank {my_rank}: Original Template = {template}, World size = {world_size}")

    if template_len == 1:
        return [[i] for i in range(world_size)]

    if template_len < 2:
        raise ValueError(f"Template must have at least 2 ranks, got {template}")

    # 1. Template normalization: convert to 0-based template
    template_base = template[0]  # original template start value
    normalized_template = [x - template_base for x in template]  # normalize to 0-based
    if verbose:
        print(f"Rank {my_rank}: Normalized Template = {normalized_template}")

    # 2. Analyze normalized template core params
    # intra-step: spacing between elements in template
    intra_step = _validate_intra_step(normalized_template, template_len)
    # template span: last - first element of normalized template
    template_span = normalized_template[-1] - normalized_template[0]
    # block size: ranks per block (determines inter-step)
    block_size = int(intra_step * template_len)
    # inter-step: spacing between adjacent blocks (equals block_size)
    inter_step = block_size

    if verbose:
        print(
            f"Rank {my_rank}: Template analysis - "
            f"intra_step={intra_step}, template_span={template_span}, "
            f"block_size={block_size}, inter_step={inter_step}"
        )
363
364
365
366
367
368
369
370
371
372
373
374
375
376
            f"block_size={block_size}, inter_step={inter_step}"
        )

    # 3. Compute all valid block start positions
    group_starts = _compute_group_starts(world_size, block_size, inter_step)
    if verbose:
        print(f"Rank {my_rank}: Possible block starts: {group_starts}")

    # 4. Generate all valid sub-groups for each block
    template_span_int = int(template_span)
    all_groups = _build_groups_for_blocks(
        group_starts, block_size, template_span_int,
        normalized_template, template_len, world_size
    )
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
        normalized_template, template_len, world_size
    )

    # 5. Validate: ensure each rank appears exactly once
    all_ranks = [rank for group in all_groups for rank in group]
    unique_ranks = set(all_ranks)
    if len(all_ranks) != len(unique_ranks):
        raise ValueError("Duplicate ranks found! Some ranks appear in multiple groups.")

    # 6. Sort: ensure all processes generate groups in same order
    all_groups.sort(key=lambda x: (x[0], x[1] if len(x) > 1 else 0))

    if verbose:
        print(
            f"Rank {my_rank}: Generated {len(all_groups)} groups, "
            f"covering {len(unique_ranks)} unique ranks\n"
            f"Final group list: {all_groups}"
        )
390
391
392
393
394
395
396
397
398
            f"covering {len(unique_ranks)} unique ranks\n"
            f"Final group list: {all_groups}"
        )

    return all_groups


def create_sub_groups(
    rank_list: Union[list[int], tuple[int, ...]],
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463

    Returns:
        Dict, key is tuple of group ranks, value is ProcessGroup
    """
    my_rank = dist.get_rank()
    world_size = dist.get_world_size()
    template = list(rank_list)
    full_rank_list = generate_groups_from_template(template, world_size, my_rank, verbose=verbose)

    if verbose:
        print(f"Rank {my_rank}: Full rank list to create: {full_rank_list}")

    # validate full group list format
    for i, group in enumerate(full_rank_list):
        if not isinstance(group, (list, tuple)):
            raise ValueError(f"Group {i} must be a list or tuple, got {type(group)}")
        if len(group) == 0:
            raise ValueError(f"Group {i} is empty")
        if len(group) != len(set(group)):
            raise ValueError(f"Group {i} contains duplicate ranks")
        for rank in group:
            if not isinstance(rank, int):
                raise ValueError(f"Rank must be integer, got {type(rank)} in group {i}")

    # sort by first element to ensure all processes create groups in same order
    sorted_groups = sorted(full_rank_list, key=lambda x: x[0])

    if verbose:
        print(f"Rank {my_rank}: Sorted groups for creation: {sorted_groups}")

    # create all groups and collect groups current process belongs to
    group_dict = {}
    for group_ranks in sorted_groups:
        # ensure ranks are ordered so each process passes same order
        sorted_ranks = sorted(group_ranks)

        if verbose:
            print(f"Rank {my_rank}: Creating group with ranks {sorted_ranks}")

        # key: all processes participate in each group creation
        group = dist.new_group(ranks=sorted_ranks)
        EXISTING_COMM_GROUPS[str(tuple(sorted_ranks))] = group

        # only save when current process is in the group
        if my_rank in sorted_ranks:
            group_dict[tuple(sorted_ranks)] = group

    if verbose:
        print(f"Rank {my_rank}: Created {len(group_dict)} groups I belong to")

    return group_dict


# ---------------------------------------------------------------------------
# Differentiable collectives
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483

    @staticmethod
    def forward(ctx: Any, tensor: Tensor) -> Tensor:  # pylint: disable=arguments-differ
        """Return the input unchanged in the forward pass."""
        del ctx
        return tensor

    @staticmethod
    def backward(ctx: Any, grad_output: Tensor) -> Tensor:  # pylint: disable=arguments-differ
        """Return a contiguous gradient to the preceding autograd node."""
        del ctx
        return grad_output.contiguous()


class _TorchAsyncA2AFunction(torch.autograd.Function):
    """Differentiable wrapper for pre-launched async all-to-all.
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
    @staticmethod
    def forward(ctx, x, work, out_perm, group, world_size, concat_dim, split_dim,  # pylint: disable=arguments-differ
                handle_box):
        """Wait for pre-launched async A2A and return reconstructed output."""
        ctx.group = group
        ctx.world_size = world_size
        ctx.concat_dim = concat_dim
        ctx.split_dim = split_dim
        ctx.handle_box = handle_box
        ctx.x_shape = x.shape
        work.wait()
        return _a2a_reconstruct(out_perm, concat_dim)

    @staticmethod
    def backward(ctx, grad_output):
        """Launch async head→seq A2A for backward overlap, or return zero grad."""
        if ctx.handle_box is not None:
            # Launch async head→seq A2A (reverse of forward seq→head)
            g = grad_output.contiguous()
            shape = list(g.shape)
            seq_dim = ctx.concat_dim
            s_full = shape[seq_dim]
            ndim = len(shape) + 1
            x_perm = g.reshape(
                shape[:seq_dim] + [ctx.world_size, s_full // ctx.world_size] + shape[seq_dim + 1:]
            ).permute(
                [seq_dim] + list(range(seq_dim)) + list(range(seq_dim + 1, ndim))
            ).contiguous()
            out_perm = torch.empty_like(x_perm)
            work = dist.all_to_all_single(out_perm, x_perm, group=ctx.group, async_op=True)
            ctx.handle_box.append((work, out_perm))
        return grad_output.new_zeros(ctx.x_shape), None, None, None, None, None, None, None


class _TorchAsyncAllGatherFunction(torch.autograd.Function):
    """Differentiable wrapper for pre-launched async all-gather."""
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559

    @staticmethod
    def forward(ctx, x, work, out_perm, group, world_size, gather_dim, handle_box):  # pylint: disable=arguments-differ
        """Wait for pre-launched all-gather and reconstruct the gathered tensor."""
        ctx.group = group
        ctx.world_size = world_size
        ctx.gather_dim = gather_dim
        ctx.handle_box = handle_box
        ctx.x_shape = x.shape
        work.wait()
        return _move_dim_from_front(out_perm, gather_dim)

    @staticmethod
    def backward(ctx, grad_output):
        """Launch reverse reduce-scatter for the all-gather."""
        grad_perm = _move_dim_to_front(grad_output.contiguous(), ctx.gather_dim)
        output_shape = list(grad_perm.shape)
        if output_shape[0] % ctx.world_size != 0:
            raise ValueError(
                "all_gather backward expected gathered dimension to be divisible by world_size, "
                f"got {output_shape[0]} and {ctx.world_size}."
            )
        output_shape[0] //= ctx.world_size
        output = torch.empty(output_shape, dtype=grad_perm.dtype, device=grad_perm.device)
        work = dist.reduce_scatter_tensor(output, grad_perm, group=ctx.group, async_op=True)
        if ctx.handle_box is not None:
            ctx.handle_box.append((work, output, ctx.gather_dim))
            return grad_output.new_zeros(ctx.x_shape), None, None, None, None, None, None
        work.wait()
        return _move_dim_from_front(output, ctx.gather_dim), None, None, None, None, None, None


class _AsyncA2ALazyBwd(torch.autograd.Function):
    """All-to-all whose forward AND backward return ``AsyncCollectiveTensor``.
574
575
576
577
578
579
580
581
582
583
584
585
586
587

    @staticmethod
    def forward(ctx, input_tensor, output_splits, input_splits, group):  # pylint: disable=arguments-differ
        """Perform the forward all-to-all single collective, saving splits and group for backward."""
        ctx.input_splits = input_splits
        ctx.output_splits = output_splits
        ctx.group = group
        # pylint: disable=C0415
        from torch.distributed._functional_collectives import all_to_all_single
        return all_to_all_single(
            input_tensor, output_splits, input_splits, group,
        )

    @staticmethod
587
588
589
590
591
592
593
594
595
596
597
598
599
    @staticmethod
    def backward(ctx, grad_output):
        """Compute the backward pass by performing the inverse all-to-all with swapped splits."""
        # pylint: disable=C0415
        from torch.distributed._functional_collectives import all_to_all_single
        grad_input = all_to_all_single(
            grad_output, ctx.input_splits, ctx.output_splits, ctx.group,
        )
        return grad_input, None, None, None


class _TorchSyncHookFunction(torch.autograd.Function):
    """Autograd identity that fires HookCoordinator rendezvous on fwd/bwd.
639
640
641
642
643
644
645
646
647
648
649
650
651
652
    _ROLE_CACHE = None

    @staticmethod
    def _role_enum(idx: int):
        if _TorchSyncHookFunction._ROLE_CACHE is None:
            from hyper_parallel.core.pipeline_parallel.hook_coordinator import (  # pylint: disable=C0415
                HookRole,
            )
            _TorchSyncHookFunction._ROLE_CACHE = (None, HookRole.COMM, HookRole.COMPUTE)
        return _TorchSyncHookFunction._ROLE_CACHE[idx]  # pylint: disable=E1136

    @staticmethod
    def forward(ctx, x, hook_name, coordinator):  # pylint: disable=arguments-differ
        """Identity forward that fires a HookCoordinator rendezvous.
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
        role per the ``_FWD_ROLES`` table.  ``"D_LAST"`` is a sentinel
        meaning "skip this rendezvous" (last layer's closing D — no
        Attention follows).
        """
        ctx.hook_name = hook_name
        ctx.coordinator = coordinator

        if not coordinator.is_enabled():
            return x

        if hook_name == "D_LAST":
            # ``D_LAST`` marks the last layer's closing D hook — no
            # Attention follows in this chunk, so the rendezvous is
            # meaningless and is skipped.  We still
            # ``notify_dispatched(COMM)`` so the COMPUTE side of the
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
            # preceding ``C`` rendezvous unblocks early, letting
            # BWD's Attn.bwd_last overlap with FWD's post-combine
            # work — Torch autograd is thread-safe so this concurrent
            # FWD-record + BWD-replay is fine.
            prev_idx, _ = _TorchSyncHookFunction._FWD_ROLES["D"]
            role_of = _TorchSyncHookFunction._role_enum
            coordinator.notify_dispatched(role_of(prev_idx))
            return x

        prev_idx, next_idx = _TorchSyncHookFunction._FWD_ROLES[hook_name]
        role_of = _TorchSyncHookFunction._role_enum
        coordinator.notify_dispatched(role_of(prev_idx))
        coordinator.rendezvous(role_of(next_idx))
        return x

    @staticmethod
    def backward(ctx, grad_output):
        """Identity backward that fires a HookCoordinator rendezvous.
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
        ``"D_LAST"`` skips the rendezvous because this is the first BWD
        hook to fire and ``combine.bwd`` has already dispatched freely
        before any rendezvous can happen.
        """
        hook_name = ctx.hook_name
        coordinator = ctx.coordinator

        if not coordinator.is_enabled():
            return grad_output, None, None

        if hook_name == "D_LAST":
            # First BWD hook to fire; combine.bwd has already
            # dispatched freely before any rendezvous can happen.
            # Skipping here is safe on Torch because CUDA streams
            # are process-wide and the NCCL FIFO order is consistent
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
            # Skipping here is safe on Torch because CUDA streams
            # are process-wide and the NCCL FIFO order is consistent
            # across ranks regardless of which thread launched
            # combine.bwd.
            return grad_output, None, None

        prev_idx, next_idx = _TorchSyncHookFunction._BWD_ROLES[hook_name]
        role_of = _TorchSyncHookFunction._role_enum
        coordinator.notify_dispatched(role_of(prev_idx))
        coordinator.rendezvous(role_of(next_idx))
        return grad_output, None, None


class _TorchP2PExchangeFunction(torch.autograd.Function):
    """Symmetric bidirectional P2P: send local tensor to peer, receive peer's tensor."""
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749

    @staticmethod
    def forward(ctx, tensor: torch.Tensor, peer_rank: int, group) -> torch.Tensor:  # pylint: disable=arguments-differ
        """Perform symmetric bidirectional P2P exchange with peer_rank."""
        ctx.peer_rank = peer_rank
        ctx.group = group
        send_buf = tensor.contiguous()
        recv_buf = torch.empty_like(send_buf)
        reqs = dist.batch_isend_irecv([
            dist.P2POp(dist.isend, send_buf, peer_rank, group),
            dist.P2POp(dist.irecv, recv_buf, peer_rank, group),
        ])
        for req in reqs:
            req.wait()
        return recv_buf

    @staticmethod
    def backward(ctx, grad_output: torch.Tensor):
        """Perform symmetric P2P exchange for the backward gradient pass."""
        send_buf = grad_output.contiguous()
        recv_buf = torch.empty_like(send_buf)
        reqs = dist.batch_isend_irecv([
            dist.P2POp(dist.isend, send_buf, ctx.peer_rank, ctx.group),
            dist.P2POp(dist.irecv, recv_buf, ctx.peer_rank, ctx.group),
        ])
        for req in reqs:
            req.wait()
        return recv_buf, None, None


class _TorchDifferentiableVariableAllGather(torch.autograd.Function):
    """Variable dim-zero all-gather with an uneven reduce-scatter backward."""
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770

    @staticmethod
    def forward(ctx, input_tensor, output_splits, group):  # pylint: disable=arguments-differ
        """Gather each rank's true row count without replicating inputs for A2A."""
        if input_tensor.ndim == 0:
            raise ValueError("variable all-gather input must have at least one dimension")
        splits = tuple(output_splits)
        if not splits:
            raise ValueError("output_splits must contain at least one group rank")
        if any(not isinstance(rows, int) or isinstance(rows, bool) or rows < 0 for rows in splits):
            raise ValueError(f"output_splits must contain non-negative integers, got {splits!r}")

        group_rank = dist.get_rank(group=group)
        if group_rank < 0 or group_rank >= len(splits):
            raise ValueError(f"group rank must be in [0, {len(splits)}), got {group_rank}")
        if input_tensor.shape[0] != splits[group_rank]:
            raise ValueError(
                "variable all-gather local rows must match output_splits at the group rank, "
                f"got local_rows={input_tensor.shape[0]}, group_rank={group_rank}, "
                f"output_splits={splits!r}"
            )
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
                f"got local_rows={input_tensor.shape[0]}, group_rank={group_rank}, "
                f"output_splits={splits!r}"
            )

        input_tensor = input_tensor.contiguous()
        feature_shape = tuple(input_tensor.shape[1:])
        if input_tensor.device.type == "npu":
            gathered = [input_tensor.new_empty((rows, *feature_shape)) for rows in splits]
            dist.all_gather(gathered, input_tensor, group=group)
        else:
            max_rows = max(splits)
            if max_rows == 0:
                gathered = [input_tensor.new_empty((0, *feature_shape)) for _ in splits]
            else:
                padded = input_tensor.new_zeros((max_rows, *feature_shape))
                if input_tensor.shape[0] > 0:
                    padded[:input_tensor.shape[0]].copy_(input_tensor)
                padded_outputs = [torch.empty_like(padded) for _ in splits]
                dist.all_gather(padded_outputs, padded, group=group)
                gathered = [
                    output[:rows].contiguous()
                    for output, rows in zip(padded_outputs, splits)
                ]

        ctx.output_splits = splits
        ctx.group = group
        ctx.group_rank = group_rank
        return torch.cat(gathered, dim=0)

    @staticmethod
    def backward(ctx, grad_output):
        """Sum replicated output gradients and return this rank's uneven shard."""
        output_rows = ctx.output_splits[ctx.group_rank]
        output = grad_output.new_empty((output_rows, *grad_output.shape[1:]))
        if sum(ctx.output_splits) == 0:
            return output, None, None

        grad_output = grad_output.contiguous()
        if grad_output.device.type == "npu":
            from torch_npu.distributed import reduce_scatter_tensor_uneven  # pylint: disable=C0415
            reduce_scatter_tensor_uneven(
                output,
                grad_output,
                input_split_sizes=list(ctx.output_splits),
                op=dist.ReduceOp.SUM,
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
                op=dist.ReduceOp.SUM,
                group=ctx.group,
            )
        else:
            reduced = grad_output.clone()
            dist.all_reduce(reduced, op=dist.ReduceOp.SUM, group=ctx.group)
            start = sum(ctx.output_splits[:ctx.group_rank])
            output.copy_(reduced.narrow(0, start, output_rows))
        return output, None, None


def differentiable_all_gather_concat(data, group, concat_size, concat_dim, rank_list=None):  # pylint: disable=W0613
    """Autograd-aware all-gather whose results are concatenated along ``concat_dim``."""
    data = _ensure_contiguous(data)
    output = [
        _TorchContiguousGrad.apply(tensor)
        for tensor in dist_func.all_gather(data, group=group)
    ]
    if rank_list is not None:
        group_ranks = dist.get_process_group_ranks(group)
        if tuple(rank_list) != tuple(group_ranks):
            rank_to_idx = {int(rank): idx for idx, rank in enumerate(group_ranks)}
            output = [output[rank_to_idx[int(rank)]] for rank in rank_list]
    return torch.cat(output, dim=concat_dim)


def chunk(data, split_dim, split_size, index):
    """Return chunk *index* of ``data`` split into ``split_size`` pieces."""
    return torch.chunk(data, split_size, dim=split_dim)[index]


def differentiable_all_to_all(input_data, output_shape, group):
    """Autograd-aware all-to-all producing a tensor of ``output_shape``."""
    input_data = _ensure_contiguous(input_data)
    output_tensor = torch.empty(output_shape, device=input_data.device, dtype=input_data.dtype)
    return dist_func.all_to_all_single(output_tensor, input_data, group=group)


def differentiable_all_reduce(data, op, group):
    """Autograd-aware all-reduce with string or ``ReduceOp`` *op*."""
    data = _ensure_contiguous(data)
    # Resolve the op from string to ReduceOp enum if necessary
    reduce_op = _OP_MAP.get(op, dist.ReduceOp.SUM) if isinstance(op, str) else op
    return dist_func.all_reduce(data, op=reduce_op, group=group)


def differentiable_reduce_scatter(data, dev_num, axis, op, group):
    """Autograd-aware reduce-scatter splitting ``axis`` into ``dev_num`` parts."""
    data = _ensure_contiguous(data)
    input_tuple = torch.chunk(data, dev_num, dim=axis)
    output_tensor = torch.empty(input_tuple[0].shape, device=data.device, dtype=data.dtype)

    # Resolve the op from string to ReduceOp enum
    reduce_op = _OP_MAP.get(op, dist.ReduceOp.SUM) if isinstance(op, str) else op

    output_tensor = dist_func.reduce_scatter(output_tensor, input_tuple, op=reduce_op, group=group)

    # Keep manual handling for 'avg' string as it maps to SUM in _OP_MAP
    if op == 'avg':
        output_tensor = output_tensor / dev_num
    return output_tensor


def differentiable_all_to_all_single(input_tensor, input_splits, output_splits, group):
    """Variable-split all-to-all with autograd support for EP token dispatch/combine."""
    out_total = sum(output_splits)
    output = torch.empty(
        out_total, *input_tensor.shape[1:],
        dtype=input_tensor.dtype, device=input_tensor.device,
    )
    return dist_func.all_to_all_single(
        output, input_tensor,
        output_split_sizes=output_splits,
        input_split_sizes=input_splits,
        group=group,
893
894
895
896
897
898
899
900
901
    Both forward AND backward return ``AsyncCollectiveTensor``, so the
    ``wait_tensor`` op is queued lazily — only when a downstream kernel
    actually reads the result.  See :class:`_AsyncA2ALazyBwd`.
    """
    return _AsyncA2ALazyBwd.apply(input_tensor, output_splits, input_splits, group)


def differentiable_variable_all_gather(
        input_tensor: Tensor, output_splits: Sequence[int], group: Any) -> Tensor:
899
900
901
902
903
904
905
906

def differentiable_variable_all_gather(
        input_tensor: Tensor, output_splits: Sequence[int], group: Any) -> Tensor:
    """Gather variable dim-zero shards on HCCL or Gloo with autograd support."""
    return _TorchDifferentiableVariableAllGather.apply(
        input_tensor, tuple(output_splits), group
    )

909
910
911
912
913
914
915
916
917
918
919
    """Wait for an async collective tensor to become materialised.

    Idempotent — calling on an already-waited tensor is a no-op.
    """
    from torch.distributed._functional_collectives import wait_tensor  # pylint: disable=C0415
    wait_tensor(tensor)
    return tensor


def differentiable_async_allgather_wait(x, work, out_perm, group, world_size, gather_dim,
                                        handle_box=None):
917
918
919
920
921
922
923
924

def differentiable_async_allgather_wait(x, work, out_perm, group, world_size, gather_dim,
                                        handle_box=None):
    """Wait async all-gather handle and reconstruct result (differentiable)."""
    return _TorchAsyncAllGatherFunction.apply(
        x, work, out_perm, group, world_size, gather_dim, handle_box
    )

925
926
927
928
929
930
931
932

def differentiable_async_a2a_wait(x, work, out_perm, group, world_size, concat_dim, split_dim,
                                  handle_box=None):
    """Wait async A2A handle and reconstruct result (differentiable)."""
    return _TorchAsyncA2AFunction.apply(
        x, work, out_perm, group, world_size, concat_dim, split_dim, handle_box
    )

932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947


def differentiable_sync_hook(x, hook_name: str, coordinator):
    """Insert a HookCoordinator rendezvous into the autograd graph."""
    return _TorchSyncHookFunction.apply(x, hook_name, coordinator)


def p2p_exchange(tensor, peer_rank: int, group=None):
    """Symmetric bidirectional P2P exchange with *peer_rank*."""
    if peer_rank == dist.get_rank(group):
        return tensor
    return _TorchP2PExchangeFunction.apply(tensor, peer_rank, group)


# ---------------------------------------------------------------------------
# Unsupported legacy redistribution hooks
948
949
950
951
952
953
954
955
956
957
958
959
960
961
# ---------------------------------------------------------------------------

def get_tensor_transform():
    """Legacy MindSpore-side tensor transform hook — not available on torch."""
    raise NotImplementedError("Unsupported get_tensor_transform for torch platform")


def construct_strided_slice(x, begin, end, stride):
    """Legacy MindSpore-side strided-slice hook — not available on torch."""
    raise NotImplementedError("Unsupported construct_strided_slice for torch platform")


# ---------------------------------------------------------------------------
# Weight initialization
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
    Args:
        device (torch.device): Target device.
        include_buffers (bool): Also redirect buffers to *device*.
    """
    orig_register_parameter = nn.Module.register_parameter
    orig_register_buffer = nn.Module.register_buffer

    # pylint: disable=W0212
    def _register_parameter(module, name, param):
        orig_register_parameter(module, name, param)
        if param is None or param.device == device:
            return
        # Rebuild with data only, then restore instance attributes via __dict__:
        # forwarding them to __new__ crashes subclasses with a narrow signature.
        new_param = type(param)(param.to(device))
        new_param.__dict__.update(param.__dict__)
        new_param.requires_grad = param.requires_grad
        module._parameters[name] = new_param

    # pylint: disable=W0212
    def _register_buffer(module, name, buffer, persistent=True):
        orig_register_buffer(module, name, buffer, persistent=persistent)
        if buffer is not None:
            module._buffers[name] = module._buffers[name].to(device)

    try:
        nn.Module.register_parameter = _register_parameter
        if include_buffers:
            nn.Module.register_buffer = _register_buffer
        yield
    finally:
        nn.Module.register_parameter = orig_register_parameter
        if include_buffers:
            nn.Module.register_buffer = orig_register_buffer
hyper_parallel/core/dtensor/debug/_collective_tracer.py
46
47
48
49
50
51
52
53
54
55
56
57
    def install(self):
        """Replace the ``_utils`` collective functions with tracing wrappers."""
        with self._patch_lock:
            for name in _COLLECTIVE_METHODS:
                if not hasattr(_utils, name):
                    continue
                # Save the raw function for exact restoration.
                original_func = getattr(_utils, name)
                self._originals[name] = original_func

                callback = self._callback
                method_name = name
66
67
68
69
70
71
72
73
74
75
76
77
                        return result
                    return wrapper

                wrapper = _make_wrapper(original_func, callback, method_name)
                setattr(_utils, name, wrapper)

    def uninstall(self):
        """Restore the original ``_utils`` collective functions."""
        with self._patch_lock:
            for name, original_func in self._originals.items():
                setattr(_utils, name, original_func)
            self._originals.clear()
hyper_parallel/core/dtensor/device_mesh.py
36
37
38
39
40
41
42
43
44
    ``torch.from_numpy`` keeps the tensor off the meta device, so it stays
    materialized even when a DeviceMesh is built while ``fully_shard`` runs with
    ``mesh=None``.
    """
    return torch.from_numpy(np_array)


class _MeshEnv(threading.local):
    """Per-thread stack of active :class:`DeviceMesh` (PyTorch ``_mesh_resources`` parity)."""
187
188
189
190
191
192
193
194
195
196
197
198
        self._validate_device_type(device_type)
        self.device_type = device_type

        if _init_backend:
            _utils.init_process_group()

        self._layout, self._rank_map = self._resolve_layout_and_rank_map(mesh, _layout, _rank_map)
        self._rank = dist.get_rank() if dist.is_initialized() else 0
        self._root_mesh = _root_mesh
        self._refresh_mesh_view()
        self._set_mesh_dim_names(mesh_dim_names)
        self._initialize_runtime_state(_init_backend)
200
201
202
203
204
205
206
207
208

    @classmethod
    def _validate_device_type(cls, device_type: str) -> None:
        """Validate that the requested device type is supported on the torch backend."""
        if device_type not in cls._VALID_DEVICE_TYPES:
            raise ValueError(
                f"Invalid device_type '{device_type}'. "
                f"Valid device types are: {sorted(cls._VALID_DEVICE_TYPES)}"
            )
218
219
220
221
222
223
224
225
226
        if mesh is not None and (layout is not None or rank_map is not None):
            raise TypeError("Cannot provide both explicit mesh and private _layout/_rank_map arguments.")

        if mesh is None and (layout is None or rank_map is None):
            world_size = dist.get_world_size()
            mesh = list(range(world_size))

        if mesh is not None:
            mesh_tensor = cls._convert_mesh_to_tensor(mesh)
242
243
244
245
246
247
248
249
250
        # when DeviceMesh is constructed while a meta device context is active.
        # block — e.g., from ``DeviceMesh.concatenate`` invoked under
        # ``fully_shard``, which forces fresh ``Tensor()`` constructions onto
        # the meta device and any subsequent op (asnumpy, nonzero, …) crashes.
        rank_map_np = self._rank_map.cpu().numpy().reshape(-1)
        full_mesh_np = self._layout.remap_to_numpy(rank_map_np)
        if full_mesh_np.shape[0] == 1:
            per_rank_mesh_np = full_mesh_np[0]
        else:
315
316
317
318
319
320
321
322
323
        return _MeshLayout(mesh_shape, _contiguous_strides(mesh_shape))

    @staticmethod
    def _build_rank_map_from_mesh(mesh: Tensor) -> Tensor:
        return _host_tensor_from_numpy(mesh.cpu().numpy().reshape(-1).astype(np.int32))

    @staticmethod
    def _convert_rank_map_to_tensor(rank_map: Tensor) -> Tensor:
        """Normalize a rank-map input into the flat int32 Tensor stored on the mesh.
344
345
346
347
348
349
350
351
352
        if full_mesh.shape[0] == 1:
            return full_mesh[0]

        if current_rank is None:
            current_rank = dist.get_rank()

        rank_coords = (full_mesh == current_rank).nonzero()
        if rank_coords.shape[0] > 0:
            return full_mesh[rank_coords[0, 0]]
416
417
418
419
420
421
422
423
424
    @staticmethod
    def _convert_mesh_to_tensor(mesh: Union[Tensor, list, tuple, np.ndarray]) -> Tensor:
        """Convert a public mesh input into an int32 torch tensor."""
        if isinstance(mesh, Tensor):
            mesh = mesh.cpu().numpy()
        elif isinstance(mesh, (list, tuple)):
            mesh = np.array(mesh)
        elif not isinstance(mesh, np.ndarray):
            raise TypeError(
439
440
441
442
443
444
445
446
447
448
449
450
        for rank in rank_list:
            split_rank = _get_sub_rank_list(mesh_shape, mesh_dim_names, rank_list, dim_name, rank)
            sorted_rank = tuple(sorted(split_rank))
            split_ranks.add(sorted_rank)
            if rank == dist.get_rank():
                group_key = str(sorted_rank)
        split_ranks = sorted([list(item) for item in split_ranks])
        _utils.split_group(split_ranks=split_ranks)
        return group_key

    @staticmethod
    def _build_dim_split_ranks(
451
452
453
454
455
456
457
458
459
460
            sub_layout: _MeshLayout,
            rank_map: Tensor,
    ) -> tuple[list[list[int]], Optional[str]]:
        """Build rank lists and the local cache key for one logical mesh axis."""
        pg_ranks_by_dim = sub_layout.remap_to_numpy(rank_map.cpu().numpy())
        current_rank = dist.get_rank()
        split_ranks = []
        split_ranks_set = set()
        group_key = None
        for dim_mesh in np.array(pg_ranks_by_dim):
499
500
501
502
503
504
505
506
            split_ranks, group_key = DeviceMesh._build_dim_split_ranks(sub_layout, rank_map)
            if _should_defer_group_init(sub_layout, backend_override[dim]):
                dim_group_names.append(None)
                continue
            group = _utils.split_group(split_ranks=split_ranks)
            DeviceMesh._cache_group_if_needed(group_key, group)
            dim_group_names.append(group_key)
        return dim_group_names
751
752
753
754
755
756
757
758
759
760
761
                   mesh_dim_names: Union[tuple[str, ...], list[str]] = None
                   ) -> 'DeviceMesh':
        """Build a DeviceMesh from an existing process group or a list of groups."""
        if not isinstance(group, list):
            group_ranks = dist.get_process_group_ranks(group)
            group_key = str(tuple(sorted(group_ranks)))
            if not _utils.get_created_group(group_ranks):
                EXISTING_COMM_GROUPS[group_key] = group
            tensor_type_mesh_invalid = isinstance(mesh, Tensor) and mesh.tolist() != group_ranks
            not_tensor_type_mesh_invalid = mesh is not None and not isinstance(mesh, Tensor) and mesh != group_ranks
            if tensor_type_mesh_invalid or not_tensor_type_mesh_invalid:
776
777
778
779
780
781
782
783
784
785
            raise ValueError("mesh dimensions must match group dimensions.")
        device_mesh = DeviceMesh(device_type, mesh, mesh_dim_names=mesh_dim_names, _init_backend=False)
        device_mesh._dim_group_names = []  # pylint: disable=W0212
        for dim_group in groups:
            group_ranks = dist.get_process_group_ranks(dim_group)
            group_key = str(tuple(sorted(group_ranks)))
            if not _utils.get_created_group(group_ranks):
                EXISTING_COMM_GROUPS[group_key] = dim_group
            device_mesh._dim_group_names.append(group_key)  # pylint: disable=W0212
        return device_mesh
1311
1312
1313
1314
1315
1316
1317
1318
        if group_key is not None and group_key in EXISTING_COMM_GROUPS:
            return group_key

        split_ranks, group_key = DeviceMesh._build_dim_split_ranks(self._layout[mesh_dim], self._rank_map)
        group = _utils.split_group(split_ranks=split_ranks)
        DeviceMesh._cache_group_if_needed(group_key, group)
        self._dim_group_names[mesh_dim] = group_key
        return group_key
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
                f"rank_list length ({len(rank_list)}) must equal mesh size ({total_devices})"
            )
    else:
        if init_backend:
            _utils.init_process_group()
        try:
            current_rank = dist.get_rank()
        except Exception as exc:
            raise RuntimeError(
                "init_device_mesh: failed to get current rank for automatic rank_list generation. "
                "Either pass rank_list explicitly, or ensure the process group is initialized before calling "
hyper_parallel/core/dtensor/dtensor.py
78
79
80
81
82
83
84
85
            for op in no_skip:
                if isinstance(op, str):
                    names.add(op)
                else:
                    names.add(_utils.get_op_name(op))
            self._no_skip_names = frozenset(names)
        self._dispatch_token = None
        self._ops_token = None
430
431
432
433
434
435
436
437
438
        return self._placements

    def _from_converted_local(self, local_tensor: Tensor) -> 'DTensor':
        """Rebuild converted DTensor data without preserving Parameter identity."""
        cls = DTensor if isinstance(self, torch.nn.Parameter) else self.__class__
        if not isinstance(self._layout, Layout):
            constructor_kwargs = {
                "device_mesh": self._device_mesh,
                "placements": self._alias_placements(),
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
        """
        if isinstance(size, int):
            size = (size,)

        local_kwargs = {}
        if dtype is not None:
            local_kwargs["dtype"] = dtype
        if device is not None:
            self._validate_factory_device(device)
            # An unindexed device such as "cuda" resolves to the framework's
            # current device, which may differ from this DTensor's local device.
            local_kwargs["device"] = self._local_tensor.device
        if requires_grad:
            local_kwargs["requires_grad"] = True
        if layout is not None:
            local_kwargs["layout"] = layout
        if pin_memory:
            local_kwargs["pin_memory"] = True

        factory = getattr(self._local_tensor, method_name)
        local_result = factory(size, **local_kwargs)
1000
1001
1002
1003
1004
1005
1006
1007
1008
                raise ValueError(f"invalid mesh dim size {num_chunks} on mesh_dim={mesh_dim}")
            chunks = tuple(local.chunk(num_chunks, dim=shard_dim))
            if not chunks:
                raise ValueError(f"cannot shard dim {shard_dim} into {num_chunks} chunks")
            output = torch.empty_like(chunks[0])
            local = mesh_scatter(output, chunks, device_mesh, mesh_dim, group_src=src_data_rank)
        elif placement.is_replicate() or placement.is_partial():
            local = mesh_broadcast(local, device_mesh, mesh_dim, group_src=src_data_rank)
            if isinstance(placement, Partial):
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088


def _distribute_module_param_source(param: Any) -> Tensor:
    """Tensor data used as the global tensor for :func:`distribute_tensor`."""
    return param.data


def _distribute_module_new_parameter(key: str, dtensor: DTensor, requires_grad: bool) -> Any:
    """Build a :class:`torch.nn.Parameter` holding *dtensor*."""
    del key
    return torch.nn.Parameter(dtensor, requires_grad=requires_grad)


def _distribute_module_set_param(module: Any, key: str, new_param: Any) -> None:
    """Register or assign a parameter on *module* (``nn.Module``-like)."""
1313
1314
1315
1316
1317
1318
1319
1320
1321
        size, device_mesh, placements
    )

    # initialize the local tensor
    if init_op is torch.full:
        fill_value = kwargs.pop("fill_value", 0)
        local_tensor = init_op(local_shape, fill_value, **kwargs)
    elif rng_tracked:
        # pylint: disable=C0415
1364
1365
1366
1367
1368
1369
1370
1371
1372

    Returns:
        A :class:`DTensor` object on each rank
    """
    ones_ = torch.ones
    return _dtensor_init_helper(
        ones_,
        size,
        device_mesh=device_mesh,
1393
1394
1395
1396
1397
1398
1399
1400
1401

    Returns:
        A :class:`DTensor` object on each rank
    """
    empty_ = torch.empty
    return _dtensor_init_helper(
        empty_,
        size,
        device_mesh=device_mesh,
1425
1426
1427
1428
1429
1430
1431
1432
1433

    Returns:
        A :class:`DTensor` object on each rank
    """
    full_ = torch.full
    return _dtensor_init_helper(
        full_,
        size,
        fill_value=fill_value,
1454
1455
1456
1457
1458
1459
1460
1461
1462

    Returns:
        A :class:`DTensor` object on each rank
    """
    zeros_ = torch.zeros
    return _dtensor_init_helper(
        zeros_,
        size,
        device_mesh=device_mesh,
hyper_parallel/core/dtensor/init_weights.py
45
46
47
48
49
50
51
52
53
    Note:
        A model initialised under this context has **no weights**.  You cannot
        call ``model.to(some_device)`` directly; load a checkpoint first.
    """
    with _init_on_device(torch.device("meta"), include_buffers=include_buffers):
        yield


@contextmanager
66
67
68
69
70
71

        with init_on_device(torch.device("npu")):
            model = MyModel()  # parameters live on Ascend
    """
    with _init_on_device(device, include_buffers=include_buffers):
        yield
hyper_parallel/core/dtensor/layout.py
839
840
841
842
843
844
845
846
847
            return 0
        dim_entry = alias_tm[tensor_dim]
        if dim_entry == 'None':
            return 0
        rank = dist.get_rank()
        if isinstance(dim_entry, tuple):
            non_none = [ax for ax in dim_entry if ax != 'None']
            if not non_none:
                return 0
hyper_parallel/core/dtensor/parameter_init.py
25
26
27
28
29
30
31
32
            stage_index: stage index for init.
        Raises:
            ValueError: If the `module` is not a module.
    """
    if module is None:
        raise ValueError("input module must not be none.")
    if stage_index < 0:
        raise ValueError("input stage_index must be positive.")
hyper_parallel/core/dtensor/random.py
66
67
68
69
70
71
72
73
74
            f"DTensor random operators may not have complete support on {device_mesh.device_type} device mesh",
            stacklevel=2,
        )
        return False
    device_handle = _utils.get_device_handle()
    if device_handle and hasattr(device_handle, "set_rng_state"):
        return True
    if device_mesh is not None:
        warnings.warn(
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108

    @property
    def offset(self) -> int:
        """Return the offset value (last 8 bytes) of the Philox RNG state."""
        return int(self._state[8:].view(dtype=torch.int64).item())

    @offset.setter
    def offset(self, offset: int) -> None:
        """Set the offset value of the Philox RNG state."""
        offset_tensor = Tensor([offset], dtype=torch.uint64).view(
            torch.uint8
        ) # device?
        self._state[8:] = offset_tensor
109
110
111
112
113
114
115
116
117
118
119
120
121

    @property
    def seed(self) -> int:
        """Return the seed value (first 8 bytes) of the Philox RNG state."""
        return int(self._state[:8].view(dtype=torch.uint64).item())

    @seed.setter
    def seed(self, seed: int) -> None:
        """Set the seed value of the Philox RNG state."""
        seed_tensor = Tensor([seed], dtype=torch.uint64).view(
            torch.uint8
        )# device
        self._state[:8] = seed_tensor
133
134
135
136
137
138
139
140
141
    """

    def __init__(self, device):
        self._device = device
        self._device_handle = _utils.get_device_handle()
        if not self._device_handle:
            raise RuntimeError(
                f"{self.__class__.__name__} instantiation requires the presence of "
            )
174
175
176
177
178
179
180
181
182
        super().__init__(_resolve_device())
        rng_state = self._get_device_state()
        if run_state_sync:
            # synchronize RNG state using rank 0's current one
            dist.broadcast(rng_state, 0)
            my_rng_state = self._get_device_state()
            if not all(my_rng_state == rng_state):
                logger.warning(
                    "DTensor is synchronizing RNG states of every rank with the state from rank 0. "
189
190
191
192
193
194
195
196
197
            self._set_device_state(rng_state)

    def _manual_seed(self, parallel_seed: int) -> None:
        """Set the default RNG seed (``torch.manual_seed``), as in PyTorch DTensor."""
        torch.manual_seed(parallel_seed)

    def _get_device_state(self):
        rng_state = self._device_handle.get_rng_state().to(self._device)
        return rng_state
439
440
441
442
443
444
445
446
447
448
449
450
    return shard_linear_idx


def _resolve_device():
    device_handle = _utils.get_device_handle()
    device_idx = dist.get_rank() % _utils.device_count(device_handle)

    def get_device(device_idx):
        return _utils.device(device_idx)

    return get_device(device_idx)

488
489
490
491
492
493
494
495
496
            "otherwise DTensor RNG state on the rank will not be initialized and "
            "the behavior of DTensor random ops is undefined."
        )

    torch.manual_seed(seed)


def local_shard_size_and_offset(
    curr_local_size: int,
552
553
554
555
556
557
558
559
560
        device_type (str): device type str, default is `npu`. As for supported device,
            see details in :ref:`accelerator<accelerators>`
    """

    device_mod = _utils.get_device_handle()
    if device_mod is None:
        raise RuntimeError(
            f"torch has no module of `{device_type}`, you should register it first."
        )
564
565
566
567
568
569
570
571
572
        yield
        return

    if devices is None:
        num_devices = _utils.device_count(device_mod)
        if num_devices > 1 and not _fork_rng_warned_already:
            _fork_rng_warned_already = True
        devices = list(range(num_devices))
    else:
573
574
575
576
577
578
579
580
581
582
583
584
585
        # Protect against user passing us a generator; we need to traverse this
        # multiple times but a generator will be exhausted upon first traversal
        devices = list(devices)

    cpu_rng_state = _utils.get_rng_state()
    device_rng_states = [_utils.get_rng_state(device, device_mod) for device in devices]

    try:
        yield
    finally:
        _utils.set_rng_state(cpu_rng_state)
        for device, device_rng_state in zip(devices, device_rng_states):
            _utils.set_rng_state(device_rng_state, device, device_mod)
hyper_parallel/core/dtensor/tensor_redistribution.py
71
72
73
74
75
76
77
78
79
    def _construct_all_concat(x, *args):
        """args: (*rank_list, concat_dim)"""
        rank_list = args[0:-1]
        concat_dim = args[-1]
        group = _utils.create_group(rank_list)
        concat_size = len(rank_list)
        logger.debug(
            "differentiable_all_gather_concat: input_shape=%s, concat_dim=%d, "
            "concat_size=%d, rank_list=%s",
78
79
80
81
82
83
84
85
86
            "differentiable_all_gather_concat: input_shape=%s, concat_dim=%d, "
            "concat_size=%d, rank_list=%s",
            tuple(x.shape), concat_dim, concat_size, rank_list,
        )
        return _utils.differentiable_all_gather_concat(x, group, concat_size, concat_dim, rank_list)


    @staticmethod
    def _construct_strided_slice(x, *args):
85
86
87
88
89
90
91
92
93
    @staticmethod
    def _construct_strided_slice(x, *args):
        """args: (begin, end, strides)"""
        dims = len(args) // 3
        return _utils.construct_strided_slice(x, args[0: dims], args[dims: 2 * dims], args[2 * dims:])

    @staticmethod
    def _construct_all_concat_new(x, *args):
        """args: (concat_dim, concat_size, group)"""
 93
 94
 95
 96
 97
 98
 99
100
101
        """args: (concat_dim, concat_size, group)"""
        rank_list = args[2]
        concat_dim = args[0]
        concat_size = args[1]
        group = _utils.create_group(rank_list)
        logger.debug(
            "differentiable_all_gather_concat: input_shape=%s, concat_dim=%d, "
            "concat_size=%d, rank_list=%s",
            tuple(x.shape), concat_dim, concat_size, rank_list,
 99
100
101
102
103
104
105
106
107
            "differentiable_all_gather_concat: input_shape=%s, concat_dim=%d, "
            "concat_size=%d, rank_list=%s",
            tuple(x.shape), concat_dim, concat_size, rank_list,
        )
        return _utils.differentiable_all_gather_concat(x, group, concat_size, concat_dim, rank_list)

    def _construct_all_split(self, x, *args):
        """args: (split_dim, split_size, group)"""
        rank_list = list(args[2])
107
108
109
110
111
112
113
114
115
        rank_list = list(args[2])
        split_dim = args[0]
        split_size = args[1]
        idx = rank_list.index(self.rank_id)
        return _utils.chunk(x, split_dim, split_size, idx)

    @staticmethod
    def _construct_all_to_all(x, *args):
        """args: (split_dim, concat_dim, permute_size, group)"""
113
114
115
116
117
118
119
120
121
    @staticmethod
    def _construct_all_to_all(x, *args):
        """args: (split_dim, concat_dim, permute_size, group)"""
        split_dim, concat_dim, split_count, rank_list = args
        group = _utils.create_group(rank_list)
        logger.debug(
            "differentiable_all_to_all: input_shape=%s, split_dim=%d, "
            "concat_dim=%d, split_count=%d, rank_list=%s",
            tuple(x.shape), split_dim, concat_dim, split_count, rank_list,
154
155
156
157
158
159
160
161
162
            reshape_shape.pop(1)
            reshape_shape = tuple(reshape_shape)
            x_reshaped = x_reshaped.reshape(reshape_shape)
        x_reshaped = x_reshaped.contiguous()
        output_tensor = _utils.differentiable_all_to_all(
            input_data=x_reshaped,
            output_shape=reshape_shape,
            group=group
        )
296
297
298
299
300
301
302
303
304
        """Run the existing redistribution path for normal layouts."""
        from_layout = input_x.layout
        x = input_x
        if not self.is_init:
            self.rank_id = dist.get_rank()
            self.is_init = True
        key = from_layout.compact_str + to_layout.compact_str + str(self.rank_id)
        if key in self._transform_cache:
            x = x.to_local()
341
342
343
344
345
346
347
348
349
        if len(output_splits) == 1:
            gathered = local_tensor
        else:
            group = from_layout.mesh.get_group(info.mesh_dim)
            gathered = _utils.differentiable_variable_all_gather(
                local_tensor,
                output_splits,
                group,
            )
414
415
416
417
418
419
420
421
422
        if len(input_splits) == 1:
            flat_output = flat_input
        else:
            group = from_layout.mesh.get_group(source_info.mesh_dim)
            flat_output = _utils.differentiable_all_to_all_single(
                flat_input,
                input_splits,
                output_splits,
                group,
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
        if zero_dim:
            x = x.unsqueeze(0)
        if op == 'avg':
            dev_num = layout.mesh_shape[layout.alias_name.index(dev_dim)]
            x = _utils.differentiable_all_reduce(x, 'sum', group)
            x = x / dev_num
        elif op == 'all':
            x_int32 = _utils.tensor_type_cast(x.bool(), 'int32')  # True→1, False→0
            x = _utils.differentiable_all_reduce(x_int32, 'all', group)
            x = x.bool()
        else:
            x = _utils.differentiable_all_reduce(x, op, group)
        if zero_dim:
            x = x.squeeze(0)
        return x
475
476
477
478
479
480
481
482
483
            "op=%s, dev_dim=%s, dev_num=%d",
            tuple(x.shape), axis, op, dev_dim, dev_num,
        )
        group = layout.get_comm_group_by_axis(dev_dim)
        output_tensor = _utils.differentiable_reduce_scatter(x, dev_num, axis, op, group)
        return output_tensor

    def reduce_partial(self, input_x, to_layout):
        """Reduce partial status."""