Module contents
Lesson 19 of 22Advanced 100 min

Diagnostics II: activations, gradients and updates layer by layer

Instrument networks layer by layer and interpret activation statistics, gradient norms and actual update-to-weight ratios, while examining plasticity and limitations of loss-landscape slices.

After this lesson you can

  • Instrument a model with hooks and record layer statistics at a controlled frequency.
  • Interpret activation and gradient histograms and test hypotheses about saturation and scale.
  • Monitor update-to-weight ratios and distinguish simple SGD from Adam and momentum.
  • Diagnose layer-level failure cases using controlled interventions.
  • Use loss-landscape slices while recognizing what they cannot show.

Before you start

When loss hides a stalled layer

Two networks can show the same loss while one has a frozen layer or a succession of saturated activations. A global curve compresses thousands of variables into one scalar. To decide which intervention is worthwhile, observe together what enters and leaves each layer, the gradient it receives, and how much it actually changes.

InteractiveLayer-by-layer health

Real measurements from a five-hidden-layer MLP on Fashion-MNIST. Each row describes that layer’s activations and matrix at the same step; conditions are measured combinations, not invented independent controls.

Layer 1
Range [0, 4]; outside: 1.0 %
‖W‖ 11.265
‖∇W‖ 11.651
Change 0.350
‖ΔW‖/‖W‖
Ratio: 0.031; axis: 10⁻⁸ to 10²
Mean 0.593 · std. 0.909
Inactive in batch: 0.0 %
Sigmoid saturation: not applicable
Layer 2
Range [0, 4]; outside: 1.6 %
‖W‖ 11.310
‖∇W‖ 4.245
Change 0.127
‖ΔW‖/‖W‖
Ratio: 0.011; axis: 10⁻⁸ to 10²
Mean 0.567 · std. 0.998
Inactive in batch: 3.1 %
Sigmoid saturation: not applicable
Layer 3
Range [0, 4]; outside: 2.4 %
‖W‖ 11.155
‖∇W‖ 5.370
Change 0.161
‖ΔW‖/‖W‖
Ratio: 0.014; axis: 10⁻⁸ to 10²
Mean 0.639 · std. 1.088
Inactive in batch: 6.3 %
Sigmoid saturation: not applicable
Layer 4
Range [0, 4]; outside: 3.4 %
‖W‖ 11.333
‖∇W‖ 6.181
Change 0.185
‖ΔW‖/‖W‖
Ratio: 0.016; axis: 10⁻⁸ to 10²
Mean 0.860 · std. 1.219
Inactive in batch: 6.3 %
Sigmoid saturation: not applicable
Layer 5
Range [0, 4]; outside: 7.0 %
‖W‖ 11.505
‖∇W‖ 6.257
Change 0.188
‖ΔW‖/‖W‖
Ratio: 0.016; axis: 10⁻⁸ to 10²
Mean 1.023 · std. 1.652
Inactive in batch: 17.2 %
Sigmoid saturation: not applicable

One seed, 1024 training images, batch 64, and up to 60 SGD updates. Each histogram is scaled separately to its maximum: bars show shape, not heights comparable across layers. The outside-range fraction is indicated; histograms of non-finite activations are omitted.

A unit inactive in this batch can activate in another. Sigmoid saturation is the fraction of values below 0.01 or above 0.99. An absent gradient is not a zero norm. The ratio compares actual post-step change with prior weight norm and excludes biases.

Step1
Batch loss4.0984
Run statusComplete
Compare histograms and measurements from recorded training runs. Each row is a layer and each condition retains its protocol.

Activation logging starts with a fixed diagnostic batch chosen without consulting test data. Observe each output’s mean, standard deviation, and histogram, and keep training steps separate from evaluation mode. One batch summary is a sample: repeat with other examples before claiming a symptom persists.

For ReLU, “zero fraction” counts elements, while “units inactive in the batch” counts channels that are zero in all observed examples and positions. They are different. A unit inactive in one batch may activate in another; even inactivity on all observed examples does not prove it is dead for every possible input. For sigmoid we can define outputs below 0.01 or above 0.99 as saturated. This is a diagnostic threshold, not a mathematical boundary of death.

One value per layer without turning training into measurement

A PyTorch hook can observe a module’s output or associated gradient. On sampling steps, detach outputs from the graph and reduce statistics on device. Avoid .item(), printing, or immediate CPU copies inside a CUDA hook: reading on the host can force a device wait. Batch data and transfer when presenting or saving the report. Training still pays for reductions and capture; instrumentation is not free.

The implementation below has an explicit lifecycle: handles are installed, data recorded every k steps, and handles removed with remove() even on exception. Module names identify what is measured; if a module is reused, record every call or define aggregation. Do not retain tensors with their graph throughout training. Hooks and asynchronous CUDA execution explain the tools; here the focus is interpreting readouts.

Second moment versus standard deviation

For random activation aa, the second moment is q=E[a2]q=\mathbb E[a^2] and centered variance is q−E[a]2q-\mathbb E[a]^2. ReLU output is nonnegative, so its mean is not generally zero. With independent centered weights, zero biases, and approximately symmetric preactivations, He initialization is designed to approximately preserve second moment through ReLU layers, not guarantee constant standard deviation in every finite network.

The lab compares prediction with measurements of a 30-layer MLP before and after training. Disagreement is informative too: trained weights no longer satisfy initial independence assumptions, and finite width or batch size introduces variation. Normalization can stabilize scale under its own conditions but does not itself guarantee every useful gradient reaches every layer. Review variance propagation and He for the derivation.

Gradient, weight, and actual change

Gradient norm indicates loss sensitivity to each tensor, but comparing raw norms favors tensors with more elements. Complement ∥g∥2\|g\|_2 with ∥g∥2/n\|g\|_2/\sqrt{n} and ∥g∥2/∥w∥2\|g\|_2/\|w\|_2 when the denominator is nonzero. Keep weights and biases separate. A small gradient can reflect convergence, parameterization scale, or blockage: interpretation requires context and an intervention.

The update-to-weight ratio of a tensor before the step is

rt=∥wt+1−wt∥2∥wt∥2.r_t=\frac{\|w_{t+1}-w_t\|_2}{\|w_t\|_2}.

If ∥wt∥2=0\|w_t\|_2=0, this ratio is undefined; also report absolute change norm. In plain SGD without momentum, clipping, or regularization, Δw=−ηg\Delta w=-\eta g and therefore r=η∥g∥2/∥w∥2r=\eta\|g\|_2/\|w\|_2. With ∥w∥=10\|w\|=10, ∥g∥=0,5\|g\|=0,5, and η=0,04\eta=0,04, the result is 0.002.

InteractiveUpdate thermometer

This MLP trains when the control moves: 24 fixed synthetic pairs, 2→8→8→1 network with ReLU, MSE and full-batch SGD without momentum or decay. Each rate starts from the same seed and weights.

Measured per-matrix ratio: ‖W after − W before‖/‖W before‖. Biases are excluded; if prior norm is zero the ratio is undefined. Exactly zero changes are omitted on log scale. Gray lines mark 3×10⁻⁴ and 3×10⁻³ to guide around 10⁻³, without guaranteeing good training.

Preparing charts…

x₁,x₂ uniform on [−1,1]; y=(x₁+0.5x₂²)/2. Weights initialize uniformly on [−√(6/fan-in), √(6/fan-in)] and biases at zero. Curves omit the first non-finite step if it occurs; they do not extrapolate to Adam or other architectures.

Finite steps100
Statuscomplete
Last observed loss0.01805
Last ratio matrix 10.000171
Last ratio matrix 20.000301
Last ratio matrix 30.000535
Change learning rate and observe a network trained live. The reference is guidance, not a condition for success.

CS231n presents 10−310^{-3} as an approximate reference per tensor. It is not a universal law: parameterization, architecture, training stage, and optimizer matter. If rr appears large, check loss evolution, non-finite values, and the effect of reducing rate; if small, investigate whether the layer has converged, is frozen, or receives insufficient signal.

For Adam, if the entire gradient history is multiplied by a positive constant cc, corrected moments transform as m↦cmm\mapsto cm and v↦c2vv\mapsto c^2v. Ignoring epsilon, decay, and other transforms, m/vm/\sqrt v is unchanged in components with v>0v>0; with v=0v=0 the ideal expression without epsilon is undefined. In the real algorithm epsilon, prior history, clipping, and weight decay can break this invariance. Thus rate affects step scale but does not alone determine the ratio. With momentum or AdamW, measure actual change before and after optimizer.step() instead of substituting η∥g∥\eta\|g\|.

Weights, rank, and plasticity

Weight norms and singular values help locate scale growth or nearly degenerate transformations. A weight matrix’s spectrum differs from that of the activation matrix obtained from data: they answer different questions. There are also several definitions of effective rank. If using stable rank ∥A∥F2/∥A∥22\|A\|_F^2/\|A\|_2^2 for a nonzero matrix, state the formula and dataset used; for a zero matrix the ratio is undefined.

Loss of plasticity describes reduced ability to learn new tasks during continual training, not merely higher loss at one step. Dohare and colleagues studied changing tasks and observed associations between plasticity loss, weight magnitude, sparsely active units, and representation diversity. In their incremental CIFAR-100 classification, Figure 2 averages 30 runs: the reference system degrades after 40 classes and the proportion of units active less than 1% of the time increases.

Selectively reinitializing units or layers introduces diversity but also erases some learning and can require resetting optimizer state. Shrink and Perturb shrinks weights and adds noise at a declared strength and frequency. Results depend on task and hyperparameters: the same study reports that in Ant this intervention did not markedly improve over L2 regularization. Lower rank and more inactive units are signals to investigate, not universal causal proof.

To test plasticity, change the objective after a fixed budget and measure learning on each new task using separate evaluation examples. Compare one network continuing with its weights, one reinitializing parameters, and one shrinking and perturbing: record seed, affected weights, and optimizer moments. After each change also observe norms, inactive channels, and activation rank on a declared probe. Compare curves under the same budget and do not infer causality from correlation. Reinitialization can improve adaptation to a new task while degrading prior learning: measure both if retention matters.

The reproducible short run below has five synthetic tasks, 40 steps per task, and three seeds; Adam resets for every strategy at task changes. Mean validation MSE on the final task was 0.05824 for continuing, 0.18590 for reinitializing the entire network, and 0.05451 for shrinking and perturbing. In this sample reinitialization did not improve adaptation. The validation probe changes with each task and the experiment does not measure retention of prior tasks: these observations establish no law about plasticity and do not reproduce a paper’s budget.

Blind diagnosis

InteractiveWhich layer is unhealthy?

Hidden panel from a real test. Step 1 and five hidden matrices are shown. Some interventions lack paired runs and cannot be tested; panel shape alone does not prove a unique cause.

Before

Layer 1
Range [0, 4]; outside: 17.4 %
‖W‖ 33.794
‖∇W‖ 1080.117
Change 32.404
‖ΔW‖/‖W‖
Ratio: 0.959; axis: 10⁻⁸ to 10²
Mean 1.780 · std. 2.728
Inactive in batch: 0.0 %
Sigmoid saturation: not applicable
Layer 2
Range [0, 4]; outside: 33.1 %
‖W‖ 33.930
‖∇W‖ 397.683
Change 11.930
‖ΔW‖/‖W‖
Ratio: 0.352; axis: 10⁻⁸ to 10²
Mean 5.107 · std. 8.986
Inactive in batch: 3.1 %
Sigmoid saturation: not applicable
Layer 3
Range [0, 4]; outside: 45.7 %
‖W‖ 33.466
‖∇W‖ 511.014
Change 15.330
‖ΔW‖/‖W‖
Ratio: 0.458; axis: 10⁻⁸ to 10²
Mean 17.256 · std. 29.369
Inactive in batch: 6.3 %
Sigmoid saturation: not applicable
Layer 4
Range [0, 4]; outside: 58.6 %
‖W‖ 33.998
‖∇W‖ 597.652
Change 17.930
‖ΔW‖/‖W‖
Ratio: 0.527; axis: 10⁻⁸ to 10²
Mean 69.669 · std. 98.714
Inactive in batch: 6.3 %
Sigmoid saturation: not applicable
Layer 5
Range [0, 4]; outside: 52.7 %
‖W‖ 34.514
‖∇W‖ 611.269
Change 18.338
‖ΔW‖/‖W‖
Ratio: 0.531; axis: 10⁻⁸ to 10²
Mean 248.588 · std. 401.498
Inactive in batch: 17.2 %
Sigmoid saturation: not applicable

Short Fashion-MNIST runs: same seed and batch indices; the panel compares step 1 with step 1. The control changes only the condition named in each case; BatchNorm is an additional intervention where measured. Bars are rescaled per histogram; the ratio is measured on weights and the gradient can be absent when a layer is frozen.

Distinct interventions tried0
Observed initial loss899.4091
Inspect the dashboard, choose an intervention, and compare with its recorded run. One signal can admit several hypotheses.

A layer with near-zero gradient can be saturated, receive improperly scaled inputs, or be near an optimum. A layer frozen via requires_grad=False usually has gradient None, not necessarily a zero tensor. If a parameter receives a gradient but is excluded from the optimizer, its gradient can be nonzero and its change zero. These situations should not be depicted as equivalent.

To compare interventions, preserve seed, data, batch order, and budget, changing only what you want to study. A tenfold rate need not be too high; evaluate loss, gradients, and update ratio for the particular run. If two conditions are indistinguishable on the dashboard, report the ambiguity.

A small window into the landscape

A slice fixes a point θ\theta and two directions d1,d2d_1,d_2, and evaluates L(θ+αd1+βd2)L(\theta+\alpha d_1+\beta d_2) on a grid. Li and colleagues normalize each filter of each direction by the norm of the corresponding filter of θ\theta, so scale differences do not dominate comparison.

Choose and publish directions, treatment of zero-norm filters, evaluation set, and model state. Freeze dropout and avoid updating BN statistics when evaluating the slice. A two-dimensional surface represents only the chosen plane: it can hide steep directions and does not prove two minima generalize equally. Filter normalization helps compare scales but does not turn a projection into a full-space view; revisit landscape visualization.

Labs

The first cell checks SGD calculations and approximate invariance of one Adam step. It is deliberately small for browser execution. Local labs instrument a network, compare measured propagation with prediction, and study adaptation to changing objectives. Their short runs feed figures where applicable; the full budget remains available to explore.

[ ]Two ratios and an invariance with limitsBrowser
import numpy as np

w = np.array([10.])
g = np.array([0.5])
eta = 0.04
ratio = np.linalg.norm(-eta*g)/np.linalg.norm(w)
print('SGD, razón:', ratio)
assert np.isclose(ratio, 0.002)

# Primer paso Adam, momentos corregidos iguales a g y g².
def first_adam_step(gradient, rate, epsilon):
    return -rate*gradient/(np.abs(gradient)+epsilon)

for epsilon in (0., 0.1):
    delta = first_adam_step(np.array([0.4]), eta, epsilon)
    scaled = first_adam_step(np.array([4.]), eta, epsilon)
    print('epsilon', epsilon, 'pasos', delta[0], scaled[0])
assert np.allclose(first_adam_step(g, eta, 0), first_adam_step(10*g, eta, 0))
assert not np.allclose(first_adam_step(g, eta, .1), first_adam_step(10*g, eta, .1))
[ ]Diagnostic dashboard and measured propagationLocal GPU
"""Clínica de activaciones, gradientes y actualizaciones en Fashion-MNIST.

Las estadísticas se construyen en el dispositivo cada k pasos y se copian en
un único bloque al acabar cada corrida. ORYON_VERIFY_SHORT=1 reduce anchura,
profundidad, ejemplos y pasos. No usa el test oficial. Los tiempos son de esta
ejecución y dependen del equipo y de la carga compartida.
"""
import json
import math
import os
import time
from pathlib import Path

import numpy as np
import torch
from torch import nn
from torchvision.datasets import FashionMNIST

torch.set_num_threads(1)
SHORT = os.getenv('ORYON_VERIFY_SHORT') == '1'
DEVICE = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
TRAIN_SIZE, VALID_SIZE = (1024, 256) if SHORT else (5000, 1000)
WIDTH, DEPTH, STEPS, EVERY, BATCH = (64, 5, 60, 15, 64) if SHORT else (256, 8, 600, 50, 128)
SEED = 19191
INIT_SEED, BATCH_SEED = 19191, 19192

FashionMNIST.mirrors = ['https://raw.githubusercontent.com/zalandoresearch/fashion-mnist/master/data/fashion/']
dataset = FashionMNIST(Path.home()/'.cache'/'atlas-data', train=True, download=True)
permutation = torch.randperm(len(dataset), generator=torch.Generator().manual_seed(19190))
train_ids, validation_ids = permutation[:TRAIN_SIZE], permutation[TRAIN_SIZE:TRAIN_SIZE+VALID_SIZE]
assert not set(train_ids.tolist()).intersection(validation_ids.tolist())
raw_train = dataset.data[train_ids].reshape(TRAIN_SIZE, -1).float()/255
raw_valid = dataset.data[validation_ids].reshape(VALID_SIZE, -1).float()/255
mean, std = raw_train.mean(), raw_train.std(unbiased=False)
train_x = ((raw_train-mean)/(std+1e-6)).to(DEVICE)
valid_x = ((raw_valid-mean)/(std+1e-6)).to(DEVICE)
train_y, valid_y = dataset.targets[train_ids].to(DEVICE), dataset.targets[validation_ids].to(DEVICE)
generator = torch.Generator().manual_seed(BATCH_SEED)
indices = torch.randint(TRAIN_SIZE, (STEPS, BATCH), generator=generator)


class MLP(nn.Module):
    def __init__(self, width, depth, activation='relu', init_scale=1., batchnorm=False, frozen=-1, dead=-1):
        super().__init__()
        torch.manual_seed(INIT_SEED)
        sizes = [784] + [width]*depth
        self.layers = nn.ModuleList([nn.Linear(sizes[i], sizes[i+1]) for i in range(depth)])
        self.norms = nn.ModuleList([nn.BatchNorm1d(width) if batchnorm else nn.Identity() for _ in range(depth)])
        self.activations = nn.ModuleList([nn.ReLU() if activation == 'relu' else nn.Sigmoid() for _ in range(depth)])
        self.output = nn.Linear(width, 10)
        for layer in self.layers:
            nn.init.kaiming_normal_(layer.weight, nonlinearity='relu')
            with torch.no_grad(): layer.weight.mul_(init_scale)
            nn.init.zeros_(layer.bias)
        nn.init.xavier_normal_(self.output.weight)
        nn.init.zeros_(self.output.bias)
        if frozen >= 0:
            for parameter in self.layers[frozen].parameters(): parameter.requires_grad_(False)
        if dead >= 0:
            # Una capa muerta demostrable: entradas cero y bias negativo.
            with torch.no_grad():
                self.layers[dead].weight.zero_()
                self.layers[dead].bias.fill_(-1.)

    def forward(self, x):
        for layer, norm, act in zip(self.layers, self.norms, self.activations):
            x = act(norm(layer(x)))
        return self.output(x)


class Diagnostics:
    """Hooks por activación sin .item(), .cpu(), impresiones ni sincronización dentro del hook."""
    def __init__(self, model, activation):
        self.model, self.activation = model, activation
        self.capture = False
        self.current = {}
        self.handles = [module.register_forward_hook(self._hook(i)) for i, module in enumerate(model.activations)]

    def _hook(self, index):
        def hook(module, args, output):
            if not self.capture: return
            x = output.detach()
            # MLP (N,D): inactiva en el lote si nunca fue positiva.
            inactive = (x <= 0).all(dim=0).float().mean() if self.activation == 'relu' else x.new_tensor(float('nan'))
            saturated = ((x < .01) | (x > .99)).float().mean() if self.activation == 'sigmoid' else x.new_tensor(float('nan'))
            high = 4. if self.activation == 'relu' else 1.
            summary = torch.stack((x.mean(), x.std(unbiased=False), x.square().mean().sqrt(),
                                   (x == 0).float().mean(), inactive, saturated,
                                   (x < 0).float().mean(), (x > high).float().mean()))
            hist = torch.histc(x.float(), bins=20, min=0, max=high)
            self.current[index] = {'activation':summary, 'histogram':hist, 'range':[0., high]}
            if output.requires_grad:
                def backward_hook(grad):
                    g = grad.detach()
                    self.current[index]['activation_gradient'] = torch.stack((g.norm(), g.square().mean().sqrt(),
                        (g < -.01).float().mean(), (g > .01).float().mean()))
                    self.current[index]['gradient_histogram'] = torch.histc(g.float(), bins=20, min=-.01, max=.01)
                output.register_hook(backward_hook)
        return hook

    def close(self):
        for handle in self.handles: handle.remove()


def pack(tensors):
    """Una sola transferencia de todos los resúmenes y pesos del caso."""
    sizes = [t.numel() for t in tensors]
    flat = torch.cat([t.detach().reshape(-1).to(dtype=torch.float64) for t in tensors]).cpu().numpy()
    result, offset = [], 0
    for size in sizes:
        result.append(flat[offset:offset+size])
        offset += size
    return result


def finite(value):
    value = float(value)
    return value if math.isfinite(value) else None


def run(case, instrument=True):
    activation = case.get('activation','relu')
    model = MLP(WIDTH, DEPTH, activation, case.get('init_scale',1.), case.get('batchnorm',False),
                case.get('frozen',-1), case.get('dead',-1)).to(DEVICE)
    optimizer = torch.optim.SGD((p for p in model.parameters() if p.requires_grad), lr=case.get('lr',.03))
    diagnostics = Diagnostics(model, activation) if instrument else None
    pending, schema = [], []
    # Se sincroniza únicamente en las fronteras de cronometraje, no dentro de los hooks.
    if DEVICE.type == 'cuda': torch.cuda.synchronize(DEVICE)
    start = time.perf_counter()
    try:
        for step in range(1, STEPS+1):
            sample = instrument and (step == 1 or step % EVERY == 0 or step == STEPS)
            if sample:
                diagnostics.capture = True
                diagnostics.current = {}
                before = [layer.weight.detach().clone() for layer in model.layers]
            model.train()
            ids = indices[step-1].to(DEVICE)
            optimizer.zero_grad(set_to_none=True)
            loss = nn.functional.cross_entropy(model(train_x[ids]),train_y[ids])
            loss.backward()
            if sample:
                weights = [layer.weight.detach().norm() for layer in model.layers]
                gradients = [layer.weight.grad.detach().norm() if layer.weight.grad is not None else None for layer in model.layers]
            optimizer.step()
            if sample:
                diagnostics.capture = False
                offsets = []
                for i, layer in enumerate(model.layers):
                    info = diagnostics.current[i]
                    names = ['activation','histogram','activation_gradient','gradient_histogram']
                    ids_for_fields = {}
                    for name in names:
                        item = info.get(name)
                        ids_for_fields[name] = None if item is None else len(pending)
                        if item is not None: pending.append(item)
                    ids_for_fields['weight'] = len(pending)
                    # Gradiente None se conserva como None, no se dibuja como cero.
                    pending.append(torch.stack((weights[i], (layer.weight.detach()-before[i]).norm())))
                    ids_for_fields['gradient'] = None if gradients[i] is None else len(pending)
                    if gradients[i] is not None: pending.append(gradients[i].reshape(1))
                    offsets.append({'fields':ids_for_fields,'hist_range':info['range']})
                schema.append({'step':step,'loss_index':len(pending),'layers':offsets})
                pending.append(loss.detach().reshape(1))
        model.eval()
        with torch.no_grad():
            logits = model(valid_x)
            val_loss = nn.functional.cross_entropy(logits,valid_y)
            val_accuracy = (logits.argmax(1)==valid_y).float().mean()
        if DEVICE.type == 'cuda': torch.cuda.synchronize(DEVICE)
        elapsed = time.perf_counter()-start
        # Pesos completos para espectro final, procesado en CPU después del entrenamiento.
        final_weights = [layer.weight.detach() for layer in model.layers]
        pending += [val_loss.reshape(1),val_accuracy.reshape(1)] + final_weights
        values = pack(pending)
        result = []
        for entry in schema:
            layers = []
            for info in entry['layers']:
                fields=info['fields']
                activation_stats = values[fields['activation']]
                weight_norm, delta_norm = values[fields['weight']]
                grad = None if fields['gradient'] is None else finite(values[fields['gradient']][0])
                g_act = None if fields['activation_gradient'] is None else [finite(v) for v in values[fields['activation_gradient']]]
                g_hist = None if fields['gradient_histogram'] is None else [finite(v) for v in values[fields['gradient_histogram']]]
                layers.append({'activation_mean':finite(activation_stats[0]),'activation_std':finite(activation_stats[1]),
                    'activation_rms':finite(activation_stats[2]),'zero_fraction':finite(activation_stats[3]),
                    'inactive_units_on_batch':finite(activation_stats[4]),'sigmoid_saturated_fraction':finite(activation_stats[5]),
                    'hist_under_fraction':finite(activation_stats[6]),'hist_over_fraction':finite(activation_stats[7]),
                    'histogram':[finite(x) for x in values[fields['histogram']]],'histogram_range':info['hist_range'],
                    'activation_gradient_norm_rms_outside':g_act,'gradient_histogram':g_hist,'gradient_histogram_range':[-.01,.01],
                    'weight_norm':finite(weight_norm),'weight_gradient_norm':grad,
                    'actual_update_norm':finite(delta_norm),
                    'update_ratio':finite(delta_norm/weight_norm) if np.isfinite(weight_norm) and weight_norm > 0 else None})
            result.append({'step':entry['step'],'training_loss':finite(values[entry['loss_index']][0]),'layers':layers})
        val_index = len(values)-DEPTH-2
        spectra = []
        for layer, raw in zip(model.layers,values[-DEPTH:]):
            matrix=raw.reshape(layer.weight.shape)
            if np.isfinite(matrix).all():
                singular=np.linalg.svd(matrix,compute_uv=False)
                spectra.append({'spectral_norm':finite(singular[0]),'frobenius_norm':finite(np.linalg.norm(singular)),
                                'stable_rank':finite((singular@singular)/(singular[0]**2)) if singular[0]>0 else None})
            else: spectra.append({'spectral_norm':None,'frobenius_norm':None,'stable_rank':None})
        status = 'complete' if (not instrument or (result and all(row['training_loss'] is not None for row in result))) and finite(values[val_index][0]) is not None else 'nonfinite_observed'
        validation_loss = finite(values[val_index][0])
        return {'id':case['id'],'settings':case,'status':status,'history':result,
                'validation_loss':validation_loss,'validation_accuracy':finite(values[val_index+1][0]) if validation_loss is not None else None,
                'final_weight_spectra':spectra,'elapsed_seconds':elapsed,'instrumented':instrument}
    finally:
        if diagnostics is not None: diagnostics.close()
        del model,optimizer
        if DEVICE.type == 'cuda': torch.cuda.empty_cache()


def variance_study():
    """30 capas, evolución al inicio/final, predicción del segundo momento en ReLU."""
    result = []
    study_depth, study_width, study_steps = 30, (64 if SHORT else 256), (5 if SHORT else 50)
    for scale in (.5,1.,3.):
        for use_bn in (False,True):
            model = MLP(study_width,study_depth,'relu',scale,use_bn).to(DEVICE)
            probe = Diagnostics(model,'relu')
            optimizer = torch.optim.SGD(model.parameters(),lr=.01)
            captures=[]
            updates=[]
            try:
                def fixed_probe():
                    # Misma sonda disjunta de validación, estadísticas de lote
                    # para BN y restauración de sus buffers tras la medición.
                    snapshots=[(bn.running_mean.clone(),bn.running_var.clone(),bn.num_batches_tracked.clone())
                               for bn in model.norms if isinstance(bn,nn.BatchNorm1d)]
                    model.train()
                    probe.capture=True
                    probe.current={}
                    with torch.no_grad(): model(valid_x[:BATCH])
                    measurement=[probe.current[i]['activation'][:3] for i in range(study_depth)]
                    for bn,(m,v,n) in zip((b for b in model.norms if isinstance(b,nn.BatchNorm1d)),snapshots):
                        bn.running_mean.copy_(m); bn.running_var.copy_(v); bn.num_batches_tracked.copy_(n)
                    probe.capture=False
                    return measurement
                captures.append(fixed_probe())
                for step in range(study_steps):
                    model.train()
                    ids=indices[step % STEPS].to(DEVICE)
                    optimizer.zero_grad(set_to_none=True)
                    loss=nn.functional.cross_entropy(model(train_x[ids]),train_y[ids])
                    loss.backward()
                    save_update = step in (0, study_steps-1)
                    if save_update:
                        before = [layer.weight.detach().clone() for layer in model.layers]
                    optimizer.step()
                    if save_update:
                        updates.append([torch.stack((old.norm(), (layer.weight.detach()-old).norm()))
                                        for layer,old in zip(model.layers,before)])
                captures.append(fixed_probe())
                flat = pack([item for batch in captures for item in batch] + [item for batch in updates for item in batch])
                phases = [[{'mean':finite(v[0]),'std':finite(v[1]),'rms':finite(v[2])} for v in flat[k*study_depth:(k+1)*study_depth]] for k in range(2)]
                update_records = []
                for k, update_step in enumerate((1,study_steps)):
                    values = flat[(2+k)*study_depth:(3+k)*study_depth]
                    update_records.append({'step':update_step, 'ratio':[finite(v[1]/v[0]) if np.isfinite(v[0]) and v[0]>0 else None for v in values]})
                result.append({'init_scale':scale,'batchnorm':use_bn,'steps':study_steps,'initial':phases[0],'final':phases[1],
                    'updates':update_records,
                    'probe':'Mismo lote de validación disjunta, BN en modo train con buffers restaurados antes y después de entrenar.',
                    'theoretical_rms_multiplier_per_relu_layer':scale,
                    'theory_scope':'Solo predicción aproximada para ReLU sin BN, pesos i.i.d. centrados e hipótesis de simetría; no es predicción con BN.'})
            finally:
                probe.close()
                del model,optimizer
                if DEVICE.type == 'cuda': torch.cuda.empty_cache()
    return result


def main():
    cases=[{'id':'control','lr':.03}, {'id':'sigmoide','activation':'sigmoid','lr':.03},
           {'id':'he_x3','init_scale':3.,'lr':.03}, {'id':'lr_x10','lr':.3},
           {'id':'congelada','frozen':2,'lr':.03}, {'id':'muerta','dead':2,'lr':.03},
           {'id':'he_x3_bn','init_scale':3.,'batchnorm':True,'lr':.03},
           {'id':'sigmoide_bn','activation':'sigmoid','batchnorm':True,'lr':.03}]
    results=[]
    for case in cases:
        row=run(case)
        results.append(row)
        print(case['id'],row['status'],'pérdida de validación',row['validation_loss'],flush=True)
    # Comparación de coste emparejada: un solo ensayo, no valor universal.
    uninstrumented=run(cases[0], instrument=False)
    measurements={'with_hooks_seconds':results[0]['elapsed_seconds'],'without_hooks_seconds':uninstrumented['elapsed_seconds'],
                  'scope':'Una ejecución por variante, sin warmup independiente; el coste depende del dispositivo y de su carga.'}
    study=variance_study()
    output={'dataset':'Fashion-MNIST train oficial, particiones disjuntas','mode':'short' if SHORT else 'full',
            'device':str(DEVICE),'torch':torch.__version__,'train_examples':TRAIN_SIZE,'validation_examples':VALID_SIZE,
            'width':WIDTH,'depth':DEPTH,'steps':STEPS,'batch_size':BATCH,'capture_every':EVERY,
            'seed':SEED,'batch_seed':BATCH_SEED,'train_mean':float(mean),'train_std':float(std),
            'protocol':'SGD sin momentum ni decay; inicialización y lotes emparejados; resumen en dispositivo y transferencia en bloque al final. Test oficial sin consultar.',
            'records':results,'instrumentation_timing':measurements,'variance_study':study}
    target=Path(os.getenv('ORYON_DIAGNOSTICS_OUTPUT','diagnostics-fashion.json'))
    target.parent.mkdir(parents=True,exist_ok=True)
    target.write_text(json.dumps(output,ensure_ascii=False,indent=2,allow_nan=False),encoding='utf-8')
    import matplotlib
    matplotlib.use('Agg')
    import matplotlib.pyplot as plt
    fig, axes = plt.subplots(4,len(results),figsize=(3*len(results),11),constrained_layout=True,squeeze=False)
    for column,row in enumerate(results):
        visible = next((entry for entry in reversed(row['history']) if entry['training_loss'] is not None),row['history'][0])
        layers=visible['layers']
        hist=np.array([[float(v) if v is not None else np.nan for v in layer['histogram']] for layer in layers])
        # Cuentas por capa; cada fila usa un rango explícito, 0..4 en ReLU y 0..1 en sigmoide.
        axes[0,column].imshow(hist,aspect='auto',origin='lower',interpolation='nearest')
        axes[0,column].set_title(f"{row['id']}\npaso {visible['step']} ({row['status']})",fontsize=8)
        axes[0,column].set_xlabel('Bin activación')
        depths=np.arange(1,len(layers)+1)
        for axis,key in ((axes[1,column],'activation_rms'),(axes[3,column],'update_ratio')):
            vals=[layer[key] if layer[key] is not None and layer[key]>0 else np.nan for layer in layers]
            axis.plot(depths,vals,marker='.')
            axis.set_xlim(.5,len(layers)+.5)
            axis.set_yscale('log')
            if not np.isfinite(vals).any():
                axis.set_ylim(1e-4,1e-2)
                axis.text(.5,.5,'Sin valor positivo',transform=axis.transAxes,ha='center',va='center',fontsize=7)
            axis.grid(alpha=.2); axis.set_xlabel('Capa')
        relative=[]
        for layer in layers:
            w,g=layer['weight_norm'],layer['weight_gradient_norm']
            relative.append(g/w if w is not None and g is not None and w>0 and g>0 else np.nan)
        axes[2,column].plot(depths,relative,marker='.')
        axes[2,column].set_xlim(.5,len(layers)+.5)
        axes[2,column].set_yscale('log')
        if not np.isfinite(relative).any():
            axes[2,column].set_ylim(1e-4,1e-2)
            axes[2,column].text(.5,.5,'Sin valor positivo',transform=axes[2,column].transAxes,ha='center',va='center',fontsize=7)
        axes[2,column].grid(alpha=.2); axes[2,column].set_xlabel('Capa')
        axes[3,column].axhline(1e-3,color='gray',linestyle=':',linewidth=.8)
    for i,label in enumerate(('Histograma por capa','RMS activación','‖g‖/‖w‖','‖Δw‖/‖w‖')):
        axes[i,0].set_ylabel(label)
    fig.suptitle('Escala log: los valores cero y no definidos se omiten; consulta el JSON para distinguirlos.',fontsize=10)
    figure=target.with_suffix('.png')
    fig.savefig(figure,dpi=120)
    plt.close(fig)
    print('Panel guardado en',figure,flush=True)
    print('Guardado en',target,flush=True)
    if DEVICE.type=='cuda': torch.cuda.empty_cache()


if __name__=='__main__': main()
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.
[ ]Plasticity under changing objectivesLocal GPU
"""Plasticidad en tareas sintéticas cambiantes, con intervenciones emparejadas.

ORYON_VERIFY_SHORT=1 verifica el flujo. El resto es una comparación mayor para
el lector, no una reproducción del presupuesto ni de los resultados de un paper.
Se reinicia Adam en cada tarea para todas las condiciones.
"""
import json
import math
import os
from pathlib import Path
import numpy as np
import torch
from torch import nn

torch.set_num_threads(1)
short = os.getenv('ORYON_VERIFY_SHORT') == '1'
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
tasks, steps, width, seeds = (5, 40, 32, (11, 23, 37)) if short else (10, 250, 128, (11, 23, 37))
dimension, train_size, validation_size, batch_size = 8, 256, 128, 64


class Model(nn.Module):
    def __init__(self, init_seed):
        super().__init__()
        torch.manual_seed(init_seed)
        self.layers=nn.ModuleList([nn.Linear(dimension,width),nn.Linear(width,width)])
        self.output=nn.Linear(width,1)
        for layer in self.layers:
            nn.init.kaiming_normal_(layer.weight,nonlinearity='relu'); nn.init.zeros_(layer.bias)
        nn.init.xavier_normal_(self.output.weight); nn.init.zeros_(self.output.bias)

    def forward(self,x,features=False):
        for layer in self.layers: x=torch.relu(layer(x))
        out=self.output(x)
        return (out,x) if features else out


def task_data(seed, task):
    """La tarea cambia el vector maestro; ejemplos y lotes se emparejan."""
    generator=torch.Generator().manual_seed(190000+seed*100+task)
    teacher=torch.randn(dimension,1,generator=generator)
    x=torch.randn(train_size+validation_size,dimension,generator=generator)
    y=torch.tanh(x@teacher/math.sqrt(dimension))
    train_x,valid_x=x[:train_size].to(device),x[train_size:].to(device)
    train_y,valid_y=y[:train_size].to(device),y[train_size:].to(device)
    indices=torch.randint(train_size,(steps,batch_size),generator=generator)
    return train_x,train_y,valid_x,valid_y,indices


def evaluate(model,x,y):
    model.eval()
    with torch.no_grad():
        pred,features=model(x,features=True)
        loss=(pred-y).square().mean()
        dead=(features<=0).all(dim=0).float().mean()
        weight_norm=torch.stack([p.detach().norm() for p in model.parameters() if p.ndim==2]).norm()
        # Transferencia una sola vez para las métricas de esta tarea; SVD en CPU.
        size=features.numel()
        packed=torch.cat((loss.reshape(1),dead.reshape(1),weight_norm.reshape(1),features.reshape(-1))).cpu().numpy()
        matrix=packed[3:].reshape(features.shape)
    if not np.isfinite(packed).all():
        return {'validation_mse':None,'inactive_units_on_probe':None,'weight_norm':None,'effective_rank':None}
    singular=np.linalg.svd(matrix-matrix.mean(axis=0),compute_uv=False)
    if singular.sum()==0: effective_rank=0.
    else:
        probs=singular[singular>0]/singular.sum()
        effective_rank=float(np.exp(-np.sum(probs*np.log(probs))))
    assert size==len(packed)-3
    return {'validation_mse':float(packed[0]),'inactive_units_on_probe':float(packed[1]),
            'weight_norm':float(packed[2]),'effective_rank':effective_rank}


def run(seed, strategy):
    model=Model(200000+seed*100).to(device)
    history=[]
    for task in range(tasks):
        x,y,vx,vy,indices=task_data(seed,task)
        if task>0 and strategy in ('reiniciar','encoger_perturbar'):
            reference=Model(200000+seed*100+task).to(device)
            with torch.no_grad():
                for parameter,initial in zip(model.parameters(),reference.parameters()):
                    if strategy=='reiniciar': parameter.copy_(initial)
                    else: parameter.mul_(.9).add_(initial,alpha=.1)
            del reference
        # Mismo tratamiento del estado del optimizador al cambiar de tarea.
        optimizer=torch.optim.Adam(model.parameters(),lr=.003)
        for step in range(steps):
            model.train()
            ids=indices[step].to(device)
            optimizer.zero_grad(set_to_none=True)
            pred=model(x[ids]); loss=(pred-y[ids]).square().mean()
            loss.backward(); optimizer.step()
        metrics=evaluate(model,vx,vy)
        history.append({'task':task+1,**metrics})
        del optimizer,x,y,vx,vy
    del model
    if device.type=='cuda': torch.cuda.empty_cache()
    return {'seed':seed,'strategy':strategy,'history':history}


def main():
    records=[]
    for seed in seeds:
        for strategy in ('continuar','reiniciar','encoger_perturbar'):
            row=run(seed,strategy);records.append(row)
            print('semilla',seed,'estrategia',strategy,'última tarea',row['history'][-1],flush=True)
    for strategy in ('continuar','reiniciar','encoger_perturbar'):
        values=[row['history'][-1]['validation_mse'] for row in records if row['strategy']==strategy]
        mean=float(np.mean(values)) if all(value is not None for value in values) else None
        print('MSE media última tarea',strategy,mean,flush=True)
    output={'dataset':'tareas sintéticas de regresión tanh con maestro nuevo por tarea',
        'mode':'short' if short else 'full','torch':torch.__version__,'device':str(device),
        'tasks':tasks,'steps_per_task':steps,'seeds':list(seeds),'input_dimension':dimension,
        'width':width,'train_examples':train_size,'validation_examples':validation_size,'batch_size':batch_size,
        'optimizer':'Adam, lr 0,003; estado reiniciado al comienzo de cada tarea en todas las estrategias',
        'conditions':{'continuar':'Conserva los pesos entre tareas.',
                      'reiniciar':'Reinicializa todas las capas con semilla específica de tarea; pierde lo aprendido.',
                      'encoger_perturbar':'Aplica 0,9·peso anterior + 0,1·inicialización nueva a cada parámetro.'},
        'metrics':'MSE y fracción de neuronas nunca positivas sobre validación disjunta; rango efectivo entrópico de valores singulares de activaciones centradas.',
        'caveat':'Datos sintéticos y presupuestos pequeños: no prueban un mecanismo universal ni equivalen a un experimento de aprendizaje continuo publicado.',
        'records':records}
    target=Path(os.getenv('ORYON_PLASTICITY_OUTPUT','plasticity-changing-tasks.json'))
    target.parent.mkdir(parents=True,exist_ok=True)
    target.write_text(json.dumps(output,ensure_ascii=False,indent=2,allow_nan=False),encoding='utf-8')
    print('Guardado en',target,flush=True)
    if device.type=='cuda': torch.cuda.empty_cache()


if __name__=='__main__': main()
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Exercises

NumericRelative step
With SGD without momentum or regularization, ‖w‖=12.0, ‖g‖=0.4, and rate 0.03, what is ‖Δw‖/‖w‖?
QuizA layer with little signal
Layer 7 receives gradients four orders of magnitude smaller than nearby layers. What is the most defensible next step?

The following exercise uses the same hook interface as PyTorch, with lightweight test doubles for browser execution. In real PyTorch, define nn using from torch import nn before installing hooks. Each output has shape (N,C,...): the unit is a channel, not an individual element. Keep results as detached tensors on device and leave transfer to the reader.

CodeDetect units inactive in the batch
Implement register_activation_stats(model), traversing named_modules(), installing a forward hook on every nn.ReLU, and returning (stats, handles). Each stats[name] is the fraction of channels producing exactly zero across every example and spatial position of the last call. Output has shape (N,C,...) with positive N and C. Use output.detach() and tensor operations without copying to CPU or calling item(). Handles must allow hook removal. Reject output with fewer than two dimensions or empty axes with ValueError.
def register_activation_stats(model):
  pass
Shift+Enter to run
QuizGradient scale in Adam
When is the Adam step invariant to multiplying gradients by a positive constant?

References