Chapter 03 / 12 · AI Engineering

Deep learning fundamentals

When customers say the same thing in different words, hand-built features run out. A network learns its own, and we work its gradient steps through with real numbers.

The intent classifier from the first chapter is right 88% of the time. When the team reads through a sample of its mistakes, about a third share a cause. “Funds not credited”, “the money from my sale is stuck” and “paise abhi tak bank mein nahi aaye” all belong in the withdrawals queue, and they share almost no words. A model that sees each message as a set of word counts has no way to know that “credited”, “stuck” and “nahi aaye” are doing the same job.

We could keep adding synonyms by hand, but the list never ends, and customers write in three languages and several spellings of each. What we want is for the model to learn its own features: a representation of each message in which messages that mean the same thing end up close together. Neural networks do this. This chapter builds one from the logistic regression we already have, works through how it learns with real numbers, and covers the ways training goes wrong. By the end, the transformer in the next chapter should look like an arrangement of parts you have already seen.

Logistic regression is a network with one neuron

Recall the fraud model: multiply each input by a weight, add the results and a bias, pass the total through the sigmoid. That is exactly one artificial neuron. A neural network puts several of these side by side in a layer, feeds their outputs into another layer, and so on. The units in the middle layers are called hidden units, and their outputs are features the network invents for itself.

Between layers we need a nonlinear function. The usual choice is ReLU, which returns its input if positive and zero otherwise. Without it, stacking adds nothing. If one layer multiplies its input by 2 and the next multiplies by 3, the pair multiplies by 6, which a single layer could have done. The same holds for matrices: two linear layers W2(W1x) collapse into one, (W2W1)x, however many we stack.

ReLU breaks the collapse, and a small case shows what that buys. Take two inputs from the escalation problem, “withdrawal pending” and “market open”, each 0 or 1. A hidden unit with weights of 1 on each and a bias of −1 computes ReLU(w + m − 1). It outputs 1 when both are 1 and 0 in every other case. That unit has learned an AND, the interaction we had to hand-code as a column for the linear model in the previous chapter. A layer of 64 such units can learn 64 different combinations, and the next layer can combine those. Nobody specifies what each unit should detect. Training finds whatever combinations reduce the loss.

Gradient descent, one step at a time

Training means adjusting weights to lower the loss. The gradient tells us, for each weight, how much the loss would change if we nudged that weight up a little. We move each weight a small step in the opposite direction, and repeat.

Here is a single example worked through. The fraud model has one input, x = 1 (the message contains “unauthorised”), one weight w and a bias b, both starting at 0. The label is y = 1. The prediction is σ(0) = 0.5, and the log loss is −ln(0.5) = 0.693. For logistic regression with log loss, the gradient with respect to w has a tidy form: (p − y) × x = (0.5 − 1) × 1 = −0.5. The gradient for b is p − y, also −0.5. We choose a learning rate of 0.5 and update: w becomes 0 − 0.5 × (−0.5) = 0.25, and b becomes 0.25 as well.

Run the example again. Now z = 0.25 + 0.25 = 0.5, p = σ(0.5) = 0.622, and the loss has fallen to 0.474. The gradient is 0.622 − 1 = −0.378, so both parameters grow by 0.5 × 0.378 = 0.189, to 0.439. Next time z = 0.878, p = 0.706, loss 0.348. Each step moves the prediction toward the label, and each step is smaller than the last because the error shrinks. With 42,000 messages, we compute this gradient for a minibatch of, say, 64 messages at a time, average them, and step. One pass over all the training data is called an epoch.

The learning rate is the knob that most often decides whether training works. To see why, drop the classifier and take the simplest possible loss: L(w) = (w − 3)², which is lowest at w = 3. Its gradient is 2(w − 3). Start at w = 0. With a learning rate of 0.1, the first step moves w by −0.1 × (−6) = 0.6, the next brings it to 1.08, then 1.46, approaching 3 a bit more slowly each time.

Predict first

Same loss, same start at w = 0, but now the learning rate is 1.1. Where is w after two steps, and does it ever reach 3?

Show the worked answer

The first step moves w by −1.1 × (−6) = 6.6. It has jumped past 3 to 6.6, now 3.6 away on the other side. The gradient there is 2 × 3.6 = 7.2, so the second step moves it by −7.92, to −1.32, which is 4.32 away.

Each step multiplies the distance from 3 by 1 − 2 × 1.1 = −1.2. The sign flips (it bounces from side to side) and the size grows by 20%. It never arrives; it diverges. Any learning rate above 1.0 does this for this loss. In a real network the symptom is a loss that suddenly jumps, or becomes NaN, a few hundred steps into training. Too small a rate fails more quietly: the loss falls so slowly that training appears stuck.

Real networks have millions of weights, and the right step size differs between them. Adam, the optimiser most networks use, keeps a running average of each weight’s recent gradients and of their squared size, and scales each weight’s step accordingly, so that weights with consistently large gradients take careful steps and rarely-updated ones take bolder ones. It is common to start with a very small learning rate for the first few hundred steps (warmup), while those running averages are still noisy, and to decay it toward the end of training.

Backpropagation is the chain rule with good bookkeeping

With one layer, the gradient formula is short. With several layers, a weight early in the network affects the loss only through everything after it. Backpropagation computes all the gradients in one backward sweep using the chain rule from calculus: the effect of a weight on the loss is the product of the effects along the path from that weight to the loss.

Take the smallest network with a hidden layer. Input x = 1 goes through weight w1= 0.5 into a ReLU unit, giving h = 0.5. That goes through w2 = 1.0 to the output, so z = 0.5 and p = σ(0.5) = 0.622. The label is 1, and the loss is 0.474.

forward: values · backward: gradients of the lossx= 1hrelu · 0.5pσ(0.5) = 0.622loss 0.474label y = 1w1 = 0.5w2 = 1.0∂L/∂z = p − y = −0.378∂L/∂w2 = −0.378 × h = −0.189∂L/∂h = −0.378 × w2 = −0.378∂L/∂w1 = −0.378 × 1 × x = −0.378negative gradients mean “increase this weight to lower the loss”
Values flow forward along the top. Gradients flow backward along the bottom, each one the previous gradient times the local slope.

Going backward, the gradient of the loss with respect to z is p − y = −0.378, as before. The gradient for w2 is that times the value w2 multiplied, which was h: −0.378 × 0.5 = −0.189. To keep going backward, we need the gradient with respect to h, which is −0.378 × w2 = −0.378. ReLU passes the gradient through unchanged when its input was positive, and its input w1x = 0.5 was. Finally, the gradient for w1 is −0.378 × x = −0.378. With a learning rate of 0.5, w1 rises to 0.689 and w2 to 1.095. Running forward again gives h = 0.689, z = 0.754, p = 0.680, and a loss of 0.386, down from 0.474.

One detail in that calculation explains a common failure. Had w1 been −0.5, the ReLU input would have been negative, its output zero, and the gradient passed back through it zero. The unit would learn nothing from this example. If a large update pushes a unit’s weights so that its input is negative for every training example, it never receives a gradient again and stays switched off for good. A network that has lost many units this way has less capacity than its size suggests. Too high a learning rate is the usual cause.

Backpropagation also explains why training needs much more memory than prediction. To compute the backward sweep, every intermediate value from the forward pass (every h, every z) must be kept until its gradient has been used, and the optimiser keeps its running averages for each weight as well. Prediction only needs the weights and the current layer’s values.

Embeddings are features the network writes for itself

Words are not numbers, so the first layer of a text network is a lookup table. Each token in the vocabulary gets a row of, say, 128 numbers, called its embedding. A message becomes the list of its tokens’ rows, and for a simple classifier we average them into one 128-number vector and put a small network on top. At the start, the rows are random.

Training changes them. When “credited” appears in a message labelled withdrawals, the gradient flows back into the row for “credited” and moves it in whatever direction makes the withdrawals output more likely. The same happens to “stuck” in its withdrawal messages and to “nahi aaye” in its. Because they are all being pushed toward the same output, they drift toward the same region of the space. Nobody told the network they were synonyms. Their similar effect on the label made them similar vectors.

We measure that closeness with cosine similarity: the dot product of two vectors divided by the product of their lengths, which is 1 for vectors pointing the same way and near 0 for unrelated ones. In a toy three-number space, suppose “withdrawal” = (0.8, 0.1, 0.3), “funds” = (0.7, 0.2, 0.4) and “chart” = (0.1, 0.9, 0.0). The dot product of withdrawal and funds is 0.56 + 0.02 + 0.12 = 0.70, their lengths are 0.860 and 0.831, and the cosine is 0.98. For withdrawal and chart, the dot product is 0.17 and the cosine 0.22. The retrieval chapter will run exactly this calculation over help-centre passages, with vectors of a thousand numbers instead of three.

In practice the team did not learn embeddings from its 42,000 messages alone. Embedding models trained on very large amounts of text, by predicting words from their surroundings, already place “credited” near “deposited” and “received”, because those words appear in similar company. The team took a pretrained sentence-embedding model that handles Hindi-English mixed text, turned each message into a vector, and trained logistic regression on top. Accuracy rose from 88% to 92%, and most of the paraphrase errors disappeared. This pattern, a pretrained representation with a small trained layer on top, is how most teams should use deep learning on modest amounts of labelled data.

Averaging token vectors has one obvious flaw. “Order executed but not showing” and “order showing but not executed” contain the same words, so they average to the same vector. The first is a display problem and goes to app support; the second means an order is stuck and goes to order status. Order matters, and averaging throws it away. The next chapter is about the architecture that keeps it.

Reading what the training curves say

Before the team settled on pretrained embeddings, an engineer trained a network from scratch for 20 epochs and logged training and validation loss after each one. Here is what went wrong, because it is the most common story in the field.

Both losses fell for the first four epochs. From epoch five, training loss kept falling while validation loss rose. The engineer saved the epoch-20 weights, since they had the lowest training loss, and reported validation accuracy from epoch 4, the best epoch. Production accuracy came in four points below the report. The network had spent sixteen epochs memorising training messages, and the shipped weights were the most overfitted of the run.

The fix is early stopping: save weights after each epoch and keep the ones with the best validation loss, stopping once it has not improved for a few epochs. Two other tools slow overfitting so that the best epoch comes later and is better. Weight decay adds a small penalty for large weights. Dropout randomly zeroes a fraction of hidden units during each training step, so that no prediction can rely on any single unit. Each adds a setting to tune against validation data, and each makes a training run take longer to reach its best point.

The second failure was quieter. The network’s validation loss looked healthy, but it never predicted the fraud intent. With 1% of examples in that class, the cheapest way to lower the average loss was to give fraud a tiny probability every time. Overall loss and accuracy hid this completely, and only per-class recall exposed it. The fix was to weight fraud examples more heavily in the loss, and then, because that weighting inflates fraud scores, to choose the threshold again from validation data as in the first chapter.

What the curves showLikely causeFirst thing to try
Training falls, validation turns upwardoverfittingearly stopping, then dropout or weight decay, then more data
Both stay high and flatlearning rate too low, model too small, or a bugraise the learning rate; check the model can fit one batch
Loss jumps suddenly or becomes NaNlearning rate too high, exploding gradientslower the rate, add warmup, clip gradient size
Loss looks fine, one class never predictedclass imbalancereport recall per class, weight the rare class, re-pick the threshold

Why deep networks needed extra parts

The backward sweep multiplies one local slope per layer. Through 30 layers, if each factor is around 0.8, the gradient reaching the first layer is 0.830, about 0.001 of its original size, and the early layers barely learn. If each factor is around 1.2, it is 1.230, about 237 times larger, and training blows up. These are the vanishing and exploding gradient problems, and they kept networks shallow for years.

Four parts fixed them, and every transformer uses all four. Careful initialisation sets the starting weights at a scale where signals neither shrink nor grow from layer to layer. Normalisation layers rescale each layer’s outputs to a steady range during training. Residual connections compute each layer’s output as its input plus a learned change, x + f(x), so that the gradient always has a path backward with a factor of exactly 1, however many layers there are. Dropout, as above, keeps the larger networks this allows from memorising. When you read the next chapter’s description of a transformer block, look for these four.

When not to train a network

The escalation predictor stayed a boosted tree model. On tables of account fields, networks rarely beat boosting, take longer to train, and are harder to explain to the compliance team. Training a text network from scratch on 42,000 messages was also the wrong call, as the overfitting story shows; the pretrained embedding with logistic regression on top was cheaper, faster to retrain and more accurate. A network trained from scratch earns its cost when there is a lot of labelled data, the inputs are raw text, images or audio, and nothing pretrained covers the domain. For a support team, that combination is rare.

What the team does need is the vocabulary: weights, loss, gradients, learning rate, embeddings, overfitting. Every one of them reappears at a much larger scale in the language model that will power the assistant. The next chapter, What the model actually does, opens that model up: how text becomes tokens, how attention lets each token use the ones before it, and how a probability distribution becomes an answer to a customer.