Coverage for / home / jenkins / .local / lib / python3.10 / site-packages / hyper_parallel / core / utils / clip_grad.py: 78%
468 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"""Distributed-aware gradient clipping for parallel training.
17Communication is driven by each parameter's DTensorSpec (device_mesh +
18placements) rather than any specific parallelism strategy, so a single
19implementation covers FSDP, HSDP, TP+FSDP, and other DTensor-expressed
20parallelisms.
22Collective safety aligned with FSDP1; numerical precision aligned with
23FSDP2's ``_NormPartial`` norm computation path:
25* Gradient norms from sharded parameters are all-reduced across the
26 corresponding shard process group.
27* Non-sharded / replicated norms contribute locally without communication.
28* **All ranks participate in the same collectives** regardless of local
29 gradient availability, preventing collective-misalignment deadlocks.
31The finite p-norm is bit-exact with upstream only for the pure-FSDP,
32single-dtype case; mixed sharded + replicated is mathematically correct
33but intentionally diverges (see ``_total_norm_fsdp2_aligned``).
35Note: PP does not use DTensor layout for gradients today. Cross-stage
36norm aggregation will require an additional manual all-reduce and is
37left for future work.
38"""
39# pylint: disable=not-callable
40import functools
41import math
42import warnings
43from collections import defaultdict, namedtuple
44from collections.abc import Mapping
45from dataclasses import dataclass
46from typing import TYPE_CHECKING, Any, Dict, Iterable, List, Optional, Tuple, Union
48import torch
49import torch.distributed as dist
51from hyper_parallel.core.dtensor.placement_types import Partial
52from hyper_parallel.core.utils import communication
54if TYPE_CHECKING:
55 from hyper_parallel.core.dtensor.layout import Layout
57try:
58 from torch.utils._foreach_utils import (
59 _device_has_foreach_support,
60 _group_tensors_by_device_and_dtype,
61 _has_foreach_support,
62 )
63except ImportError:
64 _device_has_foreach_support = None # type: ignore[assignment]
65 _group_tensors_by_device_and_dtype = None # type: ignore[assignment]
66 _has_foreach_support = None # type: ignore[assignment]
68__all__: list[str] = ["clip_grad_norm_"]
71@dataclass(frozen=True)
72class NormShardPlan:
73 """One norm contributor and its replica ranks for each dense parameter."""
75 representatives: dict[str, bool]
76 replica_ranks: dict[str, tuple[int, ...]]
79def _norm_coverage(param: torch.nn.Parameter) -> tuple[tuple[int, ...], tuple[tuple[int, int], ...]]:
80 """Describe the exact global rectangle represented by a local parameter."""
81 global_shape = tuple(param.shape)
82 layout = getattr(param, "layout", None) if _is_dtensor(param) else None
83 if layout is None:
84 area = tuple((0, size) for size in global_shape)
85 else:
86 from hyper_parallel.core.dtensor.layout import infer_slice_area_by_layout # pylint: disable=C0415
88 rank = dist.get_rank() if dist.is_initialized() else 0
89 if rank not in layout.rank_list:
90 raise ValueError("Norm layout does not contain the current global rank")
91 area = infer_slice_area_by_layout(
92 layout, layout.rank_list.index(rank), global_shape,
93 )
94 local = param._local_tensor if _is_dtensor(param) else param # pylint: disable=W0212
95 if tuple(end - start for start, end in area) != tuple(local.shape):
96 raise ValueError("Norm layout cannot describe the exact local parameter coverage")
97 return global_shape, tuple((int(start), int(end)) for start, end in area)
100def _norm_representative(fqn: str, shape: tuple[int, ...],
101 stage_data: dict[int, dict], rank: int,
102 local_area: tuple) -> tuple[bool, tuple[int, ...]]:
103 """Validate disjoint shard coverage and identify copies of this area."""
104 representatives = {}
105 for member, data in stage_data.items():
106 if data[fqn][0] != shape:
107 raise ValueError(f"Norm shard global shape mismatch: {fqn}")
108 area = data[fqn][1]
109 representatives.setdefault(area, []).append(member)
110 nonempty = [area for area in representatives if all(end > start for start, end in area)]
111 volume = sum(math.prod(end - start for start, end in area) for area in nonempty)
112 if volume != math.prod(shape):
113 raise ValueError(f"Norm shard coverage is incomplete or duplicated: {fqn}")
114 for index, left in enumerate(nonempty):
115 for right in nonempty[index + 1:]:
116 if all(max(a[0], b[0]) < min(a[1], b[1]) for a, b in zip(left, right)):
117 raise ValueError(f"Norm shard rectangles overlap: {fqn}")
118 copies = tuple(representatives[local_area])
119 return rank == min(copies), copies
122def build_norm_shard_plan(model: torch.nn.Module, excluded_params: Iterable[torch.nn.Parameter],
123 mesh_context: Any) -> NormShardPlan:
124 """Choose one rank per identical global shard and verify full coverage.
126 Args:
127 model: Model with final FSDP parameter layouts.
128 excluded_params: Parameters managed by an external optimizer.
129 mesh_context: Stage-local mesh and topology metadata.
130 """
131 excluded_ids = {id(param) for param in excluded_params}
132 local = {
133 fqn: _norm_coverage(param)
134 for fqn, param in model.named_parameters()
135 if param.requires_grad and id(param) not in excluded_ids
136 }
137 if dist.is_initialized():
138 gathered = [None] * dist.get_world_size()
139 dist.all_gather_object(gathered, local)
140 rank = dist.get_rank()
141 else:
142 gathered = [local]
143 rank = 0
144 mesh = getattr(mesh_context, "device_mesh", None)
145 stage_ranks = (tuple(mesh.rank_list) if mesh is not None and hasattr(mesh, "rank_list")
146 else tuple(range(len(gathered))))
147 stage_data = {member: gathered[member] for member in stage_ranks}
148 reference_names = set(local)
149 if any(set(data) != reference_names for data in stage_data.values()):
150 raise ValueError("Norm shard plan has different dense FQNs within one PP stage")
151 representatives = {}
152 replica_ranks = {}
153 for fqn in sorted(reference_names):
154 representatives[fqn], replica_ranks[fqn] = _norm_representative(
155 fqn, local[fqn][0], stage_data, rank, local[fqn][1],
156 )
157 return NormShardPlan(representatives, replica_ranks)
160def _effective_dense_grads(parameters: list[tuple[str, torch.nn.Parameter]]) -> tuple[list, dict]:
161 """Collect local gradients and reduce partial placements once."""
162 infos = []
163 mesh_cache = {}
164 for _, param in parameters:
165 mesh, shard_dims, partial_info = _get_param_mesh_info(param)
166 if mesh is not None:
167 mesh_cache[id(mesh)] = mesh
168 infos.append((param, _get_local_grad(param), mesh, partial_info,
169 (id(mesh) if mesh is not None else None, shard_dims)))
170 return infos, _coalesce_partial_reduce(infos, mesh_cache)
173def _check_dense_grad_presence(present: dict[str, bool], replica_ranks: dict[str, tuple[int, ...]]) -> None:
174 """Reject mismatched gradient presence on copies of the same shard."""
175 if not dist.is_initialized():
176 return
177 gathered = [None] * dist.get_world_size()
178 dist.all_gather_object(gathered, present)
179 for fqn, ranks in replica_ranks.items():
180 copies = [gathered[member][fqn] for member in ranks]
181 if any(value != copies[0] for value in copies[1:]):
182 raise ValueError(f"Norm shard gradient presence differs across replicas: {fqn}")
185def _norm_scalar_device(parameter_device: Optional[torch.device], mesh_context: Any) -> torch.device:
186 """Keep offloaded gradients on CPU while reducing scalar norms on the mesh device."""
187 mesh = getattr(mesh_context, "device_mesh", None)
188 mesh_type = getattr(mesh, "device_type", None)
189 if mesh_type is not None:
190 return torch.device(mesh_type)
191 return parameter_device if parameter_device is not None else torch.device("cpu")
194def dense_grad_norm_sq_and_refs(model: torch.nn.Module,
195 excluded_params: Iterable[torch.nn.Parameter],
196 norm_shard_plan: NormShardPlan,
197 mesh_context: Any) -> tuple[torch.Tensor, list[torch.Tensor]]:
198 """Sum each dense global shard once and return mutable effective gradients.
200 Args:
201 model: Model with final FSDP parameter layouts.
202 excluded_params: Parameters managed by an external optimizer.
203 norm_shard_plan: Validated coverage and one representative per shard.
204 mesh_context: Stage-local mesh and topology metadata.
205 """
206 excluded_ids = {id(param) for param in excluded_params}
207 parameters = [
208 (fqn, param) for fqn, param in model.named_parameters()
209 if param.requires_grad and id(param) not in excluded_ids
210 ]
211 device = next(((_param_device(param)) for _, param in parameters), None)
212 device = _norm_scalar_device(device, mesh_context)
213 infos, reduced = _effective_dense_grads(parameters)
214 refs = []
215 local_sq = torch.zeros((), device=device, dtype=torch.float32)
216 present = {}
217 for index, (fqn, _) in enumerate(parameters):
218 grad = infos[index][1]
219 present[fqn] = grad is not None
220 if grad is None:
221 continue
222 refs.append(grad)
223 if norm_shard_plan.representatives[fqn]:
224 view = reduced.get(index, grad)
225 local_sq.add_(view.float().square().sum().to(device))
226 _check_dense_grad_presence(present, norm_shard_plan.replica_ranks)
227 for name in getattr(getattr(mesh_context, "device_mesh", None), "mesh_dim_names", ()) or ():
228 axis = mesh_context.device_mesh[name]
229 if axis.size() > 1:
230 local_sq = _all_reduce_offloaded(local_sq, dist.ReduceOp.SUM, axis.get_group())
231 return local_sq, refs
234def scale_grad_refs_(refs: Iterable[torch.Tensor], coefficient: torch.Tensor) -> None:
235 """Scale the exact dense gradients that the optimizer will consume.
237 Args:
238 refs: Mutable dense effective gradients.
239 coefficient: Shared clipping coefficient.
240 """
241 coefficients = {}
242 for grad in refs:
243 if grad.device not in coefficients:
244 coefficients[grad.device] = coefficient.to(grad.device)
245 grad.mul_(coefficients[grad.device])
248# (id(mesh) or None, shard_dims) -> list of local grads for norm computation
249_GradGroupKey = Tuple[Optional[int], Tuple[int, ...]]
251# (mesh_dim_index, dist.ReduceOp, needs_manual_avg)
252_PartialReduceInfo = Tuple[int, "dist.ReduceOp", bool]
254# Result of _build_grad_groups; tuple-unpacking compatible with prior 7-tuple.
255_GradGroups = namedtuple(
256 "_GradGroups",
257 "grad_groups all_grads norm_grads key_per_grad mesh_cache device "
258 "has_dtensor_grad",
259)
262def _is_dtensor(value: object) -> bool:
263 """Return whether *value* is a HyperParallel DTensor.
265 The DTensor module imports ``core.utils`` during initialization, so keep
266 this import lazy to avoid a package initialization cycle.
267 """
268 from hyper_parallel.core.dtensor.dtensor import DTensor # pylint: disable=C0415
270 return isinstance(value, DTensor)
273# ---------------------------------------------------------------------------
274# Reduce-op mapping
275# ---------------------------------------------------------------------------
277_REDUCE_OP_AVG_SUPPORTED = hasattr(dist.ReduceOp, "AVG")
279_STR_TO_REDUCE_OP: Dict[str, "dist.ReduceOp"] = {
280 "sum": dist.ReduceOp.SUM,
281 "max": dist.ReduceOp.MAX,
282 "min": dist.ReduceOp.MIN,
283}
284if _REDUCE_OP_AVG_SUPPORTED:
285 _STR_TO_REDUCE_OP["avg"] = dist.ReduceOp.AVG
288def _str_to_reduce_op(op_str: str) -> Tuple["dist.ReduceOp", bool]:
289 """Map a ``Partial`` placement's *reduce_op* string to ``dist.ReduceOp``.
291 Returns ``(reduce_op, needs_manual_avg)`` where *needs_manual_avg*
292 is ``True`` when ``"avg"`` is requested but the backend does not
293 support ``dist.ReduceOp.AVG`` — the caller should use SUM and
294 manually divide by the group size.
295 """
296 lower = op_str.lower()
297 if lower == "avg" and not _REDUCE_OP_AVG_SUPPORTED:
298 return dist.ReduceOp.SUM, True
299 op = _STR_TO_REDUCE_OP.get(lower)
300 if op is None:
301 raise ValueError(
302 f"Unsupported Partial reduce_op: {op_str!r}. "
303 f"Supported: {sorted(set(list(_STR_TO_REDUCE_OP) + ['avg']))}"
304 )
305 return op, False
308# ---------------------------------------------------------------------------
309# Helpers
310# ---------------------------------------------------------------------------
312def _normalize_parameters(
313 parameters: Union["torch.nn.Module", torch.Tensor, Iterable[torch.Tensor]],
314) -> List[torch.Tensor]:
315 """Normalize *parameters* to a flat list of tensors.
317 * ``torch.nn.Module`` -> ``list(module.parameters())``
318 * single ``torch.Tensor`` -> ``[tensor]``
319 * iterable of tensors -> ``list(iterable)``
320 """
321 if isinstance(parameters, torch.nn.Module):
322 return list(parameters.parameters())
323 if isinstance(parameters, torch.Tensor):
324 return [parameters]
325 return list(parameters)
328def _param_device(param: torch.Tensor) -> torch.device:
329 """Return the local device of *param* (unwrap DTensor if needed)."""
330 if _is_dtensor(param):
331 return param._local_tensor.device # pylint: disable=protected-access
332 return param.device
335def _all_reduce_offloaded(
336 tensor: torch.Tensor, op: dist.ReduceOp, group: object,
337) -> torch.Tensor:
338 """Reduce CPU-offloaded values on the backend's communication device."""
339 original_device = tensor.device
340 if original_device.type == "cpu":
341 try:
342 backend = dist.get_backend(group)
343 except (ValueError, RuntimeError):
344 # Test doubles answer every device; reduce in place.
345 backend = None
346 device_type = communication.comm_device_type(backend)
347 if device_type is not None:
348 device_module = torch.get_device_module(device_type)
349 tensor = tensor.to(torch.device(device_type, device_module.current_device()))
350 dist.all_reduce(tensor, op=op, group=group)
351 return tensor.to(original_device)
354def _get_grad_obj(param: torch.nn.Parameter) -> Optional[torch.Tensor]:
355 """Return the gradient object for *param*.
357 Checks ``param.main_grad`` first (used when
358 ``MixedPrecisionPolicy.apply_grad_on_fp32_main_grad=True``),
359 falling back to ``param.grad``.
360 """
361 grad = getattr(param, "main_grad", None)
362 if grad is not None:
363 return grad
364 return param.grad
367def _get_local_grad(param: torch.nn.Parameter) -> Optional[torch.Tensor]:
368 """Return the local gradient tensor, or ``None`` if absent.
370 Supports ``main_grad`` for fp32 mixed-precision training.
371 """
372 if not param.requires_grad:
373 return None
374 grad = _get_grad_obj(param)
375 if grad is None:
376 return None
377 if _is_dtensor(grad):
378 return grad._local_tensor # pylint: disable=protected-access
379 return grad
382def _get_param_mesh_info(
383 param: torch.nn.Parameter,
384 parameter_layout: Optional["Layout"] = None,
385) -> Tuple[
386 Optional[object],
387 Tuple[int, ...],
388 Tuple[_PartialReduceInfo, ...],
389]:
390 """Derive DeviceMesh, Shard dims and Partial info from DTensorSpec.
392 Checks the *gradient's* spec first; falls back to the *parameter's*
393 spec when the gradient is a plain tensor on a DTensor parameter
394 (common after FSDP/HSDP backward where ``param.grad`` is stored as
395 the local shard tensor).
397 Returns ``(mesh, shard_dims, partial_info)`` where *partial_info*
398 is a tuple of ``(mesh_dim, dist.ReduceOp, needs_manual_avg)``
399 triples that respect the ``Partial`` placement's ``reduce_op``
400 attribute. *needs_manual_avg* is ``True`` when ``"avg"`` was
401 requested but the backend lacks ``dist.ReduceOp.AVG`` support.
402 """
403 grad = _get_grad_obj(param)
404 # Prefer grad's spec (most accurate); fall back to param's.
405 spec_source = grad if _is_dtensor(grad) else param
406 if parameter_layout is None:
407 if not _is_dtensor(spec_source):
408 return None, (), ()
409 placements = spec_source.placements
410 mesh = spec_source.device_mesh
411 else:
412 layout = spec_source.layout if _is_dtensor(spec_source) else None
413 if layout is not None and (
414 layout.mesh_shape, layout.rank_list, layout.alias_name, layout.placements, layout.tensor_shape
415 ) != (
416 parameter_layout.mesh_shape, parameter_layout.rank_list, parameter_layout.alias_name,
417 parameter_layout.placements, parameter_layout.tensor_shape
418 ):
419 raise ValueError("Explicit parameter layout conflicts with its DTensor layout")
420 layout = layout if layout is not None else parameter_layout
421 placements = layout.placements
422 mesh = layout.mesh
424 shard_dims = tuple(
425 i for i, p in enumerate(placements)
426 if p.is_shard()
427 )
428 partial_info = tuple(
429 (i, *_str_to_reduce_op(p.reduce_op))
430 for i, p in enumerate(placements)
431 if isinstance(p, Partial)
432 )
433 return mesh, shard_dims, partial_info
436def _sum_p_norms(
437 dev_grads: List[torch.Tensor],
438 norm_type: float,
439 device: torch.device,
440 total: torch.Tensor,
441) -> None:
442 """Accumulate sum-of-p-th-powers for *dev_grads* into *total*."""
443 for g in dev_grads:
444 n = torch.linalg.vector_norm(g, norm_type)
445 total.add_(n.to(device=device) ** norm_type)
448def _foreach_p_norms(
449 grads: List[torch.Tensor],
450 norm_type: float,
451 device: torch.device,
452) -> torch.Tensor:
453 """Fast path: fuse per-tensor norms via ``_foreach_norm``.
455 Restricted to float32 tensors to preserve the same numerical
456 precision as ``vector_norm(dtype=float32)``. Non-float32 tensors
457 and backends that raise ``RuntimeError`` fall back to per-tensor
458 ``vector_norm``.
459 """
460 total = torch.tensor(0.0, device=device, dtype=torch.float32)
461 grouped = _group_tensors_by_device_and_dtype(
462 [[g.detach() for g in grads]],
463 )
464 for (dev, _), ([dev_grads], _) in grouped.items():
465 if (
466 dev_grads[0].dtype == torch.float32
467 and _has_foreach_support(dev_grads, dev)
468 ):
469 try:
470 per_norms = torch._foreach_norm( # pylint: disable=W0212
471 dev_grads, norm_type,
472 )
473 except RuntimeError:
474 per_norms = None
475 if per_norms is not None:
476 total.add_(
477 torch.stack([
478 n.to(device=device) ** norm_type
479 for n in per_norms
480 ]).sum(),
481 )
482 else:
483 _sum_p_norms(dev_grads, norm_type, device, total)
484 else:
485 _sum_p_norms(dev_grads, norm_type, device, total)
486 return total
489def _per_tensor_norms(
490 grads: List[torch.Tensor],
491 norm_type: float,
492 device: torch.device,
493) -> List[torch.Tensor]:
494 """Return per-tensor norms as a list of scalar tensors on *device*."""
495 if not grads:
496 return []
498 if _group_tensors_by_device_and_dtype is None or not hasattr(torch, "_foreach_norm"):
499 return [
500 torch.linalg.vector_norm(g.detach(), norm_type).to(device=device)
501 for g in grads
502 ]
504 norms: List[torch.Tensor] = []
505 grouped = _group_tensors_by_device_and_dtype(
506 [[g.detach() for g in grads]],
507 )
508 for (dev, _), ([dev_grads], _) in grouped.items():
509 if dev_grads and _has_foreach_support(dev_grads, dev):
510 try:
511 per_norms = torch._foreach_norm( # pylint: disable=W0212
512 dev_grads, norm_type,
513 )
514 except RuntimeError:
515 per_norms = None
516 if per_norms is not None:
517 norms.extend(
518 [n.to(device=device) for n in per_norms],
519 )
520 continue
521 norms.extend([
522 torch.linalg.vector_norm(g, norm_type).to(device=device)
523 for g in dev_grads
524 ])
525 return norms
528def _compute_local_norm( # pylint: disable=R0911
529 grads: List[torch.Tensor],
530 norm_type: float,
531 device: torch.device,
532) -> torch.Tensor:
533 """Compute the combined norm of *grads* locally in FP32.
535 When *grads* is empty, returns the **identity element** for the
536 subsequent all-reduce so that this rank contributes a neutral value
537 (aligned with FSDP1's ``_zero_scalar`` approach):
539 * ``inf`` -> 0 (neutral for MAX; norms are non-negative)
540 * ``-inf`` -> +inf (neutral for MIN)
541 * ``0`` -> 0 (neutral for SUM)
542 * finite -> 0 (neutral for SUM)
543 """
544 if not grads:
545 if norm_type == -math.inf:
546 return torch.tensor(
547 float("inf"), device=device, dtype=torch.float32,
548 )
549 return torch.tensor(0.0, device=device, dtype=torch.float32)
551 if norm_type == math.inf:
552 norms = [
553 torch.linalg.vector_norm(g.detach(), math.inf)
554 for g in grads
555 ]
556 return torch.stack(norms).max().to(device)
558 if norm_type == -math.inf:
559 norms = [
560 torch.linalg.vector_norm(g.detach(), -math.inf)
561 for g in grads
562 ]
563 return torch.stack(norms).min().to(device)
565 if norm_type == 0:
566 norms = [
567 torch.linalg.vector_norm(g.detach(), 0)
568 for g in grads
569 ]
570 return torch.stack(norms).sum().to(device)
572 # Finite p-norm: return sum of p-th powers.
573 if (
574 len(grads) > 1
575 and _group_tensors_by_device_and_dtype is not None
576 and hasattr(torch, "_foreach_norm")
577 ):
578 return _foreach_p_norms(grads, norm_type, device)
580 # Scalar fallback when foreach utilities are unavailable.
581 norms = [
582 torch.linalg.vector_norm(g.detach(), norm_type)
583 for g in grads
584 ]
585 norm_powers = [n.to(device=device) ** norm_type for n in norms]
586 return torch.stack(norm_powers).sum()
589# ---------------------------------------------------------------------------
590# Total norm aggregation with collectives
591# ---------------------------------------------------------------------------
593def _get_total_norm(
594 grad_groups: Dict[_GradGroupKey, List[torch.Tensor]],
595 norm_type: float,
596 mesh_cache: Dict[int, object],
597 device: torch.device,
598 norm_grads: List[torch.Tensor],
599 key_per_grad: List[_GradGroupKey],
600) -> torch.Tensor:
601 """Compute total gradient norm with per-group all-reduce.
603 ``norm_grads`` (parallel to ``key_per_grad``) holds the tensor whose
604 norm to take per parameter; only the finite p-norm path consumes it.
605 """
606 if norm_type == math.inf:
607 return _total_norm_inf(
608 grad_groups, norm_type, mesh_cache, device,
609 dist.ReduceOp.MAX,
610 )
612 if norm_type == -math.inf:
613 return _total_norm_inf(
614 grad_groups, norm_type, mesh_cache, device,
615 dist.ReduceOp.MIN,
616 )
618 if norm_type == 0:
619 return _total_norm_sum(
620 grad_groups, norm_type, mesh_cache, device,
621 )
623 # Finite p-norm: FSDP2-aligned sequence.
624 total_p = _total_norm_fsdp2_aligned(
625 grad_groups, norm_type, mesh_cache, device,
626 norm_grads, key_per_grad,
627 )
628 return total_p ** (1.0 / norm_type)
631def _total_norm_inf( # pylint: disable=R0913,R0917
632 grad_groups, norm_type, mesh_cache, device, reduce_op,
633):
634 """Shared logic for inf / -inf norms."""
635 group_norms: List[torch.Tensor] = []
636 for (mesh_id, shard_dims), grads in grad_groups.items():
637 local_norm = _compute_local_norm(grads, norm_type, device)
638 if mesh_id is not None:
639 mesh = mesh_cache[mesh_id]
640 for dim in shard_dims:
641 local_norm = _all_reduce_offloaded(local_norm, reduce_op, mesh.get_group(dim))
642 group_norms.append(local_norm)
643 if not group_norms:
644 if norm_type == -math.inf:
645 return torch.tensor(float("inf"), device=device)
646 return torch.tensor(0.0, device=device)
647 stacked = torch.stack(group_norms)
648 return stacked.max() if reduce_op == dist.ReduceOp.MAX else stacked.min()
651def _total_norm_sum(grad_groups, norm_type, mesh_cache, device):
652 """Shared logic for finite norms and L0 (all use SUM all-reduce)."""
653 total = torch.tensor(0.0, device=device)
654 for (mesh_id, shard_dims), grads in grad_groups.items():
655 local_val = _compute_local_norm(grads, norm_type, device)
656 if mesh_id is not None:
657 mesh = mesh_cache[mesh_id]
658 for dim in shard_dims:
659 local_val = _all_reduce_offloaded(local_val, dist.ReduceOp.SUM, mesh.get_group(dim))
660 total.add_(local_val)
661 return total
664def _reduction_signature(grad_groups, mesh_cache):
665 """Bucket grad-group keys by the *process group(s)* they reduce over.
667 Two keys that reduce over the same set of process groups (same global
668 ranks per shard dim) must be **pooled** so their norms accumulate in
669 one stack -- matching FSDP2's single foreach-norm + single reduce and
670 keeping the loss bit-exact even when params live on several distinct
671 ``DeviceMesh`` objects that share the same DP process group (common
672 for multi-component models). Keys that reduce over *different*
673 process groups (TP+FSDP heterogeneous sharding, expert parallel) get
674 separate buckets, each reduced over its own group.
676 Returns ``(key_to_sig, sig_groups, sig_order)``:
678 * ``key_to_sig`` -- ``key -> signature`` (hashable; ``()`` = replicate
679 / no communication).
680 * ``sig_groups`` -- ``signature -> list[ProcessGroup]`` to all-reduce.
681 * ``sig_order`` -- signatures in first-seen (parameter) order, so all
682 ranks issue the same collectives in the same order.
683 """
684 key_to_sig: Dict[_GradGroupKey, Tuple] = {}
685 sig_groups: Dict[Tuple, List[object]] = {}
686 sig_order: List[Tuple] = []
687 for mesh_id, shard_dims in grad_groups:
688 if shard_dims and mesh_id is not None:
689 mesh = mesh_cache[mesh_id]
690 groups = [mesh.get_group(dim) for dim in shard_dims]
691 sig = tuple(
692 tuple(dist.get_process_group_ranks(group)) for group in groups
693 )
694 else:
695 groups = []
696 sig = ()
697 key_to_sig[(mesh_id, shard_dims)] = sig
698 if sig not in sig_groups:
699 sig_groups[sig] = groups
700 sig_order.append(sig)
701 return key_to_sig, sig_groups, sig_order
704def _total_norm_fsdp2_aligned(grad_groups, norm_type, mesh_cache, device,
705 norm_grads, key_per_grad):
706 """FSDP2-aligned norm for finite p-norms.
708 Grads are bucketed by the *process group* they reduce over (see
709 :func:`_reduction_signature`); ``norm_grads`` supplies, in global
710 parameter order, the Partial-reduced (already-global) view for Partial
711 grads and the raw local grad otherwise. Each bucket does ONE ``stack``
712 → ONE ``vector_norm`` → ``^p`` → ONE ``all_reduce SUM`` per shard dim,
713 and the buckets are summed locally.
715 Reduction rules:
717 * Sharded bucket -- reduce over its own group(s). Same-group params
718 across distinct ``DeviceMesh`` objects pool into one reduce; distinct
719 groups (TP+FSDP heterogeneous, expert parallel) stay separate -- the
720 per-group convention also used by :func:`_total_norm_inf` /
721 :func:`_total_norm_sum` and by VeOmni / torchtitan.
722 * Replicate bucket (signature ``()``) -- contribute norm² locally with
723 NO communication; reducing it over the shard group would over-count
724 it ``shard_world_size`` times (the FSDP1 convention).
726 Empty-but-present buckets still issue their all_reduce (identity ``0``
727 for SUM) so all ranks run the same collectives.
729 Bit-exact with upstream ``torch.nn.utils.clip_grad_norm_`` only for the
730 pure-FSDP, single-bucket, single-dtype case. Mixed shard + replicate is
731 mathematically correct but intentionally diverges (upstream folds the
732 replicate norm into one ``_NormPartial`` reduce and over-counts it);
733 mixed-dtype follows upstream's :func:`_per_tensor_norms` device/dtype
734 regrouping rather than strict global order.
736 Returns the global sum of p-th powers (caller takes p-th root).
737 """
738 key_to_sig, sig_groups, sig_order = _reduction_signature(
739 grad_groups, mesh_cache,
740 )
742 # Bucket norms by reduction signature, preserving global parameter order.
743 sig_grads: Dict[Tuple, List[torch.Tensor]] = {sig: [] for sig in sig_order}
744 for grad, key in zip(norm_grads, key_per_grad):
745 sig_grads[key_to_sig[key]].append(grad)
747 total_p = torch.tensor(0.0, device=device, dtype=torch.float32)
748 for sig in sig_order:
749 grads = sig_grads[sig]
750 if grads:
751 norms = _per_tensor_norms(grads, norm_type, device)
752 local_p = torch.linalg.vector_norm(
753 torch.stack(norms).to(torch.float32), norm_type,
754 ) ** norm_type
755 else:
756 local_p = torch.tensor(0.0, device=device, dtype=torch.float32)
758 for group in sig_groups[sig]:
759 local_p = _all_reduce_offloaded(local_p, dist.ReduceOp.SUM, group)
761 total_p = total_p + local_p
763 return total_p
766def _build_coalesce_buffer(
767 param_infos: List[Tuple],
768 indices: List[int],
769) -> Tuple[List[torch.Tensor], List[int], List[bool], List[int]]:
770 """Build flat fp32 chunks for one coalesce group.
772 Returns ``(chunks, chunk_sizes, has_grad, active_indices)``.
773 Frozen params are skipped; trainable grad-free params contribute
774 zeros so the collective matches ranks that have a grad.
775 """
776 chunks: List[torch.Tensor] = []
777 chunk_sizes: List[int] = []
778 has_grad: List[bool] = []
779 active_indices: List[int] = []
781 for idx in indices:
782 param = param_infos[idx][0]
783 local_grad = param_infos[idx][1]
784 if local_grad is not None:
785 chunks.append(
786 local_grad.detach().reshape(-1).to(torch.float32),
787 )
788 chunk_sizes.append(local_grad.numel())
789 has_grad.append(True)
790 active_indices.append(idx)
791 elif param.requires_grad:
792 local_p = (
793 param._local_tensor # pylint: disable=W0212
794 if _is_dtensor(param) else param.data
795 )
796 numel = local_p.numel()
797 chunks.append(
798 torch.zeros(
799 numel, device=local_p.device,
800 dtype=torch.float32,
801 ),
802 )
803 chunk_sizes.append(numel)
804 has_grad.append(False)
805 active_indices.append(idx)
807 return chunks, chunk_sizes, has_grad, active_indices
810def _coalesce_partial_reduce( # pylint: disable=R0914
811 param_infos: List[Tuple],
812 mesh_cache: Dict[int, object],
813) -> Dict[int, torch.Tensor]:
814 """Coalesce Partial all-reduces: O(N) collectives → O(G).
816 Groups parameters sharing the same ``(mesh, partial_info)`` and
817 flattens their gradients (or zeros for trainable grad-free params)
818 into a single fp32 buffer. **One** ``all_reduce`` per buffer
819 replaces the previous per-parameter collective calls.
821 For TP+FSDP (all params share the same mesh / placements), this
822 turns ~200 individual all-reduces into 1 — saving 10-20 ms per
823 training step at typical HCCS/NCCL latencies.
825 Frozen params (``requires_grad=False``) are consistently grad-free
826 across all ranks and are excluded from the buffer to avoid wasting
827 bandwidth.
829 All buffers use float32 to guarantee dtype consistency across ranks
830 in mixed-precision training (grad may be fp16/bf16 while param is
831 fp32).
833 Returns a dict mapping *param_infos* index → reduced gradient view
834 (1-D fp32 slice of the coalesced buffer). Only entries for params
835 with actual gradients are included.
836 """
837 # Group by Partial coalesce key: (mesh_id, partial_info)
838 coalesce_groups: Dict[
839 Tuple, List[int],
840 ] = defaultdict(list)
841 for idx, info in enumerate(param_infos):
842 mesh, partial_info = info[2], info[3]
843 if partial_info:
844 if mesh is None:
845 raise RuntimeError(
846 "clip_grad_norm_: parameter has Partial placements "
847 "but no DeviceMesh. This is a DTensor invariant "
848 "violation."
849 )
850 pck = (id(mesh), partial_info)
851 coalesce_groups[pck].append(idx)
853 reduced: Dict[int, torch.Tensor] = {}
855 for (mesh_id, partial_info), indices in coalesce_groups.items():
856 mesh = mesh_cache[mesh_id]
857 chunks, chunk_sizes, has_grad, active_indices = (
858 _build_coalesce_buffer(param_infos, indices)
859 )
861 if not chunks:
862 continue # all params frozen, no collective needed
864 # Sanity check: same mesh → same device. Fail fast on
865 # misconfigured inputs rather than silent NCCL errors.
866 buf_device = chunks[0].device
867 for chunk in chunks[1:]:
868 if chunk.device != buf_device:
869 raise RuntimeError(
870 f"clip_grad_norm_: parameters in the same Partial "
871 f"coalesce group are on different devices "
872 f"({buf_device} vs {chunk.device}). All parameters "
873 f"sharing the same DeviceMesh must reside on the "
874 f"same local device."
875 )
877 buf = torch.cat(chunks)
879 for pdim, reduce_op, needs_avg in partial_info:
880 group = mesh.get_group(pdim)
881 buf = _all_reduce_offloaded(buf, reduce_op, group)
882 if needs_avg:
883 buf /= dist.get_world_size(group=group)
885 # Extract views for params with actual gradients.
886 offset = 0
887 for i, idx in enumerate(active_indices):
888 numel = chunk_sizes[i]
889 if has_grad[i]:
890 reduced[idx] = buf[offset:offset + numel]
891 offset += numel
893 return reduced
896def _build_grad_groups( # pylint: disable=R0914
897 params: List[torch.Tensor],
898 parameter_layouts: Optional[Mapping[torch.nn.Parameter, "Layout"]] = None,
899) -> Tuple[
900 Dict[_GradGroupKey, List[torch.Tensor]],
901 List[torch.Tensor],
902 List[torch.Tensor],
903 List[_GradGroupKey],
904 Dict[int, object],
905 torch.device,
906 bool,
907]:
908 """Classify parameters into grad groups and pre-reduce Partial grads.
910 Group structure is derived from *parameter* DTensorSpecs (always
911 present on every rank) rather than gradients (which may be ``None``
912 on some ranks). This ensures every rank enters the same set of
913 collectives, preventing deadlocks (aligned with FSDP1 where all
914 ranks unconditionally execute the same all-reduce path).
916 Partial gradients are reduced via a **coalesced** all-reduce
917 (see ``_coalesce_partial_reduce``), turning O(N) per-parameter
918 collectives into O(G) where G is the number of distinct
919 ``(mesh, partial_info)`` groups (typically 1 for TP+FSDP).
921 Returns
922 ``(grad_groups, all_grads, norm_grads, key_per_grad, mesh_cache,
923 device, has_dtensor_grad)``. ``grad_groups`` maps each
924 ``(mesh_id, shard_dims)`` key to its grads; ``all_grads`` is the
925 flat list of raw local grads (global parameter order) scaled
926 in-place by the clip step; ``norm_grads`` is parallel to
927 ``all_grads`` but holds the Partial-reduced view for Partial grads
928 (the value whose norm is taken on the finite-p path);
929 ``key_per_grad`` is parallel to both and maps each grad back to its
930 group key.
931 """
932 # --- Phase 1: classify all parameters ---
933 param_infos: List[Tuple] = []
934 mesh_cache: Dict[int, object] = {}
935 device: Optional[torch.device] = None
937 for param in params:
938 if parameter_layouts is None:
939 mesh, shard_dims, partial_info = _get_param_mesh_info(param)
940 else:
941 layout = parameter_layouts.get(param)
942 if layout is None and not _is_dtensor(param) and not _is_dtensor(_get_grad_obj(param)):
943 raise ValueError("Explicit layouts must cover every local parameter participating in clipping")
944 mesh, shard_dims, partial_info = _get_param_mesh_info(param, layout)
945 key: _GradGroupKey = (
946 id(mesh) if mesh is not None else None, shard_dims,
947 )
948 if mesh is not None:
949 mesh_cache[id(mesh)] = mesh
950 if device is None:
951 device = _param_device(param)
952 local_grad = _get_local_grad(param)
953 param_infos.append(
954 (param, local_grad, mesh, partial_info, key),
955 )
957 if device is None:
958 device = torch.device("cpu")
960 # --- Phase 2: coalesced Partial reduction (O(N) → O(G)) ---
961 reduced = _coalesce_partial_reduce(param_infos, mesh_cache)
963 # --- Phase 3: build grad_groups ---
964 grad_groups: Dict[_GradGroupKey, List[torch.Tensor]] = defaultdict(
965 list,
966 )
967 all_grads: List[torch.Tensor] = []
968 # norm_grads / key_per_grad are parallel to all_grads (see Returns): the
969 # norm-input view (Partial-reduced where coalesced, else raw local) and
970 # the group key per grad, kept in global parameter order.
971 norm_grads: List[torch.Tensor] = []
972 key_per_grad: List[_GradGroupKey] = []
973 has_dtensor_grad = False
975 for idx, info in enumerate(param_infos):
976 param, local_grad, key = info[0], info[1], info[4]
977 if local_grad is None:
978 # Ensure the key exists so the Shard norm all-reduce is
979 # entered even when this rank has no grads for the group.
980 if key not in grad_groups:
981 grad_groups[key] = []
982 continue
984 grad_obj = _get_grad_obj(param)
985 if _is_dtensor(grad_obj):
986 has_dtensor_grad = True
987 all_grads.append(local_grad)
988 key_per_grad.append(key)
989 if idx in reduced:
990 grad_groups[key].append(reduced[idx])
991 norm_grads.append(reduced[idx])
992 else:
993 grad_groups[key].append(local_grad)
994 norm_grads.append(local_grad)
996 return _GradGroups(
997 grad_groups, all_grads, norm_grads, key_per_grad,
998 mesh_cache, device, has_dtensor_grad,
999 )
1002def _clip_grads_with_norm_(
1003 all_grads: List[torch.Tensor],
1004 max_norm: float,
1005 total_norm: torch.Tensor,
1006 foreach: Optional[bool] = None,
1007) -> None:
1008 """Scale gradients in-place so the total norm <= *max_norm*."""
1009 clip_coef = max_norm / (total_norm + 1e-6)
1010 clip_coef_clamped = torch.clamp(clip_coef, max=1.0)
1012 if _group_tensors_by_device_and_dtype is not None:
1013 grouped_grads = _group_tensors_by_device_and_dtype(
1014 [all_grads],
1015 )
1016 for (device, dtype), ([device_grads], _) in grouped_grads.items():
1017 use_foreach = (
1018 foreach is None and _has_foreach_support(device_grads, device)
1019 ) or (foreach and _device_has_foreach_support(device))
1020 if use_foreach:
1021 torch._foreach_mul_( # pylint: disable=W0212
1022 device_grads,
1023 clip_coef_clamped.to(device=device, dtype=dtype),
1024 )
1025 elif foreach:
1026 raise RuntimeError(
1027 f"foreach=True was passed, but can't use the "
1028 f"foreach API on {device.type} tensors"
1029 )
1030 else:
1031 clip_coef_clamped_cast = clip_coef_clamped.to(device=device, dtype=dtype)
1032 for g in device_grads:
1033 g.mul_(clip_coef_clamped_cast)
1034 else:
1035 # Fallback when _foreach_utils is unavailable.
1036 if foreach:
1037 raise RuntimeError(
1038 "foreach=True was passed, but "
1039 "torch.utils._foreach_utils is not available"
1040 )
1041 for grad in all_grads:
1042 grad.mul_(clip_coef_clamped.to(grad.device, grad.dtype))
1045def _reduce_pipeline_norm(norm: torch.Tensor, norm_type: float, group: object) -> torch.Tensor:
1046 """Combine norms of disjoint stages on the group's communication device."""
1047 if math.isinf(norm_type):
1048 op = dist.ReduceOp.MAX if norm_type > 0 else dist.ReduceOp.MIN
1049 return _all_reduce_offloaded(norm, op, group)
1050 if norm_type == 0:
1051 return _all_reduce_offloaded(norm, dist.ReduceOp.SUM, group)
1052 power_sum = _all_reduce_offloaded(norm.pow(norm_type), dist.ReduceOp.SUM, group)
1053 return power_sum.pow(1.0 / norm_type)
1056def _check_finite_norm(total_norm: torch.Tensor, norm_type: float) -> None:
1057 """Reject a non-finite global norm before using it to scale gradients."""
1058 if torch.logical_or(total_norm.isnan(), total_norm.isinf()):
1059 raise RuntimeError(
1060 f"The total norm of order {norm_type} for gradients from "
1061 "`parameters` is non-finite, so it cannot be clipped. To "
1062 "disable this error and scale the gradients by the "
1063 "non-finite norm anyway, set "
1064 "`error_if_nonfinite=False`"
1065 )
1068# ---------------------------------------------------------------------------
1069# Public API
1070# ---------------------------------------------------------------------------
1072@torch.no_grad()
1073def clip_grad_norm_(
1074 parameters: Union[
1075 "torch.nn.Module", torch.Tensor, Iterable[torch.Tensor],
1076 ],
1077 max_norm: float,
1078 norm_type: float = 2.0,
1079 error_if_nonfinite: bool = False,
1080 foreach: Optional[bool] = None,
1081 *,
1082 parameter_layouts: Optional[Mapping[torch.nn.Parameter, "Layout"]] = None,
1083 pp_group: Optional[Any] = None,
1084) -> torch.Tensor:
1085 """Compute and clip gradient norm for distributed models.
1087 Drop-in replacement for the standard ``clip_grad_norm_`` that
1088 correctly handles DTensor-sharded parameters by deriving
1089 communication from each parameter's DTensorSpec.
1091 .. warning:: This function uses collective communications. It
1092 **must be called on all ranks** to avoid deadlocks. Aligned
1093 with FSDP1: every rank participates in the same collectives
1094 regardless of local gradient availability.
1096 Communication is derived from each parameter's DTensorSpec:
1098 * ``Shard`` on mesh dim *d* -- all-reduce norm statistics
1099 across ``device_mesh.get_group(d)``
1100 * ``Partial`` on mesh dim *d* -- all-reduce gradient values
1101 using the placement's ``reduce_op`` before norm computation
1102 * ``Replicate`` / plain tensor -- no communication
1104 This covers FSDP, HSDP, TP+FSDP, and combinations expressible via DTensor
1105 placements. An explicit PP group adds disjoint stages before clipping.
1107 Args:
1108 parameters: An ``nn.Module``, a single ``Tensor``, or an
1109 iterable of ``Tensor`` s whose gradients to clip.
1110 max_norm: Maximum allowed gradient norm.
1111 norm_type: Type of the norm (default ``2.0``).
1112 error_if_nonfinite: If ``True``, raise a ``RuntimeError``
1113 when the total norm is non-finite. Default ``False``.
1114 foreach: Use the faster foreach-based implementation for the
1115 gradient clipping step. If ``None``, use the foreach
1116 implementation for devices that support it and silently
1117 fall back to the per-tensor implementation for others.
1118 Default ``None``.
1119 parameter_layouts: Optional parameter-identity mapping to final HyperParallel
1120 Layouts for local tensors. DTensor gradient/parameter layouts take
1121 precedence and must agree with explicit metadata. Local trainable
1122 parameters must be fully covered; frozen parameters are ignored.
1123 pp_group: Process group joining corresponding ranks in disjoint stages.
1125 Returns:
1126 The total (unclipped) gradient norm as a scalar tensor,
1127 cast to the promoted dtype of all gradient tensors.
1128 """
1129 max_norm = float(max_norm)
1130 norm_type = float(norm_type)
1132 params = _normalize_parameters(parameters)
1133 if parameter_layouts is not None:
1134 params = [param for param in dict.fromkeys(params) if param.requires_grad]
1135 if foreach is None:
1136 foreach = False
1138 (
1139 grad_groups, all_grads, norm_grads, key_per_grad,
1140 mesh_cache, device, has_dtensor_grad,
1141 ) = (_build_grad_groups(params) if parameter_layouts is None
1142 else _build_grad_groups(params, parameter_layouts))
1144 # -- Norm + clip (all ranks participate) --------------------------------
1145 # _compute_local_norm returns identity elements for empty groups,
1146 # so the subsequent all-reduce is safe and semantically neutral.
1147 total_norm = _get_total_norm(
1148 grad_groups, norm_type, mesh_cache, device,
1149 norm_grads, key_per_grad,
1150 )
1152 if pp_group is not None:
1153 total_norm = _reduce_pipeline_norm(total_norm, norm_type, pp_group)
1155 if error_if_nonfinite:
1156 _check_finite_norm(total_norm, norm_type)
1158 if all_grads:
1159 # Disable foreach for dtensor-backed grads to avoid dispatch issues.
1160 effective_foreach = False if has_dtensor_grad and foreach is None else foreach
1161 _clip_grads_with_norm_(
1162 all_grads, max_norm, total_norm, effective_foreach,
1163 )
1165 # Promote return dtype to match gradient dtypes (FSDP1 convention).
1166 # When this rank has no gradients, return in the default FP32 dtype
1167 # (same as FSDP1's behavior to avoid extra communication).
1168 if not all_grads:
1169 warnings.warn(
1170 "clip_grad_norm_ called on this rank with no gradients -- "
1171 "returning the local norm in the default dtype "
1172 f"{total_norm.dtype}",
1173 stacklevel=2,
1174 )
1175 return total_norm
1177 total_norm_dtype = functools.reduce(
1178 torch.promote_types,
1179 [g.dtype for g in all_grads],
1180 )
1181 # Return global all-reduced norm, consistent with torchtitan's
1182 # full_tensor() approach — .item() returns the correct global value.
1183 return total_norm.to(total_norm_dtype)