TExcelTAD

Training vs Inference

Every model lives two lives. In training it learns its parameters from data: slow, expensive, done once or now and then. In inference it uses those fixed parameters to make predictions: fast, cheap, done millions of times. Keeping the two apart explains a lot about how ML systems are built and what they cost.

Two phases

Training Inference
Goal find good parameters θ\theta compute y^=fθ(x)\hat{y} = f_\theta(x) for new inputs
Needs the training data, labels, a loss, an optimiser only the model: its structure and the learned θ\theta
Parameters change at every step frozen
Cost many passes over the data; for large models days on many GPUs one pass through the model per input; milliseconds
How often once per model version every request, every day
Where a workstation, a cluster a server, a phone, a browser, a sensor
scikit-learn model.fit(X, y) model.predict(X_new)
Also called fitting, learning prediction, scoring, serving

What training does: gradient descent

Most models are trained by gradient descent. The loss L(θ)L(\theta) is a landscape over the parameters; its gradient ∇L(θ)\nabla L(\theta) points uphill, in the direction where the loss grows fastest. So we take repeated small steps the other way:

θ←θ−η ∇L(θ)\theta \leftarrow \theta - \eta \, \nabla L(\theta)

The step size η\eta is the learning rate, a hyperparameter. For a line y^=wx+b\hat{y} = wx + b with mean squared error, the two partial derivatives are

∂L∂w=2n∑i=1n(wxi+b−yi) xi,∂L∂b=2n∑i=1n(wxi+b−yi)\frac{\partial L}{\partial w} = \frac{2}{n} \sum_{i=1}^{n} (w x_i + b - y_i)\, x_i, \qquad \frac{\partial L}{\partial b} = \frac{2}{n} \sum_{i=1}^{n} (w x_i + b - y_i)

Each step looks at all nn training points to compute these sums. The derivation is in Gradient Descent (math-ml) and Gradient Descent (calculus).

The lab shows the optimiser walking down a loss landscape with two parameters, drawn as contour lines (each line joins points of equal loss; the minimum is in the middle of the innermost ring). It takes one step every 0.2 s.

−2−1012−202Loss contours: narrow valleyxy10−610−410−211001040204060stepLoss f(x, y), log scalepath / lossstartminimumGD stable for η < 0.2

With η=0.08\eta = 0.08 it reaches the minimum within the 60 steps (the status turns to "converged"). Try these:

  • η=0.02\eta = 0.02: every step is tiny; after 60 steps the loss is still 0.0615 and the path has not arrived.
  • η=0.19\eta = 0.19: the path zig-zags across the narrow valley but still converges.
  • η=0.21\eta = 0.21: the steps overshoot further each time and the loss explodes to over two million by step 60. On this surface plain gradient descent is stable only for η<0.2\eta < 0.2.

Choosing the learning rate, and better optimisers such as momentum and Adam (the "Optimizer" buttons), are topics of Training, Evaluation & Improvement.

Training and inference from scratch

The example trains a line by gradient descent on 100 points, printing the parameters and the loss as training goes on, and then uses the result for inference.

python · try it yourself
import numpy as np

rng = np.random.default_rng(7)
x = rng.uniform(0, 5, size=100)
y = 2.0 * x - 1.0 + rng.normal(0, 0.5, size=100)

# Training: many passes over the data, adjusting the parameters to lower the loss.
w, b, lr = 0.0, 0.0, 0.05
for epoch in range(301):
    err = (w * x + b) - y
    loss = np.mean(err ** 2)
    if epoch in (0, 10, 50, 300):
        print(f"epoch {epoch:3}: w = {w:6.3f}, b = {b:6.3f}, loss {loss:.4f}")
    w -= lr * 2 * np.mean(err * x)          # gradient of the loss with respect to w
    b -= lr * 2 * np.mean(err)              # ... and with respect to b
print("training touched", 301 * len(x), "data points")

# Inference: the training data is gone; only (w, b) is needed.
def predict(x_new):
    return w * x_new + b
print("inference for x = 3:", round(predict(3.0), 3), "(one multiply, one add)")
epoch   0: w =  0.000, b =  0.000, loss 22.5654
epoch  10: w =  1.610, b =  0.157, loss 0.5398
epoch  50: w =  1.835, b = -0.559, loss 0.2394
epoch 300: w =  1.972, b = -0.995, loss 0.1892
training touched 30100 data points
inference for x = 3: 4.921 (one multiply, one add)

One full pass over the training data is an epoch. In 300 epochs the parameters move from (0,0)(0, 0) to w=1.972w = 1.972, b=−0.995b = -0.995, close to the true 22 and −1-1, and the loss falls from 22.57 to 0.189 (the loss cannot reach zero: what remains is the random noise in the data, which no line can predict; 0.189 is also exactly the least-squares minimum for these 100 points). Training processed 30,100 data points. Inference for one input costs one multiplication and one addition.

The same split in scikit-learn

In scikit-learn the two phases are fit and predict. The example trains logistic regression on 10,000 rows with 20 features, then shows that inference needs only 21 numbers, and recomputes a prediction by hand from them.

python · try it yourself
import numpy as np
from sklearn.datasets import make_classification
from sklearn.linear_model import LogisticRegression

X, y = make_classification(n_samples=10000, n_features=20, random_state=0)
model = LogisticRegression(max_iter=1000).fit(X, y)      # training: the expensive, one-off part

print("training data:", X.size, "numbers")
print("what inference needs:", model.coef_.size + model.intercept_.size, "numbers")
print("optimizer iterations during fit:", model.n_iter_[0])

new_customer = X[:1] + 0.1                                # inference: cheap, repeated per request
print("predict:      ", model.predict(new_customer))
print("predict_proba:", model.predict_proba(new_customer).round(3))
z = new_customer @ model.coef_.T + model.intercept_       # the same computation by hand
print("by hand:      ", (1 / (1 + np.exp(-z))).round(3).ravel())
training data: 200000 numbers
what inference needs: 21 numbers
optimizer iterations during fit: 6
predict:       [1]
predict_proba: [[0.055 0.945]]
by hand:       [0.945]

Training read 200,000 numbers; the deployed model is 21 numbers (20 weights and a bias). Inference is the formula p=11+e−zp = \frac{1}{1 + e^{-z}} with z=w⊤x+bz = \mathbf{w}^\top \mathbf{x} + b, and the hand computation gives the same 0.945 as predict_proba.

Why the split matters in practice

  • Cost. For large models, training is a one-off investment, but inference runs for every user and request, so over a model's life inference often costs more in total. That is why models are compressed and optimised for serving.
  • Hardware and place. Training needs the data and strong hardware; inference can run on a phone or in a browser, close to the user, with no access to the training data.
  • Reproducibility. Training should be a script that can be rerun from versioned data; inference should be a function with no hidden state.
  • Train/serve skew. Inference must prepare inputs exactly as training did. Shipping the whole fitted pipeline prevents mismatches.
  • Frozen models do not learn. A deployed model does not improve from the requests it sees unless you retrain it. Learning during operation is a separate design, online learning.

Pitfalls

  • Calling fit at serving time. Refitting a scaler or a model on incoming requests changes the model and can leak information. Load the fitted pipeline and call only predict or transform.
  • Too large a learning rate. As in the lab, training then diverges: the loss grows instead of falling. Too small a rate wastes time.
  • Measuring speed on the first call. Libraries load and compile on the first prediction; time inference over many calls.

Practice

  1. In the NumPy example, set lr = 0.2 and run it. What happens, and why?
Answer

The loss grows instead of falling and the parameters blow up to huge values (or nan). The inputs go up to 5, so the loss surface is steep in the ww direction, and a step of 0.2 overshoots the minimum by more each time, exactly as in the lab with η=0.21\eta = 0.21.

  1. A model is trained once a week for 2 hours on a GPU, and answers 50 requests per second, each taking 4 ms of GPU time. Which phase uses more GPU time per week?
Answer

Inference: 50×0.004=0.250 \times 0.004 = 0.2 GPU-seconds per second, and a week has 604,800604{,}800 seconds, so about 121,000121{,}000 GPU-seconds, about 33.6 hours. Training uses 2 hours. Inference costs about 17 times more.

Test yourself

Which phase changes the model's parameters?

  1. Training
  2. Inference
  3. Both equally
  4. Neither

What does the update θ←θ−η∇L(θ)\theta \leftarrow \theta - \eta \nabla L(\theta) do?

  1. Moves the parameters uphill on the loss
  2. Moves the parameters a small step in the direction that decreases the loss fastest
  3. Resets the parameters
  4. Computes predictions

In the lab, plain gradient descent diverges at η=0.21\eta = 0.21 but converges at η=0.19\eta = 0.19. What is the lesson?

  1. Larger learning rates are always better
  2. The learning rate must be below a limit set by the steepness of the loss surface
  3. Learning rate does not matter
  4. Divergence means the data is wrong

After training, what does the logistic-regression model need for inference on 20 features?

  1. All 10,000 training rows
  2. 20 weights and 1 bias
  3. The optimiser state
  4. The labels