Chapter 3 · Diagnose signal and ship

Regularize, normalize, debug, and ship

Shipping a network means freezing its inference behavior, not merely saving its weights.

65–90 min4 key conceptsReviewed 26 Aug 2026
01 · Production proposition

A nonlinear sensor classifier defeats every classical baseline.

This chapter moves from prove the unregularized path to freeze the inference contract. We will make the idea concrete in a small code example before placing it back inside a production system with a declared latency, cost, and operator-capacity budget.

Decision

Export the exact transforms, category maps, weights, mode, output semantics, and thresholds, then run golden raw-request parity tests.

Evidence

Verify the behavior illustrated in train_eval_modes.py, then measure decision utility, slice reliability, and system latency.

Failure consequence

An excessive learning rate causes NaNs; dead ReLUs and a BatchNorm train/eval mismatch hide the cause. An unsafe release must degrade to a named baseline or the last known-good version.

02 · Guided chapter

Build the idea one layer at a time.

A network that fits training data is only halfway built. Regularization controls what it learns, normalization controls how signals travel, diagnostics explain failures, and export proves the behavior survives outside the training process.

Weight decay discourages overly large parameters; dropout samples subnetworks during training; normalization stabilizes activation scales. These mechanisms solve different problems and create train/eval behavior differences. More regularization is not automatically safer: excessive decay or dropout can erase scarce signal.

Debug in a deliberate order: validate data and shapes, overfit one tiny batch, inspect activations and gradients, then add regularization and scale. Before release, switch to evaluation mode, serialize preprocessing and vocabularies, compare batch-one outputs with the exported runtime, and calibrate probabilities on held-out data.

Keep in view
  • AdamW
  • dropout
  • normalization
  • gradient checks
WORKED PATH

Follow the reasoning before touching the code.

  1. 01

    Prove the unregularized path

    Make a tiny deterministic batch reach near-zero training loss; failure here points to data, shape, loss, or gradient bugs rather than overfitting.

  2. 02

    Add controls one at a time

    Introduce normalization, decay, dropout, clipping, or augmentation separately and record their effects on train/validation gaps and telemetry.

  3. 03

    Freeze the inference contract

    Export the exact transforms, category maps, weights, mode, output semantics, and thresholds, then run golden raw-request parity tests.

pythontrain_eval_modes.py
import torch

torch.manual_seed(4)
model = torch.nn.Sequential(
    torch.nn.Linear(3, 3),
    torch.nn.LayerNorm(3),
    torch.nn.ReLU(),
    torch.nn.Dropout(0.5),
)
x = torch.ones(1, 3)
model.train(); train_a, train_b = model(x), model(x)
model.eval(); eval_a, eval_b = model(x), model(x)
print('train equal', torch.equal(train_a, train_b))
print('eval equal', torch.equal(eval_a, eval_b))

Show why dropout requires an explicit inference mode.

READ THE EXAMPLE

What to notice

  • Dropout samples different masks in training mode, so repeated forward passes need not match.
  • Evaluation mode disables dropout while LayerNorm continues using each sample’s features, producing stable repeated inference here.
YOUR TURN Pause and predict before revealing the answer.

What production bug appears if export parity is tested while one model remains in train mode?

Need a hint?

The comparison now includes random behavior that should not exist in serving.

Check your reasoning

Predictions become stochastic and can disagree for the wrong reason, hiding or inventing parity failures; both reference and exported paths must use inference semantics.

Bring forward

Lessons 1, 2, 3, 4 in this course.

03 · Formal treatment

Connect the chapter to the course’s quantitative spine.

Shipping a network means freezing its inference behavior, not merely saving its weights. The backpropagated error below is the shared course-level lens that helps quantify the surrounding system. Name each symbol, check its units or shape, and use only values that were available at the production cutoff.

Formal treatment
δl=(Wl+1⊤δl+1)⊙φ′(zl)\delta_l = \left(W_{l+1}^\top \delta_{l+1}\right) \odot \varphi'(z_l)

Backpropagated error

Symbol, shape or unit contract
SymbolMeaning / shape / unit
δ_lloss gradient at layer l
Wweight matrix
φ′activation derivative
Open derivation and numerical substitution

Start from the production quantity being optimized, substitute the observed values with their declared units, then isolate the model-controlled term. Preserve shape annotations at each step so broadcasting or aggregation cannot silently change the result.

  1. Write the named inputs: δ_l, W, φ′.
  2. Substitute one small, hand-checkable batch before vectorizing.
  3. Calculate an independent reference value and compare within a declared tolerance.
# equation → code contract
inputs = validate_shapes_and_units(batch)
value = compute_c09(inputs)
assert is_finite(value)
04 · Deterministic lab

Change one assumption and make the tradeoff visible.

Use the worked chapter as your prediction, then change one input in the lab and explain why the output moves. The lab runs predefined TypeScript and never executes learner code, so the focus stays on the concept rather than setup.

Exact computation

Optimizer stability lab

Sweep learning rate over a deterministic convex-plus-curvature loss.

Primary0.04813 loss
Secondaryw=0.310
DiagnosisStable

Assumption: Twenty gradient steps from w=4 on L(w)=w²/2.

Open nonvisual data table
ItemComputed stateInterpretation
step 13.52006.19520
step 52.11092.22801
step 101.11400.62050
step 150.58790.17281
step 200.31030.04813
05 · Production implications

Trace the complete operating path.

Carry the chapter’s central idea into the system: Shipping a network means freezing its inference behavior, not merely saving its weights. The path below shows where that reasoning needs an artifact, a test, an owner, or a fallback.

  1. 01

    Turn “Prove the unregularized path” into a written invariant and a failing test.

  2. 02

    Promote train_eval_modes.py from illustration to a versioned implementation with representative fixtures.

  3. 03

    Use “Freeze the inference contract” as the release checkpoint: Export the exact transforms, category maps, weights, mode, output semantics, and thresholds, then run golden raw-request parity tests.

  4. 04

    Serve or materialize behind explicit a declared latency, cost, and operator-capacity budget.

  5. 05

    Join telemetry to mature outcomes and retain a rollback path.

Observability

Join service health, input quality, prediction distributions, slice behavior, and mature outcomes by exact version.

Cost

Measure storage, preprocessing, compute, queueing, and human review under a representative arrival pattern.

Failure modes

An excessive learning rate causes NaNs; dead ReLUs and a BatchNorm train/eval mismatch hide the cause. Add a detector, owner, mitigation, and stop condition for this class of failure.

Alternatives

Compare a rule, a simpler statistical baseline, and a different system boundary before adding model complexity.

06 · Check understanding

Explain the contract, not just the vocabulary.

Browser-graded checkpointPass ≥ 80%
01What does backprop compute?
02Why gradient-check a tiny network?
03Why do stacked linear layers remain linear?
07 · Apply in production

Network from first principles

Specify a NumPy MLP, finite-difference checks, PyTorch parity, calibrated inference, and debugging report.

  • Forward/backward derivation
  • Gradient check plan
  • Optimizer/regularization ablations
  • Export and batch-one parity
Open assignment and rubric
08 · Sources & next depth

Read primary material with a purpose.

09 · Production resolution

Return to the opening failure.

Package preprocessing, vocabularies, weights, calibration, output semantics, and batch-one parity as one artifact.

For this lesson, the release evidence is the worked code example, a hand-checked formal result, deterministic simulation output, a ≥80% checkpoint, the production rubric, and a named fallback. The course resolves when the system can produce a small network built from forward pass through backpropagation and optimization.