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

158 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"""Batch probing, value erasure (mocking), and dataloader adaptation for dry-run.""" 

16 

17import copy 

18from collections.abc import Mapping 

19from dataclasses import dataclass, fields, is_dataclass, replace 

20from typing import Any, Optional 

21 

22import torch 

23from torch._subclasses.fake_tensor import FakeTensorMode, unset_fake_temporarily 

24 

25from hyper_parallel.data.constants import IGNORE_INDEX 

26 

27 

28@dataclass(frozen=True) 

29class PreparedDryRunBatch: 

30 """One real CPU training batch and its CPU-derived token counts.""" 

31 

32 model_inputs: Mapping[str, Any] 

33 loss_inputs: Mapping[str, Any] 

34 token_counts: Mapping[str, int] 

35 

36 

37@dataclass(frozen=True) 

38class DryRunTrainingBatch: 

39 """Value-free FakeTensor inputs and their CPU-derived statistics.""" 

40 

41 model_inputs: dict[str, Any] 

42 loss_inputs: dict[str, Any] 

43 token_counts: dict[str, int] 

44 valid_token_count: int 

45 target_tokens_per_rank: tuple[int, ...] 

46 

47 

48class DryRunBatchMocker: 

49 """Replace tensor leaves in a CPU batch with value-free FakeTensors.""" 

50 

51 def __init__(self, fake_mode: Any, device: Any) -> None: 

52 """Store the FakeTensor mode and logical simulation device.""" 

53 self.fake_mode = fake_mode 

54 self.device = device 

55 

56 def mock(self, value: Any) -> Any: 

57 """Recursively replace tensor leaves while preserving container structure. 

58 

59 Args: 

60 value: Batch value whose tensor leaves are replaced. 

61 

62 Returns: 

63 Structure-preserving copy with FakeTensor leaves. 

64 """ 

65 if isinstance(value, torch.Tensor): 

66 with self.fake_mode: 

67 return torch.empty_like( 

68 value, 

69 device=self.device, 

70 memory_format=torch.preserve_format, 

71 ) 

72 if isinstance(value, Mapping): 

73 return self._mock_mapping(value) 

74 if isinstance(value, (list, tuple)): 

75 return self._mock_sequence(value) 

76 if is_dataclass(value) and not isinstance(value, type): 

77 return self._mock_dataclass(value) 

78 if hasattr(value, "__dict__") and self._contains_tensor(vars(value)): 

79 raise ValueError( 

80 "Dry-run cannot mock tensor-bearing batch carrier " 

81 f"{type(value).__module__}.{type(value).__qualname__}" 

82 ) 

83 return value 

84 

85 def _mock_mapping(self, value: Mapping[Any, Any]) -> Mapping[Any, Any]: 

86 """Mock mapping values while preserving the mapping carrier type.""" 

87 mocked_items = [(key, self.mock(item)) for key, item in value.items()] 

88 if value.__class__ is dict: 

89 return dict(mocked_items) 

90 try: 

91 mocked_mapping = copy.copy(value) 

92 mocked_mapping.clear() 

93 mocked_mapping.update(mocked_items) 

94 return mocked_mapping 

95 except (AttributeError, TypeError): 

96 try: 

97 return type(value)(mocked_items) 

98 except TypeError as exc: 

99 raise ValueError( 

100 "Dry-run cannot preserve batch mapping carrier " 

101 f"{type(value).__module__}.{type(value).__qualname__}" 

102 ) from exc 

103 

104 def _mock_sequence(self, value: Any) -> Any: 

105 """Mock list and tuple values while preserving named tuples.""" 

106 mocked = tuple(self.mock(item) for item in value) 

107 if isinstance(value, list): 

108 return list(mocked) 

109 if hasattr(value, "_fields"): 

110 return type(value)(*mocked) 

111 return mocked 

112 

113 def _mock_dataclass(self, value: Any) -> Any: 

114 """Mock initialized and post-init dataclass fields.""" 

115 updates = { 

116 field.name: self.mock(getattr(value, field.name)) 

117 for field in fields(value) 

118 if field.init 

119 } 

120 mocked_dataclass = replace(value, **updates) 

121 for field in fields(value): 

122 if not field.init: 

123 object.__setattr__( 

124 mocked_dataclass, 

125 field.name, 

126 self.mock(getattr(value, field.name)), 

127 ) 

128 return mocked_dataclass 

129 

130 def _contains_tensor(self, value: Any) -> bool: 

131 """Return whether an unsupported object recursively owns a tensor.""" 

132 if isinstance(value, torch.Tensor): 

133 return True 

134 if isinstance(value, Mapping): 

135 return any(self._contains_tensor(item) for item in value.values()) 

136 if isinstance(value, (list, tuple)): 

137 return any(self._contains_tensor(item) for item in value) 

138 return False 

139 

140 

141def derive_tp_target_counts( 

142 loss_inputs: Mapping[str, Any], 

143 vocab_size: int, 

144 tp_size: int, 

145) -> tuple[int, tuple[int, ...]]: 

146 """Derive valid-label ownership using the real loss-parallel vocab split. 

147 

148 Args: 

149 loss_inputs: Loss inputs of the real CPU batch. 

150 vocab_size: Model vocabulary size. 

151 tp_size: Tensor-parallel size the vocabulary is split across. 

152 

153 Returns: 

154 Tuple of ``(valid_label_count, owned_counts_per_tp_rank)``. 

155 """ 

156 labels = loss_inputs.get("shift_labels") 

157 if labels is None: 

158 labels = loss_inputs.get("labels") 

159 if labels is None: 

160 raise ValueError("Dry-run loss_inputs must contain labels") 

161 labels = labels[..., 1:] 

162 if not isinstance(labels, torch.Tensor): 

163 raise ValueError("Dry-run labels must be a torch.Tensor") 

164 valid_mask = labels.ne(IGNORE_INDEX) 

165 loss_mask = loss_inputs.get("loss_mask") 

166 if isinstance(loss_mask, torch.Tensor): 

167 if loss_mask.shape != labels.shape: 

168 loss_mask = loss_mask[..., -labels.shape[-1]:] 

169 valid_mask = valid_mask & loss_mask.reshape_as(labels).bool() 

170 valid_labels = labels[valid_mask] 

171 chunk_size = (vocab_size + tp_size - 1) // tp_size 

172 owned = tuple( 

173 int(((valid_labels >= rank * chunk_size) & 

174 (valid_labels < min((rank + 1) * chunk_size, vocab_size))).sum().item()) 

175 for rank in range(tp_size) 

176 ) 

177 valid_count = int(valid_labels.numel()) 

178 if sum(owned) != valid_count: 

179 raise ValueError("Dry-run labels contain token IDs outside the configured vocabulary") 

180 return valid_count, owned 

181 

182 

183def collect_tensor_leaves(value: Any) -> tuple[torch.Tensor, ...]: 

184 """Recursively collect all tensor leaves from nested mappings, sequences, or dataclasses. 

185 

186 Args: 

187 value: Arbitrary nested container value. 

188 

189 Returns: 

190 Flat tuple of ``torch.Tensor`` instances found inside ``value``. 

191 """ 

192 if isinstance(value, torch.Tensor): 

193 return (value,) 

194 if isinstance(value, Mapping): 

195 return tuple( 

196 tensor 

197 for item in value.values() 

198 for tensor in collect_tensor_leaves(item) 

199 ) 

200 if isinstance(value, (list, tuple)): 

201 return tuple( 

202 tensor 

203 for item in value 

204 for tensor in collect_tensor_leaves(item) 

205 ) 

206 if is_dataclass(value) and not isinstance(value, type): 

207 return tuple( 

208 tensor 

209 for field in fields(value) 

210 for tensor in collect_tensor_leaves(getattr(value, field.name)) 

211 ) 

212 return () 

213 

214 

215def serialize_batch_shapes(value: Any) -> Any: 

216 """Serialize nested batch tensor shapes without retaining tensor values. 

217 

218 Args: 

219 value: Nested batch structure. 

220 

221 Returns: 

222 JSON-safe metadata structure describing tensor shapes, dtypes, and layouts. 

223 """ 

224 if isinstance(value, torch.Tensor): 

225 return { 

226 "shape": [int(size) for size in value.shape], 

227 "dtype": str(value.dtype), 

228 "layout": str(value.layout), 

229 } 

230 if isinstance(value, Mapping): 

231 return {name: serialize_batch_shapes(item) for name, item in value.items()} 

232 if isinstance(value, (list, tuple)): 

233 return [serialize_batch_shapes(item) for item in value] 

234 if is_dataclass(value) and not isinstance(value, type): 

235 return { 

236 field.name: serialize_batch_shapes(getattr(value, field.name)) 

237 for field in fields(value) 

238 } 

239 return value 

240 

241 

242def mock_training_batch( 

243 batch: PreparedDryRunBatch, 

244 fake_mode: FakeTensorMode, 

245 device: torch.device, 

246 vocab_size: int, 

247 tp_size: int, 

248) -> DryRunTrainingBatch: 

249 """Erase CPU batch values into FakeTensors while preserving CPU label stats. 

250 

251 Args: 

252 batch: Real CPU batch and its token counts. 

253 fake_mode: Active FakeTensorMode for fake tensor construction. 

254 device: Target logical simulation device. 

255 vocab_size: Model vocabulary size. 

256 tp_size: Tensor-parallel world size. 

257 

258 Returns: 

259 :class:`DryRunTrainingBatch` ready for the simulated training step. 

260 """ 

261 with unset_fake_temporarily(): 

262 valid_count, owned = derive_tp_target_counts( 

263 batch.loss_inputs, 

264 vocab_size, 

265 tp_size, 

266 ) 

267 mocker = DryRunBatchMocker(fake_mode, device) 

268 return DryRunTrainingBatch( 

269 model_inputs=mocker.mock(batch.model_inputs), 

270 loss_inputs=mocker.mock(batch.loss_inputs), 

271 token_counts=dict(batch.token_counts), 

272 valid_token_count=valid_count, 

273 target_tokens_per_rank=owned, 

274 ) 

275 

276 

277class DryRunDataAdapter: 

278 """Keep the native DataLoader contract while replacing values at ``get_batch``.""" 

279 

280 def __init__( 

281 self, 

282 raw_get_batch: Any, 

283 *, 

284 vocab_size: int, 

285 tp_size: int, 

286 fake_mode: FakeTensorMode, 

287 device: torch.device, 

288 ) -> None: 

289 """Bind a real ``get_batch`` callable to FakeTensor conversion and replay state.""" 

290 self.raw_get_batch = raw_get_batch 

291 self.vocab_size = int(vocab_size) 

292 self.tp_size = int(tp_size) 

293 self.fake_mode = fake_mode 

294 self.device = device 

295 self.current_batch: Optional[DryRunTrainingBatch] = None 

296 self.batch_count = 0 

297 self.last_batch_shapes: dict[str, Any] = {} 

298 self.last_token_counts: dict[str, int] = {} 

299 self.tp_replay: Any = None 

300 self.scalar_shim: Any = None 

301 

302 @property 

303 def runtime_input_adapter(self) -> Any: 

304 """Expose the model-provided runtime adapter expected by BaseTrainer.""" 

305 return getattr(self.raw_get_batch, "runtime_input_adapter", None) 

306 

307 def current_token_counts(self) -> dict[str, int]: 

308 """Return the CPU-derived token counts for the most recent batch.""" 

309 if self.current_batch is None: 

310 return {} 

311 return dict(self.current_batch.token_counts) 

312 

313 def __call__(self, iterator: Any) -> tuple[dict[str, Any], dict[str, Any]]: 

314 """Read one real CPU batch, refresh value replays, and return fake inputs.""" 

315 # Lazy import avoids pulling optional trainer/transformers deps when only 

316 # DryRunBatchMocker or derive_tp_target_counts is used in unit tests. 

317 from hyper_parallel.trainer.runtime.loss_aggregation import count_loss_token # pylint: disable=import-outside-toplevel 

318 

319 with unset_fake_temporarily(): 

320 model_inputs, loss_inputs = self.raw_get_batch(iterator) 

321 if not isinstance(model_inputs, Mapping) or not isinstance(loss_inputs, Mapping): 

322 raise ValueError("dataloader.get_batch must return model_inputs and loss_inputs mappings") 

323 token_counts = { 

324 name: int(value.item()) 

325 for name, value in count_loss_token(dict(loss_inputs)).items() 

326 } 

327 prepared = PreparedDryRunBatch( 

328 dict(model_inputs), 

329 dict(loss_inputs), 

330 token_counts, 

331 ) 

332 batch = mock_training_batch( 

333 prepared, 

334 self.fake_mode, 

335 self.device, 

336 self.vocab_size, 

337 self.tp_size, 

338 ) 

339 self.current_batch = batch 

340 self.batch_count += 1 

341 self.last_token_counts = dict(batch.token_counts) 

342 self.last_batch_shapes = { 

343 "model_inputs": serialize_batch_shapes(batch.model_inputs), 

344 "loss_inputs": serialize_batch_shapes(batch.loss_inputs), 

345 } 

346 if self.tp_replay is not None: 

347 self.tp_replay.update(batch.valid_token_count, batch.target_tokens_per_rank) 

348 if self.scalar_shim is not None: 

349 self.scalar_shim.clear() 

350 return batch.model_inputs, batch.loss_inputs 

351 

352 

353__all__ = [ 

354 "DryRunBatchMocker", 

355 "DryRunDataAdapter", 

356 "DryRunTrainingBatch", 

357 "PreparedDryRunBatch", 

358 "collect_tensor_leaves", 

359 "derive_tp_target_counts", 

360 "mock_training_batch", 

361 "serialize_batch_shapes", 

362]