# AIpedia > The AI Encyclopedia: a growing collection of time-tested cool things in AI (papers, software, interviews, positions, demos, and blogs), the things worth knowing on the way into the singularity. Each entry has a plain-language explanation, an interactive demo on the website, and links to the originals. Source: https://aipedia.org. 58 entries follow. # AlexNet > The deep CNN that won ImageNet 2012 and sparked the deep learning revolution - Type: Paper - By: Krizhevsky, Sutskever & Hinton - Year: 2012 - Topics: Deep learning, CNNs, Vision, Imagenet - Page: https://aipedia.org/alexnet ## Resources - [ImageNet Classification with Deep Convolutional Neural Networks](https://papers.nips.cc/paper/4824-imagenet-classification-with-deep-convolutional-neural-networks): Paper, Krizhevsky, Sutskever & Hinton, 2012 **AlexNet** is the deep convolutional neural network that won the 2012 ImageNet Large Scale Visual Recognition Challenge (ILSVRC). It cut the top-5 error rate from 26% to 15.3%, a huge jump that convinced the field that deep learning could dramatically outperform traditional computer vision methods. > If convolutional networks are new to you, start with [CS231n](https://aipedia.org/cs231n), Stanford's course on CNNs. For what came after AlexNet, see [ResNet](https://aipedia.org/resnet). ## Why Students Should Care - AlexNet is widely considered the **starting gun of the modern deep learning era**. Almost every architecture you will study came after it, and often in response to it. - Its ingredients — ReLU, [dropout](https://aipedia.org/dropout), GPU training, big datasets — are still standard practice today. - It is a compact case study in why deep learning works: a simple recipe, scaled up, beating years of hand-crafted engineering. ## The Problem It Solved Before 2012, image classification systems were built by hand: researchers designed feature detectors (edges, corners, textures) and then trained a shallow classifier on top. Progress was slow and incremental. AlexNet took the opposite approach: feed the network raw pixels and let it **learn its own features** from 1.2 million labeled ImageNet images. The result was not a small improvement — it was a 10+ percentage point gap over the runner-up. ## Architecture AlexNet consists of 8 learned layers: 5 convolutional and 3 fully-connected: $$ \text{Input} \rightarrow \text{Conv}_1 \rightarrow \text{Conv}_2 \rightarrow \text{Conv}_3 \rightarrow \text{Conv}_4 \rightarrow \text{Conv}_5 \rightarrow \text{FC}_6 \rightarrow \text{FC}_7 \rightarrow \text{FC}_8 $$ The network takes a 224×224 RGB image and processes it through progressively smaller spatial dimensions but increasing channel depth. Intuitively, early layers see small patches and detect simple patterns; later layers see larger regions and detect whole objects. The final layer is a 1000-way softmax, one output per ImageNet category. ## Key Innovations **ReLU activation.** Instead of tanh or sigmoid, AlexNet used Rectified Linear Units: $$ f(x) = \max(0, x) $$ In plain English: pass positive values through, zero out negative ones. Because ReLU does not flatten out (saturate) for large positive inputs, gradients stay healthy and training runs about 6× faster than with tanh. **Dropout.** During training, neurons are randomly zeroed with probability 0.5: $$ \tilde{h} = h \cdot m, \quad m_i \sim \text{Bernoulli}(0.5) $$ The idea: if any neuron can vanish at any moment, no neuron can rely too heavily on specific partners. This prevents complex co-adaptations and reduces overfitting in the large fully-connected layers. See [Dropout](https://aipedia.org/dropout) for the full story. **Local Response Normalization.** Inspired by lateral inhibition in biological neurons (active neurons suppressing their neighbors), LRN normalizes activations across adjacent feature maps at each spatial position. **Overlapping pooling.** Using 3×3 pooling windows with stride 2 — so neighboring windows overlap — slightly reduced error rates compared to non-overlapping pooling. You do not need to memorize the details. The important idea is: **each trick either made training faster (ReLU, GPUs) or fought overfitting (dropout, pooling choices)**. ## Interactive Demo Explore AlexNet's layer-by-layer architecture and key innovations: *Interactive demo: https://aipedia.org/alexnet* ## Historical Impact AlexNet's victory was decisive: the runner-up used hand-crafted features and achieved 26.2% error. That 10+ percentage point gap proved three things at once: - Deep networks could learn hierarchical features automatically — no hand engineering needed - GPUs were essential for training large models - Sufficient data (1.2M ImageNet images) enables generalization The paper has over 100,000 citations and is considered the catalyst of the modern deep learning era. ## Common Confusion - **AlexNet did not invent convolutional networks.** CNNs existed earlier; AlexNet showed that a deep CNN, trained on GPUs with enough data, could win at scale. - **AlexNet is a specific architecture; ImageNet is the dataset; ILSVRC is the competition.** "Winning ImageNet" is shorthand for winning the ILSVRC challenge on the ImageNet dataset. - **[Dropout](https://aipedia.org/dropout) has its own paper and page.** AlexNet is one of its most famous applications, not its origin. ## Where To Go Next - Read [ResNet](https://aipedia.org/resnet) for how skip connections took networks from 8 layers to 150+ - Read [Dropout](https://aipedia.org/dropout) for a deeper look at AlexNet's regularization trick - Read [CS231n](https://aipedia.org/cs231n) for the Stanford course that teaches this whole lineage - Read [Vision Transformer](https://aipedia.org/vision-transformer) for the architecture that eventually challenged CNNs # Deep Q-Networks (DQN) > Combining Q-learning with deep neural networks for Atari-level game playing - Type: Paper - By: Mnih et al. - Year: 2013 - Topics: Deep learning, Reinforcement learning, Games, Classic - Page: https://aipedia.org/dqn ## Resources - [Playing Atari with Deep Reinforcement Learning](https://arxiv.org/abs/1312.5602): Paper, Mnih et al., 2013 - [google-deepmind/dqn](https://github.com/google-deepmind/dqn): Code, Original Lua/Torch code - [Human-level control through deep reinforcement learning](https://www.nature.com/articles/nature14236): Paper, Mnih et al., Nature 2015 - [Rainbow: Combining Improvements in Deep Reinforcement Learning](https://arxiv.org/abs/1710.02298): Paper, Hessel et al., 2017 **Deep Q-Networks (DQN)** showed that a neural network could learn to play Atari games at superhuman level directly from raw pixels, using nothing but trial and error. It was the landmark result that sparked the modern deep reinforcement learning revolution. > If terms like "Q-value" or "policy" are new to you, read [Reinforcement Learning](https://aipedia.org/reinforcement-learning) first. This page covers the classic **value-based** approach; [Policy Gradient](https://aipedia.org/policy-gradient) covers the other big family. ## Why Students Should Care - DQN is the standard first "deep RL" algorithm: it connects supervised deep learning to reinforcement learning. - Its two stabilization tricks (experience replay and target networks) show up all over modern RL. - It opened the door to AlphaGo, robotic control, and much of today's RL research. ## The Setup in Plain English Imagine learning to play a video game with no instructions. All you see is the screen, all you get is the score. You need a way to answer one question at every moment: **"How good is each button press right now, counting all the points it will lead to later?"** A function that answers that question is called a **Q-function**. DQN's whole job is to learn it with a neural network. ## Q-Learning Refresher Q-learning tries to learn the optimal action-value function: the best total future reward you can get by taking action $a$ in state $s$ and playing well afterwards. $$ Q^*(s, a) = \mathbb{E}\left[r + \gamma \max_{a'} Q^*(s', a') \mid s, a\right] $$ In words: the value of an action equals the immediate reward, plus the (discounted) value of the best action available in the next state. Once you know $Q^*$, acting well is easy — just pick the highest-scoring action: $\pi^*(s) = \arg\max_a Q^*(s, a)$. ## The Challenge: Too Many States for a Table Classic Q-learning stores one Q-value per state-action pair in a table. That works for tiny grid worlds, but an Atari screen has far too many possible pixel configurations to enumerate. The fix is to **approximate** the table with a neural network: $$ Q(s, a; \theta) \approx Q^*(s, a) $$ Here $\theta$ is the network's weights. But there is a catch: naively combining deep learning with Q-learning is unstable. The network chases its own predictions and training tends to blow up. DQN's real contribution is two tricks that make it stable. ## Key Innovations ### 1. Experience Replay Instead of training on experiences in the order they happen, store each transition $(s, a, r, s')$ in a large **replay buffer** and train on random mini-batches drawn from it. Why this helps: - Consecutive game frames are nearly identical. Random sampling breaks that correlation, which neural networks need for stable training. - Each experience gets reused many times, so learning is more data-efficient. - Overall, training becomes much more stable. ### 2. Target Network The Q-learning update is strange: the network's training target is computed *from the network itself*. As the network changes, its own targets shift underneath it — like an archer aiming at a target strapped to their own arm. DQN fixes this by computing targets with a frozen copy of the network: $$ y = r + \gamma \max_{a'} Q(s', a'; \theta^-) $$ where $\theta^-$ is a copy of $\theta$ that is only refreshed periodically (e.g., every 10k steps). Between refreshes the target stays still, which dramatically improves stability. ## The DQN Loss Put together, DQN minimizes a squared error between predicted Q-values and the (frozen-target) estimates: $$ \mathcal{L}(\theta) = \mathbb{E}_{(s,a,r,s') \sim \mathcal{D}}\left[(y - Q(s, a; \theta))^2\right] $$ where $y = r + \gamma \max_{a'} Q(s', a'; \theta^-)$. You do not need to memorize the equation. The important idea is: **make the network's Q-value prediction match "reward plus best next-state value", using a stale copy of the network for the second part.** ## Interactive Visualization Watch DQN learn to estimate Q-values: *Interactive demo: https://aipedia.org/dqn* ## Algorithm ```python Initialize replay buffer D, Q-network θ, target network θ⁻ for episode in range(num_episodes): s = env.reset() for t in range(max_steps): # ε-greedy action selection if random() < ε: a = random_action() else: a = argmax_a Q(s, a; θ) s', r, done = env.step(a) D.store(s, a, r, s', done) # Sample and train batch = D.sample(batch_size) targets = r + γ * max_a' Q(s', a'; θ⁻) * (1 - done) loss = MSE(Q(s, a; θ), targets) θ.update(loss) # Periodic target update if t % target_update_freq == 0: θ⁻ = θ ``` The "ε-greedy" part handles **exploration**: with probability ε the agent tries a random action instead of its current best guess, so it keeps discovering new strategies. ## Hyperparameters | Parameter | Typical Value | |-----------|---------------| | Replay buffer size | 1M transitions | | Batch size | 32 | | Learning rate | 0.00025 | | Discount γ | 0.99 | | Target update freq | 10,000 steps | | ε decay | 1.0 → 0.1 over 1M steps | ## Improvements (Rainbow DQN) Later work stacked several upgrades on top of vanilla DQN. The combination is called **Rainbow**: | Enhancement | Benefit | |-------------|---------| | Double DQN | Reduces overestimation bias | | Prioritized replay | Focus on important transitions | | Dueling networks | Separate value and advantage | | Multi-step returns | Better credit assignment | | Distributional RL | Model return distribution | | Noisy networks | Better exploration | ## Impact DQN proved that: 1. Deep RL can learn from high-dimensional sensory input (raw pixels) 2. Experience replay + target networks stabilize training 3. A single architecture can master diverse tasks This opened the door to AlphaGo, robotic manipulation, and modern RL research. ## Common Confusion - **DQN vs. Q-learning**: Q-learning is the underlying update rule; DQN is Q-learning plus a neural network approximator plus the two stability tricks. - **Value-based vs. policy-based**: DQN never represents a policy directly — it learns action *values* and derives the policy by taking the argmax. [Policy Gradient](https://aipedia.org/policy-gradient) methods learn the policy itself. - **Target network vs. replay buffer**: both fight instability, but differently. Replay breaks *sample correlation*; the target network stops the *moving target* problem. - **DQN and continuous actions**: the $\max_{a'}$ step requires enumerating actions, so vanilla DQN only works for discrete action spaces. ## Where To Go Next - Read [Reinforcement Learning](https://aipedia.org/reinforcement-learning) for the MDP framing and value functions DQN builds on. - Read [Policy Gradient](https://aipedia.org/policy-gradient) for the other major family of RL algorithms. - Read [PPO](https://aipedia.org/ppo) for the policy-based algorithm that dominates modern practice. - Read [RLHF](https://aipedia.org/rlhf) to see how RL ideas reach language model training. # Neural Machine Translation by Jointly Learning to Align and Translate > The paper that introduced the attention mechanism for sequence-to-sequence models - Type: Paper - By: Bahdanau, Cho & Bengio - Year: 2014 - Topics: Deep learning, Attention, NLP, Translation - Page: https://aipedia.org/bahdanau-attention ## Resources - [Neural Machine Translation by Jointly Learning to Align and Translate](https://arxiv.org/abs/1409.0473): Paper, Bahdanau, Cho & Bengio, 2014 - [Attention and Augmented Recurrent Neural Networks](https://distill.pub/2016/augmented-rnns/): Article, Olah & Carter, Distill 2016 This landmark paper by Bahdanau, Cho, and Bengio introduced the **attention mechanism** for neural machine translation: instead of squeezing a whole sentence into one vector, let the decoder look back at the input and pick what is relevant at each step. It is one of the most influential papers in modern AI. > If this page feels too fast, read [Sequence to Sequence](https://aipedia.org/seq2seq) first — this paper fixes seq2seq's biggest weakness. For where attention went next, see [Transformer](https://aipedia.org/transformer). ## Why Students Should Care - This is where **attention** — the mechanism behind Transformers and every modern LLM — was born. - It is a perfect case study in research: identify a bottleneck, design a mechanism that removes it, measure the gain. - The idea generalizes far beyond translation: "let the model choose what to look at" shows up in vision, speech, and multimodal models. ## A Quick Example Imagine translating a 50-word German sentence into English. A standard seq2seq model forces you to read the whole sentence once, memorize it as a single fixed-size summary, then write the translation purely from memory. A human translator does not work that way — they glance back at the relevant source words while writing each output word. Attention gives the model that ability to glance back. ## The Bottleneck Problem In standard seq2seq models, the encoder compresses the entire input into a fixed-size context vector $c$: $$ c = f(x_1, x_2, ..., x_T) $$ This becomes a bottleneck for long sequences — all information must squeeze through a single vector, no matter how long the input is. ## The Attention Solution Instead of a single context vector, attention computes a **different context for each output step**: $$ c_i = \sum_{j=1}^{T} \alpha_{ij} h_j $$ where $\alpha_{ij}$ is the attention weight that output position $i$ places on input position $j$, and $h_j$ is the encoder state for input word $j$. The important idea is: each output word gets its own **weighted mix of all input words**, with the weights chosen by the model. ## Computing Attention Weights How does the model choose the weights? An alignment model scores how relevant each input position is, then a softmax turns the scores into weights that sum to 1: $$ e_{ij} = a(s_{i-1}, h_j) $$ $$ \alpha_{ij} = \frac{\exp(e_{ij})}{\sum_{k=1}^{T} \exp(e_{ik})} $$ The alignment function $a$ (often a small neural network) scores how well input $j$ and output $i$ match. You do not need to memorize the formulas — the recipe is: **score every input word, softmax the scores, use them as mixing weights**. ## Interactive Demo Watch attention align source and target words during translation: *Interactive demo: https://aipedia.org/bahdanau-attention* ## The Alignment Model Bahdanau attention uses an additive alignment function: $$ e_{ij} = v^T \tanh(W_s s_{i-1} + W_h h_j) $$ This learnable function discovers which source words are relevant for generating each target word — no hand-built dictionary or word alignments required. ## Why This Changed Everything 1. **No bottleneck**: each output step accesses all encoder states 2. **Interpretable**: attention weights show what the model "looks at" 3. **Handles long sequences**: performance doesn't degrade with length 4. **Generalizable**: the mechanism applies far beyond translation ## Results | Model | BLEU Score | |-------|------------| | RNNsearch (no attention) | 26.75 | | RNNsearch-50 (attention) | **28.45** | | Phrase-based SMT | 33.30 | Attention closed the gap with statistical MT and enabled future improvements. ## Legacy This paper's attention mechanism became: - The foundation of **Transformers** (self-attention) — see [Transformer](https://aipedia.org/transformer) - Used in **image captioning** (visual attention) - Core to **speech recognition** (CTC-attention) - Essential for **modern LLMs** ## Common Confusion - **Bahdanau attention vs. self-attention.** Here, the decoder attends to the *encoder's* states (cross-attention between two sequences). In Transformers, tokens in one sequence attend to *each other* (self-attention). - **Attention vs. alignment.** "Alignment" is the translation-specific framing (which source word maps to which target word); "attention" is the general mechanism computing it. - **This paper vs. Attention Is All You Need.** This 2014 paper *introduced* attention as an add-on to RNNs; the 2017 [Transformer paper](https://aipedia.org/attention-is-all-you-need) removed the RNN entirely and kept only attention. ## Where To Go Next - Read [Sequence to Sequence](https://aipedia.org/seq2seq) for the bottlenecked architecture this paper improved - Read [Understanding LSTMs](https://aipedia.org/understanding-lstms) for the RNN machinery used underneath - Read [Transformer](https://aipedia.org/transformer) for the architecture built purely from attention - Read [Attention Is All You Need](https://aipedia.org/attention-is-all-you-need) for the paper that took that final step # Neural Turing Machines > Neural networks augmented with external memory and attention-based read/write heads - Type: Paper - By: Graves, Wayne & Danihelka - Year: 2014 - Topics: Deep learning, Memory, Attention, Reasoning - Page: https://aipedia.org/neural-turing-machines ## Resources - [Neural Turing Machines](https://arxiv.org/abs/1410.5401): Paper, Graves, Wayne & Danihelka, 2014 - [Attention and Augmented Recurrent Neural Networks](https://distill.pub/2016/augmented-rnns/): Article, Olah & Carter, Distill 2016 **Neural Turing Machines** (NTMs) bolt an external, readable-and-writable memory onto a neural network — like giving the network a notepad. Because every memory operation is differentiable, the whole system can learn *algorithms* (copy, sort, recall) end-to-end by gradient descent. > Helpful background: [Understanding LSTMs](https://aipedia.org/understanding-lstms) for the controller, and [Bahdanau Attention](https://aipedia.org/bahdanau-attention) for the attention idea the read/write heads are built on. ## Why Students Should Care - NTMs are a landmark attempt to make neural networks compute more like computers — with explicit storage, not just learned reflexes. - They pioneered **differentiable attention over memory**, an idea that echoes through Memory Networks, DNCs, and [Transformer](https://aipedia.org/transformer) attention. - The core trick — replace a discrete choice ("read slot 7") with a soft, differentiable weighting over all choices — is one of the most reusable ideas in deep learning. ## Motivation Think about how you multiply two long numbers by hand: you write down intermediate results and read them back later. A standard neural network cannot do this — its "memory" lives implicitly in weights and hidden activations, with no way to deliberately store a value and retrieve it later. Computers, by contrast, have explicit addressable memory. NTMs bridge this gap. The catch is that ordinary memory access is discrete ("read address 7"), and discrete choices block gradients. NTMs solve this by making every access *soft*: instead of reading one slot, read a weighted blend of all slots, with learnable weights. ## Architecture An NTM consists of: 1. **Controller**: Neural network (LSTM or feedforward) — the "CPU" that decides what to read and write 2. **Memory Bank**: $N \times M$ matrix of memory locations — $N$ slots, each holding a vector of size $M$ 3. **Read Head**: Retrieves information from memory 4. **Write Head**: Modifies memory contents ## Reading from Memory The read head produces attention weights $w_t$ over memory locations, and the read result is a weighted average: $$ r_t = \sum_{i=1}^{N} w_t(i) \cdot M_t(i) $$ The read vector $r_t$ is a weighted sum of memory rows. If the weights concentrate on one slot, this behaves like a normal memory read; because the weights are soft, gradients flow through the operation. ## Writing to Memory Writing combines **erase** and **add** operations — first partially blank a slot, then add new content: $$ \tilde{M}_t(i) = M_{t-1}(i) \cdot [1 - w_t(i) \cdot e_t] $$ $$ M_t(i) = \tilde{M}_t(i) + w_t(i) \cdot a_t $$ The erase vector $e_t$ clears, the add vector $a_t$ writes new content. Both are scaled by the attention weight $w_t(i)$, so the head mostly modifies the slots it is "looking at." The takeaway: **reads and writes are both just attention-weighted arithmetic**, which is why the whole machine trains with backpropagation. ## Addressing Mechanisms How does the head decide *where* to look? NTMs compute the attention weights in four stages, combining two styles of addressing: **content-based** ("find the slot that looks like this") and **location-based** ("move one slot to the right of where I was"). ### 1. Content Addressing Compare a key vector $k_t$ to memory rows using cosine similarity, then softmax: $$ w_t^c(i) = \frac{\exp(\beta_t \cdot K(k_t, M_t(i)))}{\sum_j \exp(\beta_t \cdot K(k_t, M_t(j)))} $$ This is "search by similarity" — like looking up a memory by what it contains. ### 2. Interpolation Blend content-based weights with the previous step's weights: $$ w_t^g = g_t \cdot w_t^c + (1 - g_t) \cdot w_{t-1} $$ The gate $g_t$ lets the head either jump to new content or stay where it was. ### 3. Convolutional Shift Allow location-based addressing via circular convolution — the head can shift its focus left or right by a slot, enabling sequential iteration like a tape head. ### 4. Sharpening Focus attention with a sharpening parameter $\gamma_t$, counteracting the blurring that shifting introduces. ## Interactive Demo Explore memory read/write operations: *Interactive demo: https://aipedia.org/neural-turing-machines* ## What NTMs Can Learn The paper demonstrated learning of small algorithms from input-output examples alone: - **Copy**: Reproduce an input sequence - **Associative Recall**: Retrieve values by key - **N-Gram modeling**: Track recent symbols - **Priority Sort**: Sort by priority values Notably, NTMs generalized to longer sequences than they were trained on — evidence they learned something algorithm-like, not just pattern matching. ## Legacy NTMs pioneered ideas now central to modern AI: - External memory augmentation - Differentiable attention mechanisms - Content-based retrieval These concepts evolved into Memory Networks, Differentiable Neural Computers (DNC), and influenced Transformer attention. ## Common Confusion - **NTM vs. Turing machine**: an NTM is not a formal Turing machine. The name signals the analogy — controller as CPU, memory bank as tape — but everything is continuous and learned. - **NTM vs. LSTM**: an LSTM's memory is a fixed-size hidden state entangled with computation; an NTM separates computation (controller) from storage (memory bank), which can be made larger without adding parameters. - **NTM attention vs. Transformer attention**: both use content-based, softmax-weighted lookup. But NTMs attend over an explicit *memory the model writes to*, while [Transformers](https://aipedia.org/transformer) attend over the input sequence's own representations, with no separate writable store. - **NTM vs. DNC**: the Differentiable Neural Computer is the successor architecture by the same group, with improved memory management (e.g., tracking which slots are free). ## Where To Go Next - Read [Understanding LSTMs](https://aipedia.org/understanding-lstms) for the recurrent controller at an NTM's core. - Read [Bahdanau Attention](https://aipedia.org/bahdanau-attention) for the contemporaneous attention mechanism in translation. - Read [Transformer](https://aipedia.org/transformer) and [Attention Is All You Need](https://aipedia.org/attention-is-all-you-need) to see where differentiable attention ended up. - Read [Relational RNN](https://aipedia.org/relational-rnn) for a later memory-plus-attention architecture. # Recurrent Neural Network Regularization > How to apply dropout to LSTMs without disrupting memory dynamics - Type: Paper - By: Zaremba, Sutskever & Vinyals - Year: 2014 - Topics: Deep learning, RNNs, LSTMs, Regularization - Page: https://aipedia.org/rnn-regularization ## Resources - [Recurrent Neural Network Regularization](https://arxiv.org/abs/1409.2329): Paper, Zaremba, Sutskever & Vinyals, 2014 **Recurrent Neural Network Regularization** is the paper by Zaremba, Sutskever, and Vinyals that solved an annoying practical problem: standard dropout, the go-to trick for preventing overfitting, breaks RNNs. Their fix — drop only the "vertical" connections, never the "horizontal" memory path — became the standard recipe. > Prerequisites: know what [dropout](https://aipedia.org/dropout) is and how an [LSTM](https://aipedia.org/understanding-lstms) carries memory across timesteps. Both pages are short. ## Why Students Should Care - LSTMs of this era overfit badly; without a working regularizer they had to be kept small. This paper let people train much larger recurrent models. - It teaches a transferable lesson: **where** you apply a regularizer matters as much as whether you apply it. - The "protect the memory path" insight echoes through later designs — residual streams in [Transformers](https://aipedia.org/transformer) are similarly kept clean. ## The Problem: Dropout Noise Compounds Over Time Dropout randomly zeroes activations during training. In a feedforward net, each activation gets zapped at most once per forward pass — no big deal. But an RNN reuses its hidden state at *every* timestep. Naively dropping the recurrent connection looks like this: $$ h_t = f(W_h \cdot \text{dropout}(h_{t-1}) + W_x \cdot x_t) $$ Now the memory gets corrupted by fresh noise at every single step. Over a 100-step sequence, that is 100 rounds of damage — the network can no longer retain long-term information, which was the whole point of using an LSTM. ## The Solution: Only Drop the Non-Recurrent Connections Apply dropout on the way *into* and *out of* each layer, but leave the timestep-to-timestep path untouched: $$ h_t = f(W_h \cdot h_{t-1} + W_x \cdot \text{dropout}(x_t)) $$ $$ y_t = \text{dropout}(h_t) $$ The recurrent path $h_{t-1} \rightarrow h_t$ remains clean, preserving memory. Information still gets regularized — but only once per layer it passes through, not once per timestep. ## Where to Apply Dropout | Connection | Apply Dropout? | |-----------|---------------| | Input → Hidden | ✓ Yes | | Hidden → Hidden (recurrent) | ✗ No | | Hidden → Output | ✓ Yes | | Between LSTM layers | ✓ Yes | One rule of thumb captures the whole paper: **drop vertical arrows, never horizontal ones**. ## Interactive Demo Visualize how dropout randomly masks neurons during training: *Interactive demo: https://aipedia.org/rnn-regularization* ## LSTM-Specific Details For multi-layer LSTMs, dropout is applied between layers: ``` Layer 1: dropout(x) → LSTM → h1 Layer 2: dropout(h1) → LSTM → h2 Layer 3: dropout(h2) → LSTM → h3 Output: dropout(h3) → Linear → y ``` Within each LSTM cell, the recurrent connections remain untouched. ## Results On Penn Treebank word-level language modeling (lower perplexity = better): | Model | Perplexity | |-------|------------| | LSTM (no dropout) | 120.7 | | LSTM (naive dropout) | Diverges | | LSTM (this paper) | **78.4** | Proper dropout reduces perplexity by 35% — and note that naive dropout is not just worse, it fails to train at all. ## Mathematical Formulation During training with dropout rate $p$, kept activations are rescaled: $$ \tilde{h}_t^l = \text{dropout}(h_t^l, p) \cdot \frac{1}{1-p} $$ The scaling factor ensures expected values match at test time, so you can turn dropout off for inference without recalibrating anything. ## Key Insights 1. **Dropout placement matters**: the recurrent path needs to stay clean so memory and gradients survive 2. **Same mask per sequence**: use a consistent dropout mask across timesteps rather than resampling each step 3. **Higher dropout for deeper networks**: more layers tolerate — and benefit from — more regularization ## Common Confusion - **This is not "no dropout in RNNs"**: dropout works great in RNNs — just on the input, output, and between-layer connections, not on the hidden-to-hidden loop. - **Regularization vs. architecture**: this paper changes *training*, not the LSTM cell itself. The model at test time is a plain LSTM. - **Later variants exist**: "variational dropout" (Gal and Ghahramani) later showed a principled way to drop recurrent connections using one fixed mask per sequence; this paper's simpler recipe was the established baseline. ## Where To Go Next - Read [Dropout](https://aipedia.org/dropout) for the original technique and why randomly deleting neurons prevents overfitting. - Read [Understanding LSTMs](https://aipedia.org/understanding-lstms) for the memory dynamics this paper is careful not to break. - Read [RNN Effectiveness](https://aipedia.org/rnn-effectiveness) for the kind of language models this recipe made trainable at scale. - Read [Layer Normalization](https://aipedia.org/layer-normalization) for another technique adapted specially for recurrent networks. # Sequence to Sequence Learning > Encoder-decoder architecture for mapping sequences to sequences - Type: Paper - By: Sutskever, Vinyals & Le - Year: 2014 - Topics: Architecture, Deep learning, NLP, Encoder decoder, Seq2seq, RNNs - Page: https://aipedia.org/seq2seq ## Resources - [Sequence to Sequence Learning with Neural Networks](https://arxiv.org/abs/1409.3215): Paper, Sutskever, Vinyals & Le, 2014 - [Learning Phrase Representations using RNN Encoder-Decoder](https://arxiv.org/abs/1406.1078): Paper, Cho et al., 2014 - [Neural Machine Translation by Jointly Learning to Align and Translate](https://arxiv.org/abs/1409.0473): Paper, Bahdanau, Cho & Bengio, 2014 - [Effective Approaches to Attention-based Neural Machine Translation](https://arxiv.org/abs/1508.04025): Paper, Luong et al., 2015 **Sequence-to-Sequence** (Seq2Seq) is a neural architecture that turns one sequence into another: read the input with an **encoder**, then write the output with a **decoder**. Introduced by Sutskever et al. at Google in 2014, it enabled neural machine translation and became the foundation for modern language models. > This page assumes basic familiarity with recurrent networks — read [Understanding LSTMs](https://aipedia.org/understanding-lstms) first if needed. Seq2Seq's main weakness led directly to [Bahdanau Attention](https://aipedia.org/bahdanau-attention) and then the [Transformer](https://aipedia.org/transformer). ## Why Students Should Care - The **encoder-decoder** split introduced here is still the mental model behind translation, summarization, and chat systems. - Seq2Seq is the first step in the chain that leads to attention and Transformers — you cannot appreciate what attention fixed without knowing this design. - Practical ideas born here — teacher forcing, beam search — are still used to train and run today's language models. ## The Problem Traditional neural networks require fixed-size inputs and outputs. But many tasks have variable lengths on both sides: - Translation: "Hello" (1 word) → "Bonjour" (1 word) - Translation: "How are you?" (3 words) → "Comment allez-vous?" (2 words) There is no fixed slot count you can design a plain feed-forward network around. Seq2Seq needed a way to map *any-length* input to *any-length* output. ## The Solution: Encoder-Decoder Split the problem into two parts: 1. **Encoder**: read the entire input sequence and compress it into a fixed-size vector (the "thought vector" or "context") 2. **Decoder**: generate the output sequence, one token at a time, starting from this context vector $$ \text{Input} \xrightarrow{\text{Encoder}} \mathbf{c} \xrightarrow{\text{Decoder}} \text{Output} $$ Think of it as: read the whole sentence, form a thought, then say the thought in the other language. ## Interactive Demo Watch how Seq2Seq encodes a sentence and decodes its translation: *Interactive demo: https://aipedia.org/seq2seq* ## The Architecture ### Encoder (LSTM) The encoder is an LSTM that processes the input sequence $x_1, x_2, ..., x_T$ one token at a time, updating its hidden state: $$ h_t = \text{LSTM}(x_t, h_{t-1}) $$ The final hidden state $h_T$ becomes the context vector $\mathbf{c}$ — a summary of everything it read. ### Decoder (LSTM) The decoder is another LSTM that generates the output sequence $y_1, y_2, ..., y_{T'}$, feeding each generated word back in as input for the next step: $$ s_t = \text{LSTM}(y_{t-1}, s_{t-1}) $$ $$ P(y_t | y_{