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 and , where is diagonal with activation derivatives evaluated at that example. At a differentiable point,
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 matrices and the parameter gradient combines their contributions.
The product spectrum describes its action by direction. For and any output vector ,
The first bound uses the product’s largest singular value; the second is submultiplicativity. It is usually not an equality. For example, and have norm 2, but : 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, . If all layers satisfy uniform bound with the same , the bound’s factor is at most ; 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 versus at output. With ReLU and scale 4, the norms are approximately and . 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 , whitened inputs, aligned diagonal matrices, and equal scalar factors . With loss , gradient flow maintains balance between factors and, for ,
Time is normalized to unit flow rate. For a logistic equation appears; for the exponent changes and the curve is different. If , the mode grows toward ; with small initial scale it can change very slowly. At and , the point is stationary: one cannot divide by to infer that it leaves zero.
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.
Global-norm clipping conceptually concatenates gradients of all parameters. With threshold and finite norm,
For the zero vector is retained; if , every finite gradient becomes zero. Global clipping preserves direction when and reduces norm to at most . In SGD without momentum or decay, ; 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 can change direction and does not bound total norm by . 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, 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.
"""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.
"""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)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 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 . 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 and , global clipping gives , while coordinate clipping gives and changes direction.
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 outimport 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
Step 1 of 4. If Dᵏ is diagonal with derivatives of φ at layer k, what is the Jacobian of hᵏ with respect to hᵏ⁻¹?
import math
import numpy as np
def clip_grad_norm(params, max_norm):
pass