Module contents
Lesson 13 of 22Core 85 min

Vanishing and exploding gradients

Analyze vanishing and exploding gradients through products of layer Jacobians and deep linear networks, examine saturation, weight scale and depth, and implement gradient clipping.

After this lesson you can

  • Express an early-layer gradient as a Jacobian product and bound its norm using singular values.
  • Measure gradient norms by layer for sigmoid and large-weight deep MLPs.
  • Analyze deep linear learning dynamics and the role of initial scale.
  • Implement global-norm and value gradient clipping and explain their uses.
  • Relate initialization, activations, normalization, residual connections and clipping to the problems they address.

Before you start

A signal crossing many layers

An early layer can change little even when output error is large: the correction signal must pass through all intermediate layers. If attenuated too much, early-layer learning slows; if amplified, an update can move parameters out of the region where the gradient was informative. These are vanishing gradients and exploding gradients. An isolated small norm does not prove the cause: a layer may have inactive ReLUs, nearly optimal loss, or a different parameter scale.

The difficulty of training deep networks does not mean nobody succeeded before 2010. Glorot and Bengio describe earlier advances with specific initializations and training mechanisms; they study why random initialization and sigmoid make standard descent difficult. In their experiment with four hidden layers and one thousand units each, the last layer saturates and slowly exits saturation around epoch 100; with five layers it did not exit during training. These are observations of the setup in their Figure 2, not a property of every sigmoid network.

The product received by the gradient

We use column vectors for one example. Let hk=ϕk(Wkhk−1+bk)h_k=\phi_k(W_kh_{k-1}+b_k) and Jk=∂hk/∂hk−1=DkWkJ_k=\partial h_k/\partial h_{k-1}=D_kW_k, where DkD_k is diagonal with activation derivatives evaluated at that example. At a differentiable point,

∇hlL=Jl+1TJl+2T⋯JLT∇hLL.\nabla_{h_l}L=J_{l+1}^{\mathsf T}J_{l+2}^{\mathsf T}\cdots J_L^{\mathsf T}\nabla_{h_L}L.

The backpropagation expression multiplies Jacobians evaluated on a particular trajectory: knowing each matrix’s size separately is insufficient. In a minibatch, each example can have different DkD_k matrices and the parameter gradient combines their contributions.

InteractiveThe Jacobian product

Width-8 network with zero biases: each weight is the chosen scale times a random orthogonal matrix. The same unit terminal vector is propagated backward. This is a fixed realization, not a law for all networks.

Gradient flow by layer: log₁₀ of norm
Preparing chart…
Layer index: 0 is input and 20 is output. An exact zero has no logarithm and is omitted.
Resolved spectrum histogram
0
0
4
4
0
log₁₀ σ = -14log₁₀ σ = -12

0 of 8 values remain unresolved due to numerical precision. Values not exceeding 8·ε·σmax in float64 are omitted; they are not concluded to be zero. For these orthogonal matrices and smooth activations, this numerical test does not establish exact zeros.

The 84 cases were computed with NumPy, seed 13, and QR; you can reproduce them in the “Jacobian product and spectrum” cell. The derivative is also checked with finite differences; error can vary by environment. The count diagnoses precision, not the exact remaining rank.

20 layers
Input norm1.78e-13
Output norm1
Resolved singular values8 of 8
Change activation, scale, and depth. Weights, input, and terminal direction come from a reproducible experiment, not an imposed spectrum.

The product spectrum describes its action by direction. For P=JL⋯Jl+1P=J_L\cdots J_{l+1} and any output vector gg,

∥PTg∥2≤∥P∥2∥g∥2≤∥g∥2∏k=l+1L∥Jk∥2≤∥g∥2∏k=l+1L∥Wk∥2max⁡z∣ϕk′(z)∣.\|P^\mathsf Tg\|_2\leq\|P\|_2\|g\|_2 \leq\|g\|_2\prod_{k=l+1}^L\|J_k\|_2 \leq\|g\|_2\prod_{k=l+1}^L\|W_k\|_2\max_z|\phi_k'(z)|.

The first bound uses the product’s largest singular value; the second is submultiplicativity. It is usually not an equality. For example, A=diag⁡(2,1/2)A=\operatorname{diag}(2,1/2) and B=diag⁡(1/2,2)B=\operatorname{diag}(1/2,2) have norm 2, but BA=IBA=I: the product of norms is 4 and the actual norm is 1. Changing orientation can cancel an expansion or align it with another. The smallest singular value provides a lower bound only in relevant directions and without a null space: for rectangular matrices lost directions must also be counted, even if a compact list of positive singular values omits them.

For sigmoid, max⁡∣σ′∣=1/4\max|\sigma'|=1/4. If all layers satisfy uniform bound ∥Wk∥2≤4q\|W_k\|_2\leq4q with the same q<1q<1, the bound’s factor is at most qL−lq^{L-l}; if output-gradient norm also stays bounded as depth grows, the input-gradient bound tends to zero. Saying only that each norm is below 4 is insufficient as depth grows: factors below 1 can approach 1 so fast that their product does not tend to zero. A per-layer norm above 1 does not ensure explosion in every direction either. The figure shows the exact product from a small experiment: values below the precision threshold are marked unresolved, not presented as measured zeros.

Saturation, scale, and depth

Sigmoid has a small derivative at both extremes, tanh also saturates, and ReLU has derivative 0 for negative inputs and 1 for positive ones, except at its kink where the framework chooses a convention. An inactive ReLU in one layer can eliminate directions even when other layers preserve norm. Increasing weights can amplify some directions while saturating more units: no universal optimal scale is independent of activation and data.

In the local check, with 20 orthogonal layers of width 32 and scale 1, the input-gradient norm for sigmoid is approximately 2,62×10−142{,}62\times10^{-14} versus 0,09930{,}0993 at output. With ReLU and scale 4, the norms are approximately 2,00×10172{,}00\times10^{17} and 5,54×1075{,}54\times10^7. These measurements use a particular batch and initialization: scales also change output and loss, so the difference does not isolate one mechanism. The lab saves norms of all layers and prints profiles for the greatest depth so you can examine where the change occurs.

A linear network can also learn in stages

Without nonlinearities the overall function remains linear, but its parameters are multiplied together. Consider a mode of a target matrix with strength s>0s>0, whitened inputs, aligned diagonal matrices, and DD equal scalar factors a>0a>0. With loss L=(aD−s)2/2L=(a^D-s)^2/2, gradient flow maintains balance between factors and, for u=aDu=a^D,

a˙=(s−u)aD−1,u˙=D u2−2/D(s−u).\dot a=(s-u)a^{D-1},\qquad \dot u=D\,u^{2-2/D}(s-u).

Time is normalized to unit flow rate. For D=2D=2 a logistic equation appears; for D>2D>2 the exponent changes and the curve is different. If 0<u0<s0<u_0<s, the mode grows toward ss; with small initial scale it can change very slowly. At a=0a=0 and D≥2D\geq2, the point is stationary: one cannot divide by aa to infer that it leaves zero.

InteractiveModes of a deep linear network

A linear network learns a diagonal matrix with target modes 1, 0.5, and 0.25. Inputs are whitened and the L matrices start diagonal, aligned, and balanced, with positive a₀ in each layer. These are assumptions of this model, not a description of every deep network.

Vertical axis: learned strength u of each mode
  • Target 1.00
  • Target 0.50
  • Target 0.25
0.000.250.500.751.000.004.0624.61Time t, log(1 + t) scale

Time is gradient-flow time, not seconds or execution steps. The axis uses log(1 + t) to include t = 0; its endpoint changes with the controls and reaches 24.61, when the slowest mode reaches 99% of its target.

For each mode, u = aᴸ and loss is (u − s)²/2. With all its layers equal, exact flow satisfies du/dt = L·u^(2 − 2/L)(s − u). We integrate that equation by quadrature and use the same time for all three modes.

For L = 2 the solution is logistic; for larger L the equation differs. Smaller a₀ can greatly extend the plateau. Initializing exactly at zero leaves the mode stuck for L ≥ 2. Unaligned initialization, correlated data, or large discrete steps can yield different dynamics.

3
0.20
60 % of axis
Marker time6.00
Target mode 10.9951
Target mode 0.50.0956
Target mode 0.250.0218
Compare depth and initial scale. Time is transformed to show long plateaus; check the window when changing settings.

Saxe and colleagues derive exact dynamics under assumptions about data and initialization and study plateaus and transitions. They also find special initializations whose learning times do not grow indefinitely with depth. These trajectories are continuous flow for aligned modes: they do not prove an arbitrary network learns all modes independently or that discrete SGD at a large rate follows the same curve.

Avoiding a destructive jump

A large gradient can point in a useful direction yet produce an excessively long step. Pascanu and colleagues analyze cliffs and propose norm clipping for exploding gradients in recurrent networks. The following landscape is an explicit model, not data from that paper.

InteractiveA cliff and two trajectories

Both descents start at (0.8, 0.9). The wall is at x > 0; contours belong to an explicit function. The clipped trajectory limits gradient norm, not each coordinate.

step 20 / 20
  • Without clipping
  • With global clipping
  • Contours

L(x,y) = (x+1)²/2 + y²/2 + 20·max(0,x)². Its gradient is (x+1+40·max(0,x), y). For g ≠ 0, clipped descent uses g·min(1,c/‖g‖₂); for g = 0, it uses zero. Per-step displacement is at most ηc. Curves and readouts are computed from these steps, without noise or external data. Clipping does not guarantee loss decreases or fix small gradients by itself.

0.25
3.0
Step20
Loss without clipping3.99e-4
Loss with clipping8.92e-6
Norm before clipping, last step0.006
Applied norm, last step0.006
Adjust rate and threshold; both trajectories start at the same point and use the gradient of the same landscape.

Global-norm clipping conceptually concatenates gradients gg of all parameters. With threshold c≥0c\geq0 and finite norm,

g~={g,∥g∥2≤c,c g/∥g∥2,∥g∥2>c.\widetilde g=\begin{cases}g,&\|g\|_2\leq c,\\ c\,g/\|g\|_2,&\|g\|_2>c.\end{cases}

For g=0g=0 the zero vector is retained; if c=0c=0, every finite gradient becomes zero. Global clipping preserves direction when c>0c>0 and reduces norm to at most cc. In SGD without momentum or decay, ∥Δθ∥≤ηc\|\Delta\theta\|\leq\eta c; with momentum, Adam, or decay, the total update also depends on their state and additional terms and is not bounded by that expression. Clipping each coordinate by value to [−c,c][-c,c] can change direction and does not bound total norm by cc. NaN or infinite gradients require finding and resolving their cause; clipping does not repair them.

Record the distribution of norms before setting a threshold and count the fraction of steps clipped. A tiny threshold can prevent learning; one too high almost never acts. In PyTorch, torch.nn.utils.clip_grad_norm_ modifies gradients in place and returns the previous norm; call backward(), check finiteness, clip, then call optimizer.step(). Account for scaled loss under mixed precision and unscale before measuring or clipping.

A map of remedies

Initialization adjusts scales at the start; less saturating activations can preserve signals where others reduce them. Normalization changes scales and training behavior, but does not guarantee every product preserves its singular values. Residual shortcuts add an identity path and can ease signal flow; even so, I+JI+J does not automatically have all singular values equal to 1. Clipping handles large updates; it does not recover a vanished gradient or activate a dead ReLU.

Besides norm, correlation between gradients matters. Balduzzi and colleagues study gradients becoming weakly correlated with depth even after accounting for scale, and compare ordinary and residual networks under their models. It does not follow that every deep network has the same decorrelation rate. Diagnose magnitude, saturation, activations, and correlation before choosing a remedy.

Lab: reproducible spectra

This cell reproduces the first figure’s data. Each matrix is a scale times an orthogonal matrix obtained by QR; seed, input, and terminal direction are fixed. The product is constructed explicitly and compared with the backward-computed VJP, plus a finite difference in one case. For ReLU a structural rank bound is shown; small singular values are classified as unresolved according to relative precision, not exact zeros.

[ ]Jacobian product and spectrumBrowser
"""Producto real de jacobianos de una MLP diminuta; solo NumPy y CPU.

Cada capa tiene anchura 8, sesgo cero y W=escala*Q, con Q ortogonal QR.
Las semillas fijan los pesos, entrada y dirección del gradiente terminal.
Se expresa como log10 la norma cero con None, sin falsa precisión de SVD.
"""
import json
from pathlib import Path

import numpy as np


def run(depth, scale, activation, seed=13, width=8):
    generator = np.random.default_rng(seed)
    x = generator.standard_normal(width)
    terminal = generator.standard_normal(width)
    terminal /= np.linalg.norm(terminal)
    weights, jacobians, states = [], [], [x.copy()]
    for _ in range(depth):
        q, r = np.linalg.qr(generator.standard_normal((width, width)))
        q *= np.where(np.diag(r) >= 0, 1., -1.)
        weight = scale * q
        z = weight @ x
        if activation == 'sigmoide':
            x = 1 / (1 + np.exp(-np.clip(z, -500, 500)))
            derivative = x * (1-x)
        elif activation == 'tanh':
            x = np.tanh(z)
            derivative = 1-x*x
        elif activation == 'relu':
            x = np.maximum(z, 0)
            derivative = (z > 0).astype(float)
        else:
            raise ValueError('activación desconocida')
        weights.append(weight)
        jacobians.append(derivative[:, None] * weight)
        states.append(x.copy())

    gradient = terminal.copy()
    gradient_norms = [None] * (depth+1)
    gradient_norms[-1] = float(np.linalg.norm(gradient))
    for i in range(depth-1, -1, -1):
        gradient = jacobians[i].T @ gradient
        gradient_norms[i] = float(np.linalg.norm(gradient))

    product = np.eye(width)
    for jacobian in jacobians:
        product = jacobian @ product
    singular_values = np.linalg.svd(product, compute_uv=False)
    threshold = np.finfo(float).eps * width * singular_values[0]
    resolved = [float(v) if v > threshold else None for v in singular_values]
    difference = np.linalg.norm(product.T @ terminal - gradient)
    gradient_scale = max(np.linalg.norm(gradient), np.linalg.norm(product.T @ terminal))
    assert difference == 0 if gradient_scale == 0 else difference / gradient_scale < 1e-10
    return {'depth': depth, 'scale': scale, 'activation': activation, 'seed': seed,
            'gradient_norms': gradient_norms, 'singular_values_resolved': resolved,
            'structural_rank_upper_bound': min(int(np.count_nonzero(np.any(j != 0, axis=1))) for j in jacobians) if activation == 'relu' else None,
            'svd_relative_threshold': float(np.finfo(float).eps * width),
            'jacobians': jacobians, 'weights': weights, 'states': states,
            'terminal': terminal, 'input_gradient': gradient}


def forward(x, weights, activation):
    for w in weights:
        z = w @ x
        if activation == 'sigmoide': x = 1/(1+np.exp(-np.clip(z, -500, 500)))
        elif activation == 'tanh': x = np.tanh(z)
        else: x = np.maximum(z, 0)
    return x


if __name__ == '__main__':
    # Comprobación independiente de la VJP por diferencias centrales.
    case = run(5, 1.2, 'tanh')
    epsilon = 1e-6
    basis = np.eye(8)
    finite = np.array([case['terminal'] @ (
        forward(case['states'][0]+epsilon*e, case['weights'], 'tanh') -
        forward(case['states'][0]-epsilon*e, case['weights'], 'tanh')) / (2*epsilon)
        for e in basis])
    error = float(np.max(np.abs(finite-case['input_gradient'])))
    assert error < 1e-8
    rows = []
    for activation in ('sigmoide', 'tanh', 'relu'):
        for scale in (.5, 1., 2., 4.):
            for depth in (1, 5, 10, 20, 50, 75, 100):
                result = run(depth, scale, activation)
                rows.append({k: result[k] for k in ('activation', 'scale', 'depth',
                             'seed', 'gradient_norms', 'singular_values_resolved',
                             'svd_relative_threshold', 'structural_rank_upper_bound')})
    destination = Path('jacobian-prototype.json')
    destination.write_text(json.dumps({'finite_difference_max_error': error,
                                      'runs': rows}, ensure_ascii=False, indent=2), encoding='utf-8')
    print('Diferencia máxima VJP frente a diferencias finitas:', error)
    print('Combinaciones:', len(rows))
    for row in rows:
        if row['depth'] == 100:
            print(row['activation'], row['scale'], 'gradiente inicial', row['gradient_norms'][0],
                  'singulares resueltos', sum(v is not None for v in row['singular_values_resolved']))

Local lab: measuring flow

The next cell builds MLPs with scaled orthogonal weights, registers hooks on activations, and measures activation and weight gradient norms on the first backward pass. It uses a fixed batch and the same weight generator for each condition. The experiment diagnoses initialization; it does not evaluate generalization. The lesson was verified in short mode (ORYON_VERIFY_SHORT=1); normal mode includes depths of 5, 20, and 50 layers.

[ ]Gradient norms by layerLocal GPU
"""Medir gradientes de activaciones y parámetros en redes profundas.

La ejecución corta usa menos casos; el barrido completo es para el lector.
"""
import json
import math
import os
from pathlib import Path
import torch
from torch import nn

torch.set_num_threads(1)
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
short = os.environ.get('ORYON_VERIFY_SHORT') == '1'
depths = [5, 20, 50] if not short else [5, 20]
scales = [0.5, 1., 4.]
activations = {'sigmoide': nn.Sigmoid, 'tanh': nn.Tanh, 'ReLU': nn.ReLU}
torch.manual_seed(1301)
x_cpu = torch.randn(16, 32, dtype=torch.float64)
y_cpu = torch.randn(16, 32, dtype=torch.float64)
rows = []
for depth in depths:
    for name, activation in activations.items():
        for scale in scales:
            torch.manual_seed(1302)
            layers = []
            for _ in range(depth):
                layer = nn.Linear(32, 32, bias=True, dtype=torch.float64)
                nn.init.orthogonal_(layer.weight, gain=scale)
                nn.init.zeros_(layer.bias)
                layers.extend([layer, activation()])
            model = nn.Sequential(*layers).to(device)
            x = x_cpu.to(device).detach().requires_grad_(True)
            target = y_cpu.to(device)
            snapshots = {}
            handles = []
            def capture(index):
                def hook(module, args, output):
                    output.register_hook(lambda grad: snapshots.__setitem__(index, float(grad.norm().detach().cpu())))
                return hook
            for i in range(depth):
                handles.append(model[2*i+1].register_forward_hook(capture(i+1)))
            prediction = model(x)
            loss = (prediction-target).square().mean()
            if not bool(torch.isfinite(loss)):
                raise RuntimeError('La pérdida no es finita')
            loss.backward()
            activation_norms = [float(x.grad.norm().detach().cpu())] + [snapshots[i] for i in range(1,depth+1)]
            weight_norms = [float(model[2*i].weight.grad.norm().detach().cpu()) for i in range(depth)]
            if not all(math.isfinite(value) for value in activation_norms+weight_norms):
                raise RuntimeError('Algún gradiente no es finito')
            rows.append({'depth':depth, 'activation':name, 'scale':scale,
                         'loss':float(loss.detach().cpu()), 'activation_gradient_norms':activation_norms,
                         'weight_gradient_norms':weight_norms})
            print('capas',depth,'activación',name,'escala',scale,'pérdida',float(loss.detach().cpu()),
                  'norma entrada',activation_norms[0],'norma salida',activation_norms[-1],flush=True)
            if depth == max(depths) and scale in (1., 4.):
                print('normas de activación desde entrada hasta salida:', activation_norms, flush=True)
            for handle in handles: handle.remove()
            del model, x, target, prediction, loss
            if device.type == 'cuda': torch.cuda.empty_cache()
output = {'device':str(device),'short':short,'seed_model':1302,'seed_data':1301,
          'batch':16,'width':32,'rows':rows}
destination = Path(os.environ.get('ORYON_FLOW_OUTPUT','gradient-flow.json'))
destination.write_text(json.dumps(output,ensure_ascii=False,indent=2),encoding='utf-8')
print('Resultados guardados en', destination)
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Lab from scratch: clipping and training

The tensor engine from lesson 9 is included here to run the experiment without external files. The network learns synthetic regression with three tanh hidden layers. Both protocols use the same initialization and 120 minibatches; any run reaching non-finite loss or loss above 101210^{12} stops. The reported norm is before clipping. The cell also compares different rates: a favorable result here does not prove clipping permits every rate or always improves validation.

At rate 0.7, the unclipped run stops at step 13; its largest recorded loss before the stopping step is approximately 3,75×10103{,}75\times10^{10}. With global threshold 0.5, 120 steps complete and the largest recorded loss is approximately 0.738. Losses correspond to different training minibatches: also compare an evaluation on a fixed batch before drawing conclusions about quality. For g=(3,4)g=(3,4) and c=2c=2, global clipping gives (1,2,1,6)(1{,}2,1{,}6), while coordinate clipping gives (2,2)(2,2) and changes direction.

[ ]Tensor and its vector-Jacobian productsBrowser
import numpy as np
from copy import deepcopy

def unbroadcast(grad, shape):
    grad = np.asarray(grad)
    while grad.ndim > len(shape):
        grad = grad.sum(axis=0)
    for axis, size in enumerate(shape):
        if size == 1 and grad.shape[axis] != 1:
            grad = grad.sum(axis=axis, keepdims=True)
    if grad.shape != tuple(shape):
        raise ValueError('formas incompatibles')
    return grad

class Tensor:
    def __init__(self, data, parents=(), backward=None):
        self.data = np.array(data, dtype=np.float64, copy=True)
        self.grad = np.zeros_like(self.data)
        self.parents = tuple(parents)
        self._backward = backward or (lambda: None)

    @staticmethod
    def wrap(x): return x if isinstance(x, Tensor) else Tensor(x)

    def __add__(self, other):
        other = Tensor.wrap(other)
        a_shape, b_shape = self.data.shape, other.data.shape
        out = Tensor(self.data + other.data, (self, other))
        def backward():
            self.grad += unbroadcast(out.grad, a_shape)
            other.grad += unbroadcast(out.grad, b_shape)
        out._backward = backward
        return out
    __radd__ = __add__

    def __mul__(self, other):
        other = Tensor.wrap(other)
        a, b = self.data.copy(), other.data.copy()
        out = Tensor(a*b, (self, other))
        def backward():
            self.grad += unbroadcast(out.grad*b, a.shape)
            other.grad += unbroadcast(out.grad*a, b.shape)
        out._backward = backward
        return out
    __rmul__ = __mul__
    def __neg__(self): return self * -1
    def __sub__(self, other): return self + (-Tensor.wrap(other))
    def __rsub__(self, other): return Tensor.wrap(other) - self

    def __matmul__(self, other):
        other = Tensor.wrap(other)
        a, b = self.data.copy(), other.data.copy()
        if a.ndim != 2 or b.ndim != 2:
            raise ValueError('matmul admite matrices 2D')
        out = Tensor(a @ b, (self, other))
        def backward():
            self.grad += out.grad @ b.T
            other.grad += a.T @ out.grad
        out._backward = backward
        return out

    def tanh(self):
        y = np.tanh(self.data)
        out = Tensor(y, (self,))
        out._backward = lambda: self._accumulate(out.grad*(1-y*y))
        return out
    def sigmoid(self):
        x = self.data
        y = np.exp(-np.logaddexp(0, -x))
        out = Tensor(y, (self,))
        out._backward = lambda: self._accumulate(out.grad*y*(1-y))
        return out
    def relu(self):
        mask = self.data > 0
        out = Tensor(np.maximum(self.data, 0), (self,))
        out._backward = lambda: self._accumulate(out.grad*mask)
        return out
    def exp(self):
        y = np.exp(self.data)
        out = Tensor(y, (self,))
        out._backward = lambda: self._accumulate(out.grad*y)
        return out
    def log(self):
        x = self.data.copy()
        if np.any(x <= 0): raise ValueError('log exige entrada positiva')
        out = Tensor(np.log(x), (self,))
        out._backward = lambda: self._accumulate(out.grad/x)
        return out
    def _accumulate(self, value): self.grad += value

    def sum(self, axis=None, keepdims=False):
        shape = self.data.shape
        axes = tuple(range(len(shape))) if axis is None else ((axis,) if isinstance(axis, int) else tuple(axis))
        axes = tuple(a % len(shape) for a in axes) if shape else ()
        out = Tensor(self.data.sum(axis=axis, keepdims=keepdims), (self,))
        def backward():
            g = out.grad
            if not keepdims:
                for a in sorted(axes): g = np.expand_dims(g, a)
            self.grad += np.broadcast_to(g, shape)
        out._backward = backward
        return out
    def mean(self, axis=None, keepdims=False):
        axes = tuple(range(self.data.ndim)) if axis is None else ((axis,) if isinstance(axis, int) else tuple(axis))
        count = int(np.prod([self.data.shape[a] for a in axes]))
        return self.sum(axis, keepdims) * (1.0/count)
    def max(self, axis=None, keepdims=False):
        shape = self.data.shape
        axes = tuple(range(len(shape))) if axis is None else ((axis,) if isinstance(axis, int) else tuple(axis))
        axes = tuple(a % len(shape) for a in axes) if shape else ()
        maxima = self.data.max(axis=axis, keepdims=True)
        mask = self.data == maxima
        counts = mask.sum(axis=axis, keepdims=True)
        out = Tensor(self.data.max(axis=axis, keepdims=keepdims), (self,))
        def backward():
            g = out.grad
            if not keepdims:
                for a in sorted(axes): g = np.expand_dims(g, a)
            self.grad += mask * (g/counts)
        out._backward = backward
        return out
    def reshape(self, *shape):
        original = self.data.shape
        out = Tensor(self.data.reshape(*shape), (self,))
        out._backward = lambda: self._accumulate(out.grad.reshape(original))
        return out
    def transpose(self, *axes):
        perm = (tuple(axes[0]) if len(axes) == 1 and isinstance(axes[0], (tuple, list))
                else tuple(axes) if axes else tuple(reversed(range(self.data.ndim))))
        transposed = self.data.transpose(perm)  # NumPy valida la permutación.
        normalized = tuple(a % self.data.ndim for a in perm) if self.data.ndim else ()
        inverse = np.argsort(normalized)
        out = Tensor(transposed, (self,))
        out._backward = lambda: self._accumulate(out.grad.transpose(inverse))
        return out
    def __getitem__(self, index):
        # También pueden mutarse listas o estructuras anidadas de índices.
        index = deepcopy(index)
        out = Tensor(self.data[index], (self,))
        def backward(): np.add.at(self.grad, index, out.grad)
        out._backward = backward
        return out
    @staticmethod
    def concat(tensors, axis=0):
        tensors = tuple(tensors)
        cuts = np.cumsum([t.data.shape[axis] for t in tensors])[:-1]
        out = Tensor(np.concatenate([t.data for t in tensors], axis=axis), tensors)
        def backward():
            for tensor, g in zip(tensors, np.split(out.grad, cuts, axis=axis)):
                tensor.grad += g
        out._backward = backward
        return out

    def backward(self, seed=None):
        if seed is None:
            if self.data.size != 1: raise ValueError('salida no escalar: proporciona semilla')
            seed = np.ones_like(self.data)
        seed = np.asarray(seed, dtype=float)
        if seed.shape != self.data.shape: raise ValueError('forma de semilla incorrecta')
        topo, seen, stack = [], set(), [(self, False)]
        while stack:
            node, done = stack.pop()
            if done: topo.append(node)
            elif node not in seen:
                seen.add(node)
                stack.append((node, True))
                stack.extend((p, False) for p in reversed(node.parents))
        for node in topo:
            if node.parents: node.grad.fill(0)
        self.grad += seed
        for node in reversed(topo): node._backward()
        return len(topo)

def cross_entropy(logits, labels):
    z = logits.data.copy()
    labels = np.asarray(labels)
    if (z.ndim != 2 or z.shape[0] == 0 or z.shape[1] == 0 or
            labels.ndim != 1 or labels.shape[0] != z.shape[0] or
            not np.issubdtype(labels.dtype, np.integer) or
            np.any(labels < 0) or np.any(labels >= z.shape[1])):
        raise ValueError('formas o etiquetas incorrectas')
    shifted = z - np.max(z, axis=1, keepdims=True)
    exp = np.exp(shifted)
    probabilities = exp/exp.sum(axis=1, keepdims=True)
    loss = np.mean(np.log(exp.sum(axis=1))-shifted[np.arange(len(labels)), labels])
    delta = probabilities.copy()
    delta[np.arange(len(labels)), labels] -= 1
    delta /= len(labels)
    out = Tensor(loss, (logits,))
    out._backward = lambda: logits._accumulate(out.grad*delta)
    return out
[ ]Clipping and regression with a deep networkBrowser
import numpy as np
import math

def unique_grads(params):
    seen, grads = set(), []
    for p in params:
        if id(p) in seen: continue
        seen.add(id(p))
        if p.grad is not None: grads.append(p.grad)
    return grads

def clip_grad_norm(params, max_norm):
    if max_norm < 0 or not np.isfinite(max_norm):
        raise ValueError('el umbral debe ser finito y no negativo')
    grads = unique_grads(params)
    if any(not np.all(np.isfinite(g)) for g in grads):
        raise ValueError('gradiente no finito')
    norm = 0.0
    for g in grads:
        for value in g.flat: norm = math.hypot(norm, float(value))
    if not np.isfinite(norm): raise ValueError('norma no finita')
    if norm > max_norm:
        factor = max_norm / norm
        for g in grads: g *= factor
    return norm

def clip_grad_value(params, limit):
    if limit < 0 or not np.isfinite(limit): raise ValueError('umbral inválido')
    grads = unique_grads(params)
    if any(not np.all(np.isfinite(g)) for g in grads):
        raise ValueError('gradiente no finito')
    for g in grads: np.clip(g, -limit, limit, out=g)

# Ambas reglas coinciden con el gradiente original por debajo de su umbral,
# pero por valor puede cambiar la dirección cuando solo algunas coordenadas exceden c.
example = Tensor([0., 0.]); example.grad[:] = [3., 4.]
before = clip_grad_norm([example, example], 2.)
print('norma previa, recorte global', before, example.grad)
example.grad[:] = [3., 4.]
clip_grad_value([example], 2.)
print('recorte por valor', example.grad)

def build_parameters(seed=75):
    rng = np.random.default_rng(seed)
    sizes = [2, 12, 12, 12, 1]
    params = []
    for a,b in zip(sizes[:-1],sizes[1:]):
        params.extend([Tensor(rng.normal(0, np.sqrt(1/a), (a,b))), Tensor(np.zeros((1,b)))])
    return params

def forward(x, params):
    h = Tensor(x)
    for i in range(0, len(params)-2, 2):
        h = (h @ params[i] + params[i+1]).tanh()
    return h @ params[-2] + params[-1]

rng = np.random.default_rng(74)
X = rng.uniform(-1, 1, (128, 2))
Y = (np.sin(np.pi*X[:, :1]) + X[:, 1:])
indices = np.random.default_rng(76).integers(0, len(X), (120, 32))

def train(lr, threshold):
    params = build_parameters()
    result = []
    for step, batch in enumerate(indices):
        for p in params: p.grad.fill(0)
        err = forward(X[batch],params) - Y[batch]
        loss = (err*err).mean()
        if not np.isfinite(loss.data) or loss.data > 1e12:
            print('detenida: pérdida no finita o >1e12 en paso', step)
            break
        loss.backward()
        if threshold is None:
            norm = float(np.sqrt(sum(np.sum(p.grad*p.grad) for p in params)))
        else:
            norm = clip_grad_norm(params,threshold)
        result.append((step,float(loss.data),norm))
        for p in params: p.data -= lr*p.grad
    return np.array(result)

for lr in (0.3, 0.7, 1.0):
    for threshold in (None, 0.5):
        curve = train(lr,threshold)
        print('lr, umbral, puntos, pérdida inicial, máxima, última, norma máxima',lr,threshold,len(curve),curve[0,1],curve[:,1].max(),curve[-1,1],curve[:,2].max())

Exercises

ProofWhen does a bound guarantee vanishing?
Prove: Bound the norm of a gradient crossing n layers and determine a sufficient condition for the bound to tend to zero.
0
In a column-vector network, each layer has hᵏ=φ(Wᵏhᵏ⁻¹+bᵏ), where φ acts coordinatewise. Fix an input, parameters, and gₙ=∇ₕ⁽ⁿ⁾L. Assume compatible dimensions and existing derivatives at the preactivations.

Step 1 of 4. If Dᵏ is diagonal with derivatives of φ at layer k, what is the Jacobian of hᵏ with respect to hᵏ⁻¹?

NumericThe bound after twenty layers
A gradient crosses 20 sigmoid layers whose matrices have spectral norm 1. What maximum factor does the product bound give for the gradient norm? Enter the factor, not its logarithm.
CodeClip one global gradient
Implement clip_grad_norm(params, max_norm). Each parameter has grad, a writable floating-point NumPy array or None; arrays of different parameters do not share memory. A parameter may appear more than once in params: count and modify it once. Return the previous global Euclidean norm and multiply all gradients by min(1,max_norm/norm) in place, using factor 1 when norm is zero. Ignore None. Accept a finite nonnegative threshold; reject a non-finite threshold, component, or total norm with ValueError. Validate everything before changing any gradient. Compute the norm stably without squaring large components.
import math
import numpy as np

def clip_grad_norm(params, max_norm):
  pass
Shift+Enter to run
QuizGlobal profile or localized failure
In three runs of the same network, norms are recorded in layers ordered from output toward input. A: [1, 0.1, 0.01, 0.001]; B: [1, 10, 100, 1000]; C: [1, 0.9, 0.001, 0.0009]. What initial reading is most defensible?