Coverage for  / home / jenkins / .local / lib / python3.10 / site-packages / hyper_parallel / data / batching / build_collate_fn.py: 85%

176 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"""Build final batch collators for Indexed and Online sources.""" 

16 

17from __future__ import annotations 

18 

19import logging 

20from collections.abc import Callable, Mapping, Sequence 

21from dataclasses import dataclass 

22from functools import partial 

23from typing import Any 

24 

25import torch 

26from torch.utils.data import default_collate 

27 

28from hyper_parallel.data.constants import ( 

29 IGNORE_INDEX, 

30 OMNI_CONCAT_FIELDS, 

31 OMNI_CP_PAD_VALUES, 

32 OMNI_CP_TOKEN_FIELDS, 

33) 

34from hyper_parallel.data.dataset_logging import get_dataset_logger 

35from hyper_parallel.data.batching.packing import SamplePacker 

36 

37logger = get_dataset_logger(__name__) 

38 

39 

40def _get_token_alignment_size(mesh_context: Any | None) -> int: 

41 """Return TP X CP, the required final batch token alignment.""" 

42 

43 if mesh_context is None: 

44 return 1 

45 

46 cp_size = int(getattr(mesh_context, "cp_size", 1)) 

47 tp_size = int(getattr(mesh_context, "tp_size", 1)) 

48 

49 if cp_size <= 0 or tp_size <= 0: 

50 raise ValueError("mesh_context tp_size and cp_size must be positive") 

51 

52 alignment_size = cp_size * tp_size 

53 return alignment_size 

54 

55 

56def _validate_padding_config(alignment_size: int, pad_to_length: int | None) -> None: 

57 """Check the shared text/Omni padding contract once at construction.""" 

58 

59 if alignment_size <= 0: 

60 raise ValueError("alignment_size must be positive") 

61 

62 if pad_to_length is None: 

63 return 

64 

65 if isinstance(pad_to_length, bool) or not isinstance(pad_to_length, int) or pad_to_length <= 0: 

66 raise ValueError("pad_to_length must be a positive integer or None") 

67 

68 if pad_to_length % alignment_size: 

69 raise ValueError( 

70 f"pad_to_length={pad_to_length} must be divisible by TP * CP alignment_size={alignment_size}" 

71 ) 

72 

73 

74def _pad_packed_token_field( 

75 name: str, 

76 values: Sequence[torch.Tensor], 

77 packed_samples: Sequence[Mapping[str, Any]], 

78 sequence_lengths: Sequence[int], 

79 target_length: int, 

80) -> torch.Tensor: 

81 """Validate one token field and pad every packed row to the target length.""" 

82 if len(values) != len(packed_samples) or any(value.shape != sample["input_ids"].shape 

83 for sample, value in zip(packed_samples, values)): 

84 raise ValueError(f"Packed token field {name!r} must match input_ids in every packed sample") 

85 

86 output = values[0].new_full((len(packed_samples), target_length), OMNI_CP_PAD_VALUES.get(name, 0)) 

87 

88 for batch_index, (value, length) in enumerate(zip(values, sequence_lengths)): 

89 output[batch_index, :length] = value 

90 

91 return output 

92 

93 

94def _collate_packed_boundaries( 

95 packed_samples: Sequence[Mapping[str, Any]], 

96 sequence_lengths: Sequence[int], 

97 target_length: int, 

98) -> torch.Tensor: 

99 """Flatten document coordinates and isolate each packed row's padding tail.""" 

100 reference = packed_samples[0]["input_ids"] 

101 boundary_parts = [reference.new_zeros(1, dtype=torch.int32)] 

102 

103 for batch_index, (sample, length) in enumerate(zip(packed_samples, sequence_lengths)): 

104 boundaries = sample.get("cu_seq_lens") 

105 

106 if boundaries is None: 

107 boundaries = reference.new_tensor([0, length], dtype=torch.int32) 

108 

109 boundaries = boundaries.reshape(-1).to(torch.int32) 

110 

111 if (boundaries.numel() < 2 or int(boundaries[0]) != 0 or int(boundaries[-1]) != length 

112 or bool(torch.any(boundaries[1:] <= boundaries[:-1]))): 

113 raise ValueError("cu_seq_lens must cover each complete packed row with increasing boundaries") 

114 

115 boundary_parts.append(boundaries[1:] + batch_index * target_length) 

116 

117 if length < target_length: 

118 boundary_parts.append(boundaries.new_tensor([(batch_index + 1) * target_length])) 

119 

120 return torch.cat(boundary_parts) 

121 

122 

123def _collate_packed_samples( 

124 packed_samples: Sequence[Mapping[str, Any]], 

125 alignment_size: int, 

126 pad_to_length: int | None, 

127 max_seq_len: int | None, 

128) -> dict[str, Any]: 

129 """Pad packed samples into [B, T] token tensors and collate their metadata. 

130 

131 Args: 

132 packed_samples: B packed sample mappings, each with one-dimensional 

133 input_ids [L], matching token fields, and optional document/media metadata. 

134 alignment_size: Required TP * CP sequence-length alignment. 

135 pad_to_length: Fixed sequence length, or None to align the longest sample. 

136 max_seq_len: Upper bound on the padded sequence length. 

137 

138 Returns: 

139 Padded token tensors with combined document boundaries and media fields. 

140 

141 Example: 

142 B=2, pad_to_length=4096: packed samples [1800+2000], [500+3000] 

143 become input_ids/labels [2, 4096], with 296/596 padding tokens (0/-100). 

144 cu_seq_lens = [0, 1800, 3800, 4096, 4596, 7596, 8192]. 

145 """ 

146 

147 if any(sample["input_ids"].ndim != 1 or sample["input_ids"].shape[-1] == 0 

148 for sample in packed_samples): 

149 raise ValueError("Packed samples must contain nonempty one-dimensional input_ids") 

150 

151 sequence_lengths = [sample["input_ids"].shape[-1] for sample in packed_samples] 

152 longest_length = max(sequence_lengths) 

153 target_length = pad_to_length 

154 

155 if target_length is None: 

156 target_length = longest_length + (-longest_length) % alignment_size 

157 

158 if longest_length > target_length: 

159 raise ValueError(f"Packed sequence length {longest_length} exceeds pad_to_length={target_length}") 

160 

161 if max_seq_len is not None and target_length > max_seq_len: 

162 raise ValueError(f"Batch padding length {target_length} exceeds max_seq_len={max_seq_len}") 

163 

164 # Token fields become [B, T]; media retain their modality-specific leading dimension. 

165 batch = {} 

166 fields = set().union(*(sample.keys() for sample in packed_samples)) - {"cu_seq_lens", "packing_length"} 

167 image_fields = {"image_patch_lengths", "image_vit_grid_hw", "image_llm_grid_hw", "image_token_starts"} 

168 

169 for name in fields: 

170 values = [sample[name] for sample in packed_samples if name in sample] 

171 

172 if name in OMNI_CP_TOKEN_FIELDS: 

173 batch[name] = _pad_packed_token_field(name, values, packed_samples, sequence_lengths, target_length) 

174 

175 elif name in OMNI_CONCAT_FIELDS or name in image_fields: 

176 batch[name] = torch.cat(values, dim=0) 

177 else: 

178 batch[name] = default_collate(values) 

179 

180 batch["cu_seq_lens"] = _collate_packed_boundaries(packed_samples, sequence_lengths, target_length) 

181 

182 if "image_patch_lengths" in fields: 

183 batch["image_batch_indices"] = torch.cat([ 

184 sample["image_patch_lengths"].new_full((sample["image_patch_lengths"].numel(),), batch_index) 

185 for batch_index, sample in enumerate(packed_samples) if "image_patch_lengths" in sample 

186 ]) 

187 

188 return batch 

189 

190 

191@dataclass 

192class TextPackingCollator: 

193 """Pack unpadded Online text samples and emit ``cu_seq_lens``. 

194 

195 Only ``input_ids`` and pre-shifted ``labels`` are packed here. Unified 

196 ``get_batch`` constructs loss, position, mask, and CP runtime fields. 

197 """ 

198 

199 alignment_size: int = 1 

200 pad_to_length: int | None = None 

201 max_seq_len: int | None = None 

202 

203 def __post_init__(self) -> None: 

204 """Validate fixed padding before any samples are read.""" 

205 _validate_padding_config(self.alignment_size, self.pad_to_length) 

206 _validate_padding_config(self.alignment_size, self.max_seq_len) 

207 

208 def __call__(self, model_samples: Sequence[Mapping[str, Any]]) -> Mapping[str, Any]: 

209 """Pad independently packed rows to one common ``[B, T]`` shape. 

210 

211 Args: 

212 model_samples: Packed rows with cu_seq_lens. A flat group without 

213 boundaries is accepted as one row for direct callers. 

214 

215 Returns: 

216 Packed ``input_ids`` and ``labels`` plus int32 ``cu_seq_lens``. 

217 

218 Raises: 

219 ValueError: If no samples are provided. 

220 """ 

221 

222 if not model_samples: 

223 raise ValueError("model_samples must contain at least one Online sample") 

224 

225 if not any("cu_seq_lens" in sample for sample in model_samples): 

226 model_samples = [SamplePacker().pack_selected_samples(model_samples)] 

227 

228 padded_batch = _collate_packed_samples( 

229 model_samples, self.alignment_size, self.pad_to_length, self.max_seq_len, 

230 ) 

231 return padded_batch 

232 

233 

234@dataclass 

235class OmniCollator: 

236 """Collate Omni samples, then pad token fields to a fixed length or TP × CP.""" 

237 

238 alignment_size: int = 1 

239 pad_to_length: int | None = None 

240 max_seq_len: int | None = None 

241 

242 def __post_init__(self) -> None: 

243 """Validate fixed padding before any samples are read.""" 

244 _validate_padding_config(self.alignment_size, self.pad_to_length) 

245 _validate_padding_config(self.alignment_size, self.max_seq_len) 

246 

247 def __call__(self, model_samples: Sequence[Mapping[str, Any]]) -> Mapping[str, Any]: 

248 """Stack token fields, concatenate media, and pad only the final batch. 

249 

250 Example: 

251 One packed sample of length 18, TP=4, CP=2 produces [1, 24] 

252 token fields. Image tensors and global image starts are unchanged. 

253 """ 

254 

255 if not model_samples: 

256 raise ValueError("model_samples must contain at least one Omni sample") 

257 

258 aligned_batch = _collate_packed_samples( 

259 model_samples, self.alignment_size, self.pad_to_length, self.max_seq_len, 

260 ) 

261 

262 if logger.isEnabledFor(logging.DEBUG) and aligned_batch["input_ids"].device.type == "cpu": 

263 self._log_batch(aligned_batch, sum(sample["input_ids"].numel() for sample in model_samples)) 

264 

265 return aligned_batch 

266 

267 def _log_batch(self, batch: Mapping[str, Any], real_token_count: int) -> None: 

268 """Inspect CPU batches before transport without synchronizing accelerator streams.""" 

269 input_ids = batch["input_ids"] 

270 labels = batch["labels"] 

271 boundaries = batch.get("cu_seq_lens") 

272 boundaries = [] if boundaries is None else boundaries.reshape(-1).tolist() 

273 padding = input_ids.numel() - real_token_count 

274 supervised = int((labels >= 0).sum()) 

275 lengths = [end - start for start, end in zip(boundaries[:-1], boundaries[1:])] 

276 logger.debug( 

277 "Omni collate: input_shape=%s label_shape=%s real_tokens=%d padding_tokens=%d " 

278 "alignment=%d cu_seq_lens=%s segment_lengths=%s supervised_tokens=%d", 

279 tuple(input_ids.shape), tuple(labels.shape), real_token_count, padding, self.alignment_size, 

280 boundaries, lengths, supervised, enabled=True, 

281 ) 

282 

283 if not supervised: 

284 logger.warning("Omni collate batch contains no supervised tokens") 

285 

286 

287def build_default_collate_fn() -> Callable[[list[Any]], Any]: 

288 """Build ordinary PyTorch collation for already prepared samples. 

289 

290 Returns: 

291 PyTorch default collation. 

292 """ 

293 collate_fn = default_collate 

294 

295 return collate_fn 

296 

297 

298# Indexed samples are already prepared and use the same ordinary collation. 

299build_indexed_collate_fn = build_default_collate_fn 

300 

301 

302def _sft_row_boundaries(boundaries: Any, sequence_length: int) -> list[int]: 

303 """Remove boundary sentinels and validate one complete SFT row.""" 

304 row = torch.as_tensor(boundaries) 

305 

306 if row.ndim != 1 or row.dtype not in (torch.int32, torch.int64): 

307 raise ValueError("Each cu_seq_lens row must be a one-dimensional integer array") 

308 

309 row = row[row != -1] 

310 

311 if (row.numel() < 2 or row[0] != 0 or row[-1] != sequence_length 

312 or torch.any(row[1:] <= row[:-1])): 

313 raise ValueError("Document boundaries must strictly increase from zero to row length") 

314 

315 return row.tolist() 

316 

317 

318def _collate_sft_samples(batch: list[Any], *, alignment_size: int) -> Any: 

319 """Stack SFT rows and retain per-row boundaries without sentinel padding. 

320 

321 Records from SFTFromMRDataset have 1D input_ids/labels; already grouped 

322 records may have [rows, S]. Variable-length rows are padded, never truncated. 

323 """ 

324 

325 if not isinstance(batch[0], Mapping) or "cu_seq_lens" not in batch[0]: 

326 return default_collate(batch) 

327 

328 token_rows, label_rows, boundary_rows = [], [], [] 

329 

330 for sample in batch: 

331 tokens, labels = torch.as_tensor(sample["input_ids"]), torch.as_tensor(sample["labels"]) 

332 

333 if tokens.ndim not in (1, 2) or tokens.shape != labels.shape or not tokens.numel(): 

334 raise ValueError("SFT tokens and labels must have matching nonempty [S] or [rows, S] shapes") 

335 

336 boundaries = sample["cu_seq_lens"] 

337 

338 if tokens.ndim == 1: 

339 tokens, labels, boundaries = tokens.unsqueeze(0), labels.unsqueeze(0), [boundaries] 

340 

341 if len(boundaries) != len(tokens): 

342 raise ValueError("cu_seq_lens must have one boundary array per token row") 

343 

344 for row in boundaries: 

345 boundary_rows.append(_sft_row_boundaries(row, tokens.shape[-1])) 

346 token_rows.extend(tokens.unbind(0)) 

347 label_rows.extend(labels.unbind(0)) 

348 

349 sequence_length = max(row.numel() for row in token_rows) 

350 sequence_length += (-sequence_length) % alignment_size 

351 packed_keys = {"input_ids", "labels", "cu_seq_lens"} 

352 result = default_collate([ 

353 {key: value for key, value in sample.items() if key not in packed_keys} for sample in batch 

354 ]) 

355 

356 for key, rows, value in (("input_ids", token_rows, 0), ("labels", label_rows, IGNORE_INDEX)): 

357 result[key] = torch.stack([ 

358 torch.nn.functional.pad(row, (0, sequence_length - row.numel()), value=value) for row in rows 

359 ]) 

360 

361 for row in boundary_rows: 

362 if row[-1] < sequence_length: 

363 # Isolate ignored tail padding from every real document. 

364 row.append(sequence_length) 

365 

366 result["cu_seq_lens"] = boundary_rows 

367 return result 

368 

369 

370def build_sft_collate_fn(mesh_context: Any | None = None) -> Callable[[list[Any]], Any]: 

371 """Build SFT collation preserving [B, S] and each row's document boundaries. 

372 

373 Args: 

374 mesh_context: Optional topology for TP x CP sequence-length alignment. 

375 

376 Returns: 

377 A CPU collator accepting 1D records or already grouped 2D records. 

378 Ordinary records without cu_seq_lens use default collation. 

379 """ 

380 return partial(_collate_sft_samples, alignment_size=_get_token_alignment_size(mesh_context)) 

381 

382 

383def _get_pad_length( 

384 pad_to_length: bool, 

385 max_seq_len: int | None = None, 

386) -> int | None: 

387 """Use the shared packing limit for fixed padding, or align actual lengths.""" 

388 

389 if not isinstance(pad_to_length, bool): 

390 raise ValueError("pad_to_length must be a bool") 

391 

392 if not pad_to_length: 

393 return None 

394 

395 if max_seq_len is None: 

396 raise ValueError("Fixed batch padding requires max_seq_len") 

397 

398 return max_seq_len 

399 

400 

401def build_omni_collate_fn( 

402 mesh_context: Any | None = None, 

403 pad_to_length: bool = True, 

404 max_seq_len: int | None = None, 

405) -> OmniCollator: 

406 """Build Omni collation with optional fixed padding after packing. 

407 

408 Args: 

409 mesh_context: Runtime TP/CP topology injected by the Trainer. 

410 pad_to_length: True pads every row to max_seq_len; False pads to the 

411 aligned maximum actual row length. Defaults to True. 

412 max_seq_len: Maximum packed row length supplied by the Trainer. 

413 

414 Returns: 

415 A collator that pads token lengths and preserves modality metadata. 

416 

417 Raises: 

418 ValueError: If pad_to_length is not a bool, fixed padding has no max_seq_len, 

419 or the length is invalid or not divisible by TP × CP. 

420 """ 

421 alignment_size = _get_token_alignment_size(mesh_context) 

422 collate_fn = OmniCollator(alignment_size=alignment_size, max_seq_len=max_seq_len, 

423 pad_to_length=_get_pad_length(pad_to_length, max_seq_len)) 

424 

425 return collate_fn 

426 

427 

428def build_online_text_collate_fn( 

429 mesh_context: Any | None = None, 

430 pad_to_length: bool = True, 

431 max_seq_len: int | None = None, 

432) -> TextPackingCollator: 

433 """Build Online text collation shared by fixed N and dynamic K batching. 

434 

435 The loader independently packs B rows. Collation pads them to max_seq_len 

436 by default, preserving document boundaries and isolating every padding tail. 

437 Dynamic padding uses the longest actual row rounded to ``cp_size * tp_size``. 

438 

439 Args: 

440 mesh_context: Runtime TP/CP topology injected by the Trainer. 

441 pad_to_length: True pads every row to max_seq_len; False pads to the 

442 aligned maximum actual row length. Defaults to True. 

443 max_seq_len: Maximum packed row length supplied by the Trainer. 

444 

445 Returns: 

446 A collator producing one forward-backward batch. 

447 

448 Raises: 

449 ValueError: If pad_to_length is not a bool, fixed padding has no max_seq_len, 

450 or the length is invalid or not divisible by TP × CP. 

451 """ 

452 alignment_size = _get_token_alignment_size(mesh_context) 

453 collate_fn = TextPackingCollator(alignment_size=alignment_size, max_seq_len=max_seq_len, 

454 pad_to_length=_get_pad_length(pad_to_length, max_seq_len)) 

455 

456 return collate_fn