Coverage for / home / jenkins / .local / lib / python3.10 / site-packages / hyper_parallel / components / losses / _vocab_parallel_cross_entropy.py: 100%
199 statements
« prev ^ index » next coverage.py v7.13.1, created at 2026-12-05 05:12 +0800
« 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"""AutoModels-private vocab-parallel cross entropy (local-first).
17Merges the former ``components/loss/loss_parallel_ops.py`` kernel with the
18``loss_parallel_ops_common.py`` validation helpers into a single private
19production implementation. The leading underscore marks this module as
20internal: the generic DTensor loss API stays in ``core.tensor_parallel``
21(frozen), while AutoModels production loss uses this module.
23The public-in-package entry is :func:`vocab_parallel_cross_entropy_local`:
24it takes the *local* logits shard plus the global vocabulary size, the mesh
25and the mesh axis that shards the class dimension — no temporary DTensor is
26created per call. The 2D mesh-axis recognition and the "class dimension
27sharded by exactly one mesh axis" validation from the former AutoModels
28DTensor wrapper are absorbed by :func:`_resolve_class_mesh_dim`.
29"""
31from __future__ import annotations
33__all__ = [
34 "vocab_parallel_cross_entropy_local",
35 "entropy_from_logits",
36 "distributed_log_softmax",
37 "distributed_nll_loss_forward",
38 "DistributedCrossEntropyFunction",
39]
41from typing import Any, NamedTuple, Optional, Tuple, TYPE_CHECKING
43import torch
44import torch.distributed.nn.functional as dist_func
45from torch import Tensor
47if TYPE_CHECKING:
48 from hyper_parallel.core.dtensor.device_mesh import DeviceMesh
50_REDUCE_OP_MAP = {
51 "sum": torch.distributed.ReduceOp.SUM,
52 "prod": torch.distributed.ReduceOp.PRODUCT,
53 "max": torch.distributed.ReduceOp.MAX,
54 "min": torch.distributed.ReduceOp.MIN,
55 "all": torch.distributed.ReduceOp.MIN,
56 "avg": torch.distributed.ReduceOp.SUM,
57}
60def _differentiable_all_reduce(data: Tensor, op: str, group: Any) -> Tensor:
61 """Autograd-aware all-reduce: backward is an identity, the loss is scaled by world size."""
62 if not data.is_contiguous() or data.storage_offset() != 0:
63 data = data.contiguous()
64 reduce_op = _REDUCE_OP_MAP.get(op, torch.distributed.ReduceOp.SUM)
65 return dist_func.all_reduce(data, op=reduce_op, group=group)
68def _validate_target_type_base(is_floating: bool) -> None:
69 """Validate target type (base check).
71 Args:
72 is_floating: Whether target tensor has floating dtype.
74 Raises:
75 ValueError: If target is floating point (probabilistic).
76 """
77 if is_floating:
78 raise ValueError(
79 "Probabilistic target (float) is not supported in loss_parallel. "
80 "Target must be class indices (int64)."
81 )
84def _resolve_class_mesh_dim(mesh: "DeviceMesh", mesh_dim: Optional[int]) -> int:
85 """Identify the single mesh axis that shards the class dimension.
87 Absorbs the 2D mesh-axis recognition of the former DTensor-based
88 implementation: an explicit ``mesh_dim`` is validated against the mesh,
89 a 1D mesh resolves to axis 0, and a multi-dimensional mesh resolves the
90 axis named ``"tp"``. The class dimension must be sharded by exactly one
91 mesh axis.
93 Args:
94 mesh: Mesh holding the class-sharding axis.
95 mesh_dim: Explicitly declared class-sharding axis, or ``None`` to
96 resolve it from the mesh shape and dimension names.
98 Returns:
99 The resolved mesh axis index.
101 Raises:
102 ValueError: If no unique class-sharding axis can be identified.
103 """
104 if mesh_dim is not None:
105 if not isinstance(mesh_dim, int) or not 0 <= mesh_dim < mesh.ndim:
106 raise ValueError(
107 "Expected the class dimension to be sharded on exactly one "
108 f"mesh dimension. Got mesh_dim={mesh_dim} for a "
109 f"{mesh.ndim}D mesh."
110 )
111 return mesh_dim
112 if mesh.ndim == 1:
113 return 0
114 names = mesh.mesh_dim_names or ()
115 matches = [axis for axis, name in enumerate(names) if name == "tp"]
116 if len(matches) != 1:
117 raise ValueError(
118 "Expected the class dimension to be sharded on exactly one mesh "
119 f"dimension. Got {mesh.ndim}D mesh with dimension names {names}; "
120 "pass mesh_dim explicitly or name the sharding axis 'tp'."
121 )
122 return matches[0]
125def _is_floating_torch(tensor: Tensor) -> bool:
126 """Check if PyTorch tensor is floating point."""
127 return tensor.is_floating_point()
130def _compute_vocab_start(vocab_size: int, tp_size: int, rank: int) -> int:
131 """Compute the starting index for this rank's vocab shard.
133 Args:
134 vocab_size: Total vocabulary size.
135 tp_size: Tensor parallel world size.
136 rank: Current rank in TP mesh.
138 Returns:
139 Starting index of this rank's vocab shard.
141 Note:
142 This follows torch.chunk behavior: chunk_size = ceil(vocab_size/tp_size),
143 and each rank's start = rank * chunk_size. The last rank may have fewer elements.
144 """
145 chunk_size = (vocab_size + tp_size - 1) // tp_size # ceil division
146 return rank * chunk_size
149def distributed_log_softmax(
150 logits_local: Tensor,
151 dim: int,
152 mesh: DeviceMesh,
153 mesh_dim: int = 0,
154) -> Tensor:
155 """K1: Stable log-softmax on class-sharded dimension.
157 Args:
158 logits_local: Local logits shard.
159 dim: Class dimension.
160 mesh: DeviceMesh.
161 mesh_dim: Mesh dimension (default 0).
163 Returns:
164 Local log-softmax with unchanged layout.
166 Communication:
167 MAX + SUM all_reduce
168 """
169 max_local = logits_local.max(dim=dim, keepdim=True).values
171 group = mesh.get_group(mesh_dim)
172 max_global = _differentiable_all_reduce(max_local, op="max", group=group)
174 exp_local = (logits_local - max_global).exp()
176 sum_local = exp_local.sum(dim=dim, keepdim=True)
178 sum_global = _differentiable_all_reduce(sum_local, op="sum", group=group)
180 log_softmax = logits_local - max_global - sum_global.log()
182 return log_softmax
185def distributed_nll_loss_forward(
186 log_probs: Tensor,
187 target: Tensor,
188 weight: Optional[Tensor],
189 ignore_index: int,
190 reduction: str,
191 vocab_start: int,
192 vocab_end: int,
193) -> Tuple[Tensor, Tensor, Tensor, Tensor]:
194 """K2: Index target + optional weight + reduction.
196 Args:
197 log_probs: Sharded log_probs.
198 target: Target class indices.
199 weight: Optional weights.
200 ignore_index: Index to ignore.
201 reduction: Reduction method.
202 vocab_start: Start index of this vocab shard.
203 vocab_end: End index of this vocab shard.
205 Returns:
206 Tuple of (loss, total_weight, target_mask, vocab_start_tensor).
207 """
208 batch_size = target.numel()
210 target_flat = target.flatten()
212 target_mask = (target_flat >= vocab_start) & (target_flat < vocab_end)
214 target_mask = target_mask & (target_flat != ignore_index)
216 if reduction == "none":
217 loss = torch.zeros(batch_size, dtype=log_probs.dtype, device=log_probs.device)
218 else:
219 loss = torch.zeros(1, dtype=log_probs.dtype, device=log_probs.device)
221 total_weight = torch.zeros(1, dtype=log_probs.dtype, device=log_probs.device)
223 if target_mask.any():
224 local_target = target_flat[target_mask] - vocab_start
226 selected_log_probs = log_probs.reshape(-1, log_probs.shape[-1])[
227 torch.where(target_mask)[0], local_target
228 ]
230 if weight is not None:
231 sample_weights = weight[target_flat[target_mask]]
232 selected_log_probs = selected_log_probs * sample_weights
233 total_weight = sample_weights.sum().reshape(1)
234 else:
235 total_weight = torch.tensor(
236 target_mask.sum().item(), dtype=log_probs.dtype, device=log_probs.device
237 ).reshape(1)
239 selected_log_probs = -selected_log_probs
241 if reduction == "none":
242 loss = torch.zeros(batch_size, dtype=log_probs.dtype, device=log_probs.device)
243 loss[target_mask] = selected_log_probs
244 loss = loss.reshape(target.shape)
245 elif reduction == "sum":
246 loss = selected_log_probs.sum().unsqueeze(0)
247 else:
248 loss = selected_log_probs.sum().unsqueeze(0)
249 else:
250 if reduction == "none":
251 loss = torch.zeros(
252 batch_size, dtype=log_probs.dtype, device=log_probs.device
253 ).reshape(target.shape)
254 total_weight = torch.zeros(1, dtype=log_probs.dtype, device=log_probs.device)
256 return loss, total_weight, target_mask, torch.tensor(
257 vocab_start, dtype=torch.long, device=log_probs.device
258 )
261class _CrossEntropyGradients(NamedTuple):
262 """Gradients aligned with the eight inputs of the autograd function."""
264 input_local: Tensor
265 target: None = None
266 weight: None = None
267 ignore_index: None = None
268 reduction: None = None
269 vocab_size: None = None
270 mesh: None = None
271 mesh_dim: None = None
274class _CrossEntropyContext(NamedTuple):
275 """State required by the custom cross-entropy backward pass."""
277 log_probs_local: Tensor
278 target: Tensor
279 weight: Optional[Tensor]
280 total_weight: Tensor
281 target_mask: Tensor
282 vocab_start_tensor: Tensor
283 reduction: str
284 ignore_index: int
285 vocab_start: int
286 vocab_end: int
289def _compute_cross_entropy_gradient(
290 state: _CrossEntropyContext,
291 grad_output: Tensor,
292) -> Tensor:
293 """Compute the local logits gradient for one reduction mode."""
294 target_flat = state.target.flatten()
295 softmax_local = state.log_probs_local.exp()
296 ignore_mask = target_flat != state.ignore_index
298 if state.weight is not None:
299 # Ignore positions can contain -100, so use a valid class index before
300 # masking their gradients out below.
301 safe_target = torch.where(ignore_mask, target_flat, torch.zeros_like(target_flat))
302 sample_weights = state.weight[safe_target]
303 else:
304 sample_weights = None
306 if state.reduction == "mean":
307 grad_scale = grad_output / state.total_weight.clamp(min=1e-12)
308 elif state.reduction == "sum":
309 grad_scale = grad_output
310 else:
311 grad_scale = grad_output.flatten()
313 in_vocab_mask = (target_flat >= state.vocab_start) & (target_flat < state.vocab_end) & ignore_mask
314 grad_scale_expanded = (
315 grad_scale.unsqueeze(-1) if state.reduction == "none" else grad_scale.reshape(1, 1)
316 )
317 if sample_weights is not None:
318 grad_scale_expanded = grad_scale_expanded * sample_weights.unsqueeze(-1)
319 grad_input = softmax_local * grad_scale_expanded
320 local_targets = torch.where(
321 in_vocab_mask, target_flat - state.vocab_start, torch.zeros_like(target_flat)
322 )
324 if in_vocab_mask.any():
325 row_indices = torch.arange(target_flat.numel(), device=state.target.device, dtype=torch.long)
326 if state.reduction == "none":
327 grad_values = -grad_scale
328 else:
329 grad_values = -grad_scale.expand_as(target_flat)
330 if sample_weights is not None:
331 grad_values = grad_values * sample_weights
332 grad_input = grad_input.contiguous()
333 grad_input[row_indices[in_vocab_mask], local_targets[in_vocab_mask]] += grad_values[in_vocab_mask]
335 if not ignore_mask.all():
336 if state.reduction == "none":
337 grad_input[~ignore_mask] = 0.0
338 else:
339 ignore_indices_expanded = (~ignore_mask).unsqueeze(-1).expand_as(grad_input)
340 grad_input[ignore_indices_expanded] = 0.0
341 return grad_input
344class DistributedCrossEntropyFunction(torch.autograd.Function):
345 """K3: Fused backward for distributed cross_entropy."""
347 @staticmethod
348 def forward(
349 ctx: Any,
350 input_local: Tensor,
351 target: Tensor,
352 weight: Optional[Tensor],
353 ignore_index: int,
354 reduction: str,
355 vocab_size: int,
356 mesh: DeviceMesh,
357 mesh_dim: int,
358 ) -> Tensor:
359 """Forward pass with shared context setup for each reduction mode."""
360 ctx.vocab_start = _compute_vocab_start(
361 vocab_size, mesh.size(mesh_dim), mesh.get_local_rank(mesh_dim)
362 )
363 ctx.vocab_end = ctx.vocab_start + input_local.shape[-1]
364 ctx.reduction = reduction
365 ctx.ignore_index = ignore_index
366 log_probs_local = distributed_log_softmax(
367 input_local, dim=-1, mesh=mesh, mesh_dim=mesh_dim
368 )
369 nll_result = distributed_nll_loss_forward(
370 log_probs_local,
371 target,
372 weight,
373 ignore_index,
374 reduction,
375 ctx.vocab_start,
376 ctx.vocab_end,
377 )
378 loss, total_weight = nll_result[:2]
379 if reduction in ("mean", "sum"):
380 group = mesh.get_group(mesh_dim)
381 loss = _differentiable_all_reduce(loss, op="sum", group=group)
382 if reduction == "mean":
383 total_weight = _differentiable_all_reduce(
384 total_weight, op="sum", group=group
385 )
386 if reduction != "mean":
387 total_weight = torch.zeros(1, dtype=loss.dtype, device=loss.device)
388 ctx.save_for_backward(
389 log_probs_local, target, weight, total_weight, nll_result[2], nll_result[3]
390 )
391 if reduction == "mean":
392 if total_weight.item() == 0:
393 return torch.tensor(float('nan'), dtype=loss.dtype, device=loss.device)
394 return loss / total_weight
395 return loss
397 @staticmethod
398 def backward(ctx: Any, grad_output: Tensor) -> Tuple[Optional[Tensor], ...]:
399 """Backward pass (vectorized implementation)."""
400 state = _CrossEntropyContext(
401 *ctx.saved_tensors,
402 reduction=ctx.reduction,
403 ignore_index=ctx.ignore_index,
404 vocab_start=ctx.vocab_start,
405 vocab_end=ctx.vocab_end,
406 )
407 return _CrossEntropyGradients(_compute_cross_entropy_gradient(state, grad_output))
410def vocab_parallel_cross_entropy_local(
411 local_logits: Tensor,
412 target: Tensor,
413 *,
414 vocab_size: int,
415 mesh: "DeviceMesh",
416 mesh_dim: Optional[int] = None,
417 ignore_index: int = -100,
418 reduction: str = "sum",
419) -> Tensor:
420 """Vocab-parallel cross entropy on a local logits shard (local-first).
422 AutoModels production entry: the caller owns the sharding contract and
423 passes the local shard directly, so no temporary DTensor is created per
424 call. ``mesh``/``mesh_dim`` identify the single mesh axis that shards the
425 class dimension; see :func:`_resolve_class_mesh_dim`.
427 Args:
428 local_logits: Local class-sharded logits, ``[..., local_vocab_size]``.
429 Rank above 2 is flattened to ``[-1, local_vocab_size]`` together
430 with ``target``.
431 target: Class indices aligned with the leading dims of
432 ``local_logits``.
433 vocab_size: Global vocabulary size (across all shard ranks).
434 mesh: Mesh holding the class-sharding axis.
435 mesh_dim: Explicit class-sharding mesh axis; ``None`` resolves it
436 from the mesh (1D mesh → axis 0; otherwise the axis named "tp").
437 ignore_index: Target value excluded from the loss.
438 reduction: Reduction method: 'none', 'mean', or 'sum'.
440 Returns:
441 Loss tensor.
443 Raises:
444 ValueError: If the class-sharding mesh axis cannot be uniquely
445 identified, the target is probabilistic, or the reduction is
446 invalid.
447 """
448 mesh_dim = _resolve_class_mesh_dim(mesh, mesh_dim)
449 _validate_target_type_base(_is_floating_torch(target))
450 if reduction not in ("none", "mean", "sum"):
451 raise ValueError(f"Invalid reduction: {reduction}. Must be 'none', 'mean', or 'sum'.")
453 local_vocab_size = local_logits.shape[-1]
454 if local_logits.ndim > 2:
455 local_logits = local_logits.reshape(-1, local_vocab_size)
456 target = target.reshape(-1)
458 return DistributedCrossEntropyFunction.apply(
459 local_logits,
460 target,
461 None,
462 ignore_index,
463 reduction,
464 vocab_size,
465 mesh,
466 mesh_dim,
467 )
469def entropy_from_logits(logits: Tensor, *, mesh: DeviceMesh, chunk_size: Optional[int] = None) -> Tensor:
470 """Return FP32 per-token entropy; optionally process ``chunk_size`` tokens at a time.
472 With ``chunk_size=None`` (the default), process all tokens together.
473 """
474 if mesh.ndim != 1:
475 raise ValueError("Vocabulary-parallel entropy requires a one-dimensional vocabulary mesh")
476 if chunk_size is not None and chunk_size <= 0:
477 raise ValueError("chunk_size must be positive or None")
478 return _VocabParallelEntropy.apply(logits, mesh, chunk_size)
481class _VocabParallelEntropy(torch.autograd.Function):
482 """Compute shard-local entropy gradients with optional token chunking."""
484 @staticmethod
485 def forward(ctx: Any, logits: Tensor, mesh: "DeviceMesh", chunk_size: Optional[int]) -> Tensor:
486 """Sum vocabulary-local entropy contributions without gathering logits."""
487 flat = logits.reshape(-1, logits.shape[-1])
488 entropy = torch.empty(
489 flat.shape[0],
490 dtype=torch.float32,
491 device=logits.device,
492 )
493 needs_backward = ctx.needs_input_grad[0]
494 chunk_size = chunk_size if chunk_size is not None else max(flat.shape[0], 1)
495 for start in range(0, flat.shape[0], chunk_size):
496 values = flat[start : start + chunk_size].float()
497 local_log_probs = distributed_log_softmax(
498 values,
499 dim=-1,
500 mesh=mesh,
501 mesh_dim=0,
502 )
503 local_probabilities = local_log_probs.exp()
504 local_entropy = -(local_probabilities * local_log_probs).sum(dim=-1)
505 torch.distributed.all_reduce(local_entropy, group=mesh.get_group())
506 entropy[start : start + len(values)] = local_entropy
507 if needs_backward:
508 ctx.save_for_backward(logits, entropy)
509 ctx.mesh = mesh
510 ctx.chunk_size = chunk_size
511 return entropy.reshape(logits.shape[:-1])
513 @staticmethod
514 def backward(ctx: Any, grad_output: Tensor) -> Tuple[Tensor, None, None]:
515 """Recompute local probabilities and return the logits-shard gradient."""
516 logits, entropy = ctx.saved_tensors
517 flat = logits.reshape(-1, logits.shape[-1])
518 gradient = torch.empty_like(flat)
519 grad = grad_output.reshape(-1)
520 for start in range(0, flat.shape[0], ctx.chunk_size):
521 end = start + ctx.chunk_size
522 log_probs = distributed_log_softmax(
523 flat[start:end].float(),
524 dim=-1,
525 mesh=ctx.mesh,
526 mesh_dim=0,
527 )
528 local = -log_probs.exp() * (log_probs + entropy[start:end, None])
529 local.mul_(grad[start:end, None])
530 gradient[start:end].copy_(local)
531 return gradient.reshape(logits.shape), None, None