AI Wiki中文/EN

Neural network debugging: make the fault observable

神经网络故障诊断

Find a missing derivative and a skipped update using a tiny realizable network and numerical checks.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

The loss falls, but is the program right?

A falling loss is evidence that something is adapting. It does not identify which parts are correct. A wrong derivative may still point roughly downhill; a trainable bias may compensate for a broken feature; a scoring bug may make a bad model look convincing.

Deep Learning Section 11.5 recommends isolating components and constructing cases with predictable behavior. Stanford CS 231n’s gradient-checking notes discuss numerical precision, perturbation size and nondifferentiable points. We turn those principles into three concrete checks: does the gradient match the stated loss, does the parameter actually change as requested, and can the model fit a tiny realizable dataset?

Give each check a precise target

Our network has one tanh hidden unit and an affine output. Its four parameters are θ=(a,b,c,d). For n scalar input/target pairs:

hi=tanh⁡(axi+b),ri=chi+d−yi,L=12n∑i=1nri2.h_i=\tanh(ax_i+b),\qquad r_i=ch_i+d-y_i,\qquad L=\frac{1}{2n}\sum_{i=1}^n r_i^2.

This objective uses half the mean squared error, not its sum. Apply the chain rule to each residual:

La=1n∑iric(1−hi2)xi,Lb=1n∑iric(1−hi2),Lc=1n∑irihi,Ld=1n∑iri.\begin{aligned} L_a&=\frac1n\sum_i r_ic(1-h_i^2)x_i,&L_b&=\frac1n\sum_i r_ic(1-h_i^2),\\ L_c&=\frac1n\sum_i r_ih_i,&L_d&=\frac1n\sum_i r_i. \end{aligned}

A deliberately faulty implementation drops the tanh factor from the a and b derivatives. It preserves the c and d derivatives, so looking at just one output-layer gradient would miss the error.

For a coordinate unit vector eⱼ, numerical perturbation ε and absolute/relative tolerances τₐ,τᵣ, compare:

gjFD=L(θ+εej)−L(θ−εej)2ε,∣gj−gjFD∣≤τa+τrmax⁡(∣gj∣,∣gjFD∣).g_j^{\mathrm{FD}}=\frac{L(\theta+\varepsilon e_j)-L(\theta-\varepsilon e_j)}{2\varepsilon},\qquad \left|g_j-g_j^{\mathrm{FD}}\right|\leq\tau_a+\tau_r\max(|g_j|,|g_j^{\mathrm{FD}}|).

FD means finite difference. Centered differences have second-order truncation error for sufficiently smooth functions; floating-point cancellation eventually dominates as ε shrinks. Our smooth float 64 example uses ε=10⁻⁵ and tests several steps and parameter points. Near-zero gradients need an absolute tolerance as well as a relative one. There is no universal tolerance that proves every network correct.

A derivative test checks the loss actually implemented. It cannot tell whether that loss matches the intended task. For plain gradient descent, a separate update check verifies that θafter−θbefore equals −ηg, using fresh copies. If gradients are correct but this residual is wrong, inspect the optimizer call, frozen parameters, overwritten tensors or stale state before redesigning the network.

Inject two faults into a four-parameter network

The complete Python 3.12 / NumPy 1.26.4 program generates three labels from a known network, so representability is established before training. It prints the missing-derivative discrepancy and compares normal training with a deliberately skipped update. Shape checks reject an n-by-1 target array that could otherwise broadcast against an n-vector and create an unintended n-by-n loss.

import numpy as np


def evaluate(parameters,x,y,broken=False):
    p=np.asarray(parameters,dtype=np.float64);x=np.asarray(x,dtype=np.float64);y=np.asarray(y,dtype=np.float64)
    if p.shape!=(4,) or x.ndim!=1 or y.shape!=x.shape or not 1<=x.size<=16:raise ValueError('four parameters and matched nonempty 1D data required')
    if not all(np.isfinite(v).all() and np.all(np.abs(v)<=100) for v in (p,x,y)):raise ValueError('finite bounded values required')
    a,b,c,d=p;h=np.tanh(a*x+b);r=c*h+d-y
    loss=float(np.mean(r*r)/2)
    chain=np.ones_like(h) if broken else 1-h*h
    grad=np.array([np.mean(r*c*chain*x),np.mean(r*c*chain),np.mean(r*h),np.mean(r)])
    return loss,grad


def numerical(parameters,x,y,step=1e-5):
    if not np.isfinite(step) or not 0<step<.1:raise ValueError('positive finite small step required')
    p=np.array(parameters,dtype=np.float64,copy=True);g=np.zeros(4)
    for j in range(4):
        delta=np.zeros(4);delta[j]=step
        g[j]=(evaluate(p+delta,x,y)[0]-evaluate(p-delta,x,y)[0])/(2*step)
    return g


def fit(parameters,x,y,steps=1000,rate=.1,frozen=False):
    if type(steps) is not int or not 0<=steps<=2000:raise ValueError('bounded integer steps required')
    if not np.isfinite(rate) or not 0<=rate<=1:raise ValueError('rate must be in [0,1]')
    p=np.array(parameters,dtype=np.float64,copy=True);history=[evaluate(p,x,y)[0]]
    for _ in range(steps):
        loss,g=evaluate(p,x,y)
        if not frozen:p=p-rate*g
        history.append(evaluate(p,x,y)[0])
    return p,np.array(history)


if __name__=='__main__':
    x=np.array([-1.,0.,1.]);y=.8*np.tanh(1.2*x-.2)+.1;p=np.array([.5,.1,.5,0.])
    good=evaluate(p,x,y)[1];bad=evaluate(p,x,y,broken=True)[1];reference=numerical(p,x,y)
    trained,losses=fit(p,x,y);_,stuck=fit(p,x,y,frozen=True)
    after=p-.1*good
    print('analytic gradient:',np.round(good,9).tolist())
    print('correct max absolute discrepancy:',format(float(np.max(np.abs(good-reference))),'.3g'))
    print('missing-tanh-derivative discrepancy:',round(float(np.max(np.abs(bad-reference))),9))
    print('update residual:',round(float(np.max(np.abs((after-p)+.1*good))),12))
    print('loss initial / fitted / frozen:',[round(float(v),9) for v in (losses[0],losses[-1],stuck[-1])])
    print('fitted predictions:',np.round(trained[2]*np.tanh(trained[0]*x+trained[1])+trained[3],9).tolist())

Actual output:

analytic gradient: [-0.11192464, 0.025159221, -0.128300826, 0.028430183]
correct max absolute discrepancy: 2.74e-12
missing-tanh-derivative discrepancy: 0.03125159
update residual: 0.0
loss initial / fitted / frozen: [0.06347472, 3.202e-06, 0.06347472]
fitted predictions: [-0.610522933, -0.054577293, 0.707501709]

The healthy run fits these three values; it does not establish generalization or recover unique ground-truth parameters. The frozen run retains its initial loss despite computing valid gradients. The faulty derivative is evaluated at the same initial parameters as the correct one; it is not silently used to generate the reference gradient.

One analytic gradient costs O(n) for this four-parameter model. Checking P parameters by centered differences costs 2P loss evaluations, or O(Pn) here. On a large model, use component tests and selected directions before a full coordinate sweep. Record the dataset slice, weights, precision, loss reduction, perturbation and random state so the failure can be repeated.

Use symptoms to choose the next experiment

A useful debugging sequence has small, falsifiable steps. First inspect a few decoded examples and target shapes, then compare an elementary baseline. Next freeze randomness and disable stochastic layers while testing the forward loss, gradient and one update. Finally fit a tiny realizable set and restore regularization and data transformations one at a time.

High training and validation errors can result from insufficient capacity, bad labels, poor optimization or an implementation error. A large train/validation gap can reflect overfitting, but also different preprocessing or a broken checkpoint reload. Neither pattern uniquely diagnoses a cause. Inspect individual failures and verify the metric with hand-counted predictions.

For dropout or data augmentation, changing random draws between the two finite-difference evaluations changes the function being compared. For ReLU or max operations, crossing a kink changes the relevant derivative regime. A tiny-set fit can fail because the examples have contradictory targets for identical inputs; it can pass while a full-data loader is still broken. The checks narrow the search; they do not certify an entire production pipeline.

Choose the discriminating check

  1. The output bias gradient passes. Does this validate the hidden-unit derivative?

Answer 1: No. The injected bug affects a and b while leaving c and d correct.

  1. Gradients match numerical differences, but parameters remain unchanged. What check comes next?

Answer 2: Compare the actual parameter difference with the optimizer’s stated update and inspect whether the update was executed.

  1. Why generate the tiny targets from the same model family?

Answer 3: This removes lack of representability as an explanation, although successful optimization still needs to be demonstrated.

  1. Does decreasing ε always improve a numerical gradient?

Answer 4: No. Truncation error decreases initially, but rounding and subtraction error can dominate for very small perturbations.

Keep the failing case, not just the fix

The textbook and course notes motivate isolated checks. The tanh fault, frozen-update run and exact shape contract are original experiments. No external training framework is invoked. Continue with backpropagation, learning curves and gradient clipping. Save a small regression test when a bug is fixed; a later falling loss is a much weaker guard.

Make a prediction, then check

Correct gradients but unchanged parameters suggest checking what next?

Choose one answer

Learning objectives

  • Separate loss, gradient and optimizer failures.
  • Build a reproducible tiny failing case.

Prerequisites & connections

Explore related knowledge →

References

  1. Deep Learning — Chapter 11: Practical Methodology
    Ian Goodfellow; Yoshua Bengio; Aaron Courville · 2016
  2. CS231n: Neural Networks, Part 3 — Learning
    Stanford CS231n course staff

Version1 · Editorial status: Recorded technical checks completed

View technical check record (AI)

Codex · 2026-09-06 · Codex single-agent authored technical review: cited primary-source scope, explicit assumptions, original calculations and counterexamples, runnable tests and bilingual review; not independent human or second-agent review.

  • Single-agent authored technical review: bounded primary-source locations, assumptions, original derivations, exact/literal references and matching bilingual equations/examples/exercises. Not independent human or second-agent review.
  • Four focused CPython3.12.4 tests passed per chapter. Bidirectional alignment/Jacobians, injected network faults, exhaustive learning curves and stochastic paths, exact momentum trajectories, Nesterov reparameterization and a smooth accelerated bound instance are checked. Bidirectional RNN/debugging use NumPy1.26.4; the other four use the standard library.
  • Promoted the full prose, equations, code and exercises. Tests read formal MDX only; removed temporary fallbacks/draft skips and updated review assertion to checked. Algorithm and independent references are unchanged; final record binds both locale hashes.
  • Publication navigation points published topics to complete articles and removes corresponding pending wording, retaining directory entries for unwritten targets. Principles, equations, programs and exercises are unchanged; final article SHA values rebound.

Source locations checked:

Related topics

No matches. Try a synonym or acronym.

0 results shown

Wrap the whole query in double quotes for a phrase match.