Coverage for  / home / jenkins / .local / lib / python3.10 / site-packages / hyper_parallel / tools / dryrun / simulation.py: 100%

61 statements  

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

1# Copyright 2026 Huawei Technologies Co., Ltd 

2# 

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

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

5# You may obtain a copy of the License at 

6# 

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

8# 

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

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

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

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

13# limitations under the License. 

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

15"""Process-wide device-runtime simulation switch with no-op stream primitives. 

16 

17Logical simulation (the dry-run tool) executes unmodified trainer and core 

18code over FakeTensors without ever binding an accelerator or initializing its 

19runtime. Components that schedule asynchronous transfers — activation swap, 

20optimizer-state swap, FSDP CPU offload — fetch their stream and event 

21primitives through seams that consult this switch. Under simulation every 

22transfer degenerates to its host-visible program order: the same storages are 

23allocated, copied, resized, and released; only device-side overlap disappears, 

24which is exactly the part a logical memory tracker does not account anyway. 

25""" 

26 

27import contextlib 

28from typing import Any, Optional 

29 

30__all__ = [ 

31 "SimulatedEvent", 

32 "SimulatedStream", 

33 "hold_for_simulated_stream", 

34 "is_device_runtime_simulated", 

35 "release_simulated_stream_holds", 

36 "simulate_device_runtime", 

37 "simulated_accelerator", 

38 "simulated_device_handle", 

39] 

40 

41_SIMULATION_STATE: dict[str, Any] = { 

42 "enabled": False, 

43 "accelerator": None, 

44} 

45_PENDING_STREAM_HOLDS: list = [] 

46 

47 

48def simulate_device_runtime(enabled: bool = True, accelerator: Optional[str] = None) -> None: 

49 """Toggle no-op device effects for logical (FakeTensor) simulation. 

50 

51 Args: 

52 enabled: Whether device-side effects become no-ops. 

53 accelerator: Device type the simulation lies as (``npu``/``cuda``), or 

54 ``None`` for plain CPU simulation. Components that pick a 

55 collective staging device consult it so simulated runs allocate 

56 communication buffers on the same (fake) device real runs do. 

57 """ 

58 _SIMULATION_STATE["enabled"] = bool(enabled) 

59 _SIMULATION_STATE["accelerator"] = accelerator if enabled else None 

60 if not enabled: 

61 _PENDING_STREAM_HOLDS.clear() 

62 

63 

64def is_device_runtime_simulated() -> bool: 

65 """Return whether device-side effects are currently simulated.""" 

66 return bool(_SIMULATION_STATE["enabled"]) 

67 

68 

69def simulated_accelerator() -> Optional[str]: 

70 """Return the accelerator type the simulation lies as, or ``None``.""" 

71 return _SIMULATION_STATE["accelerator"] 

72 

73 

74def hold_for_simulated_stream(tensor: Any) -> None: 

75 """Keep ``tensor`` alive until the next simulated synchronization point. 

76 

77 This is the simulation analogue of ``Tensor.record_stream``: a real 

78 caching allocator retains a staging buffer until the recorded stream's 

79 pending work completes, even after the last Python reference dies. The 

80 stand-in holds the reference until an event wait or stream synchronize is 

81 observed, so the logical lifetime is conservative (never shorter than the 

82 real one) without modeling stream timing. 

83 

84 Args: 

85 tensor: Staging tensor whose storage must stay live. 

86 """ 

87 _PENDING_STREAM_HOLDS.append(tensor) 

88 

89 

90def release_simulated_stream_holds() -> None: 

91 """Drop stream-held references; called from simulated waits.""" 

92 _PENDING_STREAM_HOLDS.clear() 

93 

94 

95class SimulatedEvent: 

96 """Event stand-in whose completion is always immediate. 

97 

98 Host code that records, waits on, or queries an event observes the same 

99 control flow as a synchronous device: ``query`` answers ``True`` so 

100 event-gated reuse (for example pinned-buffer pools) proceeds eagerly. 

101 Waits release any stream-held staging references (see 

102 :func:`hold_for_simulated_stream`) — the same point a real allocator would 

103 be allowed to reclaim them. 

104 """ 

105 

106 def record(self, stream: Optional[Any] = None) -> "SimulatedEvent": 

107 """Accept any stream; completion is immediate. 

108 

109 Args: 

110 stream: Stream the event would be recorded on; ignored. 

111 

112 Returns: 

113 This event, already elapsed. 

114 """ 

115 del stream 

116 return self 

117 

118 def wait(self, stream: Optional[Any] = None) -> None: 

119 """Accept any stream; pending stream holds are now reclaimable. 

120 

121 Args: 

122 stream: Stream the wait would target; ignored. 

123 """ 

124 del stream 

125 release_simulated_stream_holds() 

126 

127 def query(self) -> bool: 

128 """Report the event as elapsed.""" 

129 return True 

130 

131 def synchronize(self) -> None: 

132 """Pending stream holds are now reclaimable.""" 

133 release_simulated_stream_holds() 

134 

135 

136class SimulatedStream: 

137 """Stream stand-in on which every submission completes in program order.""" 

138 

139 def synchronize(self) -> None: 

140 """Pending stream holds are now reclaimable.""" 

141 release_simulated_stream_holds() 

142 

143 def query(self) -> bool: 

144 """Report the stream as drained.""" 

145 return True 

146 

147 def wait_event(self, event: Any) -> None: 

148 """Accept any event; pending stream holds are now reclaimable. 

149 

150 Args: 

151 event: Event the stream would wait on; ignored. 

152 """ 

153 del event 

154 release_simulated_stream_holds() 

155 

156 def wait_stream(self, stream: Any) -> None: 

157 """Accept any stream; pending stream holds are now reclaimable. 

158 

159 Args: 

160 stream: Stream the wait would target; ignored. 

161 """ 

162 del stream 

163 release_simulated_stream_holds() 

164 

165 def record_event(self, event: Optional[Any] = None) -> Any: 

166 """Return an elapsed event. 

167 

168 Args: 

169 event: Event to record; returned as-is when provided. 

170 

171 Returns: 

172 The given event, or a new elapsed event. 

173 """ 

174 return event if event is not None else SimulatedEvent() 

175 

176 

177class _SimulatedDeviceHandle: 

178 """``torch.<device>``-shaped namespace whose effects are no-ops. 

179 

180 Only the stream/event/synchronize surface is provided on purpose: a 

181 simulated process must never reach device state queries that have no 

182 meaningful logical answer, and an ``AttributeError`` names the gap. 

183 """ 

184 

185 class Stream(SimulatedStream): 

186 """Simulated device stream class exposed on the device handle.""" 

187 

188 class Event(SimulatedEvent): 

189 """Simulated device event class exposed on the device handle.""" 

190 

191 def __init__(self) -> None: 

192 self._current_stream = SimulatedStream() 

193 

194 def current_stream(self, device: Optional[Any] = None) -> SimulatedStream: 

195 """Return the process-wide simulated current stream. 

196 

197 Args: 

198 device: Device whose current stream is requested; ignored. 

199 

200 Returns: 

201 The single simulated stream shared by the process. 

202 """ 

203 del device 

204 return self._current_stream 

205 

206 @staticmethod 

207 def stream(stream: Optional[Any] = None) -> Any: 

208 """Return a context manager that activates ``stream`` logically. 

209 

210 Args: 

211 stream: Stream to activate; ignored. 

212 

213 Returns: 

214 A no-op context manager. 

215 """ 

216 del stream 

217 return contextlib.nullcontext() 

218 

219 @staticmethod 

220 def synchronize(device: Optional[Any] = None) -> None: 

221 """Pending stream holds are now reclaimable. 

222 

223 Args: 

224 device: Device to synchronize; ignored. 

225 """ 

226 del device 

227 release_simulated_stream_holds() 

228 

229 

230_SIMULATED_DEVICE_HANDLE = _SimulatedDeviceHandle() 

231 

232 

233def simulated_device_handle() -> _SimulatedDeviceHandle: 

234 """Return the process-wide simulated device handle.""" 

235 return _SIMULATED_DEVICE_HANDLE