Gradient Clipping and Scaling #
GPU kernels for:
- Global gradient norm — L2 norm across all LoRA parameter gradients
- Gradient clipping — scale gradients if norm exceeds threshold
- Gradient scaling — divide gradients by token count (loss normalization)
Standard Values (matches PyTorch defaults) #
- max_grad_norm = 1.0
- Loss normalization: divide gradients by number of output tokens
Buffers needed for gradient clipping
- normSqBuf : WebGPU.Buffer
Accumulator for sum of squared gradients [1]
- partialBuf : WebGPU.Buffer
Temporary for per-buffer partial sums [1]
Instances For
Create clip buffers
Equations
- One or more equations did not get rendered due to their size.
Instances For
Sum of Squares Kernel #
Compute sum of squares of a buffer, write result to accumulator (ADD to existing value). Uses single workgroup with shared memory reduction.
Equations
- One or more equations did not get rendered due to their size.
Instances For
Execute sum of squares and add to accumulator
Equations
- One or more equations did not get rendered due to their size.
Instances For
Gradient Clip Kernel #
Scale gradient buffer by clip_factor = maxNorm / globalNorm (if norm > maxNorm). Reads globalNormSq[0], computes norm = sqrt(normSq), clips if needed.
Equations
- One or more equations did not get rendered due to their size.
Instances For
Execute gradient clipping on a single buffer
Equations
- One or more equations did not get rendered due to their size.
Instances For
In-place Gradient Scale Kernel #
Scale gradient in-place: grad[i] *= scaleFactor
Equations
- One or more equations did not get rendered due to their size.
Instances For
Equations
- One or more equations did not get rendered due to their size.
Instances For
High-Level API #
Clip gradients of all LoRA parameters to maxNorm (global L2 norm). Returns the gradient norm before clipping (for logging).
Equations
- One or more equations did not get rendered due to their size.
Instances For
Scale all gradients by a factor (e.g., 1/numTokens for loss normalization)
Equations
- One or more equations did not get rendered due to their size.