Coverage for  / home / jenkins / .local / lib / python3.10 / site-packages / hyper_parallel / data / distributed / packed_balancing.py: 92%

166 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-isolated balancing of externally selected raw-sample steps.""" 

16 

17from __future__ import annotations 

18 

19from collections.abc import Callable, Iterable, Iterator, Sequence 

20from contextlib import ExitStack, suppress 

21from dataclasses import replace 

22from typing import TYPE_CHECKING, Any 

23 

24from hyper_parallel.data.distributed.balance_logging import log_balance_stats 

25from hyper_parallel.data.distributed.balancing_algorithm import BalancingAlgorithm, resolve_balancing_algorithm 

26from hyper_parallel.data.distributed.cost_model import CostModel, resolve_cost_model 

27from hyper_parallel.data.distributed.device_prefetch import ( 

28 DeviceStepPrefetcher, _create_device_prefetcher, _resolve_device, 

29) 

30from hyper_parallel.data.distributed.external_source import ExternalStepProducer, LocalBatch 

31from hyper_parallel.data.distributed.locality import _create_locality_groups 

32from hyper_parallel.data.distributed.planner import DynamicPackingPlanner 

33from hyper_parallel.data.distributed.process_data import DataRequest, create_data_worker 

34from hyper_parallel.data.distributed.schema import PackingConstraints, SampleMetadata 

35from hyper_parallel.data.distributed.transport import DataGroups, DataPlaneTransport 

36 

37if TYPE_CHECKING: 

38 from hyper_parallel.data.distributed.api import DistributedDatasetConfig 

39 

40 

41class LocalBalancingDataLoader(Iterator[Any]): 

42 """Balance external steps in the configured process and stage H2D on the caller.""" 

43 

44 def __init__(self, local_dataloader: Iterable[Sequence[Sequence[Any]]], *, config: DistributedDatasetConfig, 

45 metadata_fn: Callable[[Any], SampleMetadata], pack_fn: Callable[[Sequence[Any], int], Any], 

46 collate_fn: Callable[[Sequence[Any]], Any], planner: Any, transport: DataPlaneTransport, 

47 global_rank: int, device_prefetch: DeviceStepPrefetcher | None = None, 

48 groups: DataGroups | None = None, 

49 balance_stats_callback: Callable[[dict[str, Any], int], None] | None = None) -> None: 

50 """Capture a serializable CPU source without starting workers or device work.""" 

51 self.local_dataloader = local_dataloader 

52 self.config = config 

53 self.group_ranks = transport.ranks 

54 self.prefetches_to_device = device_prefetch is not None 

55 self.last_balance_stats = None 

56 self.last_host_batch = None 

57 self._source = ExternalStepProducer(local_dataloader, config=config, metadata_fn=metadata_fn, 

58 pack_fn=pack_fn, collate_fn=collate_fn, planner=planner, 

59 global_rank=global_rank, ranks=transport.ranks) 

60 self._transport = transport 

61 self._groups = groups 

62 self._global_rank = global_rank 

63 self._device_prefetch = device_prefetch 

64 self._balance_stats_callback = balance_stats_callback 

65 self._worker = None 

66 if not config.use_data_process: 

67 self._source.bind_transport(transport) 

68 self._worker = self._source 

69 self._host_request: DataRequest | None = None 

70 self._staged: LocalBatch | BaseException | None = None 

71 self._step = 0 

72 self._finished = False 

73 self._closed = False 

74 

75 def _request_host(self) -> None: 

76 if self._host_request is None: 

77 if self._worker is None: 

78 self._worker = create_data_worker(self._source, self._transport) 

79 self._host_request = DataRequest(self._worker) 

80 

81 def _stage_next(self, *, blocking: bool) -> None: 

82 """Receive one CPU result and launch its successor before submitting H2D.""" 

83 if self._staged is not None: 

84 return 

85 if self.config.use_data_process: 

86 self._request_host() 

87 try: 

88 if self._host_request is not None: 

89 if not blocking and not self._host_request.is_ready(): 

90 return 

91 result = self._host_request.result() 

92 self._host_request = DataRequest(self._worker) 

93 else: 

94 result = next(self._source) 

95 if self._device_prefetch is not None: 

96 result = replace(result, data=self._device_prefetch(result.data)) 

97 self._staged = result 

98 except BaseException as error: # pylint: disable=broad-exception-caught 

99 # Deliver a callback or copy failure at its own step, after any preceding batch. 

100 self._staged = error 

101 

102 def prefetch(self) -> None: 

103 """Start CPU lookahead and stage an available successor on the caller.""" 

104 if self._closed or self._finished or not self.config.use_data_process: 

105 return 

106 self._request_host() 

107 if self.prefetches_to_device: 

108 self._stage_next(blocking=False) 

109 

110 def prefetch_plan(self) -> None: 

111 """Retain the existing hook as an idempotent request for the complete pipeline.""" 

112 self.prefetch() 

113 

114 def __len__(self) -> int: 

115 """Return the external source length when available.""" 

116 return len(self.local_dataloader) 

117 

118 @property 

119 def step(self) -> int: 

120 """Return the number of delivered steps, excluding speculative progress.""" 

121 return self._step 

122 

123 def __next__(self) -> Any: 

124 """Consume one result and immediately request its successor.""" 

125 if self._closed or self._finished: 

126 raise StopIteration 

127 self._stage_next(blocking=True) 

128 result, self._staged = self._staged, None 

129 if isinstance(result, BaseException): 

130 self._finished = True 

131 raise result 

132 self._step += 1 

133 self.last_balance_stats = result.stats 

134 self.last_host_batch = result.host_batch 

135 batch = result.data.take_batch() if self.prefetches_to_device else result.data 

136 if result.stats is not None and self._balance_stats_callback is not None and self._global_rank == 0: 

137 self._balance_stats_callback(result.stats, self._step) 

138 if self.prefetches_to_device and self.config.use_data_process: 

139 self._stage_next(blocking=self._step == 1) 

140 return batch 

141 

142 def __iter__(self) -> LocalBalancingDataLoader: 

143 """Keep unfinished prefetch and re-enter an exhausted source in its owning process.""" 

144 if self._finished and not self._closed: 

145 self._worker.reset_iteration() 

146 self._host_request = None 

147 self._staged = None 

148 self._finished = False 

149 self._step = 0 

150 return self 

151 

152 def wait_for_prefetch(self) -> None: 

153 """Drain pending work without consuming or changing the delivered cursor.""" 

154 if self._host_request is not None and self.prefetches_to_device and not self._finished: 

155 self._stage_next(blocking=True) 

156 if isinstance(self._staged, BaseException) and not isinstance(self._staged, StopIteration): 

157 raise self._staged 

158 if self._host_request is not None: 

159 try: 

160 self._host_request.result() 

161 except StopIteration: 

162 pass 

163 if self._device_prefetch is not None: 

164 self._device_prefetch.close() 

165 

166 def set_epoch(self, epoch: int) -> None: 

167 """Reset external iteration after draining the previous source request. 

168 

169 Args: 

170 epoch: Non-negative epoch to select before the next source read. 

171 """ 

172 if self._closed: 

173 raise RuntimeError("Data loader is closed.") 

174 self.wait_for_prefetch() 

175 if self._worker is not None: 

176 self._worker.set_epoch(epoch) 

177 else: 

178 self._source.set_epoch(epoch) 

179 self._host_request = None 

180 self._staged = None 

181 self._finished = False 

182 self._step = 0 

183 self.last_host_batch = None 

184 self.last_balance_stats = None 

185 

186 def state_dict(self) -> dict[str, Any]: 

187 """Preserve the external source's existing checkpoint ownership contract.""" 

188 raise NotImplementedError("Local balancing does not yet support dataloader checkpoint/resume.") 

189 

190 def load_state_dict(self, state: dict[str, Any]) -> None: 

191 """Reject external checkpoint loading until pending source steps are specified. 

192 

193 Args: 

194 state: External checkpoint payload; currently unsupported. 

195 """ 

196 del state 

197 raise NotImplementedError("Local balancing does not yet support dataloader checkpoint/resume.") 

198 

199 def close(self) -> None: 

200 """Drain device copies and release the data process.""" 

201 with ExitStack() as cleanup: 

202 if self._groups is not None: 

203 cleanup.callback(self._groups.close) 

204 if self._closed: 

205 return 

206 self._closed = True 

207 if self._device_prefetch is not None: 

208 cleanup.callback(self._device_prefetch.close) 

209 if self._worker is not None: 

210 cleanup.callback(self._worker.close) 

211 # Delivery and explicit waits report speculative failures. Close must still release owned resources. 

212 with suppress(Exception): 

213 self.wait_for_prefetch() 

214 self._host_request = None 

215 self._staged = None 

216 self.last_host_batch = None 

217 

218 

219def build_local_balancing_dataloader( 

220 local_dataloader: Iterable[Sequence[Sequence[Any]]], 

221 mesh: Any, 

222 config: DistributedDatasetConfig, 

223 *, 

224 metadata_fn: Callable[[Any], SampleMetadata], 

225 pack_fn: Callable[[Sequence[Any], int], Any], 

226 collate_fn: Callable[[Sequence[Any]], Any] = list, 

227 model_config: Any = None, 

228 cost_model: CostModel | None = None, 

229 balancing_algorithm: BalancingAlgorithm | None = None, 

230 device: Any = None, 

231) -> LocalBalancingDataLoader: 

232 """Build the fixed node-local balancing pipeline over complete raw steps. 

233 

234 Args: 

235 local_dataloader: Each yield contains exactly local_batch_size non-empty 

236 raw-sample bins. The source owns sampling and worker prefetch. 

237 mesh: WORLD-covering named mesh with model-parallel dimensions of size one. 

238 config: Packing limits and the minimum relative improvement required. 

239 metadata_fn: CPU-only per-sample metadata and cost features. 

240 pack_fn: Construct one packed sequence from its assigned raw samples. 

241 collate_fn: Assemble the local step as a sequence of microbatches. 

242 model_config: Effective backbone dimensions for the default FLOPs model. 

243 Required when cost_model is omitted. 

244 cost_model: Optional user estimate replacing the default cost model. 

245 balancing_algorithm: Optional sample assignment and objective policy. 

246 Costs and the improvement gate remain framework-owned. 

247 device: Training device; defaults to CPU with Gloo, otherwise the current 

248 accelerator. Pass an explicit NPU/CUDA device for H2D with Gloo. 

249 

250 Returns: 

251 A local-step loader using the configured node-local communication 

252 backend, automatic one-step buffering and final H2D prefetch. Windows 

253 that clear min_balance_gain use the candidate layout. The collator 

254 receives all packed bins of the source step together. 

255 

256 Note: 

257 The external source controls iteration length and all ranks must consume 

258 the same number of steps. Checkpoint/resume and 

259 nontrivial model parallelism are not supported by this local-step path. 

260 Iteration returns device-ready batches. last_host_batch retains the CPU 

261 view for metering without a device-to-host copy. 

262 """ 

263 if config.device_prefetch_depth != 1: 

264 raise ValueError("Configurable device_prefetch_depth requires a native batch_sampler.") 

265 if config.repack_sequences: 

266 raise ValueError("repack_sequences requires a native batch_sampler.") 

267 cost_model = resolve_cost_model(cost_model, model_config) 

268 balancing_algorithm = resolve_balancing_algorithm(balancing_algorithm) 

269 device = _resolve_device(device, communication_backend=config.communication_backend) 

270 device_prefetch = _create_device_prefetcher(device) 

271 if not all(callable(callback) for callback in (metadata_fn, pack_fn, collate_fn)): 

272 raise ValueError("metadata_fn, pack_fn and collate_fn must be callable.") 

273 if not hasattr(local_dataloader, "__iter__"): 

274 raise ValueError("local_dataloader must be iterable.") 

275 if config.dataset_reader_ranks is not None or config.planner_rank is not None: 

276 raise ValueError("Node-local balancing assigns readers and planners automatically.") 

277 PackingConstraints(config.seq_len, config.oversized_policy, config.packing_budgets) 

278 communication_device = device if config.communication_backend == "hccl" else None 

279 topology, groups = _create_locality_groups( 

280 mesh, 

281 dp_dim_names=config.dp_dim_names, 

282 balance_group_size=config.balance_group_size, 

283 communication_backend=config.communication_backend, 

284 communication_device=communication_device, 

285 ) 

286 with groups.close_on_error(): 

287 planner = DynamicPackingPlanner( 

288 data_parallel_size=len(groups.data_plane_ranks), 

289 seq_len=config.seq_len, 

290 # Window destinations are (micro-batch, rank), each holding one external bin. 

291 local_batch_size=config.local_batch_size if config.balance_window_size == 1 else 1, 

292 oversized_policy=config.oversized_policy, 

293 packing_budgets=config.packing_budgets, 

294 cost_model=cost_model, 

295 balancing_algorithm=balancing_algorithm, 

296 min_balance_gain=config.min_balance_gain, 

297 validate=False, 

298 ) 

299 return LocalBalancingDataLoader( 

300 local_dataloader, 

301 groups=groups, 

302 config=config, 

303 metadata_fn=metadata_fn, 

304 pack_fn=pack_fn, 

305 collate_fn=collate_fn, 

306 planner=planner, 

307 transport=DataPlaneTransport( 

308 groups, 

309 topology.global_rank, 

310 communication_device=communication_device, 

311 ), 

312 global_rank=topology.global_rank, 

313 device_prefetch=device_prefetch, 

314 balance_stats_callback=log_balance_stats if config.log_balance else None, 

315 ) 

316 

317 

318__all__ = ["LocalBalancingDataLoader", "build_local_balancing_dataloader"]