Model debugging: separate data, gradients and updates
模型调试基础
Use a known quadratic model to distinguish stalled updates, unsuitable rates, label misalignment and lost feature information.
debugging-modelsTurn a training symptom into a smaller experiment
The loss barely moves. Is the learning rate too small, the gradient wrong, the update missing, or the input feature constant? The same flat curve can accompany all of these. Changing the optimizer immediately discards a useful opportunity to separate them.
We will investigate a two-parameter regression model with a known answer. The toy data obey y=1+2x. By deliberately disabling updates, changing the learning rate, reversing labels and deleting feature variation, we can connect observations to controlled changes. This is a debugging experiment, not a recipe for inferring a unique cause from any training curve.
First preserve the failing data, configuration, library versions and starting weights. Reproduce the behavior on a small fixed batch. Then change one condition and record what happened. Google’s Rules of Machine Learning, especially Rules 4–5, advocates checking the surrounding data and model pipeline separately from the learning algorithm.
Distinguish data, objective, derivative and update
The model predicts an intercept b plus slope a times x. Put these two coefficients into w, and let A have rows [1,x_i]. For n examples, define half the mean squared error:
The factor one-half simplifies the derivative. Report it explicitly: an MSE metric without that factor is twice this loss. Before running optimization, compute the prediction, residual and loss on one or two rows by hand. Check row identity as well as array length; a correctly shaped label vector can still be paired with the wrong examples.
A gradient is not a parameter update
Ordinary full-batch gradient descent proposes Δw=−ηg. A program must then actually apply that proposal to the parameter state used by the next prediction. Log the gradient norm, proposed-update norm and actual parameter change separately. With η=0 the proposal is zero despite a nonzero gradient. If an assignment is accidentally omitted, the proposal can be nonzero while actual movement is zero.
Those patterns narrow an investigation. They do not cover optimizers with momentum, clipping, constraints or mixed-precision state, whose proposed and applied updates may intentionally differ. Also inspect the vector or individual parameter blocks when a norm hides which component is wrong.
A quadratic gives an exact learning-rate experiment
If w* minimizes this full-rank least-squares problem, then in exact arithmetic:
Decompose the error into eigenvectors of the symmetric positive-definite H. Each component is multiplied by 1−ηλ. Therefore convergence from every initial vector follows when:
This condition belongs to fixed-step full-batch descent on this quadratic. It is not a universal safe learning-rate rule for neural networks. At a boundary, some nonzero error components may oscillate without shrinking; outside it, a component only grows if that mode is present in the initial error.
Our four inputs are −2,−1,1,2, so H is diagonal with entries 1 and 5/2. Starting at zero, the exact iterates and loss are:
The initial loss is 5.5, and rates strictly between zero and 0.8 converge. At rate one, the slope-error multiplier is −1.5; its alternating sign and growing magnitude explain the rising losses. We do not need to guess from the plot.
Instrument a deliberately small training loop
The complete example uses Python 3.12 and NumPy 1.26.4. Inputs must be finite one-dimensional float64 arrays of equal length, with 1–64 rows, |x|≤2 and |y|≤10. It starts both weights at zero, runs 0–64 full-batch steps and accepts a rate in [0,1]. These bounds keep the demonstrated arithmetic finite even when the selected rate makes the quadratic diverge. apply_update=False deliberately simulates a missing parameter assignment; it is not a training method.
Each history record pairs a loss before the step with the gradient and update norms, then a loss after that same step on the same batch. The returned weights are an intercept/slope pair. evaluate uses exactly the same loss convention and feature construction on separate rows; it does not retrain the model.
import math
import numpy as np
def data(x, y):
for a in (x, y):
if type(a) is not np.ndarray or a.ndim != 1 or a.dtype != np.dtype('float64'):
raise ValueError('one-dimensional float64 arrays required')
if not np.isfinite(a).all():
raise ValueError('finite data required')
if x.shape != y.shape or not 1 <= len(x) <= 64:
raise ValueError('matching nonempty arrays of at most 64 rows required')
if np.any(np.abs(x) > 2) or np.any(np.abs(y) > 10):
raise ValueError('teaching data bounds exceeded')
return np.column_stack((np.ones(len(x)), x)), y.copy()
def fit_probe(x, y, steps=40, rate=.2, apply_update=True):
a, target = data(x, y)
if type(steps) is not int or not 0 <= steps <= 64:
raise ValueError('steps must be an integer in [0,64]')
if type(rate) not in (int, float) or not math.isfinite(rate) or not 0 <= rate <= 1:
raise ValueError('rate must lie in [0,1]')
if type(apply_update) is not bool:
raise ValueError('apply_update must be bool')
w = np.zeros(2)
history = []
for step in range(steps):
residual = a @ w - target
loss = float(residual @ residual / (2 * len(a)))
gradient = a.T @ residual / len(a)
proposal = -rate * gradient
before = w.copy()
if apply_update:
w = w + proposal
after_residual = a @ w - target
history.append({'step': step,
'loss_before': loss,
'gradient_norm': float(np.linalg.norm(gradient)),
'proposed_update_norm': float(np.linalg.norm(proposal)),
'actual_update_norm': float(np.linalg.norm(w - before)),
'loss_after': float(after_residual @ after_residual / (2 * len(a)))})
residual = a @ w - target
return {'weights': w, 'loss': float(residual @ residual / (2 * len(a))),
'history': history, 'steps': steps}
def evaluate(weights, x, y):
a, target = data(x, y)
if type(weights) is not np.ndarray or weights.shape != (2,) or weights.dtype != np.dtype('float64'):
raise ValueError('float64 intercept/slope pair required')
if not np.isfinite(weights).all() or np.any(np.abs(weights) > 1e50):
raise ValueError('finite bounded weights required')
residual = a @ weights - target
return float(residual @ residual / (2 * len(a)))
if __name__ == '__main__':
x = np.array([-2.,-1.,1.,2.])
y = 1 + 2*x
hold_x = np.array([-1.5,.5])
hold_y = 1 + 2*hold_x
good = fit_probe(x, y)
print('initial loss:', evaluate(np.zeros(2), x, y))
print('good weights:', np.round(good['weights'], 6).tolist())
print('good training loss:', round(good['loss'], 8))
print('good held-out loss:', round(evaluate(good['weights'], hold_x, hold_y), 6))
stalled = fit_probe(x, y, steps=1, apply_update=False)['history'][0]
zero_rate = fit_probe(x, y, steps=1, rate=0)['history'][0]
print('missing-update proposal / actual:', round(stalled['proposed_update_norm'], 6), stalled['actual_update_norm'])
print('zero-rate gradient / proposal:', round(zero_rate['gradient_norm'], 6), zero_rate['proposed_update_norm'])
high = fit_probe(x, y, steps=3, rate=1)
print('large-rate losses:', [round(r['loss_after'], 6) for r in high['history']])
reversed_labels = fit_probe(x, y[::-1])
print('misaligned training / held-out:', round(reversed_labels['loss'], 8), round(evaluate(reversed_labels['weights'], hold_x, hold_y), 6))
constant_feature = fit_probe(np.zeros_like(x), y)
print('constant-feature training loss:', round(constant_feature['loss'], 6))
Output:
initial loss: 5.5
good weights: [0.999867, 2.0]
good training loss: 1e-08
good held-out loss: 0.0
missing-update proposal / actual: 1.019804 0.0
zero-rate gradient / proposal: 5.09902 0.0
large-rate losses: [11.25, 25.3125, 56.953125]
misaligned training / held-out: 1e-08 9.999734
constant-feature training loss: 5.0
The normal run approaches weights (1,2). Its printed held-out loss rounds to zero at six decimal places; the actual value is positive. With a missing update, the proposal norm is about 1.02 while actual movement is exactly zero. With rate zero, even the proposal vanishes although the gradient norm is about 5.10. These two stalled runs call for different fixes.
The large-rate experiment returns rising losses 11.25, 25.3125 and 56.953125, as predicted by the recurrence. Reducing the rate while preserving the batch, initialization and objective isolates that cause in this experiment. It does not prove that every exploding loss is a learning-rate issue; nonfinite input, an incorrect derivative or overflow may produce similar symptoms elsewhere.
Reversing the label vector creates a subtler failure. These particular reversed labels obey y=1−2x, so the model fits them almost perfectly. Against the intended held-out relation, its loss is approximately ten. The successful tiny-batch fit proves that the loop can fit the supplied relationship; it cannot prove the supplied labels belong to the right rows.
Replacing all training x values by zero removes information the model needs. The best constant prediction is the label mean, one, and the minimum possible half-MSE is five. The plateau is a capacity/information limitation in this controlled case, not a missing update. Checking feature variation and an attainable baseline prevents an endless optimizer search.
The CS231n sanity-check notes recommend trying a tiny subset and examining training signals. Interpret that experiment relative to the model’s capacity and objective: zero regression error is attainable in the original noiseless fixture but not after the feature is removed. For some losses, such as logistic loss on separable data with finite parameters, exactly zero loss is not attainable at all.
With two fixed parameters, T steps and n rows, this program uses O(n(T+1)) work and O(n+T) storage including the retained history. It records all T steps instead of pretending that a fixed iteration count certifies convergence. A real run should also record data/version identifiers and the rules for stopping and checkpoint selection.
After many divergent updates, a large slope can also contaminate the much smaller intercept through floating-point cancellation. The exact recurrence describes real arithmetic; a small relative error for the whole weight vector need not imply a small relative error for every component. The short three-step example remains directly checkable.
A local repair does not validate the whole model
Use a sequence of questions rather than a curve-to-cause lookup table. Are the right rows and labels paired? Is the stated loss computed correctly? Does an independent derivative check agree? Are the intended parameters actually changing? Can the chosen model reach the small problem’s attainable error? Only then expand the dataset and investigate held-out behavior.
The two held-out points here were chosen to expose a constructed misalignment. They are not a random test sample, and their score is not an estimate of a deployment population. In a real workflow, use validation data for debugging and model selection while preserving a separate final evaluation protocol. Repeatedly inspecting a final test set changes what its score can support.
A small training loss can coexist with leakage, wrong units, stale lookup tables, duplicated records or feature mismatch between training and prediction. Compare predictions from a saved model with the intended serving path on the same fixed examples. A successful optimization loop does not test file parsing, joins, serialization or deployment transformations.
This chapter omits regularization, minibatch noise, adaptive optimizers and neural-network layers. Their state and training/evaluation modes introduce additional checks. When simplifying such a system, record which mechanisms were disabled so that a passing simplified experiment does not silently certify the mechanisms left out.
Choose the next discriminating observation
- The gradient norm is nonzero, proposed-update norm is nonzero, and actual parameter change is zero. What should be checked before increasing the learning rate?
Follow the parameter state
Answer: Check whether the update is applied to the parameters subsequently used for prediction, and whether the optimizer owns those same objects. In this loop the disabled assignment creates exactly that pattern. Increasing the rate changes a proposal that is still never applied.
- Why does rate one fail on the four-row fixture, and what occurs at rate 0.8?
Inspect the slope mode
Answer: The slope mode has eigenvalue 2.5. Rate one multiplies its error by −1.5, so it grows while changing sign. Rate 0.8 gives multiplier −1, so the nonzero initial slope error oscillates without shrinking. The strict convergence interval is (0,0.8).
- Why is the best loss five after replacing every x with zero?
Compute the attainable constant baseline
Answer: The model can predict only its intercept. The best intercept is the mean label, one. The original labels are −3,−1,3,5, whose deviations from one are −4,−2,2,4. Their squared sum is 40; division by 2n=8 gives five. No learning rate restores the missing feature information.
- The model fits the reversed labels almost perfectly. What has the tiny-batch test established, and what has it not established?
Separate optimization from data identity
Answer: It establishes that this model and loop can fit the supplied relation y=1−2x to small error. It does not establish that these labels were paired correctly, that preprocessing is correct, or that the intended relation y=1+2x will be predicted well. Inspecting stable row IDs can reveal the misalignment.
Connect local diagnostics to pipeline checks
The CS231n notes organize practical training observations around loss, gradients and update scales. Google’s Rules 4–5 extend the check to examples entering the learner and predictions leaving it. Neither perspective replaces the other: a correct derivative cannot repair a broken join, and a valid table cannot prove that an update was applied.
Continue with numerical tests, dataframes, gradient descent and generalization. Preserve small failing cases as regression tests after the cause is understood, together with the assumption that made the expected result trustworthy.
Make a prediction, then check
The gradient and proposed update are nonzero, but the actual parameter change is zero. What should you inspect first?
Learning objectives
- Separate a missing update from a zero learning rate using measured parameter movement.
- Derive the quadratic step-size condition and recognize information-limited loss floors.
- Use controlled label and feature changes without treating tiny-batch fit as generalization evidence.
Prerequisites & connections
Explore related knowledge →References
- CS231n: Neural Networks, Part 3 — Learning
Stanford CS231n course staff - Rules of Machine Learning: Best Practices for ML Engineering
Google for Developers
Version1 · Editorial status: Recorded technical checks completed
View technical check record (AI)
Codex · 2026-09-06 · Codex technical check: primary-source locations, original runnable models, independent mathematical and computational references, bilingual review and second-agent cross-checks; not independent human peer review.
- Seven tests pass using real NumPy 1.26.4. Fraction spectral closed forms check stable and short divergent trajectories, losses and update norms; an independent nonsymmetric one-step polynomial and constant-model floor check different cases. Labels, input ownership and bounded extreme runs are covered.
- Root completed the interrupted draft metadata and review. Fixed an erroneous stdout count (nine lines) and separated a long divergent vector-relative check from invalid fixed componentwise accuracy expectations; added bilingual cancellation context. Full code is unchanged; strict rendering passes four displays, six anchors and four answers.
- Root read both full articles, complete program and all tests. Manually verified Hessian diag(1,2.5), exact recurrence, initial 5.5 loss, boundary oscillation, reversed-label held-out loss 10 and constant-feature floor 5. The actual learning program was authored by another agent; root completed metadata and corrected test expectations.
- 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:
- CS231n: Neural Networks, Part 3 — Learning · Read sanity checks including overfitting a tiny subset, lines 71–72, and update-scale discussion. Zero-cost advice is qualified by attainable loss/capacity; a fitted tiny subset does not establish row identity or generalization.
- Rules of Machine Learning: Best Practices for ML Engineering · Read Rules 4–5, lines 111–127: examples reaching the learner, model integration, independent input statistics and agreement between training/serving predictions. No production deployment was executed.
- CS231n: Neural Networks, Part 3 — Learning · Read sanity checks including overfitting a tiny subset, lines 71–72, and update-scale discussion. Zero-cost advice is qualified by attainable loss/capacity; a fitted tiny subset does not establish row identity or generalization.
- Rules of Machine Learning: Best Practices for ML Engineering · Read Rules 4–5, lines 111–127: examples reaching the learner, model integration, independent input statistics and agreement between training/serving predictions. No production deployment was executed.
Related topics