Coverage for  / home / jenkins / .local / lib / python3.10 / site-packages / hyper_parallel / trainer / runtime / data_iterator.py: 81%

108 statements  

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

1# Copyright 2025-2026 Bytedance Ltd. and/or its affiliates 

2# Copyright 2026 Huawei Technologies Co., Ltd 

3# 

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

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

6# You may obtain a copy of the License at 

7# 

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

9# 

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

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

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

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

14# limitations under the License. 

15# ============================================================================ 

16 

17"""Trainer-side dataloader iteration helpers. 

18 

19``BackgroundPrefetcher`` and ``HyperIter`` are split out of the former 

20``auto_models/trainer/base.py`` in stage 7 (05 §15.11 step 3); class names and 

21checkpointing semantics are retained. 

22""" 

23 

24from __future__ import annotations 

25 

26__all__ = [ 

27 "BackgroundPrefetcher", 

28 "HyperIter", 

29] 

30 

31import logging 

32import queue 

33import threading 

34from typing import Any, Dict, Optional 

35 

36 

37logger = logging.getLogger(__name__) 

38 

39 

40class BackgroundPrefetcher: 

41 """ 

42 Prefetches batches from a dataloader in a background thread to overlap data loading 

43 with GPU computation. Synchronizes dataloader state for correct checkpointing. 

44 """ 

45 

46 def __init__(self, dataloader: Any, maxsize: int = 1) -> None: 

47 """Start the background worker prefetching from ``dataloader``.""" 

48 self.dataloader = dataloader 

49 self.iterator = iter(dataloader) 

50 self.queue = queue.Queue(maxsize=maxsize) 

51 self.stop_event = threading.Event() 

52 self.original_state_dict = getattr(dataloader, "state_dict", None) 

53 self.current_state = None 

54 self.thread = threading.Thread(target=self._worker) 

55 self.thread.daemon = True 

56 self.thread.start() 

57 

58 def _worker(self) -> None: 

59 """Prefetch data and capture dataloader state in a background thread.""" 

60 try: 

61 while not self.stop_event.is_set(): 

62 try: 

63 item = next(self.iterator) 

64 except StopIteration: 

65 self._put_result((StopIteration, None)) 

66 break 

67 

68 # A stop request cannot interrupt next(), so discard the item once 

69 # that call returns instead of retaining another batch and state. 

70 if self.stop_event.is_set(): 

71 break 

72 

73 # Ensure we capture the state so that subsequent dataloader advances 

74 # don't mutate the captured state in-place. The underlying dataloader's 

75 # state_dict() should handle deepcopying if necessary. 

76 state = self.original_state_dict() if self.original_state_dict else None 

77 if not self._put_result((item, state)): 

78 break 

79 # The worker must transfer any producer failure back to the training thread. 

80 except Exception as exc: # pylint: disable=broad-exception-caught 

81 self._put_result((exc, None)) 

82 finally: 

83 # A timed-out stop cannot cancel next(), so the worker must release 

84 # its own references when that call eventually returns. 

85 if self.stop_event.is_set(): 

86 self._cleanup_after_stop() 

87 

88 def _put_result(self, result: tuple[Any, Any]) -> bool: 

89 """Put a worker result while allowing a stop request to cancel the write.""" 

90 while not self.stop_event.is_set(): 

91 try: 

92 self.queue.put(result, timeout=0.1) 

93 return True 

94 

95 except queue.Full: 

96 continue 

97 return False 

98 

99 def _drain_queue(self) -> None: 

100 """Release every result currently retained by the prefetch queue.""" 

101 while True: 

102 try: 

103 self.queue.get_nowait() 

104 except queue.Empty: 

105 return 

106 

107 def _cleanup_after_stop(self) -> None: 

108 """Release queued results and live dataloader references after stopping.""" 

109 self._drain_queue() 

110 self.iterator = None 

111 self.dataloader = None 

112 self.original_state_dict = None 

113 # The final checkpoint may be collected after stop(), so keep the 

114 # consumed-batch snapshot while releasing live dataloader references. 

115 

116 def __iter__(self) -> "BackgroundPrefetcher": 

117 """Return this prefetcher as its own iterator.""" 

118 return self 

119 

120 def __next__(self) -> Any: 

121 """Return the next prefetched item, re-raising worker failures.""" 

122 res = self.queue.get() 

123 

124 if isinstance(res, tuple) and len(res) == 2: 

125 item, state = res 

126 

127 if item is StopIteration: 

128 raise StopIteration 

129 

130 if isinstance(item, Exception): 

131 raise item 

132 

133 self.current_state = state 

134 return item 

135 

136 if res is StopIteration: 

137 raise StopIteration 

138 

139 if isinstance(res, Exception): 

140 raise res 

141 

142 return res 

143 

144 def state_dict(self) -> Dict[str, Any]: 

145 """Return the dataloader state captured alongside the current item.""" 

146 

147 if self.current_state is not None: 

148 return self.current_state 

149 

150 if self.original_state_dict: 

151 return self.original_state_dict() 

152 

153 return {} 

154 

155 def stop(self, timeout: Optional[float] = 5.0) -> bool: 

156 """Stop the background worker and release its dataloader references. 

157 

158 Args: 

159 timeout: Maximum seconds to wait. ``None`` waits until the worker exits. 

160 

161 Returns: 

162 Whether the worker terminated within the requested timeout. 

163 """ 

164 self.stop_event.set() 

165 self._drain_queue() 

166 if self.thread.is_alive(): 

167 self.thread.join(timeout=timeout) 

168 if self.thread.is_alive(): 

169 logger.warning("BackgroundPrefetcher worker thread did not terminate within timeout.") 

170 return False 

171 

172 self._cleanup_after_stop() 

173 return True 

174 

175 

176class HyperIter: 

177 """ 

178 A unified iterator wrapper that handles both standard iteration and background prefetching. 

179 """ 

180 

181 def __init__(self, dataloader: Any, use_background_prefetcher: bool = False, maxsize: int = 1) -> None: 

182 """Wrap ``dataloader`` in either direct iteration or background prefetching.""" 

183 self.dataloader = dataloader 

184 self.use_background_prefetcher = use_background_prefetcher 

185 if use_background_prefetcher: 

186 self.iterator = BackgroundPrefetcher(dataloader, maxsize=maxsize) 

187 else: 

188 self.iterator = iter(dataloader) 

189 

190 def __iter__(self) -> "HyperIter": 

191 """Return this wrapper as its own iterator.""" 

192 return self 

193 

194 def __next__(self) -> Any: 

195 """Return the next batch from the underlying iterator.""" 

196 return next(self.iterator) 

197 

198 def stop(self, timeout: Optional[float] = 5.0) -> bool: 

199 """Stop the background prefetch worker when one is active. 

200 

201 Args: 

202 timeout: Maximum seconds to wait. ``None`` waits until the worker exits. 

203 

204 Returns: 

205 Whether the worker is stopped, or ``True`` when prefetching is disabled. 

206 """ 

207 if self.use_background_prefetcher and hasattr(self.iterator, "stop"): 

208 return self.iterator.stop(timeout=timeout) 

209 return True 

210 

211 def state_dict(self) -> Dict[str, Any]: 

212 """Return the underlying dataloader or prefetcher state for checkpointing.""" 

213 if self.use_background_prefetcher and hasattr(self.iterator, "state_dict"): 

214 return self.iterator.state_dict() 

215 if hasattr(self.dataloader, "state_dict"): 

216 return self.dataloader.state_dict() 

217 return {}