Coverage for  / home / jenkins / .local / lib / python3.10 / site-packages / hyper_parallel / components / losses / chunked_cross_entropy.py: 79%

180 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"""Memory-efficient chunked output projection and cross-entropy. 

16 

17The full ``[batch, sequence, vocabulary]`` logits tensor is never 

18materialized. Output projection, FP32 cross-entropy, and first-order 

19gradients are evaluated one local sequence chunk at a time. 

20""" 

21 

22from __future__ import annotations 

23 

24__all__ = [ 

25 "ChunkedCausalLMLoss", 

26 "ChunkedCausalLMOutput", 

27 "chunked_cross_entropy", 

28] 

29 

30from collections.abc import Mapping 

31from dataclasses import dataclass 

32from typing import Any 

33 

34# This loss is a PyTorch Trainer component and differentiates through 

35# torch.func; there is no platform-neutral autograd equivalent. PyTorch's 

36# Function metaclass supplies its public variadic dispatch contract. 

37# pylint: disable=not-callable,abstract-method,arguments-differ 

38import torch 

39from torch import nn 

40from torch.autograd.function import once_differentiable 

41from torch.nn import functional 

42from transformers.utils import ModelOutput 

43 

44 

45def _linear_cross_entropy_chunk( 

46 hidden_chunk: torch.Tensor, 

47 weight: torch.Tensor, 

48 target_chunk: torch.Tensor, 

49 ignore_index: int, 

50) -> torch.Tensor: 

51 """Return the FP32 summed cross-entropy for one sequence chunk.""" 

52 logits = functional.linear( 

53 hidden_chunk.reshape(-1, hidden_chunk.size(-1)), 

54 weight, 

55 ).float() 

56 return functional.cross_entropy( 

57 logits, 

58 target_chunk.reshape(-1), 

59 ignore_index=ignore_index, 

60 reduction="sum", 

61 ) 

62 

63 

64class _PrecomputedChunkLoss(torch.autograd.Function): 

65 """Precompute per-chunk gradients and replay them in outer backward.""" 

66 

67 @staticmethod 

68 

69 def forward( 

70 ctx: Any, 

71 hidden_states: torch.Tensor, 

72 head_weight: torch.Tensor, 

73 targets: torch.Tensor, 

74 chunk_size: int, 

75 ignore_index: int, 

76 ) -> torch.Tensor: 

77 """Compute the loss sum and retain accumulated first-order gradients.""" 

78 grad_hidden = torch.empty_like(hidden_states) 

79 grad_weight = torch.zeros_like(head_weight) 

80 loss_sum = torch.zeros((), dtype=torch.float32, device=hidden_states.device) 

81 

82 grad_and_value = torch.func.grad_and_value( 

83 _linear_cross_entropy_chunk, 

84 argnums=(0, 1), 

85 ) 

86 hidden_chunks = torch.split(hidden_states, chunk_size, dim=1) 

87 target_chunks = torch.split(targets, chunk_size, dim=1) 

88 grad_hidden_chunks = torch.split(grad_hidden, chunk_size, dim=1) 

89 for hidden_chunk, target_chunk, grad_hidden_chunk in zip( 

90 hidden_chunks, target_chunks, grad_hidden_chunks, strict=True 

91 ): 

92 (chunk_grad_hidden, chunk_grad_weight), chunk_loss = grad_and_value( 

93 hidden_chunk, 

94 head_weight, 

95 target_chunk, 

96 ignore_index, 

97 ) 

98 grad_hidden_chunk.copy_(chunk_grad_hidden) 

99 grad_weight.add_(chunk_grad_weight) 

100 loss_sum.add_(chunk_loss) 

101 del chunk_grad_hidden, chunk_grad_weight, chunk_loss 

102 

103 ctx.save_for_backward(grad_hidden, grad_weight) 

104 return loss_sum 

105 

106 @staticmethod 

107 @once_differentiable 

108 

109 def backward(ctx: Any, grad_loss_sum: torch.Tensor | None) -> tuple: 

110 """Replay private gradients with the Trainer's upstream scale.""" 

111 if grad_loss_sum is None: 

112 return None, None, None, None, None 

113 grad_hidden, grad_weight = ctx.saved_tensors 

114 return ( 

115 grad_hidden * grad_loss_sum, 

116 grad_weight * grad_loss_sum, 

117 None, 

118 None, 

119 None, 

120 ) 

121 

122 

123def _validate_chunk_options(chunk_size: int, ignore_index: int) -> None: 

124 """Validate scalar chunk-loss options.""" 

125 if isinstance(chunk_size, bool) or not isinstance(chunk_size, int): 

126 raise TypeError( 

127 f"chunk_size must be an integer, got {type(chunk_size).__name__}" 

128 ) 

129 if chunk_size <= 0: 

130 raise ValueError(f"chunk_size must be positive, got {chunk_size}") 

131 if isinstance(ignore_index, bool) or not isinstance(ignore_index, int): 

132 raise TypeError( 

133 f"ignore_index must be an integer, got {type(ignore_index).__name__}" 

134 ) 

135 

136 

137def _validate_chunk_shapes( 

138 hidden_states: torch.Tensor, 

139 targets: torch.Tensor, 

140 head_weight: torch.Tensor, 

141) -> None: 

142 """Validate tensor ranks and logical dimensions.""" 

143 if hidden_states.dim() != 3: 

144 raise ValueError( 

145 "hidden_states must have shape [batch, sequence, hidden], " 

146 f"got {tuple(hidden_states.shape)}" 

147 ) 

148 if targets.dim() != 2 or hidden_states.shape[:2] != targets.shape: 

149 raise ValueError( 

150 "targets must match hidden_states batch/sequence dimensions, " 

151 f"got hidden={tuple(hidden_states.shape)} and targets={tuple(targets.shape)}" 

152 ) 

153 if hidden_states.size(1) == 0 or hidden_states.size(2) == 0: 

154 raise ValueError( 

155 "hidden_states sequence and hidden dimensions must be non-empty" 

156 ) 

157 if head_weight.dim() != 2 or head_weight.size(1) != hidden_states.size(2): 

158 raise ValueError( 

159 "head_weight must have shape [vocabulary, hidden] matching " 

160 f"hidden_states, got hidden={tuple(hidden_states.shape)} and " 

161 f"weight={tuple(head_weight.shape)}" 

162 ) 

163 if head_weight.size(0) == 0: 

164 raise ValueError("head_weight vocabulary dimension must be non-empty") 

165 

166 

167def _validate_chunk_dtypes_and_device( 

168 hidden_states: torch.Tensor, 

169 targets: torch.Tensor, 

170 head_weight: torch.Tensor, 

171) -> None: 

172 """Validate tensor dtypes and device ownership.""" 

173 if not torch.is_floating_point(hidden_states) or not torch.is_floating_point( 

174 head_weight 

175 ): 

176 raise TypeError("hidden_states and head_weight must be floating-point tensors") 

177 if targets.dtype != torch.long: 

178 raise TypeError(f"targets must have dtype torch.long, got {targets.dtype}") 

179 if hidden_states.dtype != head_weight.dtype: 

180 raise TypeError( 

181 "hidden_states and head_weight must have the same dtype, " 

182 f"got {hidden_states.dtype} and {head_weight.dtype}" 

183 ) 

184 if not hidden_states.device == targets.device == head_weight.device: 

185 raise ValueError( 

186 "hidden_states, targets, and head_weight must be on the same device, " 

187 f"got {hidden_states.device}, {targets.device}, and {head_weight.device}" 

188 ) 

189 

190 

191def chunked_cross_entropy( 

192 hidden_states: torch.Tensor, 

193 targets: torch.Tensor, 

194 head_weight: torch.Tensor, 

195 chunk_size: int = 1024, 

196 ignore_index: int = -100, 

197) -> torch.Tensor: 

198 """Compute summed linear cross-entropy without full-sequence logits. 

199 

200 Args: 

201 hidden_states: Local hidden states in ``[B, S, H]`` layout. 

202 targets: Integer targets aligned with ``hidden_states`` in ``[B, S]``. 

203 head_weight: Full-vocabulary output weight in ``[V, H]`` layout. 

204 chunk_size: Maximum local sequence length evaluated per chunk. 

205 ignore_index: Target value excluded from the summed loss. 

206 

207 Returns: 

208 A scalar FP32 loss sum connected to ``hidden_states`` and 

209 ``head_weight``. 

210 """ 

211 _validate_chunk_options(chunk_size, ignore_index) 

212 _validate_chunk_shapes(hidden_states, targets, head_weight) 

213 _validate_chunk_dtypes_and_device(hidden_states, targets, head_weight) 

214 return _PrecomputedChunkLoss.apply( 

215 hidden_states, 

216 head_weight, 

217 targets, 

218 chunk_size, 

219 ignore_index, 

220 ) 

221 

222 

223def _get_output_value(model_output: Any, name: str) -> Any: 

224 """Read one optional value from a mapping or Transformers output.""" 

225 if isinstance(model_output, Mapping): 

226 return model_output.get(name) 

227 return getattr(model_output, name, None) 

228 

229 

230@dataclass 

231class ChunkedCausalLMOutput(ModelOutput): 

232 """Training output produced by a model-integrated Chunk Loss adapter.""" 

233 

234 loss_sum: torch.Tensor | None = None 

235 valid_token_count: torch.Tensor | None = None 

236 aux_loss: torch.Tensor | None = None 

237 aux_loss_coef: float | None = None 

238 logits: torch.Tensor | None = None 

239 past_key_values: Any | None = None 

240 hidden_states: Any | None = None 

241 attentions: Any | None = None 

242 router_logits: Any | None = None 

243 

244 

245class ChunkedCausalLMLoss(nn.Module): 

246 """Trainer-facing model-integrated Chunk Loss objective. 

247 

248 The configured model-family adapter consumes the prepared model inputs, 

249 calls :func:`chunked_cross_entropy` before a full LM-head output exists, 

250 and returns :class:`ChunkedCausalLMOutput`. This module converts the local 

251 summed CE to one local token mean; global DP/CP weighting remains owned by 

252 ``mean_global_loss``. 

253 """ 

254 

255 def __init__(self, chunk_size: int = 1024, ignore_index: int = -100, 

256 labels_are_shifted: bool = True) -> None: 

257 """Initialize chunk options and the dataset target alignment. 

258 

259 Args: 

260 chunk_size: Number of token rows evaluated per CE chunk. 

261 ignore_index: Target value excluded from CE and token accounting. 

262 labels_are_shifted: Require pre-shifted targets by default. False permits raw labels 

263 and shifts their mask with them; explicit shift_labels always take precedence. 

264 """ 

265 super().__init__() 

266 _validate_chunk_options(chunk_size, ignore_index) 

267 if not isinstance(labels_are_shifted, bool): 

268 raise TypeError("labels_are_shifted must be a bool") 

269 self.chunk_size = chunk_size 

270 self.ignore_index = ignore_index 

271 self.labels_are_shifted = labels_are_shifted 

272 self._model_is_bound = False 

273 

274 @staticmethod 

275 

276 def _parallel_size(distributed_setup: Any, name: str) -> int: 

277 """Read one topology size from the shared mesh context.""" 

278 mesh = getattr(distributed_setup, "mesh_context", None) 

279 return int(getattr(mesh, name, 1)) 

280 

281 def _validate_distributed_contract(self, model: nn.Module, distributed_setup: Any) -> Any: 

282 """Validate Trainer topology and return the optional pipeline partition.""" 

283 from hyper_parallel.data.constants import IGNORE_INDEX # pylint: disable=import-outside-toplevel 

284 

285 if self.ignore_index != IGNORE_INDEX: 

286 raise ValueError( 

287 "ChunkedCausalLMLoss Trainer integration requires " 

288 f"ignore_index={IGNORE_INDEX}, got {self.ignore_index}" 

289 ) 

290 if not self.labels_are_shifted and self._parallel_size(distributed_setup, "cp_size") > 1: 

291 raise NotImplementedError( 

292 "Raw-label chunked loss requires CP1; shift global labels before CP partitioning instead" 

293 ) 

294 tp_size = self._parallel_size(distributed_setup, "tp_size") 

295 pp_size = self._parallel_size(distributed_setup, "pp_size") 

296 loss_parallel = bool(getattr(getattr(distributed_setup, "mesh_context", None), "loss_parallel", False)) 

297 partition = getattr(model, "_hp_pipeline_partition", None) 

298 if tp_size != 1 or (pp_size != 1 and partition is None) or loss_parallel: 

299 raise NotImplementedError( 

300 "ChunkedCausalLMLoss requires tp_size=1, pp_size=1 or a model-owned pipeline partition, " 

301 f"and loss_parallel=false; got tp_size={tp_size}, " 

302 f"pp_size={pp_size}, loss_parallel={loss_parallel}" 

303 ) 

304 return partition 

305 

306 def bind_model(self, model: nn.Module, distributed_setup: Any = None) -> None: 

307 """Bind the registered model-family Chunk Loss forward adapter. 

308 

309 Args: 

310 model: Fully constructed model whose parameter structure is fixed. 

311 distributed_setup: Shared Trainer distributed setup. 

312 

313 Raises: 

314 NotImplementedError: If an unsupported TP/PP/loss-parallel mode is 

315 active. 

316 ValueError: If the model family has no Chunk Loss adapter. 

317 """ 

318 # Token aggregation and the model objective must count the same labels. 

319 partition = self._validate_distributed_contract(model, distributed_setup) 

320 if partition is not None and not partition.is_last: 

321 return 

322 if getattr(model, "supports_chunked_loss", False): 

323 head = getattr(model, "lm_head", None) 

324 if not getattr(head, "supports_chunked_cross_entropy", False): 

325 raise TypeError("native chunked models must own a compatible terminal head") 

326 self._model_is_bound = True 

327 return 

328 

329 # Lazy imports keep generic loss-package import independent of concrete 

330 # model families and their optional backend dependencies. 

331 from hyper_parallel.models.registry import get_model_adapter # pylint: disable=import-outside-toplevel 

332 

333 model_type = getattr(getattr(model, "config", None), "model_type", "") 

334 adapter_spec = get_model_adapter(model_type) 

335 if adapter_spec is None: 

336 architectures = getattr(model.config, "architectures", None) or () 

337 if architectures: 

338 adapter_spec = get_model_adapter(architectures[0]) 

339 provider = None if adapter_spec is None else adapter_spec.loss 

340 if provider is None: 

341 raise ValueError( 

342 "ChunkedCausalLMLoss requires a registered model-family loss " 

343 f"adapter, but model_type={model_type!r} and its architecture provide none" 

344 ) 

345 adapter = provider() 

346 bind_chunk_loss = getattr(adapter, "bind_chunk_loss", None) 

347 if not callable(bind_chunk_loss): 

348 raise TypeError( 

349 f"model_type={model_type!r} loss adapter must expose bind_chunk_loss(model)" 

350 ) 

351 bind_chunk_loss(model) 

352 self._model_is_bound = True 

353 

354 def prepare_model_inputs( 

355 self, 

356 model_inputs: Mapping[str, Any], 

357 loss_inputs: Mapping[str, Any], 

358 ) -> dict[str, Any]: 

359 """Move labels to the model-family no-full-logits protocol.""" 

360 if not self._model_is_bound: 

361 raise RuntimeError("ChunkedCausalLMLoss must be bound before model forward") 

362 targets = loss_inputs.get("shift_labels") 

363 loss_mask = loss_inputs.get("loss_mask") 

364 shift_raw = not isinstance(targets, torch.Tensor) and not self.labels_are_shifted 

365 if shift_raw: 

366 targets = loss_inputs.get("labels") 

367 if not isinstance(targets, torch.Tensor): 

368 raise ValueError("ChunkedCausalLMLoss requires aligned targets: shift_labels or configured raw labels") 

369 if loss_mask is not None: 

370 if not isinstance(loss_mask, torch.Tensor) or loss_mask.shape != targets.shape: 

371 raise ValueError("loss_mask must be a Tensor with the same shape as targets") 

372 if shift_raw: 

373 targets = functional.pad(targets, (0, 1), value=self.ignore_index)[..., 1:].contiguous() 

374 if loss_mask is not None: 

375 loss_mask = functional.pad(loss_mask.to(torch.bool), (0, 1), value=False)[..., 1:].contiguous() 

376 

377 prepared = dict(model_inputs) 

378 # A legacy one-dictionary caller may leave loss-only fields in 

379 # model_inputs. Replace them with the adapter's explicit protocol so 

380 # labels and masks never leak into the decoder's generic **kwargs. 

381 prepared.pop("labels", None) 

382 prepared.pop("shift_labels", None) 

383 prepared.pop("loss_mask", None) 

384 prepared.update( 

385 { 

386 "chunk_loss_targets": targets, 

387 "chunk_loss_mask": loss_mask, 

388 "chunk_loss_chunk_size": self.chunk_size, 

389 "chunk_loss_ignore_index": self.ignore_index, 

390 } 

391 ) 

392 return prepared 

393 

394 def forward( # pylint: disable=unused-argument 

395 self, 

396 *, 

397 model_output: Any, 

398 labels: torch.Tensor | None, 

399 ) -> torch.Tensor: 

400 """Normalize one adapter-produced CE sum exactly once.""" 

401 logits = _get_output_value(model_output, "logits") 

402 if logits is not None: 

403 raise ValueError( 

404 "ChunkedCausalLMLoss model adapter materialized logits; expected logits=None" 

405 ) 

406 loss_sum = _get_output_value(model_output, "loss_sum") 

407 valid_token_count = _get_output_value(model_output, "valid_token_count") 

408 if not isinstance(loss_sum, torch.Tensor) or loss_sum.numel() != 1: 

409 raise ValueError("ChunkedCausalLMLoss requires a scalar Tensor loss_sum") 

410 if not isinstance(valid_token_count, torch.Tensor) or valid_token_count.numel() != 1: 

411 raise ValueError( 

412 "ChunkedCausalLMLoss requires a scalar Tensor valid_token_count" 

413 ) 

414 

415 denominator = valid_token_count.clamp_min(1).to(loss_sum.dtype) 

416 local_loss = loss_sum / denominator 

417 aux_loss = _get_output_value(model_output, "aux_loss") 

418 if aux_loss is not None: 

419 if not isinstance(aux_loss, torch.Tensor) or aux_loss.numel() != 1: 

420 raise ValueError("ChunkedCausalLMLoss aux_loss must be a scalar Tensor") 

421 aux_loss_coef = _get_output_value(model_output, "aux_loss_coef") 

422 local_loss = local_loss + float( 

423 0.0 if aux_loss_coef is None else aux_loss_coef 

424 ) * aux_loss 

425 return torch.where( 

426 valid_token_count.ne(0), 

427 local_loss, 

428 torch.zeros_like(local_loss), 

429 )