Training and inference are two different jobs

What a model actually does when it "learns", and what a serving API can stop doing

A training step is forward, loss, backward, update. Serving needs only the forward pass, and two separate switches control that.

A model is a function with settings: prediction = f(input, parameters). Sending it another HTTP request does not change the parameters. Only a training step does.

One training step

1. Forward: compute a prediction from the input and the current parameters. 2. Loss: compare it to the wanted answer with a numeric error. 3. Backward: work out how a small change in each parameter would change the loss. Those sensitivities are the gradients. 4. Update: the optimizer uses the gradients to move the parameters.

In PyTorch, loss.backward() computes and accumulates gradients. It does not update anything. The update is a separate call.

A step you can do by hand

Take prediction = w * x + b, with x = 2, target y = 6, starting at w = 1, b = 0, squared loss, learning rate 0.1.

  • Prediction is 2, loss is (2 - 6)^2 = 16.
  • dL/dw = 2 (2 - 6) 2 = -16, dL/db = 2 * (2 - 6) = -8.
  • New w = 1 - 0.1 -16 = 2.6, new b = 0 - 0.1 -8 = 0.8.
  • The same input now predicts 2.6 * 2 + 0.8 = 6. Loss is zero.
  • A perfect fit on one example proves nothing. If the real relationship is y = 3x, then x = 3 gives 8.6, not 9. And a step does not always shrink the error: the learning rate and the data decide that.

    What serving can drop

    At inference you run the forward pass with fixed parameters and skip gradient tracking. Two switches do two different things:

    | Call | Changes | Does not do | |---|---|---| | model.eval() | puts layers like dropout into evaluation behaviour | does not turn off autograd | | torch.inference_mode() | turns off gradient and extra tracking | does not call eval() |

    A normal prediction service wants both. Inference mode is thread-local, so enter it inside the predict function, not once in the init thread.

    The decision

    Let the serving worker load a pinned model version and only run forward. Let training produce new versions separately. That is a recommendation, not a ban on online learning. If you want to learn from live requests, design how feedback is collected, how a change is checked, and how you roll back.

    Check yourself

    An API calls model.eval() then model(x). Does the model learn from requests? No, nothing updates weights. Is an autograd graph guaranteed not to be built? Also no, eval() alone does not stop that. Wrap the call in inference_mode().

    Tagged: ai, pytorch, inference, autograd, serving

    Area: AI

    Related notes

    עברית