Coverage for / home / jenkins / .local / lib / python3.10 / site-packages / hyper_parallel / core / dtensor / debug / _collective_tracer.py: 86%
58 statements
« prev ^ index » next coverage.py v7.13.1, created at 2026-12-05 05:12 +0800
« prev ^ index » next coverage.py v7.13.1, created at 2026-12-05 05:12 +0800
1# Copyright 2026 Huawei Technologies Co., Ltd
2#
3# Licensed under the Apache License, Version 2.0 (the "License");
4# you may not use this file except in compliance with the License.
5# You may obtain a copy of the License at
6#
7# http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and
13# limitations under the License.
14# ============================================================================
15"""Tracer for the collective communication operations of core.dtensor."""
16import threading
17from typing import Any, Callable, Dict, List
19from hyper_parallel.core.dtensor import _utils
21# Collective functions in hyper_parallel.core.dtensor._utils to intercept.
22_COLLECTIVE_METHODS = (
23 "differentiable_all_gather_concat",
24 "differentiable_all_to_all",
25 "differentiable_all_reduce",
26 "differentiable_reduce_scatter",
27 "differentiable_all_to_all_single",
28 "differentiable_all_to_all_single_async",
29)
32class _PatchChain:
33 """Per-name stack of active wrappers shared by all tracers.
35 Attributes:
36 original: Raw ``_utils`` function saved before the first patch.
37 wrappers: Active wrappers ordered outermost-first, innermost-last.
38 """
40 __slots__ = ("original", "wrappers")
42 def __init__(self, original: Callable) -> None:
43 """Record the raw function and start with an empty stack.
45 Args:
46 original: Raw ``_utils`` function saved before the first patch.
47 """
48 self.original = original
49 self.wrappers: List[Callable] = []
52# One chain per patched name, shared by every tracer. Keeping the stack
53# module-level is what makes an out-of-order uninstall recoverable: each
54# uninstall removes only its own wrapper and the slot falls back to the
55# next active wrapper (or the raw function) regardless of exit order.
56_chains: Dict[str, _PatchChain] = {}
59def _make_wrapper(chain: _PatchChain, cb: Callable, mname: str) -> Callable:
60 """Build a wrapper that resolves the layer below itself at call time.
62 Resolving dynamically instead of closing over the current slot value
63 keeps an already-uninstalled outer tracer's callback out of the chain.
65 Args:
66 chain: Shared stack this wrapper joins on install.
67 cb: Callback invoked after the wrapped collective returns.
68 mname: Patched ``_utils`` attribute name.
70 Returns:
71 A callable forwarding to the next active wrapper (or the raw
72 function), then notifying ``cb`` with the result.
73 """
74 def wrapper(*args: Any, **kwargs: Any) -> Any:
75 """Call the collective below, then notify the callback.
77 A callback failure must never break the collective, so it is
78 swallowed and the original result returned untouched.
79 """
80 try:
81 idx = chain.wrappers.index(wrapper)
82 except ValueError:
83 # Uninstalled between scheduling and execution; bypass tracing.
84 return chain.original(*args, **kwargs)
85 below = chain.wrappers[idx - 1] if idx else chain.original
86 result = below(*args, **kwargs)
87 try:
88 cb(mname, args, kwargs, result)
89 except Exception: # pylint: disable=W0703
90 pass # Never break production logic
91 return result
92 return wrapper
95class CollectiveTracer:
96 """Intercepts core.dtensor collective operations via monkey-patching.
98 Args:
99 on_collective_call: Callback invoked after each collective with
100 ``(method_name, args, kwargs, result)``.
101 """
103 _patch_lock = threading.Lock()
105 def __init__(self, on_collective_call: Callable) -> None:
106 """Record the callback and start with nothing patched.
108 Args:
109 on_collective_call: Callback invoked after each collective with
110 ``(method_name, args, kwargs, result)``.
111 """
112 self._callback = on_collective_call
113 self._wrappers: Dict[str, Callable] = {}
115 def install(self) -> None:
116 """Replace the ``_utils`` collective functions with tracing wrappers.
118 Names in :data:`_COLLECTIVE_METHODS` that ``_utils`` does not define are
119 skipped, so a missing collective degrades to no tracing rather than an
120 error. Nesting another tracer stacks wrappers on a shared chain instead
121 of replacing them, so every uninstall restores exactly its own layer.
122 """
123 with self._patch_lock:
124 for name in _COLLECTIVE_METHODS:
125 if not hasattr(_utils, name):
126 continue
127 chain = _chains.get(name)
128 if chain is None:
129 # First patch on this name: save the raw function.
130 chain = _PatchChain(getattr(_utils, name))
131 _chains[name] = chain
132 wrapper = _make_wrapper(chain, self._callback, name)
133 self._wrappers[name] = wrapper
134 chain.wrappers.append(wrapper)
135 setattr(_utils, name, wrapper)
137 def uninstall(self) -> None:
138 """Restore the ``_utils`` collective functions this tracer wrapped.
140 Only the wrappers this tracer installed are removed from the shared
141 chain, so uninstall order never matters: exiting an outer tracer
142 first still lets the inner tracer's uninstall reach the raw function,
143 and the outer tracer's callback stops firing immediately.
144 """
145 with self._patch_lock:
146 for name, wrapper in self._wrappers.items():
147 chain = _chains.get(name)
148 if chain is None:
149 continue
150 try:
151 chain.wrappers.remove(wrapper)
152 except ValueError:
153 continue
154 # Restore the slot only while our wrapper is the one installed.
155 if getattr(_utils, name, None) is wrapper:
156 if chain.wrappers:
157 setattr(_utils, name, chain.wrappers[-1])
158 else:
159 setattr(_utils, name, chain.original)
160 _chains.pop(name)
161 self._wrappers.clear()