AI frameworks in practice
PyTorch provides the operations needed to build and train a model. One update is small enough to compare line for line with ordinary Python.
Open this chapter with experiments and audio
Where does the problem definition come from?
Suppose that an input of 5 should produce 25. You decide to try the rule prediction = weight × input. You also decide that squared error measures a mistake. Writing those two equations defines your model and objective. Neither equation tells the framework the correct weight. Training will use examples to find a useful value.
PyTorch represents the input and weight as tensors. A tensor can be a single number, as in this example, or a whole table. When a value requires a gradient, PyTorch can track the operations that use it. That record contains enough information to apply the chain rule backwards.
Compute one update by hand
Begin with weight 2. The prediction is 10, the error is −15, and the squared error is 225. The derivative of squared error with respect to this weight is 2 × error × input, giving −150. A negative derivative means that increasing the weight a little would reduce the loss here. With a learning rate of 0.01 the update gives 2 − 0.01 × (−150) = 3.5.
x, target, weight = 5.0, 25.0, 2.0 error = x * weight - target gradient = 2 * error * x weight -= 0.01 * gradient print(gradient, weight, (x * weight - target) ** 2)
The new loss is 56.25. Each printed number comes from a formula you supplied. A larger network would need a derivative for every path from each parameter to the loss.
Repeat the same update with automatic differentiation
Use Python with the PyTorch package installed. The three printed values match the manual calculation. Run the whole snippet again to start from the same initial value.
import torch w = torch.tensor(2.0, requires_grad=True) optimizer = torch.optim.SGD([w], lr=0.01) optimizer.zero_grad() loss = (5 * w - 25) ** 2 loss.backward() gradient = w.grad.item() optimizer.step() print(gradient, w.item(), (5 * w.item() - 25) ** 2)
The backward call computes the derivative. The optimizer performs the update. Gradients accumulate by default, so loops usually clear old gradients before processing the next batch. During inference, the application normally skips this update and uses the parameter values in its checkpoint.
How do the alternatives fit together?
| Library | What you would write |
|---|---|
| PyTorch | Tensor operations and a module, with autograd and an optimizer. |
| JAX | A mathematical function. grad constructs a function that computes its gradient. |
| TensorFlow | Tensor operations that GradientTape records for differentiation. |
| Keras | High-level layers and a training configuration. A supported backend executes them. |
Would installing any of these libraries download a trained room assistant?
A functioning language assistant also needs a trained language model and a compatible tokenizer. In this lesson you used a single trainable number and one numerical example.
When two examples share a weight, which gradient arrives?
A framework can compute derivatives, but the programmer chooses which quantity to differentiate. Start with a shared weight w = 2 and two examples [input, target] = [1, 0] and [3, 3]. The predictions w × input are 2 and 6. Their errors are 2 and 3. If you average the squared errors, the loss is (4 + 9) / 2 = 6.5.
For one squared error the weight gradient is 2 × error × input. The two paths contribute 2 × 2 × 1 = 4 and 2 × 3 × 3 = 18 before averaging. Their mean is 11. At learning rate 0.1, subtract 1.1 from w and obtain 0.9. Both examples influence the same weight, and the larger input has greater leverage in this particular update.
import torch w = torch.tensor(2.0, requires_grad=True) x = torch.tensor([1.0, 3.0]) targets = torch.tensor([0.0, 3.0]) loss = (w * x - targets).square().mean() loss.backward() print(loss.item(), w.grad.item())
Replace mean() with sum(). Which numbers change?
The predictions are still 2 and 6. Loss becomes 13, the gradient becomes 22, and a step of 0.1 now sends w to −0.2. Doubling the loss doubled the gradient. A learning rate of 0.05 would recover the original update for this fixed batch. Run each version from a fresh w: PyTorch accumulates contributions in an existing gradient buffer across backward calls.
Compare the framework’s derivative with one manual update →
Further reading · PyTorch · Automatic differentiation · PyTorch · MSELoss