Optimizer gradient utilities#
Python module dendra.opt.
Gradient hygiene#
Call dendra.opt.sanitize_grad() after loss.backward() and before
optimizer.step() to replace non-finite gradients with zero. Optional value
clipping is applied element by element before optional global L2-norm clipping
across every parameter group in the optimizer. The helper supports dense,
strided gradients; unsupported sparse layouts raise an error before any
gradient is changed.
- sanitize_grad(optimizer, clip_norm=None, clip_value=None)[source]#
Sanitize and optionally clip an optimizer’s gradients in place.
NaN, positive infinity, and negative infinity are replaced with zero. If both clipping limits are supplied, element-wise value clipping is applied first, followed by L2-norm clipping. The norm is computed over all gradients in all optimizer parameter groups as if they formed one vector. Parameters whose gradient isNoneare ignored.- Parameters:
optimizer (Optimizer) – Optimizer containing the parameters whose gradients should be sanitized. Call this function after backpropagation and before
step().clip_norm (float | None) – Optional finite, non-negative maximum for the global L2 norm.
clip_value (float | None) – Optional finite, non-negative maximum absolute value for each gradient element.
- Raises:
TypeError – If a clipping limit is not a real number or
None, or if an optimizer parameter has a non-strided (for example, sparse) gradient.ValueError – If a clipping limit is negative or non-finite.
Notes
Only dense, strided gradients are supported. Unsupported layouts are detected before any gradient is mutated. The operation runs under
torch.no_grad()and does not replace existing gradient tensors. It is an optimizer hygiene operation, not a differentiable transformation of the backward graph.Examples
>>> optimizer.zero_grad() >>> loss.backward() >>> sanitize_grad(optimizer, clip_norm=1.0, clip_value=10.0) >>> optimizer.step()