Diff Coverage

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

Source File Diff Coverage (%) Missing Lines
hyper_parallel/compile/compiler.py 100%  
hyper_parallel/compile/pass_config.py 100%  
hyper_parallel/compile/passes/aclgraph_pass.py 94.2% 82,86-90,103-105,107,161-163,231,237,245,249,491,505,556,561,664,726,770,776
hyper_parallel/compile/passes/aclgraph_runtime.py 82.3% 41,58,64,67-70,79-87,96,98,150-157,218-219,282,284,295,321,330-332,337-346,363,366,377,380-381,423,446,448-449,462,466-469,494,546-547,561-563,638,658-660,665-667,695-699
hyper_parallel/compile/passes/graph_metadata.py 97.4% 37,156
hyper_parallel/compile/passes/inductor_pass.py 87.5% 586-587
hyper_parallel/compile/passes/parallel/fsdp_pass.py 93.8% 271
hyper_parallel/compile/passes/pipeline.py 75.0% 148
hyper_parallel/compile/trainer.py 100%  
hyper_parallel/components/modules/engram/parallel_engram.py 30.0% 317,321,324-327,335
hyper_parallel/distributed/expert_parallel/_tracing.py 100%  
hyper_parallel/distributed/expert_parallel/experts.py 91.7% 556
hyper_parallel/trainer/base.py 66.7% 1393
hyper_parallel/compile/passes/aclgraph_pass.py
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
))


def _is_npu_tensor(value: Any) -> bool:
    return isinstance(value, torch.Tensor) and value.device.type == "npu"


def _same_layout(value, first):
    if value.dtype != first.dtype or len(value.shape) != len(first.shape):
        return False
    layout = (*value.shape, *value.stride(), value.storage_offset())
    other = (*first.shape, *first.stride(), first.storage_offset())
    return all(statically_known_true(left == right) for left, right in zip(layout, other, strict=True))


def _staging_aliases(placeholders, input_storages, staged_input_indices):
    """Group identical input layouts without borrowing externally writable storage."""
 99
100
101
102
103
104
105
106
107
108
109
110
111
    input_aliases = {}
    for indices in storage_inputs.values():
        if len(indices) < 2:
            continue
        first = placeholders[indices[0]].meta["val"]
        if all(i in staged_input_indices and _same_layout(placeholders[i].meta["val"], first) for i in indices):
            input_aliases.update((i, indices[0]) for i in indices[1:])
        else:
            staged_input_indices.difference_update(indices)
    return input_aliases


def _collect_inputs(gm, static_input_indices):
157
158
159
160
161
162
163
164
165
166
167
    if type(value) in (type(None), bool, int, float, complex, str, bytes):
        return True
    if type(value) in (tuple, list, immutable_list):
        return all(_known_free_metadata(item) for item in value)
    if type(value) in (dict, immutable_dict):
        return all(type(key) in (str, int) and _known_free_metadata(item) for key, item in value.items())
    return False


def _known_free_node_metadata(node):
    # FakeTensorProp omits val for None; this exact helper never returns storage.
227
228
229
230
231
232
233
234
235

def _internal_free_reason(node, region, owned, aliases, order):
    """Explain why a release cannot preserve the region-private storage lifetime."""
    if len(node.args) != 1 or node.kwargs or not isinstance(node.args[0], fx.Node):
        return "unknown_free_signature"
    target = node.args[0]
    if not isinstance(target.meta.get("val"), torch.Tensor) or target not in owned:
        return "allocation_not_internal"
    storage_aliases = aliases[target]
233
234
235
236
237
238
239
240
241
    if not isinstance(target.meta.get("val"), torch.Tensor) or target not in owned:
        return "allocation_not_internal"
    storage_aliases = aliases[target]
    if not storage_aliases <= region:
        return "external_storage_alias"
    for alias in storage_aliases:
        for reader in alias.users:
            if reader not in region:
                return "escaping_storage_alias"
241
242
243
244
245
246
247
248
249
250
251
252
253
                return "escaping_storage_alias"
            if order[reader] > order[node]:
                return "alias_read_after_free"
            if reader is not node and not _storage_free_node(reader) and written_nodes(reader):
                return "storage_alias_mutation"
            overload = _native_overload(reader.target)
            # pylint: disable-next=protected-access
            if overload is not None and not overload._schema.name.startswith(("aten::", "_c10d_functional::")):
                return "unknown_alias_consumer"
    return None


def _region_free_failures(members, frees, metadata_known, storages, aliases, order, metadata_failures):
487
488
489
490
491
492
493
494
495

def _output_clone_indices(output, escaping_storages, unknown_returns):
    nodes = [node for node in tree_leaves(output.args[0]) if isinstance(node, fx.Node)]
    if unknown_returns or any("val" not in node.meta for node in nodes):
        return None
    values = tree_map(lambda value: value.meta["val"] if isinstance(value, fx.Node) else value, output.args[0])
    return tuple(
        i for i, value in enumerate(tree_leaves(values))
        if isinstance(value, torch.Tensor) and StorageWeakRef(value.untyped_storage()) in escaping_storages
501
502
503
504
505
506
507
508
509
    captured_storages = set()
    output_clones, cloned_nodes = {}, set()
    for name, region in result.named_children():
        if not isinstance(region, torch.fx.GraphModule):
            continue
        if int(name.rsplit("_", 1)[1]) not in host_partitions:
            output = next(node for node in region.graph.nodes if node.op == "output")
            output_nodes = [node for node in tree_leaves(output.args) if isinstance(node, torch.fx.Node)]
            indices = output_clones[name] = _output_clone_indices(output, escaping_storages, unknown_returns)
552
553
554
555
556
557
558
559
560
561
562
563
564
565

def _read_only_producers(gm, escaping_storages, unknown_returns):
    """Prove producer storage is read-only across the complete scheduled graph."""
    if unknown_returns:
        return set()
    written_storages = set()
    for node in gm.graph.nodes:
        for written in written_nodes(node):
            if "val" not in written.meta:
                return set()
            written_storages.update(_storages(written))
    excluded = written_storages | escaping_storages
    native_producers, shareable = set(), set()
    for node in gm.graph.nodes:
660
661
662
663
664
665
666
667
668
        shared_producers.update(shared_keys.values())
        input_plans[name] = static_indices, borrowed_indices, shared_keys
    for name, region in result.named_children():
        if not isinstance(region, torch.fx.GraphModule):
            continue
        host = int(name.rsplit("_", 1)[1]) in host_partitions
        summaries.append(
            {
                "name": name,
722
723
724
725
726
727
728
729
730


def _validate_static_indices(indices, count):
    if any(isinstance(index, bool) or not isinstance(index, int) or index < 0 or index >= count for index in indices):
        raise ValueError("ACLGraph static_input_indices must index graph placeholders")


class ACLGraphPass(GraphPass):
    """Capture device regions after FSDP, bucketing and communication scheduling.
766
767
768
769
770
771
772
773
774
        if graph_module.meta.get("inductor_compiled") in ("regional", "full"):
            raise ValueError("ACLGraphPass cannot capture a graph already compiled with Inductor")
        placeholders = list(graph_module.graph.find_nodes(op="placeholder"))
        if example_inputs is not None or model is not None:
            propagate_fake_values(graph_module, example_inputs, model)
        if not _has_npu_work(graph_module):
            return install_aclgraph_runtime(
                graph_module, _RecaptureCoordinator(coordinate_recapture=pass_config.aclgraph_mode == "dynamic"),
            )
772
773
774
775
776
777
778
779
780
            return install_aclgraph_runtime(
                graph_module, _RecaptureCoordinator(coordinate_recapture=pass_config.aclgraph_mode == "dynamic"),
            )
        if static_input_indices is None:
            static_input_indices = range(getattr(graph_module, "num_state_inputs", 0))
        static_input_indices = set(static_input_indices)
        _validate_static_indices(static_input_indices, len(placeholders))
        prepare_aclgraph_runtime()
        result = _partition_graph(
hyper_parallel/compile/passes/aclgraph_runtime.py
37
38
39
40
41
42
43
44
45


def _get_torch_npu() -> Any:
    # Keep this optional dependency out of CPU imports and disabled pipelines.
    return importlib.import_module("torch_npu")


def _clone_capture_input(value):
    """Copy an input into independent persistent storage while preserving safe strides."""
54
55
56
57
58
59
60
61
62
        # including gapped slices where the generic overlap check is inconclusive.
        for stride, size in sorted((stride, size) for size, stride in zip(value.shape, value.stride(), strict=True)
                                   if size > 1):
            if stride < span:
                break
            span += (size - 1) * stride
        else:
            saved = torch.empty_strided(value.shape, value.stride(), dtype=value.dtype, device=value.device)
            saved.copy_(value.detach())
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
        else:
            saved = torch.empty_strided(value.shape, value.stride(), dtype=value.dtype, device=value.device)
            saved.copy_(value.detach())
            return saved
    saved = value.detach().clone()
    # clone preserves dense permutations but compacts slices with gaps.
    # Such intermediates still need their original layout during replay.
    if saved.stride() != value.stride() and _debug_has_internal_overlap(value) != 1:
        saved = torch.empty_strided(value.shape, value.stride(), dtype=value.dtype, device=value.device)
        saved.copy_(value.detach())
    return saved


def prepare_aclgraph_runtime() -> None:
    """Select a task-queue mode supported by NPU graph recording.
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91

    Raises:
        ValueError: If task queue mode 2 cannot be switched dynamically.
    """
    npu = _get_torch_npu().npu
    get_mode = getattr(npu, "get_task_queue_enable", None)
    mode = get_mode() if get_mode is not None else int(os.environ.get("TASK_QUEUE_ENABLE", "1"))
    if mode == 2:
        set_mode = getattr(npu, "set_task_queue_enable", None)
        if set_mode is None:
            raise ValueError("ACLGraph requires TASK_QUEUE_ENABLE=0/1 or the dynamic task-queue API")
        set_mode(1)
        logger.info("ACLGraph switched task queue mode from 2 to 1 before recording")


def _add_tensor_input_guard(manager, value, label):
    """Retain native layout/type guards across Dynamo binding signatures."""
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
    layout_args = (value, list(value.shape), list(value.stride()), label, [])
    type_args = (type(value), _dispatch_keys(value))
    try:
        manager.add_tensor_match_guard(*layout_args, *type_args)
    except TypeError:
        # Newer bindings require an extra guard-recording metadata argument.
        manager.add_tensor_match_guard(*layout_args, None, *type_args)


class _RecaptureCoordinator:
    """Agree across ranks before capture/replay, without capturing a collective."""
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
        """Validate the complete plan once, including ranks without captured regions."""
        if self.initialized:
            return
        if torch.distributed.is_initialized() and torch.distributed.get_world_size() > 1:
            group = torch.distributed.new_group(backend="gloo", timeout=timedelta(seconds=600))
            self.group = group
            names = [value.label for value in self.wrappers]
            gathered: list[list[str] | None] = [None] * torch.distributed.get_world_size(group)
            torch.distributed.all_gather_object(gathered, names, group=group)
            if any(value != names for value in gathered):
                self.teardown()
                raise ValueError("ACLGraph requires identical region order across ranks")
        self.initialized = True

    def before_call(self, wrapper: "ACLGraphWrapper", args: list[Any]) -> None:
        """Agree on capture state before executing any captured collective."""
214
215
216
217
218
219
220
221
222

    def teardown(self) -> None:
        """Release captured buffers or the coordination process group."""
        if self.group is not None:
            torch.distributed.destroy_process_group(self.group)
            self.group = None
        self.graph_pool = None
        self.shared_input_buffers.clear()
        self.initialized = False
278
279
280
281
282
283
284
285
286
287
288
        """Record layout, scalar, container, and explicitly static address contracts."""
        guard = RootGuardManager()
        try:
            guard.add_length_check_guard(len(args), [])
        except TypeError:
            # Keep the native length check with newer guard-recording bindings.
            guard.add_length_check_guard(len(args), [], None)
        pointers, scalars = [], []
        self._container_inputs = {}
        for i, arg in enumerate(args):
            if not isinstance(arg, torch.Tensor):
291
292
293
294
295
296
297
298
299
                    scalars.append((i, arg))
                else:
                    # Tensor leaves need layout guards, never Python equality;
                    # only explicitly static containers retain their addresses.
                    self._container_inputs[i] = (
                        structure,
                        [
                            (
                                keystr(path),
317
318
319
320
321
322
323
324
325
    @staticmethod
    def _tensor_change_reason(arg, spec, *, static):
        """Describe the first incompatible tensor layout or static address change."""
        if not isinstance(arg, torch.Tensor):
            return f"Tensor -> {type(arg).__name__}"
        for field, old, new in zip(
            ("shape", "stride", "dtype", "device"),
            spec[:4],
            (arg.shape, arg.stride(), arg.dtype, arg.device),
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
            strict=True,
        ):
            if old != new:
                return f"{field} {old} -> {new}"
        if static and arg.data_ptr() != spec[4]:
            return f"static address {spec[4]:#x} -> {arg.data_ptr():#x}"
        return None

    def _container_change_reason(self, args):
        """Validate nested input structure, tensor leaves, and Python constants."""
        for i, (structure, saved_leaves) in self._container_inputs.items():
            leaves, current_structure = tree_flatten_with_path(args[i])
            if current_structure != structure:
                return f"input[{i}] container structure changed"
            for (_, value), (path, saved, spec) in zip(leaves, saved_leaves, strict=True):
                if spec is not None:
                    reason = self._tensor_change_reason(value, spec, static=i in self.static_input_indices)
                    if reason is not None:
                        return f"input[{i}]{path} {reason}"
                elif value is not saved and (type(value) is not type(saved) or value != saved):
                    return f"input[{i}]{path} scalar {saved!r} -> {value!r}"
        return None

    def _fast_change_reason(self, args):
        for i, address in self._static_pointers:
359
360
361
362
363
364
365
366
367
368
369
370
    def _input_change_reason(self, args):
        """Check current arguments against the captured input contracts."""
        assert self.args is not None and self.input_specs is not None
        if len(args) != len(self.args):
            return f"argument count {len(self.args)} -> {len(args)}"
        reason = self._container_change_reason(args)
        if reason is not None:
            return reason
        # C++ guards check all tensor layouts without a Python loop per input.
        # Address checks remain explicit: tensor identity does not guard .data.
        if self._input_guard is not None and self._input_guard.check(args):
            return self._fast_change_reason(args)
373
374
375
376
377
378
379
380
381
382
383
384
385
                assert spec is not None
                reason = self._tensor_change_reason(arg, spec, static=i in self.static_input_indices)
                if reason is not None:
                    return f"input[{i}] {reason}"
            elif (
                i not in self._container_inputs and arg is not saved and (type(arg) is not type(saved) or arg != saved)
            ):
                return f"input[{i}] scalar {saved!r} -> {arg!r}"
        return None

    def __call__(self, *args: Any) -> Any:
        """Execute a region using positional graph inputs."""
        return self.call_boxed(list(args))
419
420
421
422
423
424
425
426
        self._prepare_input_guard(args)
        for i, (arg, saved) in enumerate(zip(args, self.args, strict=True)):
            for source, destination in zip(tree_leaves(arg), tree_leaves(saved), strict=True):
                if isinstance(source, torch.Tensor) and source.stride() != destination.stride():
                    raise ValueError(
                        f"ACLGraph {self.label}: dynamic input[{i}] copy must preserve strides; "
                        f"shape={tuple(source.shape)}, source={source.stride()}, copied={destination.stride()}"
                    )
442
443
444
445
446
447
448
449
450
451
452
                and value.device.type == "npu"
                and StorageWeakRef(value.untyped_storage()) not in protected_storages
            ):
                # The NPU backend exposes non-owning graph-pool handles only through this binding.
                handle = torch_npu._C._weak_ref_tensor(value)  # pylint: disable=protected-access
                # The FSDP release helper recognizes this library-owned handle marker.
                handle._aclgraph_non_owning = True  # pylint: disable=protected-access
                return handle
            return value

        return _replay_handle
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
            if coordinator.graph_pool is None:
                coordinator.graph_pool = torch_npu.npu.graph_pool_handle()
            pool = coordinator.graph_pool
        else:
            pool = torch_npu.npu.graph_pool_handle()
        try:
            self._prepare_capture_inputs(args, pool)
            return self._capture_graph(args, torch_npu, pool)
        except BaseException:
            if coordinator is not None:
                coordinator.shared_input_buffers.pop(pool, None)
            raise

    def _capture_graph(self, args, torch_npu, pool):
        """Record a region and preserve first-call output ownership for downstream work."""
        graph = torch_npu.npu.NPUGraph()
490
491
492
493
494
495
496
497
498
            )
            # Join pending HCCL streams before ending this region's capture.
            for value in tree_leaves(self.output):
                if isinstance(value, torch.Tensor) and value.device.type == "npu":
                    _c10d_functional.wait_tensor.default(value)
        self.graph = graph
        self.pool_id = pool
        captured_output = self.output
        if coordinator is not None:
542
543
544
545
546
547
548
549
550
551
        """Warm up, record, or replay a region, consuming its argument list."""
        torch_npu = _get_torch_npu()
        if self.recapture_coordinator is not None:
            self.recapture_coordinator.before_call(self, args)
        elif self.graph is not None and self._input_change_reason(args) is not None:
            raise ValueError("ACLGraph inputs changed without a recapture coordinator")
        if not self.warmed_up:
            output = self.runnable(*args)
            self.warmed_up = True
            logger.info("ACLGraph %s: warmup completed", self.label)
557
558
559
560
561
562
563
564
565
566
567
            for i, (arg, saved) in enumerate(zip(args, self.args, strict=True)):
                if isinstance(saved, torch.Tensor) and i not in self.static_input_indices:
                    saved.copy_(arg)
                elif i in self._container_inputs and i not in self.static_input_indices:
                    for source, destination in zip(tree_leaves(arg), tree_leaves(saved), strict=True):
                        if isinstance(destination, torch.Tensor):
                            destination.copy_(source)
        self.graph.replay()
        return self._replay_outputs(captured_output)

    def teardown(self) -> None:
634
635
636
637
638
639
640
641
642
                result = self.env[node] = self.run_node(node)
                if node.op == "output":
                    return self.graph.process_outputs(result) if enable_io_processing else result

            raise RuntimeError("ACLGraph partition graph has no output node")
        finally:
            # Returned gradients outlive this call through the caller alone;
            # detaching also preserves an externally supplied initial_env.
            self.env = {}
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
        destinations, sources = [], []
        for i in self._staged_input_indices:
            arg = args[i]
            if i in self._input_aliases:
                source = self._input_aliases[i]
                other = args[source]
                if arg.data_ptr() != other.data_ptr() or (arg.shape, arg.stride(), arg.dtype) != (
                    other.shape,
                    other.stride(),
                    other.dtype,
                ):
                    raise ValueError(f"ACLGraph shared input alias changed: input[{i}] and input[{source}]")
                values[i] = values[source]
                continue
            saved = self._input_buffers.get(i)
            if saved is None or (saved.shape, saved.stride(), saved.dtype, saved.device) != (
                arg.shape,
                arg.stride(),
691
692
693
694
695
696
697
698
699
700
701
702
703
                values = fetch(self.env)
                boxed = [values] if len(n.args) == 1 else list(values)
                del values
            else:
                args, kwargs = self.fetch_args_kwargs_from_env(n)
                if kwargs:
                    raise ValueError("ACLGraph partition calls must use positional inputs")
                boxed = list(args)
                del args
            for value in self.user_to_last_uses.get(n, []):
                del self.env[value]
            return wrapper.call_boxed(boxed)
        result = super().run_node(n)
hyper_parallel/compile/passes/graph_metadata.py
33
34
35
36
37
38
39
40
41
def _native_overload(target):
    if isinstance(target, OpOverload):
        return target
    if isinstance(target, OpOverloadPacket) and target.overloads() == ["default"]:
        return target.default
    return None


def tensor_storages(node: fx.Node) -> set[StorageWeakRef]:
152
153
154
155
156
157
158
159
160
    if example_inputs is not None:
        values = [value if value is not None else example_inputs[index] for index, value in enumerate(values)]
    mode = next((value.fake_mode for value in values if isinstance(value, FakeTensor)), None)
    if mode is None:
        return graph_module
    if model is not None:
        state = dict(model.named_parameters(remove_duplicate=False))
        state.update(model.named_buffers(remove_duplicate=False))
        for index, fqn in enumerate(getattr(graph_module, "state_fqns", ())):
hyper_parallel/compile/passes/inductor_pass.py
582
583
584
585
586
587
588
589
590
591
        _propagate_fake_vals(graph_module, model)
        example_inputs = _placeholder_fake_args(graph_module)
        if any(isinstance(value, torch.Tensor) and value.device.type == "npu" for value in example_inputs):
            # standalone_compile bypasses Dynamo's lazy NPU backend setup.
            npu_dynamo = importlib.import_module("torch_npu.utils._dynamo")
            npu_dynamo.register_inductor_npu()
        _LOG.info(
            "InductorPass: compiling graph in %r mode (%d placeholders, %d nodes)",
            mode,
            len(graph_module.graph.find_nodes(op="placeholder")),
hyper_parallel/compile/passes/parallel/fsdp_pass.py
267
268
269
270
271
272
273
274
        return
    # Replay handles borrow graph-pool storage. Resizing their non-owning
    # Storage would only invalidate the address needed by the next replay.
    if getattr(tensor, "_aclgraph_non_owning", False):
        return
    if isinstance(tensor, torch.Tensor) and tensor.untyped_storage().size() > 0:
        tensor.untyped_storage().resize_(0)

hyper_parallel/compile/passes/pipeline.py
144
145
146
147
148
149
150
151
152
            self.passes.append(InductorPass())

        # Capture the final scheduled FX regions; replay bypasses Python nodes.
        if self.config.aclgraph_mode != "off":
            self.passes.append(ACLGraphPass())

        return self

    def run(
hyper_parallel/components/modules/engram/parallel_engram.py
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
            )
        num_local_rows = padded_num_embeddings // ep_size
        row_start = ep_rank * num_local_rows
        flat_ids = hash_ids.reshape(-1)
        torch._check_index(  # pylint: disable=protected-access
            ((flat_ids >= 0) & (flat_ids < padded_num_embeddings)).all().item(),
            lambda: "Engram hash requested a row outside the padded table",
        )
        owner = torch.div(flat_ids, num_local_rows, rounding_mode="floor").long()
        # A fixed-size histogram keeps the peer counts in the graph even when
        # an owner receives no rows. The exchange only needs one count per peer.
        local_counts = owner.new_zeros(ep_size).scatter_add_(0, owner, torch.ones_like(owner))
        received_counts = ep_exchange_counts(local_counts, ep_group)
        send_counts = ep_split_sizes(local_counts, flat_ids.numel())
        recv_counts = ep_split_sizes(received_counts)

        # Ascend ArgSort executes integer inputs on AiCPU. The owner range is
        # bounded by ep_size, so float32 preserves it exactly and stays on AiCore.
        sort_indices = torch.argsort(owner.float(), stable=True)
331
332
333
334
335
336
337
338
339
        sort_indices = torch.argsort(owner.float(), stable=True)
        sorted_ids = flat_ids.index_select(0, sort_indices)
        received_ids = ep_all_to_all(sorted_ids, send_counts, recv_counts, ep_group)
        local_ids = received_ids - row_start
        torch._check_index(  # pylint: disable=protected-access
            ((local_ids >= 0) & (local_ids < num_local_rows)).all().item(),
            lambda: "Engram EP routing delivered a row to the wrong owner",
        )
        # Call the child module instead of reading ``embedding.weight``
hyper_parallel/distributed/expert_parallel/experts.py
552
553
554
555
556
557
558
559
560
    with expert_parallel_region():
        capacity_factor = _resolve_capacity_factor(module)
        keep = None
        if capacity_factor is not None:
            keep, _ = apply_capacity_limit(
                topk_indices, capacity_factor, global_expert_count, topk_weights,
            )
        return _prepare_ep_dispatch(
            hidden_states, topk_indices, topk_weights,
hyper_parallel/trainer/base.py
1389
1390
1391
1392
1393
1394
1395
1396
1397
    def destroy_distributed(self) -> None:
        """Synchronize all ranks and tear down the distributed process group."""
        graph_compiler = getattr(self, "graph_compiler", None)
        if graph_compiler is not None:
            graph_compiler.close()
        if not dist.is_available() or not dist.is_initialized():
            return

        empty_cache()