KnowML

Sequence Modeling Pre-Transformer

Follow one sentence, "The keys that I left on the table yesterday were gone," as a recurrent network tries to carry the word keys forward to the verb eight words later. You'll see how its running memory works, why the learning signal fades over many steps, how LSTM and GRU gates keep it alive, and which limit was left for attention to remove.

⏱ 33 min readAssumes: backprop & gradients (04)
Start reading

Take the sentence "The keys that I left on the table yesterday were gone." You know without thinking that the verb is were and not was, because the subject is keys, and keys is plural. Now look at what a program has to work with. It reads one word at a time, the word just before the verb is yesterday, and the nearest noun is table, which is singular. Eight words back sits the one that decides the verb, so the program has to carry something about keys forward through everything in between. A sequence is any ordered list like this one (words, characters, audio samples, prices over time), and this chapter is about models that read sequences and have to remember.

Early statistical language models looked only at the last word or two when guessing what came next. Recurrent neural networks, developed in the 1980s and 90s and revived in the 2010s, carry a running summary instead, and the LSTM (Hochreiter & Schmidhuber, 1997) and the GRU (Cho et al., 2014) added gates so that the summary could last longer. Seq2seq (Sutskever et al., 2014) chained two of these networks together to translate, although it squeezed the whole input into one vector. Bahdanau attention (2015) let the decoder look back at every encoder state, and in 2017 Vaswani et al. asked what happens if you delete the recurrence and keep only the attention. Chapter 08 tells that story. We'll define each of these names when we get to it.

You'll need backpropagation and gradients from chapter 04. A gradient, briefly, is the signal that tells each number in a network which way to change so that its error gets smaller, and a good part of this chapter is about what happens to that signal on a long sequence. We start with the simplest memory that could carry keys to were, a summary that gets updated at every word. Then we'll see exactly how it breaks, which turns out to be arithmetic you can run yourself, and how gates repair it. After that we'll meet the next limit, the one attention was built to remove.

01Reading with a memory of fixed size

Let's begin with the most direct approach to our sentence. When you need to predict the next word, look at the last couple of words and ask what usually follows them. Count, over a huge pile of text, which words came after "table yesterday", and keep the counts as a table of next-word probabilities. That's what Markov chains and hidden Markov models (HMMs) did. They assumed that what comes next depends only on the last one or two words, so language became a table of probabilities conditioned on a short, fixed window.

Watch it fail on our sentence. When we need the verb, the window holds "table yesterday", and nothing in it says the subject was plural. A bigger window would help here, but the window size is fixed in advance, so the next sentence will put its clue one word farther back than we allowed for. A model like that can't use context from ten words back, let alone a hundred. What we want is a window that's as long as it needs to be.

Recurrent networks get there by changing what gets remembered. Picture reading our sentence with a single index card and no way to flip back. After every word you update the card so that it summarises everything you've read so far, and you throw away the exact wording. It has a fixed number of slots, so after a whole novel it has no more room than it had on page 1. When you read keys you write "plural subject" on the card. Every word after that forces another rewrite, and your note survives only if you copy it across the rewrite each time. Anything that looks irrelevant for a few words gets overwritten, and it's gone. By the time you reach were, the note has been through seven rewrites, one for each word from that to yesterday.

Our card has a name. It's a vector, a fixed-length list of numbers, and the network calls it its hidden state. It's "hidden" because it's neither the input nor the answer, just the network's own notes. Only through the hidden state can the network carry anything from the past into the present. Where the window models used a lookup table, a recurrent network uses this learned vector that changes with every word, and that's how its memory can reach back as far as it needs to.

There's a catch, and it explains most of the rest of the chapter. The rewriting that carries information forward is also the route an error signal has to take backward when the network learns. An important word that sits further back has more rewrites to survive before it reaches the present, and each rewrite is a multiplication. Before we can see what that does, we need to write the rewrite down precisely.

02The same cell at every step

A recurrent network applies the same set of weights, the grids of numbers it learns, at every timestep, where a timestep is one position in the sequence. At step it takes two inputs. One is the current word, , which arrives as an embedding, the list of numbers the network has learned for that word. The other is the hidden state it had after the previous step, . Out comes a new hidden state, . In the plain version, called a vanilla RNN, the update looks like this:

Here is what each piece does.

  • h_t the hidden state after processing elements. A fixed-size vector, and the network's entire memory of everything it has seen so far.
  • W_h, W_x weight matrices shared across every timestep. The same multiplies the hidden state whether it's step 2 or step 200.
  • x_t is the input at this timestep, for example a word embedding.
  • b is a bias, a vector of numbers added in before the squashing step.
  • tanh squashes the result into the range , which keeps the state bounded. Its derivative is at most 1, and it's typically much less than 1 almost everywhere except near 0. We'll need that fact in a moment.

Because the weights are reused, the network has the same number of parameters for a sentence of ten words or ten thousand. Drawing the cell once per timestep, with the hidden state as the wire joining one copy to the next, is called unrolling the network. The diagram below unrolls five steps. Its five orange boxes are one cell used five times, the amber lines carry the hidden state, and on the far left is the starting state. Follow the path from : to affect the final state , the pulsing circle on the right that the diagram labels a "fixed-size context vector" because it holds the summary of everything read, it has to pass through the cell four more times.

A vanilla RNN unrolled across 5 timesteps — hidden state flowing left to right
h₀ init RNN x₁ RNN x₂ RNN x₃ RNN x₄ RNN x₅ h₁ h₂ h₃ h₄ h₅ fixed-size context vector
Same weights, five times. Every hidden state ht is a function of xt and ht-1 only, so information from x₁ can reach h₅ only by surviving four sequential updates. When we get to seq2seq translation in section 06, that final h₅ (pulsing) becomes the entire summary the decoder gets of the whole input, whether the sequence was 5 words or 500.

Why can't the steps run at the same time?

Because depends on . Step 500 can't start until step 499 has finished, since each step's input is the previous step's output. That's the direct cause of a fact you'll probably hear often, that RNNs can't be parallelized across the sequence, meaning their steps can't be spread over many processors working simultaneously. A GPU, the chip most networks train on, is fast precisely because it does a great many computations at once, and a recurrent network gives it little to do at once along the sequence. A Transformer's attention layer (chapter 08) has no such dependency and can compute every position together.

So the memory exists, in the sense that information can in principle ride the hidden state from keys to were. Whether the network can learn to use it is a separate matter. It depends on whether the training signal can find its way back along the same eight steps, and that's where plain RNNs ran into trouble.

03Why the learning signal fades

Suppose the network reaches were, predicts "was", and gets marked wrong. Training has to push that error back into the weights, and for that it has to work out how much the hidden state after keys contributed to the mistake. Put another way, it needs to know how much a small nudge to an early hidden state would change a later one. That's a derivative, and backpropagation, which you met in chapter 04, gets it for a long chain with the chain rule: multiply together the derivative of every step in the chain. Each step's derivative is itself a grid of numbers called a Jacobian, which records how much every entry of moves when you nudge each entry of . For steps between the first hidden state and the last, the product is:

Between keys and were there are eight such factors. Look at what each one contains. Every factor has the same matrix , multiplied by a derivative of tanh that's bounded by 1. Multiply numbers that are each consistently a bit less than 1 and the product shrinks toward zero exponentially fast as grows. This is the problem of vanishing gradients. The error signal from were reaches keys too weak to teach the network anything.

To see how fast that happens, we can replace the whole matrix with a single number and multiply a gradient by it once per step back. Starting the gradient at 1, the code below multiplies by w = 0.5 in a loop, and prints it after 1, 5, 10 and 20 steps. Its last line shows what a weight of 1.5 would do over the same twenty steps.

Try it Multiply a gradient by the same weight twenty times
w = 0.5                        # a recurrent weight below 1
grad = 1.0
for t in range(1, 21):
    grad *= w                  # each step back multiplies the gradient
    if t in (1, 5, 10, 20):
        print(f"{t:>2} steps back: gradient x {grad:.7f}")

print(f"\nwith w = 1.5, after 20 steps: x {1.5 ** 20:,.0f}")
With a weight of 0.5, the gradient is 0.5 after one step, 0.03125 after five and about a millionth (0.0000010) after twenty. With a weight of 1.5, the same twenty steps multiply it by 3,325 instead.

With a weight of 0.5 the gradient is already a thirty-second of its size after five steps, and after twenty it's about a millionth. Our eight steps from keys to were would leave about 0.004 of the signal, and a longer sentence would leave next to nothing. Now for the opposite failure. A weight of 1.5 turns a gradient of 1 into 3,325, and a real network has many numbers in play, so that kind of growth makes the weights jump wildly. Both directions break training.

Growth has a name too. If the dominant eigenvalue of is greater than 1, meaning the largest factor by which the matrix stretches a vector along the direction it stretches most, the product grows exponentially instead of shrinking. These are exploding gradients, and they show up as the loss suddenly spiking to NaN, the "not a number" value you get when arithmetic overflows.

Which failure is worse, vanishing or exploding?

In practice vanishing is the far more common one and the more damaging one. Exploding is loud, because training visibly crashes and you go looking for the cause. Vanishing doesn't crash anything. Loss keeps going down while the model is quietly unable to learn dependencies more than roughly 10 to 20 steps apart. Our sentence is eight steps wide, so it's inside that range, but add a few more clauses between keys and the verb and it isn't.

You've seen this mechanism before. Chapter 04 met the same repeated matrix multiplication when a deep feedforward network is initialised badly. An RNN unrolled over timesteps is, mathematically, a -layer-deep network whose layers all share the same weights, so a long sequence is a very deep network. What we want is a path for the gradient where no single step shrinks it much, and that's what gates provide.

04Gates: memory that isn't rewritten at every step

LSTM: the cell state and three gates

Think about where the damage comes from. At every step the hidden state is rebuilt from scratch: it's multiplied by , combined with the new word, and squashed by tanh. Anything we want to keep has to survive that rebuild, and so does its gradient on the way back. Hochreiter & Schmidhuber's 1997 fix is to stop rebuilding part of the memory. They gave the network a second, separate piece of state, the cell state , and update it almost additively: take the old cell state, keep some of it, and add something new. Adding involves no repeated matrix multiplication and no squashing.

If the cell state only ever grew, though, it would fill up with old notes and never forget anything. So the network needs to control how much to keep, how much to write, and how much to show. Each of those is a gate, a vector of numbers between 0 and 1 that multiplies another vector entry by entry. Near 1 an entry passes through, and near 0 it's blocked. A gate gets its values from a sigmoid, written , which squashes any number into the range 0 to 1, and the gates are computed from the previous hidden state and the current input joined end to end, written . In the equations, means multiplying two vectors entry by entry. Three gates plus the cell state make up the LSTM (long short-term memory):

  • f_t forget gate. Decides what fraction of the old cell state to keep, per dimension. Near 1 means "remember this," near 0 means "erase this."
  • i_t input gate. Decides how much of the new candidate information to write into the cell state.
  • C̃_t candidate values. What the network could add to memory this step, before the input gate decides how much gets written.
  • C_t the cell state update. A forget-gated copy of the old cell state plus an input-gated new candidate. The update is additive and elementwise, with a and no matrix multiply.
  • o_t output gate. Decides how much of the squashed cell state gets exposed as the hidden state feeding the next layer and the next timestep.

Run our sentence through it. At keys, the input gate can learn to open on a dimension that stands for "plural subject" and write that into the cell state. Across the seven words that follow, the forget gate on that dimension can stay near 1, so the note rides along untouched. At were, the output gate lets it influence the hidden state that predicts the verb. Nobody programs this. The weights behind the gates are learned like all the others, and training finds whatever keeps the cell state useful. In Chris Olah's diagram below, the top horizontal line is the cell state, and the three boxes under it are the forget, input and output gates.

LSTM cell internals showing the forget gate, input gate, candidate values, and output gate
Reference figureOne LSTM cell, unrolled — the top horizontal line is the cell state's additive highway; the three sigmoid gates (σ) below it are the forget/input/output gates. Source: Christopher Olah, Understanding LSTM Networks.

Why keep a separate cell state at all?

Because the hidden state has a different job. It's what the rest of the network sees at every step, so it passes through the output gate and a tanh each time. Cell state is the protected side channel. It changes only through a forget-gated copy of itself plus a gated addition, which is what lets a note survive many steps.

GRU: the simpler cousin

The Gated Recurrent Unit (Cho et al., 2014) asks whether you need three separate gates and two separate states. It merges the cell state and hidden state into one. Forget and input collapse into a single update gate , joined by a reset gate that controls how much past state is used when computing the candidate:

Look at the last line. The new state is a convex combination of the old state and a new candidate, a weighted average whose two weights, and , add up to 1. It's the same additive blend as the LSTM's, with no repeated matrix multiplication. A GRU has fewer parameters and fewer matrix multiplies per step, and in practice it performs roughly comparably to an LSTM on most tasks. That's why GRUs became the default choice when you needed an RNN and wanted it cheaper, in the years between LSTM's dominance and attention's takeover. Both designs rest on one claim about gradients, and it's time to check it.

05Why gating fixes vanishing gradients

Go back to the cell state update, , and ask the question from section 03: how much does a change in change ? Differentiate with respect to , ignoring the comparatively minor dependence of the gates themselves on , and you get . That's just the forget gate, elementwise. There's no repeated multiplication by a fixed weight matrix squashed through tanh at every step.

So if the network learns to set for a dimension carrying an important long-range signal, such as "plural subject" in our sentence, the gradient passes through that step almost unchanged. Chain that across many steps. The path is still as long as before, but each step is now close to an identity multiplication, where before it was lossy. The network can learn to keep this highway open, and a vanilla RNN has no mechanism for keeping it open at all.

If this reminds you of something, it should. It's the trick behind the residual connection in a ResNet or a Transformer block (see 04 and 08): give information an additive, near-identity shortcut that a gradient can flow through undiminished, so it never has to pass through a transformation at every step. The transformation becomes an optional adjustment on top and is no longer the only path. LSTM's cell state is a gradient highway through time, in the same sense that a residual stream is a gradient highway through depth. The failure is the same, repeated lossy transformations, and so is the fix, an additive path that bypasses them.

Gating doesn't make the vanishing gradient problem disappear entirely. With poor initialization, or extremely long sequences of thousands of steps, LSTMs still degrade. What it does is push the range of dependencies the network can learn from roughly 10 to 20 steps out to several hundred, and that was enough to make RNNs useful for translation, speech, and language modeling for most of the 2010s. Translation, though, brings a limit of a different kind.

06Encoders, decoders and one vector

Translating with two networks

Translating a sentence means reading one sequence and writing another, and the two can differ in length. The architecture that dominated neural machine translation until attention arrived, sequence-to-sequence or seq2seq (Sutskever et al., 2014), uses two recurrent networks to do it. An encoder reads the source sentence and ends with a final hidden state. A decoder, a second network, starts from that vector and writes the translation one word at a time, feeding each word it produces back in as its next input.

Reading in both directions

One limitation of a plain left-to-right RNN is easy to fix. Its hidden state at position knows only the words before , never the ones after. When the whole sequence is available up front, you can run a second RNN right to left over the same input and join the two hidden states at each position. That's a bidirectional RNN, and now every position has context from both sides. It suits tasks like these:

  • Tagging. Labelling each word, with its part of speech or as a named entity, where the word after often disambiguates the word before.
  • Classification. The whole sentence is in hand before you need a verdict.
  • Encoding for translation. The source sentence is fully known, and only the target is generated left to right.

Notice what this doesn't touch. It doesn't fix vanishing gradients, only a blind spot. That's why encoders in seq2seq systems were very often bidirectional while decoders never were. A decoder generates left to right and can't peek at words it hasn't produced yet.

The second bottleneck

However the encoder reads, the decoder receives only its final hidden state. Look back at the unrolled diagram, where the final pulsed. In seq2seq that one vector is the entire summary the decoder gets of the source, and it has the same fixed length whether the source had 5 words or 500. A longer sentence means more to compress into the same number of slots, so quality drops as sentences grow, and gating doesn't change the size of that vector. Bahdanau attention (2015) let the decoder look back at every encoder state instead of just the last one, and in 2017 Vaswani et al. asked what happens if you delete the RNN and keep only the attention (chapter 08). Production notes after the Build section come back to seq2seq, including how its decoder is trained. For now, here are the designs side by side.

07RNN, LSTM, GRU and Transformer side by side

We've now met four ways to read a sequence: the vanilla RNN, the LSTM, the GRU, and the Transformer, the attention-based architecture of chapter 08. The table lines them up on what we've seen so far. How far apart can two words be before the model stops linking them? How does the gradient travel? Can the steps run at once? And what does each one cost?

Vanilla RNNLSTMGRUTransformer
Parallelizable across sequenceNoNoNoYes, fully
Max useful dependency range~10–20 stepsSeveral hundred stepsSeveral hundred steps path, any distance
Gate / gradient pathNone — repeated · tanh' every step3 gates, additive cell state2 gates, additive hidden stateNo recurrence — direct attention weight
Params per cell (roughly) baseline (4 weight sets) (3 weight sets)Different regime — scales with and depth, not sequence length
Inference cost per generated token, tiny state, tiny state, tiny stateGrows with KV cache — see 08

The first three rows repeat the chapter: recurrent models can't run their steps at once, the gated ones reach several hundred steps where the vanilla one reaches 10 to 20, and the Transformer connects any two positions through a single attention weight. Parameters follow from the equations: an LSTM has four weight sets (forget, input, candidate and output), a GRU has three (update, reset and candidate), and a vanilla RNN has one. For the Transformer, is the width of its vectors, and its parameters grow with that width and with depth, not with sequence length. The last row is probably the one that surprises people.

Did RNNs lose on everything?

No. They never lost the argument on inference efficiency. A recurrent model's memory is a fixed-size vector, however long the conversation gets, while a Transformer has to keep a stored entry for every token it has already processed, called the KV cache, and that grows with every token it generates. RNNs lost on trainability and parallelism at scale. That trade is exactly why state-space models (Mamba-style, a newer family of recurrent-style models) resurfaced in the 2020s as a research direction. See the 2026 status note on page 08.

08Summary

  1. A recurrent network reads with a fixed-size memory. The hidden state is a vector, rewritten at every word, and it's the only thing that carries the past into the present. That replaced the short fixed window of Markov chains and HMMs, which couldn't use context beyond a word or two.
  2. One cell, used at every step. with the same weights each time, so the parameter count doesn't depend on length. Because each step needs the one before, the steps can't run in parallel.
  3. The learning signal is a product of Jacobians. Sending a gradient back steps multiplies it by the same and a tanh derivative at most 1 each time, so it shrinks or grows exponentially in .
  4. Vanishing is the one that hurts. Exploding gradients crash training loudly with NaN. Vanishing ones silently leave a vanilla RNN unable to learn dependencies more than roughly 10 to 20 steps apart.
  5. The LSTM gives memory an additive path. A separate cell state is updated as , with forget, input and output gates, all sigmoids between 0 and 1, deciding what to keep, write and show.
  6. The GRU does the same with less. It merges the two states, uses two gates, and blends the old state and a new candidate. It performs about as well on most tasks at lower cost.
  7. Gating works because . With the forget gate near 1 each step is close to an identity, a gradient highway through time, much like a residual connection turned sideways. It stretches the useful range from 10 to 20 steps to several hundred without removing the problem.
  8. Seq2seq adds a second bottleneck. The decoder sees the source only through the encoder's final state, one fixed-size vector whether the input is 5 words or 500. Bidirectional encoders fix a blind spot, not that limit.
  9. Attention removes both limits. Letting every position look at every other gives an path and parallel computation, at the cost of an inference memory that grows with length.
  10. RNNs still win on inference memory and lose on training. A fixed-size state costs the same per token however long the conversation, but recurrence can't be parallelised and gradients still decay. In one line: RNNs forget because gradients decay multiplicatively over time, and the fixes either build a straighter path for the gradient (LSTM, GRU) or remove the sequential bottleneck entirely (attention).

09Build this

This page claims a vanilla RNN gives up somewhere around 10 to 20 steps, and that gating stretches that to several hundred. Both of those are numbers you can measure yourself, on a laptop CPU.

Project Find the exact gap length where an RNN forgets ~4 hours · PyTorch

Train a recurrent network on the remember-one-bit task. The first element of the sequence is 0 or 1. Then come steps of noise, and the model must output that first bit at the end. Guessing scores 50%, so there is exactly one thing to look at. Sweep and find where the model stops beating a coin.

  1. Write the vanilla RNN cell by hand from the update rule in section 02, plus one linear head on the final hidden state. Avoid nn.RNN.
  2. Generate the task on the fly. Train a fresh model for each gap length in 5, 10, 20, 40, 80, 160.
  3. Plot final accuracy against . Mark the length where the curve drops to chance and stays there.
  4. Log the gradient norm at the first timestep, , for every . Plot it on a log axis beside the accuracy curve.
  5. Swap in an LSTM cell, also written by hand from the six equations in section 04. Rerun the identical sweep, extending it to longer until this one fails too.
  6. Now break the LSTM on purpose. Initialise the forget-gate bias to a large negative value, so starts near 0, and rerun the sweep.
You'll know it worked when both accuracy curves show a cliff rather than a slope. The vanilla RNN's cliff arrives first and the LSTM's much later. The gradient-norm plot collapses toward zero at the same gap length where the RNN's accuracy does. Those two curves, side by side, are the argument this whole page makes.
What the breakage teaches. Forcing the forget gate shut drags the LSTM's cliff back toward the vanilla RNN's. No architecture changed. One bias did. That isolates the claim in section 05: the gates are not what buys you range. sitting near 1 is, because that is what keeps each step of the gradient path close to an identity.

Where this runs in production: seq2seq machine translation, pre-attention

Sutskever, Vinyals & Le's 2014 "Sequence to Sequence Learning with Neural Networks" set up the architecture that dominated neural machine translation until attention arrived. Two pieces:

  • Encoder LSTM. Reads the source sentence and produces one final hidden state.
  • Decoder LSTM. Initialized with that vector, it generates the target sentence one word at a time, feeding each generated word back in as the next input.

During training you don't feed the decoder its own predictions, which are possibly wrong early on. You feed it the true previous word from the training data. This is teacher forcing, and it makes training converge much faster and easier to parallelize across timesteps within a batch.

But it creates a mismatch: at inference time there's no ground truth to feed back in, so the model must consume its own predictions, mistakes included, which it never practiced doing. That mismatch is exposure bias. Small errors early in generation can compound, because the model is now in a distribution of inputs (its own imperfect outputs) it rarely saw during training.

Sentences got noticeably worse as they got longer, for exactly the reason you'd expect. Everything the decoder knows about the source has to fit through one fixed-size vector, and the pressure on that vector only grows with sentence length. That's the precise, named problem Bahdanau attention was built to solve, and the one page 08 picks up from here.

Where this runs in production: CTC in speech recognition

Speech recognition has a labeling problem seq2seq doesn't directly solve. An audio signal sampled into, say, 200 frames needs to map to a transcript of maybe 12 words. You don't know in advance which frames correspond to which letters. There's no frame-level alignment in the training data.

Connectionist Temporal Classification (CTC) solves this in two moves:

  • Emit at every frame. The network outputs a probability distribution over characters, plus a special "blank" token, at every frame.
  • Collapse many-to-one. A fixed rule (merge repeated characters, drop blanks) maps many different frame-level output sequences onto the same final transcript.

Training sums the probability over every alignment that collapses to the correct label, using dynamic programming. Per-frame labels are never required.

The key structural difference from seq2seq is alignment. CTC assumes monotonic alignment, where frame order matches output order and is never reordered, and produces one output per input frame that then gets collapsed. Seq2seq's encoder-decoder has no such constraint. It can freely reorder or vary output length relative to input length, which is necessary for translation where word order differs between languages, but more than speech recognition needs.

CTC-based and CTC-hybrid systems are still in production in real-time speech recognition today. The monotonic assumption holds there, and the lower latency of a single forward pass matters, with no separate decoder generating token by token.

10Interview questions

BeginnerWhat does an RNN's hidden state actually represent?

A fixed-size vector that's the network's entire summary of everything it has read so far. It's recomputed at every timestep from the previous hidden state and the current input using the same shared weights, which is what lets the network handle sequences of any length with a fixed number of parameters — and also what forces arbitrarily long histories through a fixed-size bottleneck.

BeginnerWhy can't RNNs parallelize across the sequence dimension?

Because is defined as a function of — you literally cannot compute the hidden state at step until you have the hidden state at step . That sequential data dependency means processing a length- sequence takes sequential steps no matter how much parallel hardware you have, unlike a Transformer where every position's attention computation is independent and can run simultaneously.

IntermediateWalk me through exactly why vanilla RNN gradients vanish over long sequences.

is a product of Jacobians, each roughly — the same weight matrix and a tanh derivative bounded by 1, multiplied together times. If the typical factor is less than 1 (the common case), the product shrinks exponentially with , so gradients from far-future errors barely reach far-past parameters — the network can't learn long-range dependencies, not because it doesn't need to, but because the learning signal never arrives intact. If the dominant eigenvalue of exceeds 1, you get the opposite failure — exploding gradients.

IntermediateWalk me through why LSTMs fix vanishing gradients.

LSTM keeps a separate cell state updated additively: . Differentiating that with respect to gives approximately just the forget gate , not a repeated multiplication by a fixed weight matrix squashed through tanh. If the network learns for dimensions carrying important long-range information, the gradient passes through that step almost unchanged — an additive, near-identity path, the same mechanism as a residual connection, just through time instead of through depth.

IntermediateGRU vs. LSTM — when would you pick one over the other?

GRU merges the cell and hidden state into one and uses two gates instead of three, so it has fewer parameters and is cheaper per step. Empirically the two perform comparably on most tasks; GRU is the reasonable default when you want a lighter, faster-to-train recurrent model, LSTM when you have the compute budget and want the extra expressiveness of a separate, more protected cell state. In an interview, the important part is knowing they solve the same problem (multiplicative gradient decay) with the same core mechanism (an additive gated update) — the exact gate count is a secondary detail.

IntermediateWhat's the difference between teacher forcing and exposure bias?

Teacher forcing is a training-time choice: feed the decoder the ground-truth previous token instead of its own prediction, which speeds up and stabilizes training. Exposure bias is the consequence at inference time: the model never practiced conditioning on its own (possibly wrong) outputs, so at generation time small early mistakes push it into an input distribution it wasn't trained on, and errors can compound across the sequence.

DeepWhy does seq2seq degrade on long sentences, specifically, and how does attention fix it?

The decoder's only view of the entire source sentence is the encoder's final hidden state — one fixed-size vector, regardless of whether the source is 5 or 50 words. As sentence length grows, that vector has to compress proportionally more information into the same number of dimensions, and early words in the source are also the ones that had to survive the most sequential updates to even reach that final state — compounding the vanishing-gradient problem with a genuine information bottleneck. Attention removes the bottleneck by letting the decoder access every encoder hidden state directly at every decoding step, weighted by relevance, instead of relying on all of them being compressed into one vector — see 08 for the full mechanism.

DeepHow does CTC training work without frame-level alignment labels, and how is that different from seq2seq?

CTC outputs a distribution over the label vocabulary plus a blank token at every input frame, then defines a deterministic collapsing function (merge adjacent repeats, drop blanks) mapping many possible frame-level sequences to one label sequence. Training marginalizes — sums the probability — over every alignment that collapses to the correct label, computed efficiently with a forward-backward dynamic program, so no frame-level ground truth is ever needed, only the final label sequence. This requires monotonic, one-input-frame-to-one-output-slot alignment. Seq2seq has no such constraint — the decoder generates one token at a time conditioned on the whole encoded input (or, with attention, all encoder states) and can reorder or change length freely relative to the input, which is necessary for translation but is more flexibility than monotonic tasks like speech-to-text strictly require.

11Go deeper

●Now write it yourself

Reading the derivation and being able to produce it are different skills. These are Deep-ML problems that exercise what this page covers — each one is checked against real test cases, not multiple choice.

Matched to this page from Deep-ML's catalogue of 1,380 problems. More at deep-ml.com, and Where to practise covers the other platforms and what each one trains.