Forward propagation: inspect a complete batch
神经网络前向计算
Track batch axes, shared biases, cached values and row-wise invariants in a fully executed two-layer network.
forward-passRun the model before asking it to learn
A forward pass evaluates a model using its current parameters. Starting with inputs, it computes each operation only after that operation’s dependencies are available. Training uses a forward pass to obtain predictions and often a loss, then a backward pass for derivatives and an optimizer step for parameter changes. These are separate operations.
A wrong forward value cannot be repaired by a correct derivative of that wrong computation. Shape checks, intermediate values and a tiny scalar reference therefore belong near the start of debugging. This chapter evaluates a batch through two affine maps with a ReLU between them, keeping each intermediate array visible.
D2L, Sections 5.3.1–5.3.2 explains dependency order and intermediate variables. Deep Learning, Chapter 6 opening discussion describes feedforward function composition. Read matrix multiplication and multilayer perceptrons first.
The batch dimension is not a feature dimension
Use row-wise examples. A batch X contains n examples with d features each. Hidden width is h and output width q:
Z and H have shape n×h; O has shape n×q. The bias vectors have h and q entries. Multiplication by the all-ones column means the same bias is added to each example. In code, a one-dimensional bias broadcasts across rows. That convenience is safe only when its dimension and intended axis have been checked.
In this convention rows of W₁ correspond to input features and columns to hidden units. Other texts use column inputs and transposed weights; neither convention changes the mathematics. Mixing them without checking dimensions does change the program. A square matrix can hide a mistaken transpose because its shape still fits.
A batch small enough to calculate by hand
Our fixed parameters and input batch are:
For the first row, the hidden preactivation is(1,2,0); the second row gives(−1,2,−2); the third gives(2,−2,5). ReLU removes only the negative entries. The outputs are:
The output is a two-component real vector, not automatically a probability distribution or a class label. No target values were needed to compute it. A training objective could be evaluated afterward using separately supplied labels, but changing the objective does not change these predictions at fixed parameters.
Keep intermediate values without mutating the inputs
This complete Python 3.12 program uses the repository’s pinned NumPy 1.26.4 runtime. It copies accepted numerical inputs to float 64 arrays, checks every layer shape and returns the preactivation and hidden values as a cache. All chosen numbers are exactly representable in binary floating point.
import numpy as np
def forward(x, w1, b1, w2, b2):
arrays=[]
for value in (x,w1,b1,w2,b2):
a=np.asarray(value)
if a.dtype.kind not in 'iuf':
raise ValueError('numeric arrays required')
a=a.astype(np.float64,copy=True)
if not np.all(np.isfinite(a)) or np.any(np.abs(a)>1000):
raise ValueError('bounded finite numeric arrays required')
arrays.append(a)
x,w1,b1,w2,b2=arrays
if (x.ndim,w1.ndim,b1.ndim,w2.ndim,b2.ndim)!=(2,2,1,2,1):
raise ValueError('matrices and one-dimensional biases required')
if any(not 1<=d<=32 for a in arrays for d in a.shape):
raise ValueError('every dimension must be from 1 to 32')
n,d=x.shape;h=w1.shape[1];q=w2.shape[1]
if w1.shape!=(d,h) or b1.shape!=(h,) or w2.shape!=(h,q) or b2.shape!=(q,):
raise ValueError('incompatible layer shapes')
z=x@w1+b1
hidden=np.maximum(z,0)
output=hidden@w2+b2
return output,{'preactivation':z,'hidden':hidden}
if __name__=='__main__':
x=[[1,2],[-1,0],[2,-1]]
w1=[[1,-1,2],[0,1,-1]];b1=[0,1,0]
w2=[[1,0],[0,-1],[2,1]];b2=[0.5,-0.5]
y,cache=forward(x,w1,b1,w2,b2)
for name,array in [*cache.items(),('output',y)]:
print(name,'shape',array.shape,'values',array.tolist())
split=np.concatenate([forward([row],w1,b1,w2,b2)[0] for row in x])
print('single-row evaluation equals full batch:',np.array_equal(y,split))
Actual output:
preactivation shape (3, 3) values [[1.0, 2.0, 0.0], [-1.0, 2.0, -2.0], [2.0, -2.0, 5.0]]
hidden shape (3, 3) values [[1.0, 2.0, 0.0], [0.0, 2.0, 0.0], [2.0, 0.0, 5.0]]
output shape (3, 2) values [[1.5, -2.5], [0.5, -2.5], [12.5, 4.5]]
single-row evaluation equals full batch: True
For this deterministic, example-independent network, evaluating each row separately and concatenating the results equals evaluating the whole batch. Permuting input rows also permutes output rows in the same way. Our tests check both properties, plus literal intermediate matrices and output values. They retain shape(1,q) for a one-example batch instead of silently squeezing away the batch axis.
A forward evaluator can discard intermediates after their last use if only inference outputs are needed. Backward computation often needs them again, so training typically retains selected values or recomputes them. This program returns a small cache for inspection; it does not implement automatic differentiation or an optimizer.
For dense evaluation the arithmetic cost is O(ndh+nhq), with O(nh) work for the activation. Parameter storage is O(dh+hq+h+q). Retaining X, Z, H and O takes O(nd+nh+nq) activation storage, with constant factors for the two hidden arrays. The implementation additionally copies inputs and parameters to isolate this demonstration from accidental caller mutation. It is a correctness example, not a low-allocation inference kernel.
Forward does not always mean stateless
Our batch equivalence relies on independent rows and deterministic operations. A training-mode normalization that uses batch statistics can couple examples, and dropout can make two passes differ unless the random choices are controlled. Layers can also update internal state during a forward call. These features must be part of the model contract; the simple invariants above do not prove correctness for every network.
Evaluation mode and disabling gradient recording are different decisions in common frameworks: one concerns layer behavior, the other concerns bookkeeping for derivatives. This standard-library-plus-NumPy evaluator has neither mode, so it should not be mistaken for an implementation of those framework controls.
Matching shapes is necessary but insufficient. Feature order, units, preprocessing, masks and parameter versions can all be wrong while matrix multiplication succeeds. Compare intermediates against a small independently specified example, then evaluate the complete data pipeline. A finite output is not evidence of a useful model.
Follow the row, not just the final number
- What are the shapes of Z, H and O in the worked batch?
Answer 1: Z and H are 3×3; O is 3×2.
- What is the output for input(2,−1)?
Answer 2: The hidden values are(2,0,5), giving output(25/2,9/2).
- Should the bias b₁ be added once to the batch or once to each row?
Answer 3: The same three-entry bias is added to every row; it is shared across examples.
- Does single-row versus full-batch equality necessarily hold for training-mode batch normalization?
Answer 4: No. Batch statistics can couple examples and change the result when the batch changes.
A cache records computation, not learning
The sources explain the dependency graph and layer composition. This chapter’s matrices, cache contract and numerical checks are original. A returned cache helps inspect the computation that actually happened; it does not establish that parameters were fitted, that gradients are right, or that predictions generalize.
Continue to backpropagation for the reverse traversal, binary cross-entropy for a possible binary objective, and model evaluation for evidence beyond a successful forward call.
Make a prediction, then check
What is the output shape for this three-example, two-output batch?
Learning objectives
- Track row-batch shapes and shared biases.
- Validate cached intermediates and state the limits of batch equivalence.
Prerequisites & connections
Explore related knowledge →References
- Forward Propagation, Backward Propagation, and Computational Graphs
D2L authors - Deep Learning — Chapter 6: Deep Feedforward Networks
Ian Goodfellow; Yoshua Bengio; Aaron Courville · 2016
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. Rectifier update paths, smooth-gate moments/stationary points, batch intermediates and weighted Bernoulli optima are checked against literal references, analytic identities and finite differences. Forward-pass example uses pinned NumPy1.26.4; other examples 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:
- Forward Propagation, Backward Propagation, and Computational Graphs · Sections5.3.1–5.3.2: dependency-ordered evaluation, intermediate values and graph; current page1.0.3.
- Deep Learning — Chapter 6: Deep Feedforward Networks · Chapter6 opening pp164–165: feedforward composition and hidden representations; teaching batch original.
Related topics